xref: /freebsd/sys/netinet/tcp_stacks/bbr.c (revision 410556f1f10fd35b350102725fd8504c3cb0afc8)
1 /*-
2  * Copyright (c) 2016-2020 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  */
26 /**
27  * Author: Randall Stewart <rrs@netflix.com>
28  * This work is based on the ACM Queue paper
29  * BBR - Congestion Based Congestion Control
30  * and also numerous discussions with Neal, Yuchung and Van.
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include "opt_inet.h"
37 #include "opt_inet6.h"
38 #include "opt_ipsec.h"
39 #include "opt_tcpdebug.h"
40 #include "opt_ratelimit.h"
41 #include <sys/param.h>
42 #include <sys/arb.h>
43 #include <sys/module.h>
44 #include <sys/kernel.h>
45 #include <sys/libkern.h>
46 #ifdef TCP_HHOOK
47 #include <sys/hhook.h>
48 #endif
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>
51 #include <sys/proc.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/sysctl.h>
55 #include <sys/systm.h>
56 #ifdef STATS
57 #include <sys/qmath.h>
58 #include <sys/tree.h>
59 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
60 #endif
61 #include <sys/refcount.h>
62 #include <sys/queue.h>
63 #include <sys/eventhandler.h>
64 #include <sys/smp.h>
65 #include <sys/kthread.h>
66 #include <sys/lock.h>
67 #include <sys/mutex.h>
68 #include <sys/tim_filter.h>
69 #include <sys/time.h>
70 #include <sys/protosw.h>
71 #include <vm/uma.h>
72 #include <sys/kern_prefetch.h>
73 
74 #include <net/route.h>
75 #include <net/route/nhop.h>
76 #include <net/vnet.h>
77 
78 #define TCPSTATES		/* for logging */
79 
80 #include <netinet/in.h>
81 #include <netinet/in_kdtrace.h>
82 #include <netinet/in_pcb.h>
83 #include <netinet/ip.h>
84 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
85 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
86 #include <netinet/ip_var.h>
87 #include <netinet/ip6.h>
88 #include <netinet6/in6_pcb.h>
89 #include <netinet6/ip6_var.h>
90 #define	TCPOUTFLAGS
91 #include <netinet/tcp.h>
92 #include <netinet/tcp_fsm.h>
93 #include <netinet/tcp_seq.h>
94 #include <netinet/tcp_timer.h>
95 #include <netinet/tcp_var.h>
96 #include <netinet/tcpip.h>
97 #include <netinet/tcp_hpts.h>
98 #include <netinet/cc/cc.h>
99 #include <netinet/tcp_log_buf.h>
100 #include <netinet/tcp_ratelimit.h>
101 #include <netinet/tcp_lro.h>
102 #ifdef TCPDEBUG
103 #include <netinet/tcp_debug.h>
104 #endif				/* TCPDEBUG */
105 #ifdef TCP_OFFLOAD
106 #include <netinet/tcp_offload.h>
107 #endif
108 #ifdef INET6
109 #include <netinet6/tcp6_var.h>
110 #endif
111 #include <netinet/tcp_fastopen.h>
112 
113 #include <netipsec/ipsec_support.h>
114 #include <net/if.h>
115 #include <net/if_var.h>
116 #include <net/ethernet.h>
117 
118 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
119 #include <netipsec/ipsec.h>
120 #include <netipsec/ipsec6.h>
121 #endif				/* IPSEC */
122 
123 #include <netinet/udp.h>
124 #include <netinet/udp_var.h>
125 #include <machine/in_cksum.h>
126 
127 #ifdef MAC
128 #include <security/mac/mac_framework.h>
129 #endif
130 
131 #include "sack_filter.h"
132 #include "tcp_bbr.h"
133 #include "rack_bbr_common.h"
134 uma_zone_t bbr_zone;
135 uma_zone_t bbr_pcb_zone;
136 
137 struct sysctl_ctx_list bbr_sysctl_ctx;
138 struct sysctl_oid *bbr_sysctl_root;
139 
140 #define	TCPT_RANGESET_NOSLOP(tv, value, tvmin, tvmax) do { \
141 	(tv) = (value); \
142 	if ((u_long)(tv) < (u_long)(tvmin)) \
143 		(tv) = (tvmin); \
144 	if ((u_long)(tv) > (u_long)(tvmax)) \
145 		(tv) = (tvmax); \
146 } while(0)
147 
148 /*#define BBR_INVARIANT 1*/
149 
150 /*
151  * initial window
152  */
153 static uint32_t bbr_def_init_win = 10;
154 static int32_t bbr_persist_min = 250000;	/* 250ms */
155 static int32_t bbr_persist_max = 1000000;	/* 1 Second */
156 static int32_t bbr_cwnd_may_shrink = 0;
157 static int32_t bbr_cwndtarget_rtt_touse = BBR_RTT_PROP;
158 static int32_t bbr_num_pktepo_for_del_limit = BBR_NUM_RTTS_FOR_DEL_LIMIT;
159 static int32_t bbr_hardware_pacing_limit = 8000;
160 static int32_t bbr_quanta = 3;	/* How much extra quanta do we get? */
161 static int32_t bbr_no_retran = 0;
162 
163 static int32_t bbr_error_base_paceout = 10000; /* usec to pace */
164 static int32_t bbr_max_net_error_cnt = 10;
165 /* Should the following be dynamic too -- loss wise */
166 static int32_t bbr_rtt_gain_thresh = 0;
167 /* Measurement controls */
168 static int32_t bbr_use_google_algo = 1;
169 static int32_t bbr_ts_limiting = 1;
170 static int32_t bbr_ts_can_raise = 0;
171 static int32_t bbr_do_red = 600;
172 static int32_t bbr_red_scale = 20000;
173 static int32_t bbr_red_mul = 1;
174 static int32_t bbr_red_div = 2;
175 static int32_t bbr_red_growth_restrict = 1;
176 static int32_t  bbr_target_is_bbunit = 0;
177 static int32_t bbr_drop_limit = 0;
178 /*
179  * How much gain do we need to see to
180  * stay in startup?
181  */
182 static int32_t bbr_marks_rxt_sack_passed = 0;
183 static int32_t bbr_start_exit = 25;
184 static int32_t bbr_low_start_exit = 25;	/* When we are in reduced gain */
185 static int32_t bbr_startup_loss_thresh = 2000;	/* 20.00% loss */
186 static int32_t bbr_hptsi_max_mul = 1;	/* These two mul/div assure a min pacing */
187 static int32_t bbr_hptsi_max_div = 2;	/* time, 0 means turned off. We need this
188 					 * if we go back ever to where the pacer
189 					 * has priority over timers.
190 					 */
191 static int32_t bbr_policer_call_from_rack_to = 0;
192 static int32_t bbr_policer_detection_enabled = 1;
193 static int32_t bbr_min_measurements_req = 1;	/* We need at least 2
194 						 * measurments before we are
195 						 * "good" note that 2 == 1.
196 						 * This is because we use a >
197 						 * comparison. This means if
198 						 * min_measure was 0, it takes
199 						 * num-measures > min(0) and
200 						 * you get 1 measurement and
201 						 * you are good. Set to 1, you
202 						 * have to have two
203 						 * measurements (this is done
204 						 * to prevent it from being ok
205 						 * to have no measurements). */
206 static int32_t bbr_no_pacing_until = 4;
207 
208 static int32_t bbr_min_usec_delta = 20000;	/* 20,000 usecs */
209 static int32_t bbr_min_peer_delta = 20;		/* 20 units */
210 static int32_t bbr_delta_percent = 150;		/* 15.0 % */
211 
212 static int32_t bbr_target_cwnd_mult_limit = 8;
213 /*
214  * bbr_cwnd_min_val is the number of
215  * segments we hold to in the RTT probe
216  * state typically 4.
217  */
218 static int32_t bbr_cwnd_min_val = BBR_PROBERTT_NUM_MSS;
219 
220 static int32_t bbr_cwnd_min_val_hs = BBR_HIGHSPEED_NUM_MSS;
221 
222 static int32_t bbr_gain_to_target = 1;
223 static int32_t bbr_gain_gets_extra_too = 1;
224 /*
225  * bbr_high_gain is the 2/ln(2) value we need
226  * to double the sending rate in startup. This
227  * is used for both cwnd and hptsi gain's.
228  */
229 static int32_t bbr_high_gain = BBR_UNIT * 2885 / 1000 + 1;
230 static int32_t bbr_startup_lower = BBR_UNIT * 1500 / 1000 + 1;
231 static int32_t bbr_use_lower_gain_in_startup = 1;
232 
233 /* thresholds for reduction on drain in sub-states/drain */
234 static int32_t bbr_drain_rtt = BBR_SRTT;
235 static int32_t bbr_drain_floor = 88;
236 static int32_t google_allow_early_out = 1;
237 static int32_t google_consider_lost = 1;
238 static int32_t bbr_drain_drop_mul = 4;
239 static int32_t bbr_drain_drop_div = 5;
240 static int32_t bbr_rand_ot = 50;
241 static int32_t bbr_can_force_probertt = 0;
242 static int32_t bbr_can_adjust_probertt = 1;
243 static int32_t bbr_probertt_sets_rtt = 0;
244 static int32_t bbr_can_use_ts_for_rtt = 1;
245 static int32_t bbr_is_ratio = 0;
246 static int32_t bbr_sub_drain_app_limit = 1;
247 static int32_t bbr_prtt_slam_cwnd = 1;
248 static int32_t bbr_sub_drain_slam_cwnd = 1;
249 static int32_t bbr_slam_cwnd_in_main_drain = 1;
250 static int32_t bbr_filter_len_sec = 6;	/* How long does the rttProp filter
251 					 * hold */
252 static uint32_t bbr_rtt_probe_limit = (USECS_IN_SECOND * 4);
253 /*
254  * bbr_drain_gain is the reverse of the high_gain
255  * designed to drain back out the standing queue
256  * that is formed in startup by causing a larger
257  * hptsi gain and thus drainging the packets
258  * in flight.
259  */
260 static int32_t bbr_drain_gain = BBR_UNIT * 1000 / 2885;
261 static int32_t bbr_rttprobe_gain = 192;
262 
263 /*
264  * The cwnd_gain is the default cwnd gain applied when
265  * calculating a target cwnd. Note that the cwnd is
266  * a secondary factor in the way BBR works (see the
267  * paper and think about it, it will take some time).
268  * Basically the hptsi_gain spreads the packets out
269  * so you never get more than BDP to the peer even
270  * if the cwnd is high. In our implemenation that
271  * means in non-recovery/retransmission scenarios
272  * cwnd will never be reached by the flight-size.
273  */
274 static int32_t bbr_cwnd_gain = BBR_UNIT * 2;
275 static int32_t bbr_tlp_type_to_use = BBR_SRTT;
276 static int32_t bbr_delack_time = 100000;	/* 100ms in useconds */
277 static int32_t bbr_sack_not_required = 0;	/* set to one to allow non-sack to use bbr */
278 static int32_t bbr_initial_bw_bps = 62500;	/* 500kbps in bytes ps */
279 static int32_t bbr_ignore_data_after_close = 1;
280 static int16_t bbr_hptsi_gain[] = {
281 	(BBR_UNIT *5 / 4),
282 	(BBR_UNIT * 3 / 4),
283 	BBR_UNIT,
284 	BBR_UNIT,
285 	BBR_UNIT,
286 	BBR_UNIT,
287 	BBR_UNIT,
288 	BBR_UNIT
289 };
290 int32_t bbr_use_rack_resend_cheat = 1;
291 int32_t bbr_sends_full_iwnd = 1;
292 
293 #define BBR_HPTSI_GAIN_MAX 8
294 /*
295  * The BBR module incorporates a number of
296  * TCP ideas that have been put out into the IETF
297  * over the last few years:
298  * - Yuchung Cheng's RACK TCP (for which its named) that
299  *    will stop us using the number of dup acks and instead
300  *    use time as the gage of when we retransmit.
301  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
302  *    of Dukkipati et.al.
303  * - Van Jacobson's et.al BBR.
304  *
305  * RACK depends on SACK, so if an endpoint arrives that
306  * cannot do SACK the state machine below will shuttle the
307  * connection back to using the "default" TCP stack that is
308  * in FreeBSD.
309  *
310  * To implement BBR and RACK the original TCP stack was first decomposed
311  * into a functional state machine with individual states
312  * for each of the possible TCP connection states. The do_segement
313  * functions role in life is to mandate the connection supports SACK
314  * initially and then assure that the RACK state matches the conenction
315  * state before calling the states do_segment function. Data processing
316  * of inbound segments also now happens in the hpts_do_segment in general
317  * with only one exception. This is so we can keep the connection on
318  * a single CPU.
319  *
320  * Each state is simplified due to the fact that the original do_segment
321  * has been decomposed and we *know* what state we are in (no
322  * switches on the state) and all tests for SACK are gone. This
323  * greatly simplifies what each state does.
324  *
325  * TCP output is also over-written with a new version since it
326  * must maintain the new rack scoreboard and has had hptsi
327  * integrated as a requirment. Still todo is to eliminate the
328  * use of the callout_() system and use the hpts for all
329  * timers as well.
330  */
331 static uint32_t bbr_rtt_probe_time = 200000;	/* 200ms in micro seconds */
332 static uint32_t bbr_rtt_probe_cwndtarg = 4;	/* How many mss's outstanding */
333 static const int32_t bbr_min_req_free = 2;	/* The min we must have on the
334 						 * free list */
335 static int32_t bbr_tlp_thresh = 1;
336 static int32_t bbr_reorder_thresh = 2;
337 static int32_t bbr_reorder_fade = 60000000;	/* 0 - never fade, def
338 						 * 60,000,000 - 60 seconds */
339 static int32_t bbr_pkt_delay = 1000;
340 static int32_t bbr_min_to = 1000;	/* Number of usec's minimum timeout */
341 static int32_t bbr_incr_timers = 1;
342 
343 static int32_t bbr_tlp_min = 10000;	/* 10ms in usecs */
344 static int32_t bbr_delayed_ack_time = 200000;	/* 200ms in usecs */
345 static int32_t bbr_exit_startup_at_loss = 1;
346 
347 /*
348  * bbr_lt_bw_ratio is 1/8th
349  * bbr_lt_bw_diff is  < 4 Kbit/sec
350  */
351 static uint64_t bbr_lt_bw_diff = 4000 / 8;	/* In bytes per second */
352 static uint64_t bbr_lt_bw_ratio = 8;	/* For 1/8th */
353 static uint32_t bbr_lt_bw_max_rtts = 48;	/* How many rtt's do we use
354 						 * the lt_bw for */
355 static uint32_t bbr_lt_intvl_min_rtts = 4;	/* Min num of RTT's to measure
356 						 * lt_bw */
357 static int32_t bbr_lt_intvl_fp = 0;		/* False positive epoch diff */
358 static int32_t bbr_lt_loss_thresh = 196;	/* Lost vs delivered % */
359 static int32_t bbr_lt_fd_thresh = 100;		/* false detection % */
360 
361 static int32_t bbr_verbose_logging = 0;
362 /*
363  * Currently regular tcp has a rto_min of 30ms
364  * the backoff goes 12 times so that ends up
365  * being a total of 122.850 seconds before a
366  * connection is killed.
367  */
368 static int32_t bbr_rto_min_ms = 30;	/* 30ms same as main freebsd */
369 static int32_t bbr_rto_max_sec = 4;	/* 4 seconds */
370 
371 /****************************************************/
372 /* DEFAULT TSO SIZING  (cpu performance impacting)  */
373 /****************************************************/
374 /* What amount is our formula using to get TSO size */
375 static int32_t bbr_hptsi_per_second = 1000;
376 
377 /*
378  * For hptsi under bbr_cross_over connections what is delay
379  * target 7ms (in usec) combined with a seg_max of 2
380  * gets us close to identical google behavior in
381  * TSO size selection (possibly more 1MSS sends).
382  */
383 static int32_t bbr_hptsi_segments_delay_tar = 7000;
384 
385 /* Does pacing delay include overhead's in its time calculations? */
386 static int32_t bbr_include_enet_oh = 0;
387 static int32_t bbr_include_ip_oh = 1;
388 static int32_t bbr_include_tcp_oh = 1;
389 static int32_t bbr_google_discount = 10;
390 
391 /* Do we use (nf mode) pkt-epoch to drive us or rttProp? */
392 static int32_t bbr_state_is_pkt_epoch = 0;
393 static int32_t bbr_state_drain_2_tar = 1;
394 /* What is the max the 0 - bbr_cross_over MBPS TSO target
395  * can reach using our delay target. Note that this
396  * value becomes the floor for the cross over
397  * algorithm.
398  */
399 static int32_t bbr_hptsi_segments_max = 2;
400 static int32_t bbr_hptsi_segments_floor = 1;
401 static int32_t bbr_hptsi_utter_max = 0;
402 
403 /* What is the min the 0 - bbr_cross-over MBPS  TSO target can be */
404 static int32_t bbr_hptsi_bytes_min = 1460;
405 static int32_t bbr_all_get_min = 0;
406 
407 /* Cross over point from algo-a to algo-b */
408 static uint32_t bbr_cross_over = TWENTY_THREE_MBPS;
409 
410 /* Do we deal with our restart state? */
411 static int32_t bbr_uses_idle_restart = 0;
412 static int32_t bbr_idle_restart_threshold = 100000;	/* 100ms in useconds */
413 
414 /* Do we allow hardware pacing? */
415 static int32_t bbr_allow_hdwr_pacing = 0;
416 static int32_t bbr_hdwr_pace_adjust = 2;	/* multipler when we calc the tso size */
417 static int32_t bbr_hdwr_pace_floor = 1;
418 static int32_t bbr_hdwr_pacing_delay_cnt = 10;
419 
420 /****************************************************/
421 static int32_t bbr_resends_use_tso = 0;
422 static int32_t bbr_tlp_max_resend = 2;
423 static int32_t bbr_sack_block_limit = 128;
424 
425 #define  BBR_MAX_STAT 19
426 counter_u64_t bbr_state_time[BBR_MAX_STAT];
427 counter_u64_t bbr_state_lost[BBR_MAX_STAT];
428 counter_u64_t bbr_state_resend[BBR_MAX_STAT];
429 counter_u64_t bbr_stat_arry[BBR_STAT_SIZE];
430 counter_u64_t bbr_opts_arry[BBR_OPTS_SIZE];
431 counter_u64_t bbr_out_size[TCP_MSS_ACCT_SIZE];
432 counter_u64_t bbr_flows_whdwr_pacing;
433 counter_u64_t bbr_flows_nohdwr_pacing;
434 
435 counter_u64_t bbr_nohdwr_pacing_enobuf;
436 counter_u64_t bbr_hdwr_pacing_enobuf;
437 
438 static inline uint64_t bbr_get_bw(struct tcp_bbr *bbr);
439 
440 /*
441  * Static defintions we need for forward declarations.
442  */
443 static uint32_t
444 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain,
445     uint32_t useconds_time, uint64_t bw);
446 static uint32_t
447 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain);
448 static void
449      bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win);
450 static void
451 bbr_set_probebw_gains(struct tcp_bbr *bbr,  uint32_t cts, uint32_t losses);
452 static void
453 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int line,
454 		    int dolog);
455 static uint32_t
456 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain);
457 static void
458 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch,
459 		 int32_t pkt_epoch, uint32_t losses);
460 static uint32_t
461 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm);
462 static uint32_t bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp);
463 static uint32_t
464 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
465     struct bbr_sendmap *rsm, uint32_t srtt,
466     uint32_t cts);
467 static void
468 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
469     int32_t line);
470 static void
471      bbr_set_state_target(struct tcp_bbr *bbr, int line);
472 static void
473      bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line);
474 
475 static void
476      bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line);
477 
478 static void
479      tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts);
480 
481 static void
482      bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts);
483 
484 static void
485      bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied, uint32_t rtt,
486 			 uint32_t line, uint8_t is_start, uint16_t set);
487 
488 static struct bbr_sendmap *
489             bbr_find_lowest_rsm(struct tcp_bbr *bbr);
490 static __inline uint32_t
491 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type);
492 static void
493      bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which);
494 
495 static void
496 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
497     uint32_t thresh, uint32_t to);
498 static void
499      bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag);
500 
501 static void
502 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot,
503     uint32_t del_by, uint32_t cts, uint32_t sloton, uint32_t prev_delay);
504 
505 static void
506 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr,
507     uint32_t cts, int32_t line);
508 static void
509      bbr_stop_all_timers(struct tcpcb *tp);
510 static void
511      bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts);
512 static void
513      bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts);
514 static void
515      bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts);
516 
517 static void
518 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
519     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod);
520 
521 static inline uint8_t
522 bbr_state_val(struct tcp_bbr *bbr)
523 {
524 	return(bbr->rc_bbr_substate);
525 }
526 
527 static inline uint32_t
528 get_min_cwnd(struct tcp_bbr *bbr)
529 {
530 	int mss;
531 
532 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
533 	if (bbr_get_rtt(bbr, BBR_RTT_PROP) < BBR_HIGH_SPEED)
534 		return (bbr_cwnd_min_val_hs * mss);
535 	else
536 		return (bbr_cwnd_min_val * mss);
537 }
538 
539 static uint32_t
540 bbr_get_persists_timer_val(struct tcpcb *tp, struct tcp_bbr *bbr)
541 {
542 	uint64_t srtt, var;
543 	uint64_t ret_val;
544 
545 	bbr->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
546 	if (tp->t_srtt == 0) {
547 		srtt = (uint64_t)BBR_INITIAL_RTO;
548 		var = 0;
549 	} else {
550 		srtt = ((uint64_t)TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
551 		var = ((uint64_t)TICKS_2_USEC(tp->t_rttvar) >> TCP_RTT_SHIFT);
552 	}
553 	TCPT_RANGESET_NOSLOP(ret_val, ((srtt + var) * tcp_backoff[tp->t_rxtshift]),
554 	    bbr_persist_min, bbr_persist_max);
555 	return ((uint32_t)ret_val);
556 }
557 
558 static uint32_t
559 bbr_timer_start(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
560 {
561 	/*
562 	 * Start the FR timer, we do this based on getting the first one in
563 	 * the rc_tmap. Note that if its NULL we must stop the timer. in all
564 	 * events we need to stop the running timer (if its running) before
565 	 * starting the new one.
566 	 */
567 	uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
568 	int32_t idx;
569 	int32_t is_tlp_timer = 0;
570 	struct bbr_sendmap *rsm;
571 
572 	if (bbr->rc_all_timers_stopped) {
573 		/* All timers have been stopped none are to run */
574 		return (0);
575 	}
576 	if (bbr->rc_in_persist) {
577 		/* We can't start any timer in persists */
578 		return (bbr_get_persists_timer_val(tp, bbr));
579 	}
580 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
581 	if ((rsm == NULL) ||
582 	    ((tp->t_flags & TF_SACK_PERMIT) == 0) ||
583 	    (tp->t_state < TCPS_ESTABLISHED)) {
584 		/* Nothing on the send map */
585 activate_rxt:
586 		if (SEQ_LT(tp->snd_una, tp->snd_max) || sbavail(&(tp->t_inpcb->inp_socket->so_snd))) {
587 			uint64_t tov;
588 
589 			time_since_sent = 0;
590 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
591 			if (rsm) {
592 				idx = rsm->r_rtr_cnt - 1;
593 				if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
594 					tstmp_touse = rsm->r_tim_lastsent[idx];
595 				else
596 					tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
597 				if (TSTMP_GT(tstmp_touse, cts))
598 				    time_since_sent = cts - tstmp_touse;
599 			}
600 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
601 			if (tp->t_srtt == 0)
602 				tov = BBR_INITIAL_RTO;
603 			else
604 				tov = ((uint64_t)(TICKS_2_USEC(tp->t_srtt) +
605 				    ((uint64_t)TICKS_2_USEC(tp->t_rttvar) * (uint64_t)4)) >> TCP_RTT_SHIFT);
606 			if (tp->t_rxtshift)
607 				tov *= tcp_backoff[tp->t_rxtshift];
608 			if (tov > time_since_sent)
609 				tov -= time_since_sent;
610 			else
611 				tov = bbr->r_ctl.rc_min_to;
612 			TCPT_RANGESET_NOSLOP(to, tov,
613 			    (bbr->r_ctl.rc_min_rto_ms * MS_IN_USEC),
614 			    (bbr->rc_max_rto_sec * USECS_IN_SECOND));
615 			bbr_log_timer_var(bbr, 2, cts, 0, srtt, 0, to);
616 			return (to);
617 		}
618 		return (0);
619 	}
620 	if (rsm->r_flags & BBR_ACKED) {
621 		rsm = bbr_find_lowest_rsm(bbr);
622 		if (rsm == NULL) {
623 			/* No lowest? */
624 			goto activate_rxt;
625 		}
626 	}
627 	/* Convert from ms to usecs */
628 	if (rsm->r_flags & BBR_SACK_PASSED) {
629 		if ((tp->t_flags & TF_SENTFIN) &&
630 		    ((tp->snd_max - tp->snd_una) == 1) &&
631 		    (rsm->r_flags & BBR_HAS_FIN)) {
632 			/*
633 			 * We don't start a bbr rack timer if all we have is
634 			 * a FIN outstanding.
635 			 */
636 			goto activate_rxt;
637 		}
638 		srtt = bbr_get_rtt(bbr, BBR_RTT_RACK);
639 		thresh = bbr_calc_thresh_rack(bbr, srtt, cts, rsm);
640 		idx = rsm->r_rtr_cnt - 1;
641 		exp = rsm->r_tim_lastsent[idx] + thresh;
642 		if (SEQ_GEQ(exp, cts)) {
643 			to = exp - cts;
644 			if (to < bbr->r_ctl.rc_min_to) {
645 				to = bbr->r_ctl.rc_min_to;
646 			}
647 		} else {
648 			to = bbr->r_ctl.rc_min_to;
649 		}
650 	} else {
651 		/* Ok we need to do a TLP not RACK */
652 		if (bbr->rc_tlp_in_progress != 0) {
653 			/*
654 			 * The previous send was a TLP.
655 			 */
656 			goto activate_rxt;
657 		}
658 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
659 		if (rsm == NULL) {
660 			/* We found no rsm to TLP with. */
661 			goto activate_rxt;
662 		}
663 		if (rsm->r_flags & BBR_HAS_FIN) {
664 			/* If its a FIN we don't do TLP */
665 			rsm = NULL;
666 			goto activate_rxt;
667 		}
668 		time_since_sent = 0;
669 		idx = rsm->r_rtr_cnt - 1;
670 		if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
671 			tstmp_touse = rsm->r_tim_lastsent[idx];
672 		else
673 			tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
674 		if (TSTMP_GT(tstmp_touse, cts))
675 		    time_since_sent = cts - tstmp_touse;
676 		is_tlp_timer = 1;
677 		srtt = bbr_get_rtt(bbr, bbr_tlp_type_to_use);
678 		thresh = bbr_calc_thresh_tlp(tp, bbr, rsm, srtt, cts);
679 		if (thresh > time_since_sent)
680 			to = thresh - time_since_sent;
681 		else
682 			to = bbr->r_ctl.rc_min_to;
683 		if (to > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
684 			/*
685 			 * If the TLP time works out to larger than the max
686 			 * RTO lets not do TLP.. just RTO.
687 			 */
688 			goto activate_rxt;
689 		}
690 		if ((bbr->rc_tlp_rtx_out == 1) &&
691 		    (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq)) {
692 			/*
693 			 * Second retransmit of the same TLP
694 			 * lets not.
695 			 */
696 			bbr->rc_tlp_rtx_out = 0;
697 			goto activate_rxt;
698 		}
699 		if (rsm->r_start != bbr->r_ctl.rc_last_tlp_seq) {
700 			/*
701 			 * The tail is no longer the last one I did a probe
702 			 * on
703 			 */
704 			bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
705 			bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
706 		}
707 	}
708 	if (is_tlp_timer == 0) {
709 		BBR_STAT_INC(bbr_to_arm_rack);
710 		bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
711 	} else {
712 		bbr_log_timer_var(bbr, 1, cts, time_since_sent, srtt, thresh, to);
713 		if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
714 			/*
715 			 * We have exceeded how many times we can retran the
716 			 * current TLP timer, switch to the RTO timer.
717 			 */
718 			goto activate_rxt;
719 		} else {
720 			BBR_STAT_INC(bbr_to_arm_tlp);
721 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
722 		}
723 	}
724 	return (to);
725 }
726 
727 static inline int32_t
728 bbr_minseg(struct tcp_bbr *bbr)
729 {
730 	return (bbr->r_ctl.rc_pace_min_segs - bbr->rc_last_options);
731 }
732 
733 static void
734 bbr_start_hpts_timer(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts, int32_t frm, int32_t slot, uint32_t tot_len)
735 {
736 	struct inpcb *inp;
737 	struct hpts_diag diag;
738 	uint32_t delayed_ack = 0;
739 	uint32_t left = 0;
740 	uint32_t hpts_timeout;
741 	uint8_t stopped;
742 	int32_t delay_calc = 0;
743 	uint32_t prev_delay = 0;
744 
745 	inp = tp->t_inpcb;
746 	if (inp->inp_in_hpts) {
747 		/* A previous call is already set up */
748 		return;
749 	}
750 	if ((tp->t_state == TCPS_CLOSED) ||
751 	    (tp->t_state == TCPS_LISTEN)) {
752 		return;
753 	}
754 	stopped = bbr->rc_tmr_stopped;
755 	if (stopped && TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
756 		left = bbr->r_ctl.rc_timer_exp - cts;
757 	}
758 	bbr->r_ctl.rc_hpts_flags = 0;
759 	bbr->r_ctl.rc_timer_exp = 0;
760 	prev_delay = bbr->r_ctl.rc_last_delay_val;
761 	if (bbr->r_ctl.rc_last_delay_val &&
762 	    (slot == 0)) {
763 		/*
764 		 * If a previous pacer delay was in place we
765 		 * are not coming from the output side (where
766 		 * we calculate a delay, more likely a timer).
767 		 */
768 		slot = bbr->r_ctl.rc_last_delay_val;
769 		if (TSTMP_GT(cts, bbr->rc_pacer_started)) {
770 			/* Compensate for time passed  */
771 			delay_calc = cts - bbr->rc_pacer_started;
772 			if (delay_calc <= slot)
773 				slot -= delay_calc;
774 		}
775 	}
776 	/* Do we have early to make up for by pushing out the pacing time? */
777 	if (bbr->r_agg_early_set) {
778 		bbr_log_pacing_delay_calc(bbr, 0, bbr->r_ctl.rc_agg_early, cts, slot, 0, bbr->r_agg_early_set, 2);
779 		slot += bbr->r_ctl.rc_agg_early;
780 		bbr->r_ctl.rc_agg_early = 0;
781 		bbr->r_agg_early_set = 0;
782 	}
783 	/* Are we running a total debt that needs to be compensated for? */
784 	if (bbr->r_ctl.rc_hptsi_agg_delay) {
785 		if (slot > bbr->r_ctl.rc_hptsi_agg_delay) {
786 			/* We nuke the delay */
787 			slot -= bbr->r_ctl.rc_hptsi_agg_delay;
788 			bbr->r_ctl.rc_hptsi_agg_delay = 0;
789 		} else {
790 			/* We nuke some of the delay, put in a minimal 100usecs  */
791 			bbr->r_ctl.rc_hptsi_agg_delay -= slot;
792 			bbr->r_ctl.rc_last_delay_val = slot = 100;
793 		}
794 	}
795 	bbr->r_ctl.rc_last_delay_val = slot;
796 	hpts_timeout = bbr_timer_start(tp, bbr, cts);
797 	if (tp->t_flags & TF_DELACK) {
798 		if (bbr->rc_in_persist == 0) {
799 			delayed_ack = bbr_delack_time;
800 		} else {
801 			/*
802 			 * We are in persists and have
803 			 * gotten a new data element.
804 			 */
805 			if (hpts_timeout > bbr_delack_time) {
806 				/*
807 				 * Lets make the persists timer (which acks)
808 				 * be the smaller of hpts_timeout and bbr_delack_time.
809 				 */
810 				hpts_timeout = bbr_delack_time;
811 			}
812 		}
813 	}
814 	if (delayed_ack &&
815 	    ((hpts_timeout == 0) ||
816 	     (delayed_ack < hpts_timeout))) {
817 		/* We need a Delayed ack timer */
818 		bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
819 		hpts_timeout = delayed_ack;
820 	}
821 	if (slot) {
822 		/* Mark that we have a pacing timer up */
823 		BBR_STAT_INC(bbr_paced_segments);
824 		bbr->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
825 	}
826 	/*
827 	 * If no timers are going to run and we will fall off thfe hptsi
828 	 * wheel, we resort to a keep-alive timer if its configured.
829 	 */
830 	if ((hpts_timeout == 0) &&
831 	    (slot == 0)) {
832 		if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
833 		    (tp->t_state <= TCPS_CLOSING)) {
834 			/*
835 			 * Ok we have no timer (persists, rack, tlp, rxt  or
836 			 * del-ack), we don't have segments being paced. So
837 			 * all that is left is the keepalive timer.
838 			 */
839 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
840 				hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
841 			} else {
842 				hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
843 			}
844 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
845 		}
846 	}
847 	if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
848 	    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
849 		/*
850 		 * RACK, TLP, persists and RXT timers all are restartable
851 		 * based on actions input .. i.e we received a packet (ack
852 		 * or sack) and that changes things (rw, or snd_una etc).
853 		 * Thus we can restart them with a new value. For
854 		 * keep-alive, delayed_ack we keep track of what was left
855 		 * and restart the timer with a smaller value.
856 		 */
857 		if (left < hpts_timeout)
858 			hpts_timeout = left;
859 	}
860 	if (bbr->r_ctl.rc_incr_tmrs && slot &&
861 	    (bbr->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
862 		/*
863 		 * If configured to do so, and the timer is either
864 		 * the TLP or RXT timer, we need to increase the timeout
865 		 * by the pacing time. Consider the bottleneck at my
866 		 * machine as an example, we are sending something
867 		 * to start a TLP on. The last packet won't be emitted
868 		 * fully until the pacing time (the bottleneck will hold
869 		 * the data in place). Once the packet is emitted that
870 		 * is when we want to start waiting for the TLP. This
871 		 * is most evident with hardware pacing (where the nic
872 		 * is holding the packet(s) before emitting). But it
873 		 * can also show up in the network so we do it for all
874 		 * cases. Technically we would take off one packet from
875 		 * this extra delay but this is easier and being more
876 		 * conservative is probably better.
877 		 */
878 		hpts_timeout += slot;
879 	}
880 	if (hpts_timeout) {
881 		/*
882 		 * Hack alert for now we can't time-out over 2147 seconds (a
883 		 * bit more than 35min)
884 		 */
885 		if (hpts_timeout > 0x7ffffffe)
886 			hpts_timeout = 0x7ffffffe;
887 		bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
888 	} else
889 		bbr->r_ctl.rc_timer_exp = 0;
890 	if ((slot) &&
891 	    (bbr->rc_use_google ||
892 	     bbr->output_error_seen ||
893 	     (slot <= hpts_timeout))  ) {
894 		/*
895 		 * Tell LRO that it can queue packets while
896 		 * we pace.
897 		 */
898 		bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
899 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
900 		    (bbr->rc_cwnd_limited == 0)) {
901 			/*
902 			 * If we are not cwnd limited and we
903 			 * are running a rack timer we put on
904 			 * the do not disturbe even for sack.
905 			 */
906 			inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
907 		} else
908 			inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
909 		bbr->rc_pacer_started = cts;
910 
911 		(void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(slot),
912 					   __LINE__, &diag);
913 		bbr->rc_timer_first = 0;
914 		bbr->bbr_timer_src = frm;
915 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 1);
916 		bbr_log_hpts_diag(bbr, cts, &diag);
917 	} else if (hpts_timeout) {
918 		(void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(hpts_timeout),
919 					   __LINE__, &diag);
920 		/*
921 		 * We add the flag here as well if the slot is set,
922 		 * since hpts will call in to clear the queue first before
923 		 * calling the output routine (which does our timers).
924 		 * We don't want to set the flag if its just a timer
925 		 * else the arrival of data might (that causes us
926 		 * to send more) might get delayed. Imagine being
927 		 * on a keep-alive timer and a request comes in for
928 		 * more data.
929 		 */
930 		if (slot)
931 			bbr->rc_pacer_started = cts;
932 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
933 		    (bbr->rc_cwnd_limited == 0)) {
934 			/*
935 			 * For a rack timer, don't wake us even
936 			 * if a sack arrives as long as we are
937 			 * not cwnd limited.
938 			 */
939 			bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
940 			inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
941 		} else {
942 			/* All other timers wake us up */
943 			bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
944 			inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
945 		}
946 		bbr->bbr_timer_src = frm;
947 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 0);
948 		bbr_log_hpts_diag(bbr, cts, &diag);
949 		bbr->rc_timer_first = 1;
950 	}
951 	bbr->rc_tmr_stopped = 0;
952 	bbr_log_type_bbrsnd(bbr, tot_len, slot, delay_calc, cts, frm, prev_delay);
953 }
954 
955 static void
956 bbr_timer_audit(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, struct sockbuf *sb)
957 {
958 	/*
959 	 * We received an ack, and then did not call send or were bounced
960 	 * out due to the hpts was running. Now a timer is up as well, is it
961 	 * the right timer?
962 	 */
963 	struct inpcb *inp;
964 	struct bbr_sendmap *rsm;
965 	uint32_t hpts_timeout;
966 	int tmr_up;
967 
968 	tmr_up = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
969 	if (bbr->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
970 		return;
971 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
972 	if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
973 	    (tmr_up == PACE_TMR_RXT)) {
974 		/* Should be an RXT */
975 		return;
976 	}
977 	inp = bbr->rc_inp;
978 	if (rsm == NULL) {
979 		/* Nothing outstanding? */
980 		if (tp->t_flags & TF_DELACK) {
981 			if (tmr_up == PACE_TMR_DELACK)
982 				/*
983 				 * We are supposed to have delayed ack up
984 				 * and we do
985 				 */
986 				return;
987 		} else if (sbavail(&inp->inp_socket->so_snd) &&
988 		    (tmr_up == PACE_TMR_RXT)) {
989 			/*
990 			 * if we hit enobufs then we would expect the
991 			 * possiblity of nothing outstanding and the RXT up
992 			 * (and the hptsi timer).
993 			 */
994 			return;
995 		} else if (((V_tcp_always_keepalive ||
996 			    inp->inp_socket->so_options & SO_KEEPALIVE) &&
997 			    (tp->t_state <= TCPS_CLOSING)) &&
998 			    (tmr_up == PACE_TMR_KEEP) &&
999 		    (tp->snd_max == tp->snd_una)) {
1000 			/* We should have keep alive up and we do */
1001 			return;
1002 		}
1003 	}
1004 	if (rsm && (rsm->r_flags & BBR_SACK_PASSED)) {
1005 		if ((tp->t_flags & TF_SENTFIN) &&
1006 		    ((tp->snd_max - tp->snd_una) == 1) &&
1007 		    (rsm->r_flags & BBR_HAS_FIN)) {
1008 			/* needs to be a RXT */
1009 			if (tmr_up == PACE_TMR_RXT)
1010 				return;
1011 			else
1012 				goto wrong_timer;
1013 		} else if (tmr_up == PACE_TMR_RACK)
1014 			return;
1015 		else
1016 			goto wrong_timer;
1017 	} else if (rsm && (tmr_up == PACE_TMR_RACK)) {
1018 		/* Rack timer has priority if we have data out */
1019 		return;
1020 	} else if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1021 		    ((tmr_up == PACE_TMR_TLP) ||
1022 	    (tmr_up == PACE_TMR_RXT))) {
1023 		/*
1024 		 * Either a TLP or RXT is fine if no sack-passed is in place
1025 		 * and data is outstanding.
1026 		 */
1027 		return;
1028 	} else if (tmr_up == PACE_TMR_DELACK) {
1029 		/*
1030 		 * If the delayed ack was going to go off before the
1031 		 * rtx/tlp/rack timer were going to expire, then that would
1032 		 * be the timer in control. Note we don't check the time
1033 		 * here trusting the code is correct.
1034 		 */
1035 		return;
1036 	}
1037 	if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1038 	    ((tmr_up == PACE_TMR_RXT) ||
1039 	     (tmr_up == PACE_TMR_TLP) ||
1040 	     (tmr_up == PACE_TMR_RACK))) {
1041 		/*
1042 		 * We have outstanding data and
1043 		 * we *do* have a RACK, TLP or RXT
1044 		 * timer running. We won't restart
1045 		 * anything here since thats probably ok we
1046 		 * will get called with some timer here shortly.
1047 		 */
1048 		return;
1049 	}
1050 	/*
1051 	 * Ok the timer originally started is not what we want now. We will
1052 	 * force the hpts to be stopped if any, and restart with the slot
1053 	 * set to what was in the saved slot.
1054 	 */
1055 wrong_timer:
1056 	if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) {
1057 		if (inp->inp_in_hpts)
1058 			tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
1059 		bbr_timer_cancel(bbr, __LINE__, cts);
1060 		bbr_start_hpts_timer(bbr, tp, cts, 1, bbr->r_ctl.rc_last_delay_val,
1061 		    0);
1062 	} else {
1063 		/*
1064 		 * Output is hptsi so we just need to switch the type of
1065 		 * timer. We don't bother with keep-alive, since when we
1066 		 * jump through the output, it will start the keep-alive if
1067 		 * nothing is sent.
1068 		 *
1069 		 * We only need a delayed-ack added and or the hpts_timeout.
1070 		 */
1071 		hpts_timeout = bbr_timer_start(tp, bbr, cts);
1072 		if (tp->t_flags & TF_DELACK) {
1073 			if (hpts_timeout == 0) {
1074 				hpts_timeout = bbr_delack_time;
1075 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1076 			}
1077 			else if (hpts_timeout > bbr_delack_time) {
1078 				hpts_timeout = bbr_delack_time;
1079 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1080 			}
1081 		}
1082 		if (hpts_timeout) {
1083 			if (hpts_timeout > 0x7ffffffe)
1084 				hpts_timeout = 0x7ffffffe;
1085 			bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
1086 		}
1087 	}
1088 }
1089 
1090 int32_t bbr_clear_lost = 0;
1091 
1092 /*
1093  * Considers the two time values now (cts) and earlier.
1094  * If cts is smaller than earlier, we could have
1095  * had a sequence wrap (our counter wraps every
1096  * 70 min or so) or it could be just clock skew
1097  * getting us two differnt time values. Clock skew
1098  * will show up within 10ms or so. So in such
1099  * a case (where cts is behind earlier time by
1100  * less than 10ms) we return 0. Otherwise we
1101  * return the true difference between them.
1102  */
1103 static inline uint32_t
1104 bbr_calc_time(uint32_t cts, uint32_t earlier_time) {
1105 	/*
1106 	 * Given two timestamps, the current time stamp cts, and some other
1107 	 * time-stamp taken in theory earlier return the difference. The
1108 	 * trick is here sometimes locking will get the other timestamp
1109 	 * after the cts. If this occurs we need to return 0.
1110 	 */
1111 	if (TSTMP_GEQ(cts, earlier_time))
1112 		return (cts - earlier_time);
1113 	/*
1114 	 * cts is behind earlier_time if its less than 10ms consider it 0.
1115 	 * If its more than 10ms difference then we had a time wrap. Else
1116 	 * its just the normal locking foo. I wonder if we should not go to
1117 	 * 64bit TS and get rid of this issue.
1118 	 */
1119 	if (TSTMP_GEQ((cts + 10000), earlier_time))
1120 		return (0);
1121 	/*
1122 	 * Ok the time must have wrapped. So we need to answer a large
1123 	 * amount of time, which the normal subtraction should do.
1124 	 */
1125 	return (cts - earlier_time);
1126 }
1127 
1128 static int
1129 sysctl_bbr_clear_lost(SYSCTL_HANDLER_ARGS)
1130 {
1131 	uint32_t stat;
1132 	int32_t error;
1133 
1134 	error = SYSCTL_OUT(req, &bbr_clear_lost, sizeof(uint32_t));
1135 	if (error || req->newptr == NULL)
1136 		return error;
1137 
1138 	error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
1139 	if (error)
1140 		return (error);
1141 	if (stat == 1) {
1142 #ifdef BBR_INVARIANTS
1143 		printf("Clearing BBR lost counters\n");
1144 #endif
1145 		COUNTER_ARRAY_ZERO(bbr_state_lost, BBR_MAX_STAT);
1146 		COUNTER_ARRAY_ZERO(bbr_state_time, BBR_MAX_STAT);
1147 		COUNTER_ARRAY_ZERO(bbr_state_resend, BBR_MAX_STAT);
1148 	} else if (stat == 2) {
1149 #ifdef BBR_INVARIANTS
1150 		printf("Clearing BBR option counters\n");
1151 #endif
1152 		COUNTER_ARRAY_ZERO(bbr_opts_arry, BBR_OPTS_SIZE);
1153 	} else if (stat == 3) {
1154 #ifdef BBR_INVARIANTS
1155 		printf("Clearing BBR stats counters\n");
1156 #endif
1157 		COUNTER_ARRAY_ZERO(bbr_stat_arry, BBR_STAT_SIZE);
1158 	} else if (stat == 4) {
1159 #ifdef BBR_INVARIANTS
1160 		printf("Clearing BBR out-size counters\n");
1161 #endif
1162 		COUNTER_ARRAY_ZERO(bbr_out_size, TCP_MSS_ACCT_SIZE);
1163 	}
1164 	bbr_clear_lost = 0;
1165 	return (0);
1166 }
1167 
1168 static void
1169 bbr_init_sysctls(void)
1170 {
1171 	struct sysctl_oid *bbr_probertt;
1172 	struct sysctl_oid *bbr_hptsi;
1173 	struct sysctl_oid *bbr_measure;
1174 	struct sysctl_oid *bbr_cwnd;
1175 	struct sysctl_oid *bbr_timeout;
1176 	struct sysctl_oid *bbr_states;
1177 	struct sysctl_oid *bbr_startup;
1178 	struct sysctl_oid *bbr_policer;
1179 
1180 	/* Probe rtt controls */
1181 	bbr_probertt = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1182 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1183 	    OID_AUTO,
1184 	    "probertt",
1185 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1186 	    "");
1187 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1188 	    SYSCTL_CHILDREN(bbr_probertt),
1189 	    OID_AUTO, "gain", CTLFLAG_RW,
1190 	    &bbr_rttprobe_gain, 192,
1191 	    "What is the filter gain drop in probe_rtt (0=disable)?");
1192 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1193 	    SYSCTL_CHILDREN(bbr_probertt),
1194 	    OID_AUTO, "cwnd", CTLFLAG_RW,
1195 	    &bbr_rtt_probe_cwndtarg, 4,
1196 	    "How many mss's are outstanding during probe-rtt");
1197 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1198 	    SYSCTL_CHILDREN(bbr_probertt),
1199 	    OID_AUTO, "int", CTLFLAG_RW,
1200 	    &bbr_rtt_probe_limit, 4000000,
1201 	    "If RTT has not shrank in this many micro-seconds enter probe-rtt");
1202 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1203 	    SYSCTL_CHILDREN(bbr_probertt),
1204 	    OID_AUTO, "mintime", CTLFLAG_RW,
1205 	    &bbr_rtt_probe_time, 200000,
1206 	    "How many microseconds in probe-rtt");
1207 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1208 	    SYSCTL_CHILDREN(bbr_probertt),
1209 	    OID_AUTO, "filter_len_sec", CTLFLAG_RW,
1210 	    &bbr_filter_len_sec, 6,
1211 	    "How long in seconds does the rttProp filter run?");
1212 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1213 	    SYSCTL_CHILDREN(bbr_probertt),
1214 	    OID_AUTO, "drain_rtt", CTLFLAG_RW,
1215 	    &bbr_drain_rtt, BBR_SRTT,
1216 	    "What is the drain rtt to use in probeRTT (rtt_prop=0, rtt_rack=1, rtt_pkt=2, rtt_srtt=3?");
1217 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1218 	    SYSCTL_CHILDREN(bbr_probertt),
1219 	    OID_AUTO, "can_force", CTLFLAG_RW,
1220 	    &bbr_can_force_probertt, 0,
1221 	    "If we keep setting new low rtt's but delay going in probe-rtt can we force in??");
1222 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1223 	    SYSCTL_CHILDREN(bbr_probertt),
1224 	    OID_AUTO, "enter_sets_force", CTLFLAG_RW,
1225 	    &bbr_probertt_sets_rtt, 0,
1226 	    "In NF mode, do we imitate google_mode and set the rttProp on entry to probe-rtt?");
1227 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1228 	    SYSCTL_CHILDREN(bbr_probertt),
1229 	    OID_AUTO, "can_adjust", CTLFLAG_RW,
1230 	    &bbr_can_adjust_probertt, 1,
1231 	    "Can we dynamically adjust the probe-rtt limits and times?");
1232 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1233 	    SYSCTL_CHILDREN(bbr_probertt),
1234 	    OID_AUTO, "is_ratio", CTLFLAG_RW,
1235 	    &bbr_is_ratio, 0,
1236 	    "is the limit to filter a ratio?");
1237 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1238 	    SYSCTL_CHILDREN(bbr_probertt),
1239 	    OID_AUTO, "use_cwnd", CTLFLAG_RW,
1240 	    &bbr_prtt_slam_cwnd, 0,
1241 	    "Should we set/recover cwnd?");
1242 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1243 	    SYSCTL_CHILDREN(bbr_probertt),
1244 	    OID_AUTO, "can_use_ts", CTLFLAG_RW,
1245 	    &bbr_can_use_ts_for_rtt, 1,
1246 	    "Can we use the ms timestamp if available for retransmistted rtt calculations?");
1247 
1248 	/* Pacing controls */
1249 	bbr_hptsi = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1250 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1251 	    OID_AUTO,
1252 	    "pacing",
1253 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1254 	    "");
1255 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1256 	    SYSCTL_CHILDREN(bbr_hptsi),
1257 	    OID_AUTO, "hw_pacing", CTLFLAG_RW,
1258 	    &bbr_allow_hdwr_pacing, 1,
1259 	    "Do we allow hardware pacing?");
1260 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1261 	    SYSCTL_CHILDREN(bbr_hptsi),
1262 	    OID_AUTO, "hw_pacing_limit", CTLFLAG_RW,
1263 	    &bbr_hardware_pacing_limit, 4000,
1264 	    "Do we have a limited number of connections for pacing chelsio (0=no limit)?");
1265 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1266 	    SYSCTL_CHILDREN(bbr_hptsi),
1267 	    OID_AUTO, "hw_pacing_adj", CTLFLAG_RW,
1268 	    &bbr_hdwr_pace_adjust, 2,
1269 	    "Multiplier to calculated tso size?");
1270 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1271 	    SYSCTL_CHILDREN(bbr_hptsi),
1272 	    OID_AUTO, "hw_pacing_floor", CTLFLAG_RW,
1273 	    &bbr_hdwr_pace_floor, 1,
1274 	    "Do we invoke the hardware pacing floor?");
1275 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1276 	    SYSCTL_CHILDREN(bbr_hptsi),
1277 	    OID_AUTO, "hw_pacing_delay_cnt", CTLFLAG_RW,
1278 	    &bbr_hdwr_pacing_delay_cnt, 10,
1279 	    "How many packets must be sent after hdwr pacing is enabled");
1280 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1281 	    SYSCTL_CHILDREN(bbr_hptsi),
1282 	    OID_AUTO, "bw_cross", CTLFLAG_RW,
1283 	    &bbr_cross_over, 3000000,
1284 	    "What is the point where we cross over to linux like TSO size set");
1285 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1286 	    SYSCTL_CHILDREN(bbr_hptsi),
1287 	    OID_AUTO, "seg_deltarg", CTLFLAG_RW,
1288 	    &bbr_hptsi_segments_delay_tar, 7000,
1289 	    "What is the worse case delay target for hptsi < 48Mbp connections");
1290 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1291 	    SYSCTL_CHILDREN(bbr_hptsi),
1292 	    OID_AUTO, "enet_oh", CTLFLAG_RW,
1293 	    &bbr_include_enet_oh, 0,
1294 	    "Do we include the ethernet overhead in calculating pacing delay?");
1295 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1296 	    SYSCTL_CHILDREN(bbr_hptsi),
1297 	    OID_AUTO, "ip_oh", CTLFLAG_RW,
1298 	    &bbr_include_ip_oh, 1,
1299 	    "Do we include the IP overhead in calculating pacing delay?");
1300 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1301 	    SYSCTL_CHILDREN(bbr_hptsi),
1302 	    OID_AUTO, "tcp_oh", CTLFLAG_RW,
1303 	    &bbr_include_tcp_oh, 0,
1304 	    "Do we include the TCP overhead in calculating pacing delay?");
1305 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1306 	    SYSCTL_CHILDREN(bbr_hptsi),
1307 	    OID_AUTO, "google_discount", CTLFLAG_RW,
1308 	    &bbr_google_discount, 10,
1309 	    "What is the default google discount percentage wise for pacing (11 = 1.1%%)?");
1310 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1311 	    SYSCTL_CHILDREN(bbr_hptsi),
1312 	    OID_AUTO, "all_get_min", CTLFLAG_RW,
1313 	    &bbr_all_get_min, 0,
1314 	    "If you are less than a MSS do you just get the min?");
1315 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1316 	    SYSCTL_CHILDREN(bbr_hptsi),
1317 	    OID_AUTO, "tso_min", CTLFLAG_RW,
1318 	    &bbr_hptsi_bytes_min, 1460,
1319 	    "For 0 -> 24Mbps what is floor number of segments for TSO");
1320 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1321 	    SYSCTL_CHILDREN(bbr_hptsi),
1322 	    OID_AUTO, "seg_tso_max", CTLFLAG_RW,
1323 	    &bbr_hptsi_segments_max, 6,
1324 	    "For 0 -> 24Mbps what is top number of segments for TSO");
1325 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1326 	    SYSCTL_CHILDREN(bbr_hptsi),
1327 	    OID_AUTO, "seg_floor", CTLFLAG_RW,
1328 	    &bbr_hptsi_segments_floor, 1,
1329 	    "Minimum TSO size we will fall too in segments");
1330 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1331 	    SYSCTL_CHILDREN(bbr_hptsi),
1332 	    OID_AUTO, "utter_max", CTLFLAG_RW,
1333 	    &bbr_hptsi_utter_max, 0,
1334 	    "The absolute maximum that any pacing (outside of hardware) can be");
1335 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1336 	    SYSCTL_CHILDREN(bbr_hptsi),
1337 	    OID_AUTO, "seg_divisor", CTLFLAG_RW,
1338 	    &bbr_hptsi_per_second, 100,
1339 	    "What is the divisor in our hptsi TSO calculation 512Mbps < X > 24Mbps ");
1340 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1341 	    SYSCTL_CHILDREN(bbr_hptsi),
1342 	    OID_AUTO, "srtt_mul", CTLFLAG_RW,
1343 	    &bbr_hptsi_max_mul, 1,
1344 	    "The multiplier for pace len max");
1345 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1346 	    SYSCTL_CHILDREN(bbr_hptsi),
1347 	    OID_AUTO, "srtt_div", CTLFLAG_RW,
1348 	    &bbr_hptsi_max_div, 2,
1349 	    "The divisor for pace len max");
1350 	/* Measurement controls */
1351 	bbr_measure = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1352 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1353 	    OID_AUTO,
1354 	    "measure",
1355 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1356 	    "Measurement controls");
1357 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1358 	    SYSCTL_CHILDREN(bbr_measure),
1359 	    OID_AUTO, "min_i_bw", CTLFLAG_RW,
1360 	    &bbr_initial_bw_bps, 62500,
1361 	    "Minimum initial b/w in bytes per second");
1362 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1363 	    SYSCTL_CHILDREN(bbr_measure),
1364 	    OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1365 	    &bbr_sack_not_required, 0,
1366 	    "Do we allow bbr to run on connections not supporting SACK?");
1367 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1368 	    SYSCTL_CHILDREN(bbr_measure),
1369 	    OID_AUTO, "use_google", CTLFLAG_RW,
1370 	    &bbr_use_google_algo, 0,
1371 	    "Use has close to google V1.0 has possible?");
1372 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1373 	    SYSCTL_CHILDREN(bbr_measure),
1374 	    OID_AUTO, "ts_limiting", CTLFLAG_RW,
1375 	    &bbr_ts_limiting, 1,
1376 	    "Do we attempt to use the peers timestamp to limit b/w caculations?");
1377 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1378 	    SYSCTL_CHILDREN(bbr_measure),
1379 	    OID_AUTO, "ts_can_raise", CTLFLAG_RW,
1380 	    &bbr_ts_can_raise, 0,
1381 	    "Can we raise the b/w via timestamp b/w calculation?");
1382 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1383 	    SYSCTL_CHILDREN(bbr_measure),
1384 	    OID_AUTO, "ts_delta", CTLFLAG_RW,
1385 	    &bbr_min_usec_delta, 20000,
1386 	    "How long in usec between ts of our sends in ts validation code?");
1387 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1388 	    SYSCTL_CHILDREN(bbr_measure),
1389 	    OID_AUTO, "ts_peer_delta", CTLFLAG_RW,
1390 	    &bbr_min_peer_delta, 20,
1391 	    "What min numerical value should be between the peer deltas?");
1392 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1393 	    SYSCTL_CHILDREN(bbr_measure),
1394 	    OID_AUTO, "ts_delta_percent", CTLFLAG_RW,
1395 	    &bbr_delta_percent, 150,
1396 	    "What percentage (150 = 15.0) do we allow variance for?");
1397 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1398 	    SYSCTL_CHILDREN(bbr_measure),
1399 	    OID_AUTO, "min_measure_good_bw", CTLFLAG_RW,
1400 	    &bbr_min_measurements_req, 1,
1401 	    "What is the minimum measurment count we need before we switch to our b/w estimate");
1402 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1403 	    SYSCTL_CHILDREN(bbr_measure),
1404 	    OID_AUTO, "min_measure_before_pace", CTLFLAG_RW,
1405 	    &bbr_no_pacing_until, 4,
1406 	    "How many pkt-epoch's (0 is off) do we need before pacing is on?");
1407 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1408 	    SYSCTL_CHILDREN(bbr_measure),
1409 	    OID_AUTO, "quanta", CTLFLAG_RW,
1410 	    &bbr_quanta, 2,
1411 	    "Extra quanta to add when calculating the target (ID section 4.2.3.2).");
1412 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1413 	    SYSCTL_CHILDREN(bbr_measure),
1414 	    OID_AUTO, "noretran", CTLFLAG_RW,
1415 	    &bbr_no_retran, 0,
1416 	    "Should google mode not use retransmission measurements for the b/w estimation?");
1417 	/* State controls */
1418 	bbr_states = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1419 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1420 	    OID_AUTO,
1421 	    "states",
1422 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1423 	    "State controls");
1424 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1425 	    SYSCTL_CHILDREN(bbr_states),
1426 	    OID_AUTO, "idle_restart", CTLFLAG_RW,
1427 	    &bbr_uses_idle_restart, 0,
1428 	    "Do we use a new special idle_restart state to ramp back up quickly?");
1429 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1430 	    SYSCTL_CHILDREN(bbr_states),
1431 	    OID_AUTO, "idle_restart_threshold", CTLFLAG_RW,
1432 	    &bbr_idle_restart_threshold, 100000,
1433 	    "How long must we be idle before we restart??");
1434 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1435 	    SYSCTL_CHILDREN(bbr_states),
1436 	    OID_AUTO, "use_pkt_epoch", CTLFLAG_RW,
1437 	    &bbr_state_is_pkt_epoch, 0,
1438 	    "Do we use a pkt-epoch for substate if 0 rttProp?");
1439 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1440 	    SYSCTL_CHILDREN(bbr_states),
1441 	    OID_AUTO, "startup_rtt_gain", CTLFLAG_RW,
1442 	    &bbr_rtt_gain_thresh, 0,
1443 	    "What increase in RTT triggers us to stop ignoring no-loss and possibly exit startup?");
1444 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1445 	    SYSCTL_CHILDREN(bbr_states),
1446 	    OID_AUTO, "drain_floor", CTLFLAG_RW,
1447 	    &bbr_drain_floor, 88,
1448 	    "What is the lowest we can drain (pg) too?");
1449 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1450 	    SYSCTL_CHILDREN(bbr_states),
1451 	    OID_AUTO, "drain_2_target", CTLFLAG_RW,
1452 	    &bbr_state_drain_2_tar, 1,
1453 	    "Do we drain to target in drain substate?");
1454 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1455 	    SYSCTL_CHILDREN(bbr_states),
1456 	    OID_AUTO, "gain_2_target", CTLFLAG_RW,
1457 	    &bbr_gain_to_target, 1,
1458 	    "Does probe bw gain to target??");
1459 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1460 	    SYSCTL_CHILDREN(bbr_states),
1461 	    OID_AUTO, "gain_extra_time", CTLFLAG_RW,
1462 	    &bbr_gain_gets_extra_too, 1,
1463 	    "Does probe bw gain get the extra time too?");
1464 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1465 	    SYSCTL_CHILDREN(bbr_states),
1466 	    OID_AUTO, "ld_div", CTLFLAG_RW,
1467 	    &bbr_drain_drop_div, 5,
1468 	    "Long drain drop divider?");
1469 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1470 	    SYSCTL_CHILDREN(bbr_states),
1471 	    OID_AUTO, "ld_mul", CTLFLAG_RW,
1472 	    &bbr_drain_drop_mul, 4,
1473 	    "Long drain drop multiplier?");
1474 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1475 	    SYSCTL_CHILDREN(bbr_states),
1476 	    OID_AUTO, "rand_ot_disc", CTLFLAG_RW,
1477 	    &bbr_rand_ot, 50,
1478 	    "Random discount of the ot?");
1479 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1480 	    SYSCTL_CHILDREN(bbr_states),
1481 	    OID_AUTO, "dr_filter_life", CTLFLAG_RW,
1482 	    &bbr_num_pktepo_for_del_limit, BBR_NUM_RTTS_FOR_DEL_LIMIT,
1483 	    "How many packet-epochs does the b/w delivery rate last?");
1484 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1485 	    SYSCTL_CHILDREN(bbr_states),
1486 	    OID_AUTO, "subdrain_applimited", CTLFLAG_RW,
1487 	    &bbr_sub_drain_app_limit, 0,
1488 	    "Does our sub-state drain invoke app limited if its long?");
1489 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1490 	    SYSCTL_CHILDREN(bbr_states),
1491 	    OID_AUTO, "use_cwnd_subdrain", CTLFLAG_RW,
1492 	    &bbr_sub_drain_slam_cwnd, 0,
1493 	    "Should we set/recover cwnd for sub-state drain?");
1494 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1495 	    SYSCTL_CHILDREN(bbr_states),
1496 	    OID_AUTO, "use_cwnd_maindrain", CTLFLAG_RW,
1497 	    &bbr_slam_cwnd_in_main_drain, 0,
1498 	    "Should we set/recover cwnd for main-state drain?");
1499 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1500 	    SYSCTL_CHILDREN(bbr_states),
1501 	    OID_AUTO, "google_gets_earlyout", CTLFLAG_RW,
1502 	    &google_allow_early_out, 1,
1503 	    "Should we allow google probe-bw/drain to exit early at flight target?");
1504 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1505 	    SYSCTL_CHILDREN(bbr_states),
1506 	    OID_AUTO, "google_exit_loss", CTLFLAG_RW,
1507 	    &google_consider_lost, 1,
1508 	    "Should we have losses exit gain of probebw in google mode??");
1509 	/* Startup controls */
1510 	bbr_startup = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1511 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1512 	    OID_AUTO,
1513 	    "startup",
1514 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1515 	    "Startup controls");
1516 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1517 	    SYSCTL_CHILDREN(bbr_startup),
1518 	    OID_AUTO, "cheat_iwnd", CTLFLAG_RW,
1519 	    &bbr_sends_full_iwnd, 1,
1520 	    "Do we not pace but burst out initial windows has our TSO size?");
1521 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1522 	    SYSCTL_CHILDREN(bbr_startup),
1523 	    OID_AUTO, "loss_threshold", CTLFLAG_RW,
1524 	    &bbr_startup_loss_thresh, 2000,
1525 	    "In startup what is the loss threshold in a pe that will exit us from startup?");
1526 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1527 	    SYSCTL_CHILDREN(bbr_startup),
1528 	    OID_AUTO, "use_lowerpg", CTLFLAG_RW,
1529 	    &bbr_use_lower_gain_in_startup, 1,
1530 	    "Should we use a lower hptsi gain if we see loss in startup?");
1531 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1532 	    SYSCTL_CHILDREN(bbr_startup),
1533 	    OID_AUTO, "gain", CTLFLAG_RW,
1534 	    &bbr_start_exit, 25,
1535 	    "What gain percent do we need to see to stay in startup??");
1536 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1537 	    SYSCTL_CHILDREN(bbr_startup),
1538 	    OID_AUTO, "low_gain", CTLFLAG_RW,
1539 	    &bbr_low_start_exit, 15,
1540 	    "What gain percent do we need to see to stay in the lower gain startup??");
1541 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1542 	    SYSCTL_CHILDREN(bbr_startup),
1543 	    OID_AUTO, "loss_exit", CTLFLAG_RW,
1544 	    &bbr_exit_startup_at_loss, 1,
1545 	    "Should we exit startup at loss in an epoch if we are not gaining?");
1546 	/* CWND controls */
1547 	bbr_cwnd = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1548 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1549 	    OID_AUTO,
1550 	    "cwnd",
1551 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1552 	    "Cwnd controls");
1553 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1554 	    SYSCTL_CHILDREN(bbr_cwnd),
1555 	    OID_AUTO, "tar_rtt", CTLFLAG_RW,
1556 	    &bbr_cwndtarget_rtt_touse, 0,
1557 	    "Target cwnd rtt measurment to use (0=rtt_prop, 1=rtt_rack, 2=pkt_rtt, 3=srtt)?");
1558 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1559 	    SYSCTL_CHILDREN(bbr_cwnd),
1560 	    OID_AUTO, "may_shrink", CTLFLAG_RW,
1561 	    &bbr_cwnd_may_shrink, 0,
1562 	    "Can the cwnd shrink if it would grow to more than the target?");
1563 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1564 	    SYSCTL_CHILDREN(bbr_cwnd),
1565 	    OID_AUTO, "max_target_limit", CTLFLAG_RW,
1566 	    &bbr_target_cwnd_mult_limit, 8,
1567 	    "Do we limit the cwnd to some multiple of the cwnd target if cwnd can't shrink 0=no?");
1568 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1569 	    SYSCTL_CHILDREN(bbr_cwnd),
1570 	    OID_AUTO, "highspeed_min", CTLFLAG_RW,
1571 	    &bbr_cwnd_min_val_hs, BBR_HIGHSPEED_NUM_MSS,
1572 	    "What is the high-speed min cwnd (rttProp under 1ms)");
1573 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1574 	    SYSCTL_CHILDREN(bbr_cwnd),
1575 	    OID_AUTO, "lowspeed_min", CTLFLAG_RW,
1576 	    &bbr_cwnd_min_val, BBR_PROBERTT_NUM_MSS,
1577 	    "What is the min cwnd (rttProp > 1ms)");
1578 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1579 	    SYSCTL_CHILDREN(bbr_cwnd),
1580 	    OID_AUTO, "initwin", CTLFLAG_RW,
1581 	    &bbr_def_init_win, 10,
1582 	    "What is the BBR initial window, if 0 use tcp version");
1583 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1584 	    SYSCTL_CHILDREN(bbr_cwnd),
1585 	    OID_AUTO, "do_loss_red", CTLFLAG_RW,
1586 	    &bbr_do_red, 600,
1587 	    "Do we reduce the b/w at exit from recovery based on ratio of prop/srtt (800=80.0, 0=off)?");
1588 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1589 	    SYSCTL_CHILDREN(bbr_cwnd),
1590 	    OID_AUTO, "red_scale", CTLFLAG_RW,
1591 	    &bbr_red_scale, 20000,
1592 	    "What RTT do we scale with?");
1593 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1594 	    SYSCTL_CHILDREN(bbr_cwnd),
1595 	    OID_AUTO, "red_growslow", CTLFLAG_RW,
1596 	    &bbr_red_growth_restrict, 1,
1597 	    "Do we restrict cwnd growth for whats in flight?");
1598 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1599 	    SYSCTL_CHILDREN(bbr_cwnd),
1600 	    OID_AUTO, "red_div", CTLFLAG_RW,
1601 	    &bbr_red_div, 2,
1602 	    "If we reduce whats the divisor?");
1603 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1604 	    SYSCTL_CHILDREN(bbr_cwnd),
1605 	    OID_AUTO, "red_mul", CTLFLAG_RW,
1606 	    &bbr_red_mul, 1,
1607 	    "If we reduce whats the mulitiplier?");
1608 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1609 	    SYSCTL_CHILDREN(bbr_cwnd),
1610 	    OID_AUTO, "target_is_unit", CTLFLAG_RW,
1611 	    &bbr_target_is_bbunit, 0,
1612 	    "Is the state target the pacing_gain or BBR_UNIT?");
1613 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1614 	    SYSCTL_CHILDREN(bbr_cwnd),
1615 	    OID_AUTO, "drop_limit", CTLFLAG_RW,
1616 	    &bbr_drop_limit, 0,
1617 	    "Number of segments limit for drop (0=use min_cwnd w/flight)?");
1618 
1619         /* Timeout controls */
1620 	bbr_timeout = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1621 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1622 	    OID_AUTO,
1623 	    "timeout",
1624 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1625 	    "Time out controls");
1626 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1627 	    SYSCTL_CHILDREN(bbr_timeout),
1628 	    OID_AUTO, "delack", CTLFLAG_RW,
1629 	    &bbr_delack_time, 100000,
1630 	    "BBR's delayed ack time");
1631 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1632 	    SYSCTL_CHILDREN(bbr_timeout),
1633 	    OID_AUTO, "tlp_uses", CTLFLAG_RW,
1634 	    &bbr_tlp_type_to_use, 3,
1635 	    "RTT that TLP uses in its calculations, 0=rttProp, 1=Rack_rtt, 2=pkt_rtt and 3=srtt");
1636 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1637 	    SYSCTL_CHILDREN(bbr_timeout),
1638 	    OID_AUTO, "persmin", CTLFLAG_RW,
1639 	    &bbr_persist_min, 250000,
1640 	    "What is the minimum time in microseconds between persists");
1641 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1642 	    SYSCTL_CHILDREN(bbr_timeout),
1643 	    OID_AUTO, "persmax", CTLFLAG_RW,
1644 	    &bbr_persist_max, 1000000,
1645 	    "What is the largest delay in microseconds between persists");
1646 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1647 	    SYSCTL_CHILDREN(bbr_timeout),
1648 	    OID_AUTO, "tlp_minto", CTLFLAG_RW,
1649 	    &bbr_tlp_min, 10000,
1650 	    "TLP Min timeout in usecs");
1651 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1652 	    SYSCTL_CHILDREN(bbr_timeout),
1653 	    OID_AUTO, "tlp_dack_time", CTLFLAG_RW,
1654 	    &bbr_delayed_ack_time, 200000,
1655 	    "TLP delayed ack compensation value");
1656 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1657 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1658 	    OID_AUTO, "minrto", CTLFLAG_RW,
1659 	    &bbr_rto_min_ms, 30,
1660 	    "Minimum RTO in ms");
1661 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1662 	    SYSCTL_CHILDREN(bbr_timeout),
1663 	    OID_AUTO, "maxrto", CTLFLAG_RW,
1664 	    &bbr_rto_max_sec, 4,
1665 	    "Maxiumum RTO in seconds -- should be at least as large as min_rto");
1666 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1667 	    SYSCTL_CHILDREN(bbr_timeout),
1668 	    OID_AUTO, "tlp_retry", CTLFLAG_RW,
1669 	    &bbr_tlp_max_resend, 2,
1670 	    "How many times does TLP retry a single segment or multiple with no ACK");
1671 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1672 	    SYSCTL_CHILDREN(bbr_timeout),
1673 	    OID_AUTO, "minto", CTLFLAG_RW,
1674 	    &bbr_min_to, 1000,
1675 	    "Minimum rack timeout in useconds");
1676 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1677 	    SYSCTL_CHILDREN(bbr_timeout),
1678 	    OID_AUTO, "pktdelay", CTLFLAG_RW,
1679 	    &bbr_pkt_delay, 1000,
1680 	    "Extra RACK time (in useconds) besides reordering thresh");
1681 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1682 	    SYSCTL_CHILDREN(bbr_timeout),
1683 	    OID_AUTO, "incr_tmrs", CTLFLAG_RW,
1684 	    &bbr_incr_timers, 1,
1685 	    "Increase the RXT/TLP timer by the pacing time used?");
1686 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1687 	    SYSCTL_CHILDREN(bbr_timeout),
1688 	    OID_AUTO, "rxtmark_sackpassed", CTLFLAG_RW,
1689 	    &bbr_marks_rxt_sack_passed, 0,
1690 	    "Mark sack passed on all those not ack'd when a RXT hits?");
1691 	/* Policer controls */
1692 	bbr_policer = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1693 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1694 	    OID_AUTO,
1695 	    "policer",
1696 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1697 	    "Policer controls");
1698 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1699 	    SYSCTL_CHILDREN(bbr_policer),
1700 	    OID_AUTO, "detect_enable", CTLFLAG_RW,
1701 	    &bbr_policer_detection_enabled, 1,
1702 	    "Is policer detection enabled??");
1703 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1704 	    SYSCTL_CHILDREN(bbr_policer),
1705 	    OID_AUTO, "min_pes", CTLFLAG_RW,
1706 	    &bbr_lt_intvl_min_rtts, 4,
1707 	    "Minimum number of PE's?");
1708 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1709 	    SYSCTL_CHILDREN(bbr_policer),
1710 	    OID_AUTO, "bwdiff", CTLFLAG_RW,
1711 	    &bbr_lt_bw_diff, (4000/8),
1712 	    "Minimal bw diff?");
1713 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1714 	    SYSCTL_CHILDREN(bbr_policer),
1715 	    OID_AUTO, "bwratio", CTLFLAG_RW,
1716 	    &bbr_lt_bw_ratio, 8,
1717 	    "Minimal bw diff?");
1718 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1719 	    SYSCTL_CHILDREN(bbr_policer),
1720 	    OID_AUTO, "from_rack_rxt", CTLFLAG_RW,
1721 	    &bbr_policer_call_from_rack_to, 0,
1722 	    "Do we call the policer detection code from a rack-timeout?");
1723 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1724 	    SYSCTL_CHILDREN(bbr_policer),
1725 	    OID_AUTO, "false_postive", CTLFLAG_RW,
1726 	    &bbr_lt_intvl_fp, 0,
1727 	    "What packet epoch do we do false-postive detection at (0=no)?");
1728 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1729 	    SYSCTL_CHILDREN(bbr_policer),
1730 	    OID_AUTO, "loss_thresh", CTLFLAG_RW,
1731 	    &bbr_lt_loss_thresh, 196,
1732 	    "Loss threshold 196 = 19.6%?");
1733 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1734 	    SYSCTL_CHILDREN(bbr_policer),
1735 	    OID_AUTO, "false_postive_thresh", CTLFLAG_RW,
1736 	    &bbr_lt_fd_thresh, 100,
1737 	    "What percentage is the false detection threshold (150=15.0)?");
1738 	/* All the rest */
1739 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1740 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1741 	    OID_AUTO, "cheat_rxt", CTLFLAG_RW,
1742 	    &bbr_use_rack_resend_cheat, 0,
1743 	    "Do we burst 1ms between sends on retransmissions (like rack)?");
1744 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1745 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1746 	    OID_AUTO, "error_paceout", CTLFLAG_RW,
1747 	    &bbr_error_base_paceout, 10000,
1748 	    "When we hit an error what is the min to pace out in usec's?");
1749 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1750 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1751 	    OID_AUTO, "kill_paceout", CTLFLAG_RW,
1752 	    &bbr_max_net_error_cnt, 10,
1753 	    "When we hit this many errors in a row, kill the session?");
1754 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1755 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1756 	    OID_AUTO, "data_after_close", CTLFLAG_RW,
1757 	    &bbr_ignore_data_after_close, 1,
1758 	    "Do we hold off sending a RST until all pending data is ack'd");
1759 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1760 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1761 	    OID_AUTO, "resend_use_tso", CTLFLAG_RW,
1762 	    &bbr_resends_use_tso, 0,
1763 	    "Can resends use TSO?");
1764 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1765 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1766 	    OID_AUTO, "sblklimit", CTLFLAG_RW,
1767 	    &bbr_sack_block_limit, 128,
1768 	    "When do we start ignoring small sack blocks");
1769 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1770 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1771 	    OID_AUTO, "bb_verbose", CTLFLAG_RW,
1772 	    &bbr_verbose_logging, 0,
1773 	    "Should BBR black box logging be verbose");
1774 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1775 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1776 	    OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1777 	    &bbr_reorder_thresh, 2,
1778 	    "What factor for rack will be added when seeing reordering (shift right)");
1779 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1780 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1781 	    OID_AUTO, "reorder_fade", CTLFLAG_RW,
1782 	    &bbr_reorder_fade, 0,
1783 	    "Does reorder detection fade, if so how many ms (0 means never)");
1784 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1785 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1786 	    OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1787 	    &bbr_tlp_thresh, 1,
1788 	    "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1789 	/* Stats and counters */
1790 	/* The pacing counters for hdwr/software can't be in the array */
1791 	bbr_nohdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1792 	bbr_hdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1793 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1794 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1795 	    OID_AUTO, "enob_hdwr_pacing", CTLFLAG_RD,
1796 	    &bbr_hdwr_pacing_enobuf,
1797 	    "Total number of enobufs for hardware paced flows");
1798 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1799 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1800 	    OID_AUTO, "enob_no_hdwr_pacing", CTLFLAG_RD,
1801 	    &bbr_nohdwr_pacing_enobuf,
1802 	    "Total number of enobufs for non-hardware paced flows");
1803 
1804 	bbr_flows_whdwr_pacing = counter_u64_alloc(M_WAITOK);
1805 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1806 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1807 	    OID_AUTO, "hdwr_pacing", CTLFLAG_RD,
1808 	    &bbr_flows_whdwr_pacing,
1809 	    "Total number of hardware paced flows");
1810 	bbr_flows_nohdwr_pacing = counter_u64_alloc(M_WAITOK);
1811 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1812 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1813 	    OID_AUTO, "software_pacing", CTLFLAG_RD,
1814 	    &bbr_flows_nohdwr_pacing,
1815 	    "Total number of software paced flows");
1816 	COUNTER_ARRAY_ALLOC(bbr_stat_arry, BBR_STAT_SIZE, M_WAITOK);
1817 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1818 	    OID_AUTO, "stats", CTLFLAG_RD,
1819 	    bbr_stat_arry, BBR_STAT_SIZE, "BBR Stats");
1820 	COUNTER_ARRAY_ALLOC(bbr_opts_arry, BBR_OPTS_SIZE, M_WAITOK);
1821 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1822 	    OID_AUTO, "opts", CTLFLAG_RD,
1823 	    bbr_opts_arry, BBR_OPTS_SIZE, "BBR Option Stats");
1824 	COUNTER_ARRAY_ALLOC(bbr_state_lost, BBR_MAX_STAT, M_WAITOK);
1825 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1826 	    OID_AUTO, "lost", CTLFLAG_RD,
1827 	    bbr_state_lost, BBR_MAX_STAT, "Stats of when losses occur");
1828 	COUNTER_ARRAY_ALLOC(bbr_state_resend, BBR_MAX_STAT, M_WAITOK);
1829 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1830 	    OID_AUTO, "stateresend", CTLFLAG_RD,
1831 	    bbr_state_resend, BBR_MAX_STAT, "Stats of what states resend");
1832 	COUNTER_ARRAY_ALLOC(bbr_state_time, BBR_MAX_STAT, M_WAITOK);
1833 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1834 	    OID_AUTO, "statetime", CTLFLAG_RD,
1835 	    bbr_state_time, BBR_MAX_STAT, "Stats of time spent in the states");
1836 	COUNTER_ARRAY_ALLOC(bbr_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1837 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1838 	    OID_AUTO, "outsize", CTLFLAG_RD,
1839 	    bbr_out_size, TCP_MSS_ACCT_SIZE, "Size of output calls");
1840 	SYSCTL_ADD_PROC(&bbr_sysctl_ctx,
1841 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1842 	    OID_AUTO, "clrlost", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1843 	    &bbr_clear_lost, 0, sysctl_bbr_clear_lost, "IU", "Clear lost counters");
1844 }
1845 
1846 static void
1847 bbr_counter_destroy(void)
1848 {
1849 	COUNTER_ARRAY_FREE(bbr_stat_arry, BBR_STAT_SIZE);
1850 	COUNTER_ARRAY_FREE(bbr_opts_arry, BBR_OPTS_SIZE);
1851 	COUNTER_ARRAY_FREE(bbr_out_size, TCP_MSS_ACCT_SIZE);
1852 	COUNTER_ARRAY_FREE(bbr_state_lost, BBR_MAX_STAT);
1853 	COUNTER_ARRAY_FREE(bbr_state_time, BBR_MAX_STAT);
1854 	COUNTER_ARRAY_FREE(bbr_state_resend, BBR_MAX_STAT);
1855 	counter_u64_free(bbr_nohdwr_pacing_enobuf);
1856 	counter_u64_free(bbr_hdwr_pacing_enobuf);
1857 	counter_u64_free(bbr_flows_whdwr_pacing);
1858 	counter_u64_free(bbr_flows_nohdwr_pacing);
1859 
1860 }
1861 
1862 static __inline void
1863 bbr_fill_in_logging_data(struct tcp_bbr *bbr, struct tcp_log_bbr *l, uint32_t cts)
1864 {
1865 	memset(l, 0, sizeof(union tcp_log_stackspecific));
1866 	l->cur_del_rate = bbr->r_ctl.rc_bbr_cur_del_rate;
1867 	l->delRate = get_filter_value(&bbr->r_ctl.rc_delrate);
1868 	l->rttProp = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
1869 	l->bw_inuse = bbr_get_bw(bbr);
1870 	l->inflight = ctf_flight_size(bbr->rc_tp,
1871 			  (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
1872 	l->applimited = bbr->r_ctl.r_app_limited_until;
1873 	l->delivered = bbr->r_ctl.rc_delivered;
1874 	l->timeStamp = cts;
1875 	l->lost = bbr->r_ctl.rc_lost;
1876 	l->bbr_state = bbr->rc_bbr_state;
1877 	l->bbr_substate = bbr_state_val(bbr);
1878 	l->epoch = bbr->r_ctl.rc_rtt_epoch;
1879 	l->lt_epoch = bbr->r_ctl.rc_lt_epoch;
1880 	l->pacing_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
1881 	l->cwnd_gain = bbr->r_ctl.rc_bbr_cwnd_gain;
1882 	l->inhpts = bbr->rc_inp->inp_in_hpts;
1883 	l->ininput = bbr->rc_inp->inp_in_input;
1884 	l->use_lt_bw = bbr->rc_lt_use_bw;
1885 	l->pkts_out = bbr->r_ctl.rc_flight_at_input;
1886 	l->pkt_epoch = bbr->r_ctl.rc_pkt_epoch;
1887 }
1888 
1889 static void
1890 bbr_log_type_bw_reduce(struct tcp_bbr *bbr, int reason)
1891 {
1892 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1893 		union tcp_log_stackspecific log;
1894 
1895 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1896 		log.u_bbr.flex1 = 0;
1897 		log.u_bbr.flex2 = 0;
1898 		log.u_bbr.flex5 = 0;
1899 		log.u_bbr.flex3 = 0;
1900 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_loss_rate;
1901 		log.u_bbr.flex7 = reason;
1902 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_enters_probertt;
1903 		log.u_bbr.flex8 = 0;
1904 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1905 		    &bbr->rc_inp->inp_socket->so_rcv,
1906 		    &bbr->rc_inp->inp_socket->so_snd,
1907 		    BBR_LOG_BW_RED_EV, 0,
1908 		    0, &log, false, &bbr->rc_tv);
1909 	}
1910 }
1911 
1912 static void
1913 bbr_log_type_rwnd_collapse(struct tcp_bbr *bbr, int seq, int mode, uint32_t count)
1914 {
1915 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1916 		union tcp_log_stackspecific log;
1917 
1918 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1919 		log.u_bbr.flex1 = seq;
1920 		log.u_bbr.flex2 = count;
1921 		log.u_bbr.flex8 = mode;
1922 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1923 		    &bbr->rc_inp->inp_socket->so_rcv,
1924 		    &bbr->rc_inp->inp_socket->so_snd,
1925 		    BBR_LOG_LOWGAIN, 0,
1926 		    0, &log, false, &bbr->rc_tv);
1927 	}
1928 }
1929 
1930 static void
1931 bbr_log_type_just_return(struct tcp_bbr *bbr, uint32_t cts, uint32_t tlen, uint8_t hpts_calling,
1932     uint8_t reason, uint32_t p_maxseg, int len)
1933 {
1934 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1935 		union tcp_log_stackspecific log;
1936 
1937 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1938 		log.u_bbr.flex1 = p_maxseg;
1939 		log.u_bbr.flex2 = bbr->r_ctl.rc_hpts_flags;
1940 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
1941 		log.u_bbr.flex4 = reason;
1942 		log.u_bbr.flex5 = bbr->rc_in_persist;
1943 		log.u_bbr.flex6 = bbr->r_ctl.rc_last_delay_val;
1944 		log.u_bbr.flex7 = p_maxseg;
1945 		log.u_bbr.flex8 = bbr->rc_in_persist;
1946 		log.u_bbr.pkts_out = 0;
1947 		log.u_bbr.applimited = len;
1948 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1949 		    &bbr->rc_inp->inp_socket->so_rcv,
1950 		    &bbr->rc_inp->inp_socket->so_snd,
1951 		    BBR_LOG_JUSTRET, 0,
1952 		    tlen, &log, false, &bbr->rc_tv);
1953 	}
1954 }
1955 
1956 static void
1957 bbr_log_type_enter_rec(struct tcp_bbr *bbr, uint32_t seq)
1958 {
1959 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1960 		union tcp_log_stackspecific log;
1961 
1962 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1963 		log.u_bbr.flex1 = seq;
1964 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
1965 		log.u_bbr.flex3 = bbr->r_ctl.rc_recovery_start;
1966 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1967 		    &bbr->rc_inp->inp_socket->so_rcv,
1968 		    &bbr->rc_inp->inp_socket->so_snd,
1969 		    BBR_LOG_ENTREC, 0,
1970 		    0, &log, false, &bbr->rc_tv);
1971 	}
1972 }
1973 
1974 static void
1975 bbr_log_msgsize_fail(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t len, uint32_t maxseg, uint32_t mtu, int32_t csum_flags, int32_t tso, uint32_t cts)
1976 {
1977 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
1978 		union tcp_log_stackspecific log;
1979 
1980 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1981 		log.u_bbr.flex1 = tso;
1982 		log.u_bbr.flex2 = maxseg;
1983 		log.u_bbr.flex3 = mtu;
1984 		log.u_bbr.flex4 = csum_flags;
1985 		TCP_LOG_EVENTP(tp, NULL,
1986 		    &bbr->rc_inp->inp_socket->so_rcv,
1987 		    &bbr->rc_inp->inp_socket->so_snd,
1988 		    BBR_LOG_MSGSIZE, 0,
1989 		    0, &log, false, &bbr->rc_tv);
1990 	}
1991 }
1992 
1993 static void
1994 bbr_log_flowend(struct tcp_bbr *bbr)
1995 {
1996 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1997 		union tcp_log_stackspecific log;
1998 		struct sockbuf *r, *s;
1999 		struct timeval tv;
2000 
2001 		if (bbr->rc_inp->inp_socket) {
2002 			r = &bbr->rc_inp->inp_socket->so_rcv;
2003 			s = &bbr->rc_inp->inp_socket->so_snd;
2004 		} else {
2005 			r = s = NULL;
2006 		}
2007 		bbr_fill_in_logging_data(bbr, &log.u_bbr, tcp_get_usecs(&tv));
2008 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2009 		    r, s,
2010 		    TCP_LOG_FLOWEND, 0,
2011 		    0, &log, false, &tv);
2012 	}
2013 }
2014 
2015 static void
2016 bbr_log_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line,
2017     uint32_t lost, uint32_t del)
2018 {
2019 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2020 		union tcp_log_stackspecific log;
2021 
2022 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2023 		log.u_bbr.flex1 = lost;
2024 		log.u_bbr.flex2 = del;
2025 		log.u_bbr.flex3 = bbr->r_ctl.rc_bbr_lastbtlbw;
2026 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_rtt;
2027 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2028 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2029 		log.u_bbr.flex7 = line;
2030 		log.u_bbr.flex8 = 0;
2031 		log.u_bbr.inflight = bbr->r_ctl.r_measurement_count;
2032 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2033 		    &bbr->rc_inp->inp_socket->so_rcv,
2034 		    &bbr->rc_inp->inp_socket->so_snd,
2035 		    BBR_LOG_PKT_EPOCH, 0,
2036 		    0, &log, false, &bbr->rc_tv);
2037 	}
2038 }
2039 
2040 static void
2041 bbr_log_time_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line, uint32_t epoch_time)
2042 {
2043 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2044 		union tcp_log_stackspecific log;
2045 
2046 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2047 		log.u_bbr.flex1 = bbr->r_ctl.rc_lost;
2048 		log.u_bbr.flex2 = bbr->rc_inp->inp_socket->so_snd.sb_lowat;
2049 		log.u_bbr.flex3 = bbr->rc_inp->inp_socket->so_snd.sb_hiwat;
2050 		log.u_bbr.flex7 = line;
2051 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2052 		    &bbr->rc_inp->inp_socket->so_rcv,
2053 		    &bbr->rc_inp->inp_socket->so_snd,
2054 		    BBR_LOG_TIME_EPOCH, 0,
2055 		    0, &log, false, &bbr->rc_tv);
2056 	}
2057 }
2058 
2059 static void
2060 bbr_log_set_of_state_target(struct tcp_bbr *bbr, uint32_t new_tar, int line, int meth)
2061 {
2062 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2063 		union tcp_log_stackspecific log;
2064 
2065 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2066 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2067 		log.u_bbr.flex2 = new_tar;
2068 		log.u_bbr.flex3 = line;
2069 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2070 		log.u_bbr.flex5 = bbr_quanta;
2071 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_min_segs;
2072 		log.u_bbr.flex7 = bbr->rc_last_options;
2073 		log.u_bbr.flex8 = meth;
2074 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2075 		    &bbr->rc_inp->inp_socket->so_rcv,
2076 		    &bbr->rc_inp->inp_socket->so_snd,
2077 		    BBR_LOG_STATE_TARGET, 0,
2078 		    0, &log, false, &bbr->rc_tv);
2079 	}
2080 
2081 }
2082 
2083 static void
2084 bbr_log_type_statechange(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2085 {
2086 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2087 		union tcp_log_stackspecific log;
2088 
2089 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2090 		log.u_bbr.flex1 = line;
2091 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2092 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2093 		if (bbr_state_is_pkt_epoch)
2094 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
2095 		else
2096 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PROP);
2097 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2098 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2099 		log.u_bbr.flex7 = (bbr->r_ctl.rc_target_at_state/1000);
2100 		log.u_bbr.lt_epoch = bbr->r_ctl.rc_level_state_extra;
2101 		log.u_bbr.pkts_out = bbr->r_ctl.rc_target_at_state;
2102 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2103 		    &bbr->rc_inp->inp_socket->so_rcv,
2104 		    &bbr->rc_inp->inp_socket->so_snd,
2105 		    BBR_LOG_STATE, 0,
2106 		    0, &log, false, &bbr->rc_tv);
2107 	}
2108 }
2109 
2110 static void
2111 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
2112 		    uint32_t rtt, uint32_t line, uint8_t reas, uint16_t cond)
2113 {
2114 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2115 		union tcp_log_stackspecific log;
2116 
2117 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2118 		log.u_bbr.flex1 = line;
2119 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2120 		log.u_bbr.flex3 = bbr->r_ctl.last_in_probertt;
2121 		log.u_bbr.flex4 = applied;
2122 		log.u_bbr.flex5 = rtt;
2123 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2124 		log.u_bbr.flex7 = cond;
2125 		log.u_bbr.flex8 = reas;
2126 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2127 		    &bbr->rc_inp->inp_socket->so_rcv,
2128 		    &bbr->rc_inp->inp_socket->so_snd,
2129 		    BBR_LOG_RTT_SHRINKS, 0,
2130 		    0, &log, false, &bbr->rc_tv);
2131 	}
2132 }
2133 
2134 static void
2135 bbr_log_type_exit_rec(struct tcp_bbr *bbr)
2136 {
2137 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2138 		union tcp_log_stackspecific log;
2139 
2140 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2141 		log.u_bbr.flex1 = bbr->r_ctl.rc_recovery_start;
2142 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
2143 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2144 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2145 		    &bbr->rc_inp->inp_socket->so_rcv,
2146 		    &bbr->rc_inp->inp_socket->so_snd,
2147 		    BBR_LOG_EXITREC, 0,
2148 		    0, &log, false, &bbr->rc_tv);
2149 	}
2150 }
2151 
2152 static void
2153 bbr_log_type_cwndupd(struct tcp_bbr *bbr, uint32_t bytes_this_ack, uint32_t chg,
2154     uint32_t prev_acked, int32_t meth, uint32_t target, uint32_t th_ack, int32_t line)
2155 {
2156 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2157 		union tcp_log_stackspecific log;
2158 
2159 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2160 		log.u_bbr.flex1 = line;
2161 		log.u_bbr.flex2 = prev_acked;
2162 		log.u_bbr.flex3 = bytes_this_ack;
2163 		log.u_bbr.flex4 = chg;
2164 		log.u_bbr.flex5 = th_ack;
2165 		log.u_bbr.flex6 = target;
2166 		log.u_bbr.flex8 = meth;
2167 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2168 		    &bbr->rc_inp->inp_socket->so_rcv,
2169 		    &bbr->rc_inp->inp_socket->so_snd,
2170 		    BBR_LOG_CWND, 0,
2171 		    0, &log, false, &bbr->rc_tv);
2172 	}
2173 }
2174 
2175 static void
2176 bbr_log_rtt_sample(struct tcp_bbr *bbr, uint32_t rtt, uint32_t tsin)
2177 {
2178 	/*
2179 	 * Log the rtt sample we are applying to the srtt algorithm in
2180 	 * useconds.
2181 	 */
2182 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2183 		union tcp_log_stackspecific log;
2184 
2185 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2186 		log.u_bbr.flex1 = rtt;
2187 		log.u_bbr.flex2 = bbr->r_ctl.rc_bbr_state_time;
2188 		log.u_bbr.flex3 = bbr->r_ctl.rc_ack_hdwr_delay;
2189 		log.u_bbr.flex4 = bbr->rc_tp->ts_offset;
2190 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2191 		log.u_bbr.pkts_out = tcp_tv_to_mssectick(&bbr->rc_tv);
2192 		log.u_bbr.flex6 = tsin;
2193 		log.u_bbr.flex7 = 0;
2194 		log.u_bbr.flex8 = bbr->rc_ack_was_delayed;
2195 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2196 		    &bbr->rc_inp->inp_socket->so_rcv,
2197 		    &bbr->rc_inp->inp_socket->so_snd,
2198 		    TCP_LOG_RTT, 0,
2199 		    0, &log, false, &bbr->rc_tv);
2200 	}
2201 }
2202 
2203 static void
2204 bbr_log_type_pesist(struct tcp_bbr *bbr, uint32_t cts, uint32_t time_in, int32_t line, uint8_t enter_exit)
2205 {
2206 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2207 		union tcp_log_stackspecific log;
2208 
2209 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2210 		log.u_bbr.flex1 = time_in;
2211 		log.u_bbr.flex2 = line;
2212 		log.u_bbr.flex8 = enter_exit;
2213 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2214 		    &bbr->rc_inp->inp_socket->so_rcv,
2215 		    &bbr->rc_inp->inp_socket->so_snd,
2216 		    BBR_LOG_PERSIST, 0,
2217 		    0, &log, false, &bbr->rc_tv);
2218 	}
2219 }
2220 static void
2221 bbr_log_ack_clear(struct tcp_bbr *bbr, uint32_t cts)
2222 {
2223 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2224 		union tcp_log_stackspecific log;
2225 
2226 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2227 		log.u_bbr.flex1 = bbr->rc_tp->ts_recent_age;
2228 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2229 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2230 		log.u_bbr.flex4 = bbr->r_ctl.rc_went_idle_time;
2231 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2232 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2233 		    &bbr->rc_inp->inp_socket->so_rcv,
2234 		    &bbr->rc_inp->inp_socket->so_snd,
2235 		    BBR_LOG_ACKCLEAR, 0,
2236 		    0, &log, false, &bbr->rc_tv);
2237 	}
2238 }
2239 
2240 static void
2241 bbr_log_ack_event(struct tcp_bbr *bbr, struct tcphdr *th, struct tcpopt *to, uint32_t tlen,
2242 		  uint16_t nsegs, uint32_t cts, int32_t nxt_pkt, struct mbuf *m)
2243 {
2244 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2245 		union tcp_log_stackspecific log;
2246 		struct timeval tv;
2247 
2248 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2249 		log.u_bbr.flex1 = nsegs;
2250 		log.u_bbr.flex2 = bbr->r_ctl.rc_lost_bytes;
2251 		if (m) {
2252 			struct timespec ts;
2253 
2254 			log.u_bbr.flex3 = m->m_flags;
2255 			if (m->m_flags & M_TSTMP) {
2256 				mbuf_tstmp2timespec(m, &ts);
2257 				tv.tv_sec = ts.tv_sec;
2258 				tv.tv_usec = ts.tv_nsec / 1000;
2259 				log.u_bbr.lt_epoch = tcp_tv_to_usectick(&tv);
2260 			} else {
2261 				log.u_bbr.lt_epoch = 0;
2262 			}
2263 			if (m->m_flags & M_TSTMP_LRO) {
2264 				tv.tv_sec = m->m_pkthdr.rcv_tstmp / 1000000000;
2265 				tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000) / 1000;
2266 				log.u_bbr.flex5 = tcp_tv_to_usectick(&tv);
2267 			} else {
2268 				/* No arrival timestamp */
2269 				log.u_bbr.flex5 = 0;
2270 			}
2271 
2272 			log.u_bbr.pkts_out = tcp_get_usecs(&tv);
2273 		} else {
2274 			log.u_bbr.flex3 = 0;
2275 			log.u_bbr.flex5 = 0;
2276 			log.u_bbr.flex6 = 0;
2277 			log.u_bbr.pkts_out = 0;
2278 		}
2279 		log.u_bbr.flex4 = bbr->r_ctl.rc_target_at_state;
2280 		log.u_bbr.flex7 = bbr->r_wanted_output;
2281 		log.u_bbr.flex8 = bbr->rc_in_persist;
2282 		TCP_LOG_EVENTP(bbr->rc_tp, th,
2283 		    &bbr->rc_inp->inp_socket->so_rcv,
2284 		    &bbr->rc_inp->inp_socket->so_snd,
2285 		    TCP_LOG_IN, 0,
2286 		    tlen, &log, true, &bbr->rc_tv);
2287 	}
2288 }
2289 
2290 static void
2291 bbr_log_doseg_done(struct tcp_bbr *bbr, uint32_t cts, int32_t nxt_pkt, int32_t did_out)
2292 {
2293 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2294 		union tcp_log_stackspecific log;
2295 
2296 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2297 		log.u_bbr.flex1 = did_out;
2298 		log.u_bbr.flex2 = nxt_pkt;
2299 		log.u_bbr.flex3 = bbr->r_ctl.rc_last_delay_val;
2300 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2301 		log.u_bbr.flex5 = bbr->r_ctl.rc_timer_exp;
2302 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_bytes;
2303 		log.u_bbr.flex7 = bbr->r_wanted_output;
2304 		log.u_bbr.flex8 = bbr->rc_in_persist;
2305 		log.u_bbr.pkts_out = bbr->r_ctl.highest_hdwr_delay;
2306 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2307 		    &bbr->rc_inp->inp_socket->so_rcv,
2308 		    &bbr->rc_inp->inp_socket->so_snd,
2309 		    BBR_LOG_DOSEG_DONE, 0,
2310 		    0, &log, true, &bbr->rc_tv);
2311 	}
2312 }
2313 
2314 static void
2315 bbr_log_enobuf_jmp(struct tcp_bbr *bbr, uint32_t len, uint32_t cts,
2316     int32_t line, uint32_t o_len, uint32_t segcnt, uint32_t segsiz)
2317 {
2318 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2319 		union tcp_log_stackspecific log;
2320 
2321 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2322 		log.u_bbr.flex1 = line;
2323 		log.u_bbr.flex2 = o_len;
2324 		log.u_bbr.flex3 = segcnt;
2325 		log.u_bbr.flex4 = segsiz;
2326 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2327 		    &bbr->rc_inp->inp_socket->so_rcv,
2328 		    &bbr->rc_inp->inp_socket->so_snd,
2329 		    BBR_LOG_ENOBUF_JMP, ENOBUFS,
2330 		    len, &log, true, &bbr->rc_tv);
2331 	}
2332 }
2333 
2334 static void
2335 bbr_log_to_processing(struct tcp_bbr *bbr, uint32_t cts, int32_t ret, int32_t timers, uint8_t hpts_calling)
2336 {
2337 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2338 		union tcp_log_stackspecific log;
2339 
2340 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2341 		log.u_bbr.flex1 = timers;
2342 		log.u_bbr.flex2 = ret;
2343 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
2344 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2345 		log.u_bbr.flex5 = cts;
2346 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2347 		log.u_bbr.flex8 = hpts_calling;
2348 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2349 		    &bbr->rc_inp->inp_socket->so_rcv,
2350 		    &bbr->rc_inp->inp_socket->so_snd,
2351 		    BBR_LOG_TO_PROCESS, 0,
2352 		    0, &log, false, &bbr->rc_tv);
2353 	}
2354 }
2355 
2356 static void
2357 bbr_log_to_event(struct tcp_bbr *bbr, uint32_t cts, int32_t to_num)
2358 {
2359 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2360 		union tcp_log_stackspecific log;
2361 		uint64_t ar;
2362 
2363 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2364 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2365 		log.u_bbr.flex2 = 0;
2366 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2367 		ar = (uint64_t)(bbr->r_ctl.rc_resend);
2368 		ar >>= 32;
2369 		ar &= 0x00000000ffffffff;
2370 		log.u_bbr.flex4 = (uint32_t)ar;
2371 		ar = (uint64_t)bbr->r_ctl.rc_resend;
2372 		ar &= 0x00000000ffffffff;
2373 		log.u_bbr.flex5 = (uint32_t)ar;
2374 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2375 		log.u_bbr.flex8 = to_num;
2376 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2377 		    &bbr->rc_inp->inp_socket->so_rcv,
2378 		    &bbr->rc_inp->inp_socket->so_snd,
2379 		    BBR_LOG_RTO, 0,
2380 		    0, &log, false, &bbr->rc_tv);
2381 	}
2382 }
2383 
2384 static void
2385 bbr_log_startup_event(struct tcp_bbr *bbr, uint32_t cts, uint32_t flex1, uint32_t flex2, uint32_t flex3, uint8_t reason)
2386 {
2387 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2388 		union tcp_log_stackspecific log;
2389 
2390 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2391 		log.u_bbr.flex1 = flex1;
2392 		log.u_bbr.flex2 = flex2;
2393 		log.u_bbr.flex3 = flex3;
2394 		log.u_bbr.flex4 = 0;
2395 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2396 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2397 		log.u_bbr.flex8 = reason;
2398 		log.u_bbr.cur_del_rate = bbr->r_ctl.rc_bbr_lastbtlbw;
2399 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2400 		    &bbr->rc_inp->inp_socket->so_rcv,
2401 		    &bbr->rc_inp->inp_socket->so_snd,
2402 		    BBR_LOG_REDUCE, 0,
2403 		    0, &log, false, &bbr->rc_tv);
2404 	}
2405 }
2406 
2407 static void
2408 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag)
2409 {
2410 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2411 		union tcp_log_stackspecific log;
2412 
2413 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2414 		log.u_bbr.flex1 = diag->p_nxt_slot;
2415 		log.u_bbr.flex2 = diag->p_cur_slot;
2416 		log.u_bbr.flex3 = diag->slot_req;
2417 		log.u_bbr.flex4 = diag->inp_hptsslot;
2418 		log.u_bbr.flex5 = diag->slot_remaining;
2419 		log.u_bbr.flex6 = diag->need_new_to;
2420 		log.u_bbr.flex7 = diag->p_hpts_active;
2421 		log.u_bbr.flex8 = diag->p_on_min_sleep;
2422 		/* Hijack other fields as needed  */
2423 		log.u_bbr.epoch = diag->have_slept;
2424 		log.u_bbr.lt_epoch = diag->yet_to_sleep;
2425 		log.u_bbr.pkts_out = diag->co_ret;
2426 		log.u_bbr.applimited = diag->hpts_sleep_time;
2427 		log.u_bbr.delivered = diag->p_prev_slot;
2428 		log.u_bbr.inflight = diag->p_runningtick;
2429 		log.u_bbr.bw_inuse = diag->wheel_tick;
2430 		log.u_bbr.rttProp = diag->wheel_cts;
2431 		log.u_bbr.delRate = diag->maxticks;
2432 		log.u_bbr.cur_del_rate = diag->p_curtick;
2433 		log.u_bbr.cur_del_rate <<= 32;
2434 		log.u_bbr.cur_del_rate |= diag->p_lasttick;
2435 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2436 		    &bbr->rc_inp->inp_socket->so_rcv,
2437 		    &bbr->rc_inp->inp_socket->so_snd,
2438 		    BBR_LOG_HPTSDIAG, 0,
2439 		    0, &log, false, &bbr->rc_tv);
2440 	}
2441 }
2442 
2443 static void
2444 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
2445     uint32_t thresh, uint32_t to)
2446 {
2447 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2448 		union tcp_log_stackspecific log;
2449 
2450 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2451 		log.u_bbr.flex1 = bbr->rc_tp->t_rttvar;
2452 		log.u_bbr.flex2 = time_since_sent;
2453 		log.u_bbr.flex3 = srtt;
2454 		log.u_bbr.flex4 = thresh;
2455 		log.u_bbr.flex5 = to;
2456 		log.u_bbr.flex6 = bbr->rc_tp->t_srtt;
2457 		log.u_bbr.flex8 = mode;
2458 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2459 		    &bbr->rc_inp->inp_socket->so_rcv,
2460 		    &bbr->rc_inp->inp_socket->so_snd,
2461 		    BBR_LOG_TIMERPREP, 0,
2462 		    0, &log, false, &bbr->rc_tv);
2463 	}
2464 }
2465 
2466 static void
2467 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
2468     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod)
2469 {
2470 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2471 		union tcp_log_stackspecific log;
2472 
2473 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2474 		log.u_bbr.flex1 = usecs;
2475 		log.u_bbr.flex2 = len;
2476 		log.u_bbr.flex3 = (uint32_t)((bw >> 32) & 0x00000000ffffffff);
2477 		log.u_bbr.flex4 = (uint32_t)(bw & 0x00000000ffffffff);
2478 		if (override)
2479 			log.u_bbr.flex5 = (1 << 2);
2480 		else
2481 			log.u_bbr.flex5 = 0;
2482 		log.u_bbr.flex6 = override;
2483 		log.u_bbr.flex7 = gain;
2484 		log.u_bbr.flex8 = mod;
2485 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2486 		    &bbr->rc_inp->inp_socket->so_rcv,
2487 		    &bbr->rc_inp->inp_socket->so_snd,
2488 		    BBR_LOG_HPTSI_CALC, 0,
2489 		    len, &log, false, &bbr->rc_tv);
2490 	}
2491 }
2492 
2493 static void
2494 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2495 {
2496 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2497 		union tcp_log_stackspecific log;
2498 
2499 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2500 
2501 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2502 		log.u_bbr.flex2 = to;
2503 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2504 		log.u_bbr.flex4 = slot;
2505 		log.u_bbr.flex5 = bbr->rc_inp->inp_hptsslot;
2506 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2507 		log.u_bbr.pkts_out = bbr->rc_inp->inp_flags2;
2508 		log.u_bbr.flex8 = which;
2509 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2510 		    &bbr->rc_inp->inp_socket->so_rcv,
2511 		    &bbr->rc_inp->inp_socket->so_snd,
2512 		    BBR_LOG_TIMERSTAR, 0,
2513 		    0, &log, false, &bbr->rc_tv);
2514 	}
2515 }
2516 
2517 static void
2518 bbr_log_thresh_choice(struct tcp_bbr *bbr, uint32_t cts, uint32_t thresh, uint32_t lro, uint32_t srtt, struct bbr_sendmap *rsm, uint8_t frm)
2519 {
2520 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2521 		union tcp_log_stackspecific log;
2522 
2523 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2524 		log.u_bbr.flex1 = thresh;
2525 		log.u_bbr.flex2 = lro;
2526 		log.u_bbr.flex3 = bbr->r_ctl.rc_reorder_ts;
2527 		log.u_bbr.flex4 = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
2528 		log.u_bbr.flex5 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2529 		log.u_bbr.flex6 = srtt;
2530 		log.u_bbr.flex7 = bbr->r_ctl.rc_reorder_shift;
2531 		log.u_bbr.flex8 = frm;
2532 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2533 		    &bbr->rc_inp->inp_socket->so_rcv,
2534 		    &bbr->rc_inp->inp_socket->so_snd,
2535 		    BBR_LOG_THRESH_CALC, 0,
2536 		    0, &log, false, &bbr->rc_tv);
2537 	}
2538 }
2539 
2540 static void
2541 bbr_log_to_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts, uint8_t hpts_removed)
2542 {
2543 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2544 		union tcp_log_stackspecific log;
2545 
2546 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2547 		log.u_bbr.flex1 = line;
2548 		log.u_bbr.flex2 = bbr->bbr_timer_src;
2549 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2550 		log.u_bbr.flex4 = bbr->rc_in_persist;
2551 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2552 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2553 		log.u_bbr.flex8 = hpts_removed;
2554 		log.u_bbr.pkts_out = bbr->rc_pacer_started;
2555 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2556 		    &bbr->rc_inp->inp_socket->so_rcv,
2557 		    &bbr->rc_inp->inp_socket->so_snd,
2558 		    BBR_LOG_TIMERCANC, 0,
2559 		    0, &log, false, &bbr->rc_tv);
2560 	}
2561 }
2562 
2563 static void
2564 bbr_log_tstmp_validation(struct tcp_bbr *bbr, uint64_t peer_delta, uint64_t delta)
2565 {
2566 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2567 		union tcp_log_stackspecific log;
2568 
2569 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2570 		log.u_bbr.flex1 = bbr->r_ctl.bbr_peer_tsratio;
2571 		log.u_bbr.flex2 = (peer_delta >> 32);
2572 		log.u_bbr.flex3 = (peer_delta & 0x00000000ffffffff);
2573 		log.u_bbr.flex4 = (delta >> 32);
2574 		log.u_bbr.flex5 = (delta & 0x00000000ffffffff);
2575 		log.u_bbr.flex7 = bbr->rc_ts_clock_set;
2576 		log.u_bbr.flex8 = bbr->rc_ts_cant_be_used;
2577 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2578 		    &bbr->rc_inp->inp_socket->so_rcv,
2579 		    &bbr->rc_inp->inp_socket->so_snd,
2580 		    BBR_LOG_TSTMP_VAL, 0,
2581 		    0, &log, false, &bbr->rc_tv);
2582 	}
2583 }
2584 
2585 static void
2586 bbr_log_type_tsosize(struct tcp_bbr *bbr, uint32_t cts, uint32_t tsosz, uint32_t tls, uint32_t old_val, uint32_t maxseg, int hdwr)
2587 {
2588 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2589 		union tcp_log_stackspecific log;
2590 
2591 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2592 		log.u_bbr.flex1 = tsosz;
2593 		log.u_bbr.flex2 = tls;
2594 		log.u_bbr.flex3 = tcp_min_hptsi_time;
2595 		log.u_bbr.flex4 = bbr->r_ctl.bbr_hptsi_bytes_min;
2596 		log.u_bbr.flex5 = old_val;
2597 		log.u_bbr.flex6 = maxseg;
2598 		log.u_bbr.flex7 = bbr->rc_no_pacing;
2599 		log.u_bbr.flex7 <<= 1;
2600 		log.u_bbr.flex7 |= bbr->rc_past_init_win;
2601 		if (hdwr)
2602 			log.u_bbr.flex8 = 0x80 | bbr->rc_use_google;
2603 		else
2604 			log.u_bbr.flex8 = bbr->rc_use_google;
2605 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2606 		    &bbr->rc_inp->inp_socket->so_rcv,
2607 		    &bbr->rc_inp->inp_socket->so_snd,
2608 		    BBR_LOG_BBRTSO, 0,
2609 		    0, &log, false, &bbr->rc_tv);
2610 	}
2611 }
2612 
2613 static void
2614 bbr_log_type_rsmclear(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm,
2615 		      uint32_t flags, uint32_t line)
2616 {
2617 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2618 		union tcp_log_stackspecific log;
2619 
2620 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2621 		log.u_bbr.flex1 = line;
2622 		log.u_bbr.flex2 = rsm->r_start;
2623 		log.u_bbr.flex3 = rsm->r_end;
2624 		log.u_bbr.flex4 = rsm->r_delivered;
2625 		log.u_bbr.flex5 = rsm->r_rtr_cnt;
2626 		log.u_bbr.flex6 = rsm->r_dupack;
2627 		log.u_bbr.flex7 = rsm->r_tim_lastsent[0];
2628 		log.u_bbr.flex8 = rsm->r_flags;
2629 		/* Hijack the pkts_out fids */
2630 		log.u_bbr.applimited = flags;
2631 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2632 		    &bbr->rc_inp->inp_socket->so_rcv,
2633 		    &bbr->rc_inp->inp_socket->so_snd,
2634 		    BBR_RSM_CLEARED, 0,
2635 		    0, &log, false, &bbr->rc_tv);
2636 	}
2637 }
2638 
2639 static void
2640 bbr_log_type_bbrupd(struct tcp_bbr *bbr, uint8_t flex8, uint32_t cts,
2641     uint32_t flex3, uint32_t flex2, uint32_t flex5,
2642     uint32_t flex6, uint32_t pkts_out, int flex7,
2643     uint32_t flex4, uint32_t flex1)
2644 {
2645 
2646 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2647 		union tcp_log_stackspecific log;
2648 
2649 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2650 		log.u_bbr.flex1 = flex1;
2651 		log.u_bbr.flex2 = flex2;
2652 		log.u_bbr.flex3 = flex3;
2653 		log.u_bbr.flex4 = flex4;
2654 		log.u_bbr.flex5 = flex5;
2655 		log.u_bbr.flex6 = flex6;
2656 		log.u_bbr.flex7 = flex7;
2657 		/* Hijack the pkts_out fids */
2658 		log.u_bbr.pkts_out = pkts_out;
2659 		log.u_bbr.flex8 = flex8;
2660 		if (bbr->rc_ack_was_delayed)
2661 			log.u_bbr.epoch = bbr->r_ctl.rc_ack_hdwr_delay;
2662 		else
2663 			log.u_bbr.epoch = 0;
2664 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2665 		    &bbr->rc_inp->inp_socket->so_rcv,
2666 		    &bbr->rc_inp->inp_socket->so_snd,
2667 		    BBR_LOG_BBRUPD, 0,
2668 		    flex2, &log, false, &bbr->rc_tv);
2669 	}
2670 }
2671 
2672 static void
2673 bbr_log_type_ltbw(struct tcp_bbr *bbr, uint32_t cts, int32_t reason,
2674 	uint32_t newbw, uint32_t obw, uint32_t diff,
2675 	uint32_t tim)
2676 {
2677 	if (/*bbr_verbose_logging && */(bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2678 		union tcp_log_stackspecific log;
2679 
2680 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2681 		log.u_bbr.flex1 = reason;
2682 		log.u_bbr.flex2 = newbw;
2683 		log.u_bbr.flex3 = obw;
2684 		log.u_bbr.flex4 = diff;
2685 		log.u_bbr.flex5 = bbr->r_ctl.rc_lt_lost;
2686 		log.u_bbr.flex6 = bbr->r_ctl.rc_lt_del;
2687 		log.u_bbr.flex7 = bbr->rc_lt_is_sampling;
2688 		log.u_bbr.pkts_out = tim;
2689 		log.u_bbr.bw_inuse = bbr->r_ctl.rc_lt_bw;
2690 		if (bbr->rc_lt_use_bw == 0)
2691 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
2692 		else
2693 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
2694 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2695 		    &bbr->rc_inp->inp_socket->so_rcv,
2696 		    &bbr->rc_inp->inp_socket->so_snd,
2697 		    BBR_LOG_BWSAMP, 0,
2698 		    0, &log, false, &bbr->rc_tv);
2699 	}
2700 }
2701 
2702 static inline void
2703 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line)
2704 {
2705 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2706 		union tcp_log_stackspecific log;
2707 
2708 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2709 		log.u_bbr.flex1 = line;
2710 		log.u_bbr.flex2 = tick;
2711 		log.u_bbr.flex3 = tp->t_maxunacktime;
2712 		log.u_bbr.flex4 = tp->t_acktime;
2713 		log.u_bbr.flex8 = event;
2714 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2715 		    &bbr->rc_inp->inp_socket->so_rcv,
2716 		    &bbr->rc_inp->inp_socket->so_snd,
2717 		    BBR_LOG_PROGRESS, 0,
2718 		    0, &log, false, &bbr->rc_tv);
2719 	}
2720 }
2721 
2722 static void
2723 bbr_type_log_hdwr_pacing(struct tcp_bbr *bbr, const struct ifnet *ifp,
2724 			 uint64_t rate, uint64_t hw_rate, int line, uint32_t cts,
2725 			 int error)
2726 {
2727 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2728 		union tcp_log_stackspecific log;
2729 
2730 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2731 		log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2732 		log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2733 		log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2734 		log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2735 		log.u_bbr.bw_inuse = rate;
2736 		log.u_bbr.flex5 = line;
2737 		log.u_bbr.flex6 = error;
2738 		log.u_bbr.flex8 = bbr->skip_gain;
2739 		log.u_bbr.flex8 <<= 1;
2740 		log.u_bbr.flex8 |= bbr->gain_is_limited;
2741 		log.u_bbr.flex8 <<= 1;
2742 		log.u_bbr.flex8 |= bbr->bbr_hdrw_pacing;
2743 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
2744 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2745 		    &bbr->rc_inp->inp_socket->so_rcv,
2746 		    &bbr->rc_inp->inp_socket->so_snd,
2747 		    BBR_LOG_HDWR_PACE, 0,
2748 		    0, &log, false, &bbr->rc_tv);
2749 	}
2750 }
2751 
2752 static void
2753 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot, uint32_t del_by, uint32_t cts, uint32_t line, uint32_t prev_delay)
2754 {
2755 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2756 		union tcp_log_stackspecific log;
2757 
2758 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2759 		log.u_bbr.flex1 = slot;
2760 		log.u_bbr.flex2 = del_by;
2761 		log.u_bbr.flex3 = prev_delay;
2762 		log.u_bbr.flex4 = line;
2763 		log.u_bbr.flex5 = bbr->r_ctl.rc_last_delay_val;
2764 		log.u_bbr.flex6 = bbr->r_ctl.rc_hptsi_agg_delay;
2765 		log.u_bbr.flex7 = (0x0000ffff & bbr->r_ctl.rc_hpts_flags);
2766 		log.u_bbr.flex8 = bbr->rc_in_persist;
2767 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2768 		    &bbr->rc_inp->inp_socket->so_rcv,
2769 		    &bbr->rc_inp->inp_socket->so_snd,
2770 		    BBR_LOG_BBRSND, 0,
2771 		    len, &log, false, &bbr->rc_tv);
2772 	}
2773 }
2774 
2775 static void
2776 bbr_log_type_bbrrttprop(struct tcp_bbr *bbr, uint32_t t, uint32_t end, uint32_t tsconv, uint32_t cts, int32_t match, uint32_t seq, uint8_t flags)
2777 {
2778 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2779 		union tcp_log_stackspecific log;
2780 
2781 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2782 		log.u_bbr.flex1 = bbr->r_ctl.rc_delivered;
2783 		log.u_bbr.flex2 = 0;
2784 		log.u_bbr.flex3 = bbr->r_ctl.rc_lowest_rtt;
2785 		log.u_bbr.flex4 = end;
2786 		log.u_bbr.flex5 = seq;
2787 		log.u_bbr.flex6 = t;
2788 		log.u_bbr.flex7 = match;
2789 		log.u_bbr.flex8 = flags;
2790 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2791 		    &bbr->rc_inp->inp_socket->so_rcv,
2792 		    &bbr->rc_inp->inp_socket->so_snd,
2793 		    BBR_LOG_BBRRTT, 0,
2794 		    0, &log, false, &bbr->rc_tv);
2795 	}
2796 }
2797 
2798 static void
2799 bbr_log_exit_gain(struct tcp_bbr *bbr, uint32_t cts, int32_t entry_method)
2800 {
2801 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2802 		union tcp_log_stackspecific log;
2803 
2804 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2805 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2806 		log.u_bbr.flex2 = (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
2807 		log.u_bbr.flex3 = bbr->r_ctl.gain_epoch;
2808 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2809 		log.u_bbr.flex5 = bbr->r_ctl.rc_pace_min_segs;
2810 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_state_atflight;
2811 		log.u_bbr.flex7 = 0;
2812 		log.u_bbr.flex8 = entry_method;
2813 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2814 		    &bbr->rc_inp->inp_socket->so_rcv,
2815 		    &bbr->rc_inp->inp_socket->so_snd,
2816 		    BBR_LOG_EXIT_GAIN, 0,
2817 		    0, &log, false, &bbr->rc_tv);
2818 	}
2819 }
2820 
2821 static void
2822 bbr_log_settings_change(struct tcp_bbr *bbr, int settings_desired)
2823 {
2824 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2825 		union tcp_log_stackspecific log;
2826 
2827 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2828 		/* R-HU */
2829 		log.u_bbr.flex1 = 0;
2830 		log.u_bbr.flex2 = 0;
2831 		log.u_bbr.flex3 = 0;
2832 		log.u_bbr.flex4 = 0;
2833 		log.u_bbr.flex7 = 0;
2834 		log.u_bbr.flex8 = settings_desired;
2835 
2836 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2837 		    &bbr->rc_inp->inp_socket->so_rcv,
2838 		    &bbr->rc_inp->inp_socket->so_snd,
2839 		    BBR_LOG_SETTINGS_CHG, 0,
2840 		    0, &log, false, &bbr->rc_tv);
2841 	}
2842 }
2843 
2844 /*
2845  * Returns the bw from the our filter.
2846  */
2847 static inline uint64_t
2848 bbr_get_full_bw(struct tcp_bbr *bbr)
2849 {
2850 	uint64_t bw;
2851 
2852 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2853 
2854 	return (bw);
2855 }
2856 
2857 static inline void
2858 bbr_set_pktepoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2859 {
2860 	uint64_t calclr;
2861 	uint32_t lost, del;
2862 
2863 	if (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_pktepoch)
2864 		lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lost_at_pktepoch;
2865 	else
2866 		lost = 0;
2867 	del = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_pkt_epoch_del;
2868 	if (lost == 0)  {
2869 		calclr = 0;
2870 	} else if (del) {
2871 		calclr = lost;
2872 		calclr *= (uint64_t)1000;
2873 		calclr /= (uint64_t)del;
2874 	} else {
2875 		/* Nothing delivered? 100.0% loss */
2876 		calclr = 1000;
2877 	}
2878 	bbr->r_ctl.rc_pkt_epoch_loss_rate =  (uint32_t)calclr;
2879 	if (IN_RECOVERY(bbr->rc_tp->t_flags))
2880 		bbr->r_ctl.recovery_lr += (uint32_t)calclr;
2881 	bbr->r_ctl.rc_pkt_epoch++;
2882 	if (bbr->rc_no_pacing &&
2883 	    (bbr->r_ctl.rc_pkt_epoch >= bbr->no_pacing_until)) {
2884 		bbr->rc_no_pacing = 0;
2885 		tcp_bbr_tso_size_check(bbr, cts);
2886 	}
2887 	bbr->r_ctl.rc_pkt_epoch_rtt = bbr_calc_time(cts, bbr->r_ctl.rc_pkt_epoch_time);
2888 	bbr->r_ctl.rc_pkt_epoch_time = cts;
2889 	/* What was our loss rate */
2890 	bbr_log_pkt_epoch(bbr, cts, line, lost, del);
2891 	bbr->r_ctl.rc_pkt_epoch_del = bbr->r_ctl.rc_delivered;
2892 	bbr->r_ctl.rc_lost_at_pktepoch = bbr->r_ctl.rc_lost;
2893 }
2894 
2895 static inline void
2896 bbr_set_epoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2897 {
2898 	uint32_t epoch_time;
2899 
2900 	/* Tick the RTT clock */
2901 	bbr->r_ctl.rc_rtt_epoch++;
2902 	epoch_time = cts - bbr->r_ctl.rc_rcv_epoch_start;
2903 	bbr_log_time_epoch(bbr, cts, line, epoch_time);
2904 	bbr->r_ctl.rc_rcv_epoch_start = cts;
2905 }
2906 
2907 static inline void
2908 bbr_isit_a_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm, int32_t line, int32_t cum_acked)
2909 {
2910 	if (SEQ_GEQ(rsm->r_delivered, bbr->r_ctl.rc_pkt_epoch_del)) {
2911 		bbr->rc_is_pkt_epoch_now = 1;
2912 	}
2913 }
2914 
2915 /*
2916  * Returns the bw from either the b/w filter
2917  * or from the lt_bw (if the connection is being
2918  * policed).
2919  */
2920 static inline uint64_t
2921 __bbr_get_bw(struct tcp_bbr *bbr)
2922 {
2923 	uint64_t bw, min_bw;
2924 	uint64_t rtt;
2925 	int gm_measure_cnt = 1;
2926 
2927 	/*
2928 	 * For startup we make, like google, a
2929 	 * minimum b/w. This is generated from the
2930 	 * IW and the rttProp. We do fall back to srtt
2931 	 * if for some reason (initial handshake) we don't
2932 	 * have a rttProp. We, in the worst case, fall back
2933 	 * to the configured min_bw (rc_initial_hptsi_bw).
2934 	 */
2935 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
2936 		/* Attempt first to use rttProp */
2937 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2938 		if (rtt && (rtt < 0xffffffff)) {
2939 measure:
2940 			min_bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2941 				((uint64_t)1000000);
2942 			min_bw /= rtt;
2943 			if (min_bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2944 				min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2945 			}
2946 
2947 		} else if (bbr->rc_tp->t_srtt != 0) {
2948 			/* No rttProp, use srtt? */
2949 			rtt = bbr_get_rtt(bbr, BBR_SRTT);
2950 			goto measure;
2951 		} else {
2952 			min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2953 		}
2954 	} else
2955 		min_bw = 0;
2956 
2957 	if ((bbr->rc_past_init_win == 0) &&
2958 	    (bbr->r_ctl.rc_delivered > bbr_initial_cwnd(bbr, bbr->rc_tp)))
2959 		bbr->rc_past_init_win = 1;
2960 	if ((bbr->rc_use_google)  && (bbr->r_ctl.r_measurement_count >= 1))
2961 		gm_measure_cnt = 0;
2962 	if (gm_measure_cnt &&
2963 	    ((bbr->r_ctl.r_measurement_count < bbr_min_measurements_req) ||
2964 	     (bbr->rc_past_init_win == 0))) {
2965 		/* For google we use our guess rate until we get 1 measurement */
2966 
2967 use_initial_window:
2968 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2969 		if (rtt && (rtt < 0xffffffff)) {
2970 			/*
2971 			 * We have an RTT measurment. Use that in
2972 			 * combination with our initial window to calculate
2973 			 * a b/w.
2974 			 */
2975 			bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2976 				((uint64_t)1000000);
2977 			bw /= rtt;
2978 			if (bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2979 				bw = bbr->r_ctl.rc_initial_hptsi_bw;
2980 			}
2981 		} else {
2982 			/* Drop back to the 40 and punt to a default */
2983 			bw = bbr->r_ctl.rc_initial_hptsi_bw;
2984 		}
2985 		if (bw < 1)
2986 			/* Probably should panic */
2987 			bw = 1;
2988 		if (bw > min_bw)
2989 			return (bw);
2990 		else
2991 			return (min_bw);
2992 	}
2993 	if (bbr->rc_lt_use_bw)
2994 		bw = bbr->r_ctl.rc_lt_bw;
2995 	else if (bbr->r_recovery_bw && (bbr->rc_use_google == 0))
2996 		bw = bbr->r_ctl.red_bw;
2997 	else
2998 		bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2999 	if (bbr->rc_tp->t_peakrate_thr && (bbr->rc_use_google == 0)) {
3000 		/*
3001 		 * Enforce user set rate limit, keep in mind that
3002 		 * t_peakrate_thr is in B/s already
3003 		 */
3004 		bw = uqmin((uint64_t)bbr->rc_tp->t_peakrate_thr, bw);
3005 	}
3006 	if (bw == 0) {
3007 		/* We should not be at 0, go to the initial window then  */
3008 		goto use_initial_window;
3009 	}
3010 	if (bw < 1)
3011 		/* Probably should panic */
3012 		bw = 1;
3013 	if (bw < min_bw)
3014 		bw = min_bw;
3015 	return (bw);
3016 }
3017 
3018 static inline uint64_t
3019 bbr_get_bw(struct tcp_bbr *bbr)
3020 {
3021 	uint64_t bw;
3022 
3023 	bw = __bbr_get_bw(bbr);
3024 	return (bw);
3025 }
3026 
3027 static inline void
3028 bbr_reset_lt_bw_interval(struct tcp_bbr *bbr, uint32_t cts)
3029 {
3030 	bbr->r_ctl.rc_lt_epoch = bbr->r_ctl.rc_pkt_epoch;
3031 	bbr->r_ctl.rc_lt_time = bbr->r_ctl.rc_del_time;
3032 	bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3033 	bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3034 }
3035 
3036 static inline void
3037 bbr_reset_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts)
3038 {
3039 	bbr->rc_lt_is_sampling = 0;
3040 	bbr->rc_lt_use_bw = 0;
3041 	bbr->r_ctl.rc_lt_bw = 0;
3042 	bbr_reset_lt_bw_interval(bbr, cts);
3043 }
3044 
3045 static inline void
3046 bbr_lt_bw_samp_done(struct tcp_bbr *bbr, uint64_t bw, uint32_t cts, uint32_t timin)
3047 {
3048 	uint64_t diff;
3049 
3050 	/* Do we have a previous sample? */
3051 	if (bbr->r_ctl.rc_lt_bw) {
3052 		/* Get the diff in bytes per second */
3053 		if (bbr->r_ctl.rc_lt_bw > bw)
3054 			diff = bbr->r_ctl.rc_lt_bw - bw;
3055 		else
3056 			diff = bw - bbr->r_ctl.rc_lt_bw;
3057 		if ((diff <= bbr_lt_bw_diff) ||
3058 		    (diff <= (bbr->r_ctl.rc_lt_bw / bbr_lt_bw_ratio))) {
3059 			/* Consider us policed */
3060 			uint32_t saved_bw;
3061 
3062 			saved_bw = (uint32_t)bbr->r_ctl.rc_lt_bw;
3063 			bbr->r_ctl.rc_lt_bw = (bw + bbr->r_ctl.rc_lt_bw) / 2;	/* average of two */
3064 			bbr->rc_lt_use_bw = 1;
3065 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
3066 			/*
3067 			 * Use pkt based epoch for measuring length of
3068 			 * policer up
3069 			 */
3070 			bbr->r_ctl.rc_lt_epoch_use = bbr->r_ctl.rc_pkt_epoch;
3071 			/*
3072 			 * reason 4 is we need to start consider being
3073 			 * policed
3074 			 */
3075 			bbr_log_type_ltbw(bbr, cts, 4, (uint32_t)bw, saved_bw, (uint32_t)diff, timin);
3076 			return;
3077 		}
3078 	}
3079 	bbr->r_ctl.rc_lt_bw = bw;
3080 	bbr_reset_lt_bw_interval(bbr, cts);
3081 	bbr_log_type_ltbw(bbr, cts, 5, 0, (uint32_t)bw, 0, timin);
3082 }
3083 
3084 static void
3085 bbr_randomize_extra_state_time(struct tcp_bbr *bbr)
3086 {
3087 	uint32_t ran, deduct;
3088 
3089 	ran = arc4random_uniform(bbr_rand_ot);
3090 	if (ran) {
3091 		deduct = bbr->r_ctl.rc_level_state_extra / ran;
3092 		bbr->r_ctl.rc_level_state_extra -= deduct;
3093 	}
3094 }
3095 /*
3096  * Return randomly the starting state
3097  * to use in probebw.
3098  */
3099 static uint8_t
3100 bbr_pick_probebw_substate(struct tcp_bbr *bbr, uint32_t cts)
3101 {
3102 	uint32_t ran;
3103 	uint8_t ret_val;
3104 
3105 	/* Initialize the offset to 0 */
3106 	bbr->r_ctl.rc_exta_time_gd = 0;
3107 	bbr->rc_hit_state_1 = 0;
3108 	bbr->r_ctl.rc_level_state_extra = 0;
3109 	ran = arc4random_uniform((BBR_SUBSTATE_COUNT-1));
3110 	/*
3111 	 * The math works funny here :) the return value is used to set the
3112 	 * substate and then the state change is called which increments by
3113 	 * one. So if we return 1 (DRAIN) we will increment to 2 (LEVEL1) when
3114 	 * we fully enter the state. Note that the (8 - 1 - ran) assures that
3115 	 * we return 1 - 7, so we dont return 0 and end up starting in
3116 	 * state 1 (DRAIN).
3117 	 */
3118 	ret_val = BBR_SUBSTATE_COUNT - 1 - ran;
3119 	/* Set an epoch */
3120 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP))
3121 		bbr_set_epoch(bbr, cts, __LINE__);
3122 
3123 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
3124 	return (ret_val);
3125 }
3126 
3127 static void
3128 bbr_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts, int32_t loss_detected)
3129 {
3130 	uint32_t diff, d_time;
3131 	uint64_t del_time, bw, lost, delivered;
3132 
3133 	if (bbr->r_use_policer == 0)
3134 		return;
3135 	if (bbr->rc_lt_use_bw) {
3136 		/* We are using lt bw do we stop yet? */
3137 		diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
3138 		if (diff > bbr_lt_bw_max_rtts) {
3139 			/* Reset it all */
3140 reset_all:
3141 			bbr_reset_lt_bw_sampling(bbr, cts);
3142 			if (bbr->rc_filled_pipe) {
3143 				bbr_set_epoch(bbr, cts, __LINE__);
3144 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
3145 				bbr_substate_change(bbr, cts, __LINE__, 0);
3146 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
3147 				bbr_log_type_statechange(bbr, cts, __LINE__);
3148 			} else {
3149 				/*
3150 				 * This should not happen really
3151 				 * unless we remove the startup/drain
3152 				 * restrictions above.
3153 				 */
3154 				bbr->rc_bbr_state = BBR_STATE_STARTUP;
3155 				bbr_set_epoch(bbr, cts, __LINE__);
3156 				bbr->r_ctl.rc_bbr_state_time = cts;
3157 				bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
3158 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
3159 				bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
3160 				bbr_set_state_target(bbr, __LINE__);
3161 				bbr_log_type_statechange(bbr, cts, __LINE__);
3162 			}
3163 			/* reason 0 is to stop using lt-bw */
3164 			bbr_log_type_ltbw(bbr, cts, 0, 0, 0, 0, 0);
3165 			return;
3166 		}
3167 		if (bbr_lt_intvl_fp == 0) {
3168 			/* Not doing false-postive detection */
3169 			return;
3170 		}
3171 		/* False positive detection */
3172 		if (diff == bbr_lt_intvl_fp) {
3173 			/* At bbr_lt_intvl_fp we record the lost */
3174 			bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3175 			bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3176 		} else if (diff > (bbr_lt_intvl_min_rtts + bbr_lt_intvl_fp)) {
3177 			/* Now is our loss rate still high? */
3178 			lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3179 			delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3180 			if ((delivered == 0) ||
3181 			    (((lost * 1000)/delivered) < bbr_lt_fd_thresh)) {
3182 				/* No still below our threshold */
3183 				bbr_log_type_ltbw(bbr, cts, 7, lost, delivered, 0, 0);
3184 			} else {
3185 				/* Yikes its still high, it must be a false positive */
3186 				bbr_log_type_ltbw(bbr, cts, 8, lost, delivered, 0, 0);
3187 				goto reset_all;
3188 			}
3189 		}
3190 		return;
3191 	}
3192 	/*
3193 	 * Wait for the first loss before sampling, to let the policer
3194 	 * exhaust its tokens and estimate the steady-state rate allowed by
3195 	 * the policer. Starting samples earlier includes bursts that
3196 	 * over-estimate the bw.
3197 	 */
3198 	if (bbr->rc_lt_is_sampling == 0) {
3199 		/* reason 1 is to begin doing the sampling  */
3200 		if (loss_detected == 0)
3201 			return;
3202 		bbr_reset_lt_bw_interval(bbr, cts);
3203 		bbr->rc_lt_is_sampling = 1;
3204 		bbr_log_type_ltbw(bbr, cts, 1, 0, 0, 0, 0);
3205 		return;
3206 	}
3207 	/* Now how long were we delivering long term last> */
3208 	if (TSTMP_GEQ(bbr->r_ctl.rc_del_time, bbr->r_ctl.rc_lt_time))
3209 		d_time = bbr->r_ctl.rc_del_time - bbr->r_ctl.rc_lt_time;
3210 	else
3211 		d_time = 0;
3212 
3213 	/* To avoid underestimates, reset sampling if we run out of data. */
3214 	if (bbr->r_ctl.r_app_limited_until) {
3215 		/* Can not measure in app-limited state */
3216 		bbr_reset_lt_bw_sampling(bbr, cts);
3217 		/* reason 2 is to reset sampling due to app limits  */
3218 		bbr_log_type_ltbw(bbr, cts, 2, 0, 0, 0, d_time);
3219 		return;
3220 	}
3221 	diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
3222 	if (diff < bbr_lt_intvl_min_rtts) {
3223 		/*
3224 		 * need more samples (we don't
3225 		 * start on a round like linux so
3226 		 * we need 1 more).
3227 		 */
3228 		/* 6 is not_enough time or no-loss */
3229 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3230 		return;
3231 	}
3232 	if (diff > (4 * bbr_lt_intvl_min_rtts)) {
3233 		/*
3234 		 * For now if we wait too long, reset all sampling. We need
3235 		 * to do some research here, its possible that we should
3236 		 * base this on how much loss as occurred.. something like
3237 		 * if its under 10% (or some thresh) reset all otherwise
3238 		 * don't.  Thats for phase II I guess.
3239 		 */
3240 		bbr_reset_lt_bw_sampling(bbr, cts);
3241  		/* reason 3 is to reset sampling due too long of sampling */
3242 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3243 		return;
3244 	}
3245 	/*
3246 	 * End sampling interval when a packet is lost, so we estimate the
3247 	 * policer tokens were exhausted. Stopping the sampling before the
3248 	 * tokens are exhausted under-estimates the policed rate.
3249 	 */
3250 	if (loss_detected == 0) {
3251 		/* 6 is not_enough time or no-loss */
3252 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3253 		return;
3254 	}
3255 	/* Calculate packets lost and delivered in sampling interval. */
3256 	lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3257 	delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3258 	if ((delivered == 0) ||
3259 	    (((lost * 1000)/delivered) < bbr_lt_loss_thresh)) {
3260 		bbr_log_type_ltbw(bbr, cts, 6, lost, delivered, 0, d_time);
3261 		return;
3262 	}
3263 	if (d_time < 1000) {
3264 		/* Not enough time. wait */
3265 		/* 6 is not_enough time or no-loss */
3266 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3267 		return;
3268 	}
3269 	if (d_time >= (0xffffffff / USECS_IN_MSEC)) {
3270 		/* Too long */
3271 		bbr_reset_lt_bw_sampling(bbr, cts);
3272  		/* reason 3 is to reset sampling due too long of sampling */
3273 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3274 		return;
3275 	}
3276 	del_time = d_time;
3277 	bw = delivered;
3278 	bw *= (uint64_t)USECS_IN_SECOND;
3279 	bw /= del_time;
3280 	bbr_lt_bw_samp_done(bbr, bw, cts, d_time);
3281 }
3282 
3283 /*
3284  * Allocate a sendmap from our zone.
3285  */
3286 static struct bbr_sendmap *
3287 bbr_alloc(struct tcp_bbr *bbr)
3288 {
3289 	struct bbr_sendmap *rsm;
3290 
3291 	BBR_STAT_INC(bbr_to_alloc);
3292 	rsm = uma_zalloc(bbr_zone, (M_NOWAIT | M_ZERO));
3293 	if (rsm) {
3294 		bbr->r_ctl.rc_num_maps_alloced++;
3295 		return (rsm);
3296 	}
3297 	if (bbr->r_ctl.rc_free_cnt) {
3298 		BBR_STAT_INC(bbr_to_alloc_emerg);
3299 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
3300 		TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
3301 		bbr->r_ctl.rc_free_cnt--;
3302 		return (rsm);
3303 	}
3304 	BBR_STAT_INC(bbr_to_alloc_failed);
3305 	return (NULL);
3306 }
3307 
3308 static struct bbr_sendmap *
3309 bbr_alloc_full_limit(struct tcp_bbr *bbr)
3310 {
3311 	if ((V_tcp_map_entries_limit > 0) &&
3312 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
3313 		BBR_STAT_INC(bbr_alloc_limited);
3314 		if (!bbr->alloc_limit_reported) {
3315 			bbr->alloc_limit_reported = 1;
3316 			BBR_STAT_INC(bbr_alloc_limited_conns);
3317 		}
3318 		return (NULL);
3319 	}
3320 	return (bbr_alloc(bbr));
3321 }
3322 
3323 /* wrapper to allocate a sendmap entry, subject to a specific limit */
3324 static struct bbr_sendmap *
3325 bbr_alloc_limit(struct tcp_bbr *bbr, uint8_t limit_type)
3326 {
3327 	struct bbr_sendmap *rsm;
3328 
3329 	if (limit_type) {
3330 		/* currently there is only one limit type */
3331 		if (V_tcp_map_split_limit > 0 &&
3332 		    bbr->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
3333 			BBR_STAT_INC(bbr_split_limited);
3334 			if (!bbr->alloc_limit_reported) {
3335 				bbr->alloc_limit_reported = 1;
3336 				BBR_STAT_INC(bbr_alloc_limited_conns);
3337 			}
3338 			return (NULL);
3339 		}
3340 	}
3341 
3342 	/* allocate and mark in the limit type, if set */
3343 	rsm = bbr_alloc(bbr);
3344 	if (rsm != NULL && limit_type) {
3345 		rsm->r_limit_type = limit_type;
3346 		bbr->r_ctl.rc_num_split_allocs++;
3347 	}
3348 	return (rsm);
3349 }
3350 
3351 static void
3352 bbr_free(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
3353 {
3354 	if (rsm->r_limit_type) {
3355 		/* currently there is only one limit type */
3356 		bbr->r_ctl.rc_num_split_allocs--;
3357 	}
3358 	if (rsm->r_is_smallmap)
3359 		bbr->r_ctl.rc_num_small_maps_alloced--;
3360 	if (bbr->r_ctl.rc_tlp_send == rsm)
3361 		bbr->r_ctl.rc_tlp_send = NULL;
3362 	if (bbr->r_ctl.rc_resend == rsm) {
3363 		bbr->r_ctl.rc_resend = NULL;
3364 	}
3365 	if (bbr->r_ctl.rc_next == rsm)
3366 		bbr->r_ctl.rc_next = NULL;
3367 	if (bbr->r_ctl.rc_sacklast == rsm)
3368 		bbr->r_ctl.rc_sacklast = NULL;
3369 	if (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
3370 		memset(rsm, 0, sizeof(struct bbr_sendmap));
3371 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
3372 		rsm->r_limit_type = 0;
3373 		bbr->r_ctl.rc_free_cnt++;
3374 		return;
3375 	}
3376 	bbr->r_ctl.rc_num_maps_alloced--;
3377 	uma_zfree(bbr_zone, rsm);
3378 }
3379 
3380 /*
3381  * Returns the BDP.
3382  */
3383 static uint64_t
3384 bbr_get_bw_delay_prod(uint64_t rtt, uint64_t bw) {
3385 	/*
3386 	 * Calculate the bytes in flight needed given the bw (in bytes per
3387 	 * second) and the specifyed rtt in useconds. We need to put out the
3388 	 * returned value per RTT to match that rate. Gain will normally
3389 	 * raise it up from there.
3390 	 *
3391 	 * This should not overflow as long as the bandwidth is below 1
3392 	 * TByte per second (bw < 10**12 = 2**40) and the rtt is smaller
3393 	 * than 1000 seconds (rtt < 10**3 * 10**6 = 10**9 = 2**30).
3394 	 */
3395 	uint64_t usec_per_sec;
3396 
3397 	usec_per_sec = USECS_IN_SECOND;
3398 	return ((rtt * bw) / usec_per_sec);
3399 }
3400 
3401 /*
3402  * Return the initial cwnd.
3403  */
3404 static uint32_t
3405 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp)
3406 {
3407 	uint32_t i_cwnd;
3408 
3409 	if (bbr->rc_init_win) {
3410 		i_cwnd = bbr->rc_init_win * tp->t_maxseg;
3411 	} else if (V_tcp_initcwnd_segments)
3412 		i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
3413 		    max(2 * tp->t_maxseg, 14600));
3414 	else if (V_tcp_do_rfc3390)
3415 		i_cwnd = min(4 * tp->t_maxseg,
3416 		    max(2 * tp->t_maxseg, 4380));
3417 	else {
3418 		/* Per RFC5681 Section 3.1 */
3419 		if (tp->t_maxseg > 2190)
3420 			i_cwnd = 2 * tp->t_maxseg;
3421 		else if (tp->t_maxseg > 1095)
3422 			i_cwnd = 3 * tp->t_maxseg;
3423 		else
3424 			i_cwnd = 4 * tp->t_maxseg;
3425 	}
3426 	return (i_cwnd);
3427 }
3428 
3429 /*
3430  * Given a specified gain, return the target
3431  * cwnd based on that gain.
3432  */
3433 static uint32_t
3434 bbr_get_raw_target_cwnd(struct tcp_bbr *bbr, uint32_t gain, uint64_t bw)
3435 {
3436 	uint64_t bdp, rtt;
3437 	uint32_t cwnd;
3438 
3439 	if ((get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) ||
3440 	    (bbr_get_full_bw(bbr) == 0)) {
3441 		/* No measurements yet */
3442 		return (bbr_initial_cwnd(bbr, bbr->rc_tp));
3443 	}
3444 	/*
3445 	 * Get bytes per RTT needed (rttProp is normally in
3446 	 * bbr_cwndtarget_rtt_touse)
3447 	 */
3448 	rtt = bbr_get_rtt(bbr, bbr_cwndtarget_rtt_touse);
3449 	/* Get the bdp from the two values */
3450 	bdp = bbr_get_bw_delay_prod(rtt, bw);
3451 	/* Now apply the gain */
3452 	cwnd = (uint32_t)(((bdp * ((uint64_t)gain)) + (uint64_t)(BBR_UNIT - 1)) / ((uint64_t)BBR_UNIT));
3453 
3454 	return (cwnd);
3455 }
3456 
3457 static uint32_t
3458 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain)
3459 {
3460 	uint32_t cwnd, mss;
3461 
3462 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
3463 	/* Get the base cwnd with gain rounded to a mss */
3464 	cwnd = roundup(bbr_get_raw_target_cwnd(bbr, bw, gain), mss);
3465 	/*
3466 	 * Add in N (2 default since we do not have a
3467 	 * fq layer to trap packets in) quanta's per the I-D
3468 	 * section 4.2.3.2 quanta adjust.
3469 	 */
3470 	cwnd += (bbr_quanta * bbr->r_ctl.rc_pace_max_segs);
3471 	if (bbr->rc_use_google) {
3472 		if((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3473 		   (bbr_state_val(bbr) == BBR_SUB_GAIN)) {
3474 			/*
3475 			 * The linux implementation adds
3476 			 * an extra 2 x mss in gain cycle which
3477 			 * is documented no-where except in the code.
3478 			 * so we add more for Neal undocumented feature
3479 			 */
3480 			cwnd += 2 * mss;
3481 		}
3482  		if ((cwnd / mss) & 0x1) {
3483 			/* Round up for odd num mss */
3484 			cwnd += mss;
3485 		}
3486 	}
3487 	/* Are we below the min cwnd? */
3488 	if (cwnd < get_min_cwnd(bbr))
3489 		return (get_min_cwnd(bbr));
3490 	return (cwnd);
3491 }
3492 
3493 static uint16_t
3494 bbr_gain_adjust(struct tcp_bbr *bbr, uint16_t gain)
3495 {
3496 	if (gain < 1)
3497 		gain = 1;
3498 	return (gain);
3499 }
3500 
3501 static uint32_t
3502 bbr_get_header_oh(struct tcp_bbr *bbr)
3503 {
3504 	int seg_oh;
3505 
3506 	seg_oh = 0;
3507 	if (bbr->r_ctl.rc_inc_tcp_oh) {
3508 		/* Do we include TCP overhead? */
3509 		seg_oh = (bbr->rc_last_options + sizeof(struct tcphdr));
3510 	}
3511 	if (bbr->r_ctl.rc_inc_ip_oh) {
3512 		/* Do we include IP overhead? */
3513 #ifdef INET6
3514 		if (bbr->r_is_v6)
3515 			seg_oh += sizeof(struct ip6_hdr);
3516 		else
3517 #endif
3518 #ifdef INET
3519 			seg_oh += sizeof(struct ip);
3520 #endif
3521 	}
3522 	if (bbr->r_ctl.rc_inc_enet_oh) {
3523 		/* Do we include the ethernet overhead?  */
3524 		seg_oh += sizeof(struct ether_header);
3525 	}
3526 	return(seg_oh);
3527 }
3528 
3529 static uint32_t
3530 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain, uint32_t useconds_time, uint64_t bw)
3531 {
3532 	uint64_t divor, res, tim;
3533 
3534 	if (useconds_time == 0)
3535 		return (0);
3536 	gain = bbr_gain_adjust(bbr, gain);
3537 	divor = (uint64_t)USECS_IN_SECOND * (uint64_t)BBR_UNIT;
3538 	tim = useconds_time;
3539 	res = (tim * bw * gain) / divor;
3540 	if (res == 0)
3541 		res = 1;
3542 	return ((uint32_t)res);
3543 }
3544 
3545 /*
3546  * Given a gain and a length return the delay in useconds that
3547  * should be used to evenly space out packets
3548  * on the connection (based on the gain factor).
3549  */
3550 static uint32_t
3551 bbr_get_pacing_delay(struct tcp_bbr *bbr, uint16_t gain, int32_t len, uint32_t cts, int nolog)
3552 {
3553 	uint64_t bw, lentim, res;
3554 	uint32_t usecs, srtt, over = 0;
3555 	uint32_t seg_oh, num_segs, maxseg;
3556 
3557 	if (len == 0)
3558 		return (0);
3559 
3560 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
3561 	num_segs = (len + maxseg - 1) / maxseg;
3562 	if (bbr->rc_use_google == 0) {
3563 		seg_oh = bbr_get_header_oh(bbr);
3564 		len += (num_segs * seg_oh);
3565 	}
3566 	gain = bbr_gain_adjust(bbr, gain);
3567 	bw = bbr_get_bw(bbr);
3568 	if (bbr->rc_use_google) {
3569 		uint64_t cbw;
3570 
3571 		/*
3572 		 * Reduce the b/w by the google discount
3573 		 * factor 10 = 1%.
3574 		 */
3575 		cbw = bw *  (uint64_t)(1000 - bbr->r_ctl.bbr_google_discount);
3576 		cbw /= (uint64_t)1000;
3577 		/* We don't apply a discount if it results in 0 */
3578 		if (cbw > 0)
3579 			bw = cbw;
3580 	}
3581 	lentim = ((uint64_t)len *
3582 		  (uint64_t)USECS_IN_SECOND *
3583 		  (uint64_t)BBR_UNIT);
3584 	res = lentim / ((uint64_t)gain * bw);
3585 	if (res == 0)
3586 		res = 1;
3587 	usecs = (uint32_t)res;
3588 	srtt = bbr_get_rtt(bbr, BBR_SRTT);
3589 	if (bbr_hptsi_max_mul && bbr_hptsi_max_div &&
3590 	    (bbr->rc_use_google == 0) &&
3591 	    (usecs > ((srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div))) {
3592 		/*
3593 		 * We cannot let the delay be more than 1/2 the srtt time.
3594 		 * Otherwise we cannot pace out or send properly.
3595 		 */
3596 		over = usecs = (srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div;
3597 		BBR_STAT_INC(bbr_hpts_min_time);
3598 	}
3599 	if (!nolog)
3600 		bbr_log_pacing_delay_calc(bbr, gain, len, cts, usecs, bw, over, 1);
3601 	return (usecs);
3602 }
3603 
3604 static void
3605 bbr_ack_received(struct tcpcb *tp, struct tcp_bbr *bbr, struct tcphdr *th, uint32_t bytes_this_ack,
3606 		 uint32_t sack_changed, uint32_t prev_acked, int32_t line, uint32_t losses)
3607 {
3608 	INP_WLOCK_ASSERT(tp->t_inpcb);
3609 	uint64_t bw;
3610 	uint32_t cwnd, target_cwnd, saved_bytes, maxseg;
3611 	int32_t meth;
3612 
3613 #ifdef STATS
3614 	if ((tp->t_flags & TF_GPUTINPROG) &&
3615 	    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
3616 		/*
3617 		 * Strech acks and compressed acks will cause this to
3618 		 * oscillate but we are doing it the same way as the main
3619 		 * stack so it will be compariable (though possibly not
3620 		 * ideal).
3621 		 */
3622 		int32_t cgput;
3623 		int64_t gput, time_stamp;
3624 
3625 		gput = (int64_t) (th->th_ack - tp->gput_seq) * 8;
3626 		time_stamp = max(1, ((bbr->r_ctl.rc_rcvtime - tp->gput_ts) / 1000));
3627 		cgput = gput / time_stamp;
3628 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
3629 					 cgput);
3630 		if (tp->t_stats_gput_prev > 0)
3631 			stats_voi_update_abs_s32(tp->t_stats,
3632 						 VOI_TCP_GPUT_ND,
3633 						 ((gput - tp->t_stats_gput_prev) * 100) /
3634 						 tp->t_stats_gput_prev);
3635 		tp->t_flags &= ~TF_GPUTINPROG;
3636 		tp->t_stats_gput_prev = cgput;
3637 	}
3638 #endif
3639 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3640 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
3641 		/* We don't change anything in probe-rtt */
3642 		return;
3643 	}
3644 	maxseg = tp->t_maxseg - bbr->rc_last_options;
3645 	saved_bytes = bytes_this_ack;
3646 	bytes_this_ack += sack_changed;
3647 	if (bytes_this_ack > prev_acked) {
3648 		bytes_this_ack -= prev_acked;
3649 		/*
3650 		 * A byte ack'd gives us a full mss
3651 		 * to be like linux i.e. they count packets.
3652 		 */
3653 		if ((bytes_this_ack < maxseg) && bbr->rc_use_google)
3654 			bytes_this_ack = maxseg;
3655 	} else {
3656 		/* Unlikely */
3657 		bytes_this_ack = 0;
3658 	}
3659 	cwnd = tp->snd_cwnd;
3660 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3661 	if (bw)
3662 		target_cwnd = bbr_get_target_cwnd(bbr,
3663 						  bw,
3664 						  (uint32_t)bbr->r_ctl.rc_bbr_cwnd_gain);
3665 	else
3666 		target_cwnd = bbr_initial_cwnd(bbr, bbr->rc_tp);
3667 	if (IN_RECOVERY(tp->t_flags) &&
3668 	    (bbr->bbr_prev_in_rec == 0)) {
3669 		/*
3670 		 * We are entering recovery and
3671 		 * thus packet conservation.
3672 		 */
3673 		bbr->pkt_conservation = 1;
3674 		bbr->r_ctl.rc_recovery_start = bbr->r_ctl.rc_rcvtime;
3675 		cwnd = ctf_flight_size(tp,
3676 				       (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3677 			bytes_this_ack;
3678 	}
3679 	if (IN_RECOVERY(tp->t_flags)) {
3680 		uint32_t flight;
3681 
3682 		bbr->bbr_prev_in_rec = 1;
3683 		if (cwnd > losses) {
3684 			cwnd -= losses;
3685 			if (cwnd < maxseg)
3686 				cwnd = maxseg;
3687 		} else
3688 			cwnd = maxseg;
3689 		flight = ctf_flight_size(tp,
3690 					 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3691 		bbr_log_type_cwndupd(bbr, flight, 0,
3692 				     losses, 10, 0, 0, line);
3693 		if (bbr->pkt_conservation) {
3694 			uint32_t time_in;
3695 
3696 			if (TSTMP_GEQ(bbr->r_ctl.rc_rcvtime, bbr->r_ctl.rc_recovery_start))
3697 				time_in = bbr->r_ctl.rc_rcvtime - bbr->r_ctl.rc_recovery_start;
3698 			else
3699 				time_in = 0;
3700 
3701 			if (time_in >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
3702 				/* Clear packet conservation after an rttProp */
3703 				bbr->pkt_conservation = 0;
3704 			} else {
3705 				if ((flight + bytes_this_ack) > cwnd)
3706 					cwnd = flight + bytes_this_ack;
3707 				if (cwnd < get_min_cwnd(bbr))
3708 					cwnd = get_min_cwnd(bbr);
3709 				tp->snd_cwnd = cwnd;
3710 				bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed,
3711 						     prev_acked, 1, target_cwnd, th->th_ack, line);
3712 				return;
3713 			}
3714 		}
3715 	} else
3716 		bbr->bbr_prev_in_rec = 0;
3717 	if ((bbr->rc_use_google == 0) && bbr->r_ctl.restrict_growth) {
3718 		bbr->r_ctl.restrict_growth--;
3719 		if (bytes_this_ack > maxseg)
3720 			bytes_this_ack = maxseg;
3721 	}
3722 	if (bbr->rc_filled_pipe) {
3723 		/*
3724 		 * Here we have exited startup and filled the pipe. We will
3725 		 * thus allow the cwnd to shrink to the target. We hit here
3726 		 * mostly.
3727 		 */
3728 		uint32_t s_cwnd;
3729 
3730 		meth = 2;
3731 		s_cwnd = min((cwnd + bytes_this_ack), target_cwnd);
3732 		if (s_cwnd > cwnd)
3733 			cwnd = s_cwnd;
3734 		else if (bbr_cwnd_may_shrink || bbr->rc_use_google || bbr->rc_no_pacing)
3735 			cwnd = s_cwnd;
3736 	} else {
3737 		/*
3738 		 * Here we are still in startup, we increase cwnd by what
3739 		 * has been acked.
3740 		 */
3741 		if ((cwnd < target_cwnd) ||
3742 		    (bbr->rc_past_init_win == 0)) {
3743 			meth = 3;
3744 			cwnd += bytes_this_ack;
3745 		} else {
3746 			/*
3747 			 * Method 4 means we are at target so no gain in
3748 			 * startup and past the initial window.
3749 			 */
3750 			meth = 4;
3751 		}
3752 	}
3753 	tp->snd_cwnd = max(cwnd, get_min_cwnd(bbr));
3754 	bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed, prev_acked, meth, target_cwnd, th->th_ack, line);
3755 }
3756 
3757 static void
3758 tcp_bbr_partialack(struct tcpcb *tp)
3759 {
3760 	struct tcp_bbr *bbr;
3761 
3762 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3763 	INP_WLOCK_ASSERT(tp->t_inpcb);
3764 	if (ctf_flight_size(tp,
3765 		(bbr->r_ctl.rc_sacked  + bbr->r_ctl.rc_lost_bytes)) <=
3766 	    tp->snd_cwnd) {
3767 		bbr->r_wanted_output = 1;
3768 	}
3769 }
3770 
3771 static void
3772 bbr_post_recovery(struct tcpcb *tp)
3773 {
3774 	struct tcp_bbr *bbr;
3775 	uint32_t  flight;
3776 
3777 	INP_WLOCK_ASSERT(tp->t_inpcb);
3778 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3779 	/*
3780 	 * Here we just exit recovery.
3781 	 */
3782 	EXIT_RECOVERY(tp->t_flags);
3783 	/* Lock in our b/w reduction for the specified number of pkt-epochs */
3784 	bbr->r_recovery_bw = 0;
3785 	tp->snd_recover = tp->snd_una;
3786 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3787 	bbr->pkt_conservation = 0;
3788 	if (bbr->rc_use_google == 0) {
3789 		/*
3790 		 * For non-google mode lets
3791 		 * go ahead and make sure we clear
3792 		 * the recovery state so if we
3793 		 * bounce back in to recovery we
3794 		 * will do PC.
3795 		 */
3796 		bbr->bbr_prev_in_rec = 0;
3797 	}
3798 	bbr_log_type_exit_rec(bbr);
3799 	if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3800 		tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3801 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 15, 0, 0, __LINE__);
3802 	} else {
3803 		/* For probe-rtt case lets fix up its saved_cwnd */
3804 		if (bbr->r_ctl.rc_saved_cwnd < bbr->r_ctl.rc_cwnd_on_ent) {
3805 			bbr->r_ctl.rc_saved_cwnd = bbr->r_ctl.rc_cwnd_on_ent;
3806 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 16, 0, 0, __LINE__);
3807 		}
3808 	}
3809 	flight = ctf_flight_size(tp,
3810 		     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3811 	if ((bbr->rc_use_google == 0) &&
3812 	    bbr_do_red) {
3813 		uint64_t val, lr2use;
3814 		uint32_t maxseg, newcwnd, acks_inflight, ratio, cwnd;
3815 		uint32_t *cwnd_p;
3816 
3817 		if (bbr_get_rtt(bbr, BBR_SRTT)) {
3818 			val = ((uint64_t)bbr_get_rtt(bbr, BBR_RTT_PROP) * (uint64_t)1000);
3819 			val /= bbr_get_rtt(bbr, BBR_SRTT);
3820 			ratio = (uint32_t)val;
3821 		} else
3822 			ratio = 1000;
3823 
3824 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div,
3825 				     bbr->r_ctl.recovery_lr, 21,
3826 				     ratio,
3827 				     bbr->r_ctl.rc_red_cwnd_pe,
3828 				     __LINE__);
3829 		if ((ratio < bbr_do_red) || (bbr_do_red == 0))
3830 			goto done;
3831 		if (((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3832 		     bbr_prtt_slam_cwnd) ||
3833 		    (bbr_sub_drain_slam_cwnd &&
3834 		     (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3835 		     bbr->rc_hit_state_1 &&
3836 		     (bbr_state_val(bbr) == BBR_SUB_DRAIN)) ||
3837 		    ((bbr->rc_bbr_state == BBR_STATE_DRAIN) &&
3838 		     bbr_slam_cwnd_in_main_drain)) {
3839 			/*
3840 			 * Here we must poke at the saved cwnd
3841 			 * as well as the cwnd.
3842 			 */
3843 			cwnd = bbr->r_ctl.rc_saved_cwnd;
3844 			cwnd_p = &bbr->r_ctl.rc_saved_cwnd;
3845 		} else {
3846  			cwnd = tp->snd_cwnd;
3847 			cwnd_p = &tp->snd_cwnd;
3848 		}
3849 		maxseg = tp->t_maxseg - bbr->rc_last_options;
3850 		/* Add the overall lr with the recovery lr */
3851 		if (bbr->r_ctl.rc_lost == 0)
3852 			lr2use = 0;
3853 		else if (bbr->r_ctl.rc_delivered == 0)
3854 			lr2use = 1000;
3855 		else {
3856 			lr2use = bbr->r_ctl.rc_lost * 1000;
3857 			lr2use /= bbr->r_ctl.rc_delivered;
3858 		}
3859 		lr2use += bbr->r_ctl.recovery_lr;
3860 		acks_inflight = (flight / (maxseg * 2));
3861 		if (bbr_red_scale) {
3862 			lr2use *= bbr_get_rtt(bbr, BBR_SRTT);
3863 			lr2use /= bbr_red_scale;
3864 			if ((bbr_red_growth_restrict) &&
3865 			    ((bbr_get_rtt(bbr, BBR_SRTT)/bbr_red_scale) > 1))
3866 			    bbr->r_ctl.restrict_growth += acks_inflight;
3867 		}
3868 		if (lr2use) {
3869 			val = (uint64_t)cwnd * lr2use;
3870 			val /= 1000;
3871 			if (cwnd > val)
3872 				newcwnd = roundup((cwnd - val), maxseg);
3873 			else
3874 				newcwnd = maxseg;
3875 		} else {
3876 			val = (uint64_t)cwnd * (uint64_t)bbr_red_mul;
3877 			val /= (uint64_t)bbr_red_div;
3878 			newcwnd = roundup((uint32_t)val, maxseg);
3879 		}
3880 		/* with standard delayed acks how many acks can I expect? */
3881 		if (bbr_drop_limit == 0) {
3882 			/*
3883 			 * Anticpate how much we will
3884 			 * raise the cwnd based on the acks.
3885 			 */
3886 			if ((newcwnd + (acks_inflight * maxseg)) < get_min_cwnd(bbr)) {
3887 				/* We do enforce the min (with the acks) */
3888 				newcwnd = (get_min_cwnd(bbr) - acks_inflight);
3889 			}
3890 		} else {
3891 			/*
3892 			 * A strict drop limit of N is is inplace
3893 			 */
3894 			if (newcwnd < (bbr_drop_limit * maxseg)) {
3895 				newcwnd = bbr_drop_limit * maxseg;
3896 			}
3897 		}
3898 		/* For the next N acks do we restrict the growth */
3899 		*cwnd_p = newcwnd;
3900 		if (tp->snd_cwnd > newcwnd)
3901 			tp->snd_cwnd = newcwnd;
3902 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div, val, 22,
3903 				     (uint32_t)lr2use,
3904 				     bbr_get_rtt(bbr, BBR_SRTT), __LINE__);
3905 		bbr->r_ctl.rc_red_cwnd_pe = bbr->r_ctl.rc_pkt_epoch;
3906 	}
3907 done:
3908 	bbr->r_ctl.recovery_lr = 0;
3909 	if (flight <= tp->snd_cwnd) {
3910 		bbr->r_wanted_output = 1;
3911 	}
3912 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3913 }
3914 
3915 static void
3916 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts)
3917 {
3918 	bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3919 	/* Limit the drop in b/w to 1/2 our current filter. */
3920 	if (bbr->r_ctl.red_bw > bbr->r_ctl.rc_bbr_cur_del_rate)
3921 		bbr->r_ctl.red_bw = bbr->r_ctl.rc_bbr_cur_del_rate;
3922 	if (bbr->r_ctl.red_bw < (get_filter_value(&bbr->r_ctl.rc_delrate) / 2))
3923 		bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate) / 2;
3924 	tcp_bbr_tso_size_check(bbr, cts);
3925 }
3926 
3927 static void
3928 bbr_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type, struct bbr_sendmap *rsm)
3929 {
3930 	struct tcp_bbr *bbr;
3931 
3932 	INP_WLOCK_ASSERT(tp->t_inpcb);
3933 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3934 	switch (type) {
3935 	case CC_NDUPACK:
3936 		if (!IN_RECOVERY(tp->t_flags)) {
3937 			tp->snd_recover = tp->snd_max;
3938 			/* Start a new epoch */
3939 			bbr_set_pktepoch(bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
3940 			if (bbr->rc_lt_is_sampling || bbr->rc_lt_use_bw) {
3941 				/*
3942 				 * Move forward the lt epoch
3943 				 * so it won't count the truncated
3944 				 * epoch.
3945 				 */
3946 				bbr->r_ctl.rc_lt_epoch++;
3947 			}
3948 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
3949 				/*
3950 				 * Just like the policer detection code
3951 				 * if we are in startup we must push
3952 				 * forward the last startup epoch
3953 				 * to hide the truncated PE.
3954 				 */
3955 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
3956 			}
3957 			bbr->r_ctl.rc_cwnd_on_ent = tp->snd_cwnd;
3958 			ENTER_RECOVERY(tp->t_flags);
3959 			bbr->rc_tlp_rtx_out = 0;
3960 			bbr->r_ctl.recovery_lr = bbr->r_ctl.rc_pkt_epoch_loss_rate;
3961 			tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3962 			if (bbr->rc_inp->inp_in_hpts &&
3963 			    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) == 0)) {
3964 				/*
3965 				 * When we enter recovery, we need to restart
3966 				 * any timers. This may mean we gain an agg
3967 				 * early, which will be made up for at the last
3968 				 * rxt out.
3969 				 */
3970 				bbr->rc_timer_first = 1;
3971 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
3972 			}
3973 			/*
3974 			 * Calculate a new cwnd based on to the current
3975 			 * delivery rate with no gain. We get the bdp
3976 			 * without gaining it up like we normally would and
3977 			 * we use the last cur_del_rate.
3978 			 */
3979 			if ((bbr->rc_use_google == 0) &&
3980 			    (bbr->r_ctl.bbr_rttprobe_gain_val ||
3981 			     (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT))) {
3982 				tp->snd_cwnd = ctf_flight_size(tp,
3983 					           (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3984 					(tp->t_maxseg - bbr->rc_last_options);
3985 				if (tp->snd_cwnd < get_min_cwnd(bbr)) {
3986 					/* We always gate to min cwnd */
3987 					tp->snd_cwnd = get_min_cwnd(bbr);
3988 				}
3989 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 14, 0, 0, __LINE__);
3990 			}
3991 			bbr_log_type_enter_rec(bbr, rsm->r_start);
3992 		}
3993 		break;
3994 	case CC_RTO_ERR:
3995 		KMOD_TCPSTAT_INC(tcps_sndrexmitbad);
3996 		/* RTO was unnecessary, so reset everything. */
3997 		bbr_reset_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime);
3998 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3999 			tp->snd_cwnd = tp->snd_cwnd_prev;
4000 			tp->snd_ssthresh = tp->snd_ssthresh_prev;
4001 			tp->snd_recover = tp->snd_recover_prev;
4002 			tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
4003 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 13, 0, 0, __LINE__);
4004 		}
4005 		tp->t_badrxtwin = 0;
4006 		break;
4007 	}
4008 }
4009 
4010 /*
4011  * Indicate whether this ack should be delayed.  We can delay the ack if
4012  * following conditions are met:
4013  *	- There is no delayed ack timer in progress.
4014  *	- Our last ack wasn't a 0-sized window. We never want to delay
4015  *	  the ack that opens up a 0-sized window.
4016  *	- LRO wasn't used for this segment. We make sure by checking that the
4017  *	  segment size is not larger than the MSS.
4018  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
4019  *	  connection.
4020  *	- The data being acked is less than a full segment (a stretch ack
4021  *        of more than a segment we should ack.
4022  *      - nsegs is 1 (if its more than that we received more than 1 ack).
4023  */
4024 #define DELAY_ACK(tp, bbr, nsegs)				\
4025 	(((tp->t_flags & TF_RXWIN0SENT) == 0) &&		\
4026 	 ((tp->t_flags & TF_DELACK) == 0) && 		 	\
4027 	 ((bbr->bbr_segs_rcvd + nsegs) < tp->t_delayed_ack) &&	\
4028 	 (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4029 
4030 /*
4031  * Return the lowest RSM in the map of
4032  * packets still in flight that is not acked.
4033  * This should normally find on the first one
4034  * since we remove packets from the send
4035  * map after they are marked ACKED.
4036  */
4037 static struct bbr_sendmap *
4038 bbr_find_lowest_rsm(struct tcp_bbr *bbr)
4039 {
4040 	struct bbr_sendmap *rsm;
4041 
4042 	/*
4043 	 * Walk the time-order transmitted list looking for an rsm that is
4044 	 * not acked. This will be the one that was sent the longest time
4045 	 * ago that is still outstanding.
4046 	 */
4047 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_tmap, r_tnext) {
4048 		if (rsm->r_flags & BBR_ACKED) {
4049 			continue;
4050 		}
4051 		goto finish;
4052 	}
4053 finish:
4054 	return (rsm);
4055 }
4056 
4057 static struct bbr_sendmap *
4058 bbr_find_high_nonack(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
4059 {
4060 	struct bbr_sendmap *prsm;
4061 
4062 	/*
4063 	 * Walk the sequence order list backward until we hit and arrive at
4064 	 * the highest seq not acked. In theory when this is called it
4065 	 * should be the last segment (which it was not).
4066 	 */
4067 	prsm = rsm;
4068 	TAILQ_FOREACH_REVERSE_FROM(prsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4069 		if (prsm->r_flags & (BBR_ACKED | BBR_HAS_FIN)) {
4070 			continue;
4071 		}
4072 		return (prsm);
4073 	}
4074 	return (NULL);
4075 }
4076 
4077 /*
4078  * Returns to the caller the number of microseconds that
4079  * the packet can be outstanding before we think we
4080  * should have had an ack returned.
4081  */
4082 static uint32_t
4083 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm)
4084 {
4085 	/*
4086 	 * lro is the flag we use to determine if we have seen reordering.
4087 	 * If it gets set we have seen reordering. The reorder logic either
4088 	 * works in one of two ways:
4089 	 *
4090 	 * If reorder-fade is configured, then we track the last time we saw
4091 	 * re-ordering occur. If we reach the point where enough time as
4092 	 * passed we no longer consider reordering has occuring.
4093 	 *
4094 	 * Or if reorder-face is 0, then once we see reordering we consider
4095 	 * the connection to alway be subject to reordering and just set lro
4096 	 * to 1.
4097 	 *
4098 	 * In the end if lro is non-zero we add the extra time for
4099 	 * reordering in.
4100 	 */
4101 	int32_t lro;
4102 	uint32_t thresh, t_rxtcur;
4103 
4104 	if (srtt == 0)
4105 		srtt = 1;
4106 	if (bbr->r_ctl.rc_reorder_ts) {
4107 		if (bbr->r_ctl.rc_reorder_fade) {
4108 			if (SEQ_GEQ(cts, bbr->r_ctl.rc_reorder_ts)) {
4109 				lro = cts - bbr->r_ctl.rc_reorder_ts;
4110 				if (lro == 0) {
4111 					/*
4112 					 * No time as passed since the last
4113 					 * reorder, mark it as reordering.
4114 					 */
4115 					lro = 1;
4116 				}
4117 			} else {
4118 				/* Negative time? */
4119 				lro = 0;
4120 			}
4121 			if (lro > bbr->r_ctl.rc_reorder_fade) {
4122 				/* Turn off reordering seen too */
4123 				bbr->r_ctl.rc_reorder_ts = 0;
4124 				lro = 0;
4125 			}
4126 		} else {
4127 			/* Reodering does not fade */
4128 			lro = 1;
4129 		}
4130 	} else {
4131 		lro = 0;
4132 	}
4133 	thresh = srtt + bbr->r_ctl.rc_pkt_delay;
4134 	if (lro) {
4135 		/* It must be set, if not you get 1/4 rtt */
4136 		if (bbr->r_ctl.rc_reorder_shift)
4137 			thresh += (srtt >> bbr->r_ctl.rc_reorder_shift);
4138 		else
4139 			thresh += (srtt >> 2);
4140 	} else {
4141 		thresh += 1000;
4142 	}
4143 	/* We don't let the rack timeout be above a RTO */
4144 	if ((bbr->rc_tp)->t_srtt == 0)
4145 		t_rxtcur = BBR_INITIAL_RTO;
4146 	else
4147 		t_rxtcur = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
4148 	if (thresh > t_rxtcur) {
4149 		thresh = t_rxtcur;
4150 	}
4151 	/* And we don't want it above the RTO max either */
4152 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4153 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4154 	}
4155 	bbr_log_thresh_choice(bbr, cts, thresh, lro, srtt, rsm, BBR_TO_FRM_RACK);
4156 	return (thresh);
4157 }
4158 
4159 /*
4160  * Return to the caller the amount of time in mico-seconds
4161  * that should be used for the TLP timer from the last
4162  * send time of this packet.
4163  */
4164 static uint32_t
4165 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
4166     struct bbr_sendmap *rsm, uint32_t srtt,
4167     uint32_t cts)
4168 {
4169 	uint32_t thresh, len, maxseg, t_rxtcur;
4170 	struct bbr_sendmap *prsm;
4171 
4172 	if (srtt == 0)
4173 		srtt = 1;
4174 	if (bbr->rc_tlp_threshold)
4175 		thresh = srtt + (srtt / bbr->rc_tlp_threshold);
4176 	else
4177 		thresh = (srtt * 2);
4178 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4179 	/* Get the previous sent packet, if any  */
4180 	len = rsm->r_end - rsm->r_start;
4181 
4182 	/* 2.1 behavior */
4183 	prsm = TAILQ_PREV(rsm, bbr_head, r_tnext);
4184 	if (prsm && (len <= maxseg)) {
4185 		/*
4186 		 * Two packets outstanding, thresh should be (2*srtt) +
4187 		 * possible inter-packet delay (if any).
4188 		 */
4189 		uint32_t inter_gap = 0;
4190 		int idx, nidx;
4191 
4192 		idx = rsm->r_rtr_cnt - 1;
4193 		nidx = prsm->r_rtr_cnt - 1;
4194 		if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
4195 			/* Yes it was sent later (or at the same time) */
4196 			inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
4197 		}
4198 		thresh += inter_gap;
4199 	} else if (len <= maxseg) {
4200 		/*
4201 		 * Possibly compensate for delayed-ack.
4202 		 */
4203 		uint32_t alt_thresh;
4204 
4205 		alt_thresh = srtt + (srtt / 2) + bbr_delayed_ack_time;
4206 		if (alt_thresh > thresh)
4207 			thresh = alt_thresh;
4208 	}
4209 	/* Not above the current  RTO */
4210 	if (tp->t_srtt == 0)
4211 		t_rxtcur = BBR_INITIAL_RTO;
4212 	else
4213 		t_rxtcur = TICKS_2_USEC(tp->t_rxtcur);
4214 
4215 	bbr_log_thresh_choice(bbr, cts, thresh, t_rxtcur, srtt, rsm, BBR_TO_FRM_TLP);
4216 	/* Not above an RTO */
4217 	if (thresh > t_rxtcur) {
4218 		thresh = t_rxtcur;
4219 	}
4220 	/* Not above a RTO max */
4221 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4222 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4223 	}
4224 	/* And now apply the user TLP min */
4225 	if (thresh < bbr_tlp_min) {
4226 		thresh = bbr_tlp_min;
4227 	}
4228 	return (thresh);
4229 }
4230 
4231 /*
4232  * Return one of three RTTs to use (in microseconds).
4233  */
4234 static __inline uint32_t
4235 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type)
4236 {
4237 	uint32_t f_rtt;
4238 	uint32_t srtt;
4239 
4240 	f_rtt = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
4241 	if (get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) {
4242 		/* We have no rtt at all */
4243 		if (bbr->rc_tp->t_srtt == 0)
4244 			f_rtt = BBR_INITIAL_RTO;
4245 		else
4246 			f_rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4247 		/*
4248 		 * Since we don't know how good the rtt is apply a
4249 		 * delayed-ack min
4250 		 */
4251 		if (f_rtt < bbr_delayed_ack_time) {
4252 			f_rtt = bbr_delayed_ack_time;
4253 		}
4254 	}
4255 	/* Take the filter version or last measured pkt-rtt */
4256 	if (rtt_type == BBR_RTT_PROP) {
4257 		srtt = f_rtt;
4258 	} else if (rtt_type == BBR_RTT_PKTRTT) {
4259 		if (bbr->r_ctl.rc_pkt_epoch_rtt) {
4260 			srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
4261 		} else {
4262 			/* No pkt rtt yet */
4263 			srtt = f_rtt;
4264 		}
4265 	} else if (rtt_type == BBR_RTT_RACK) {
4266 		srtt = bbr->r_ctl.rc_last_rtt;
4267 		/* We need to add in any internal delay for our timer */
4268 		if (bbr->rc_ack_was_delayed)
4269 			srtt += bbr->r_ctl.rc_ack_hdwr_delay;
4270 	} else if (rtt_type == BBR_SRTT) {
4271 		srtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4272 	} else {
4273 		/* TSNH */
4274 		srtt = f_rtt;
4275 #ifdef BBR_INVARIANTS
4276 		panic("Unknown rtt request type %d", rtt_type);
4277 #endif
4278 	}
4279 	return (srtt);
4280 }
4281 
4282 static int
4283 bbr_is_lost(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t cts)
4284 {
4285 	uint32_t thresh;
4286 
4287 	thresh = bbr_calc_thresh_rack(bbr, bbr_get_rtt(bbr, BBR_RTT_RACK),
4288 				      cts, rsm);
4289 	if ((cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)]) >= thresh) {
4290 		/* It is lost (past time) */
4291 		return (1);
4292 	}
4293 	return (0);
4294 }
4295 
4296 /*
4297  * Return a sendmap if we need to retransmit something.
4298  */
4299 static struct bbr_sendmap *
4300 bbr_check_recovery_mode(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4301 {
4302 	/*
4303 	 * Check to see that we don't need to fall into recovery. We will
4304 	 * need to do so if our oldest transmit is past the time we should
4305 	 * have had an ack.
4306 	 */
4307 
4308 	struct bbr_sendmap *rsm;
4309 	int32_t idx;
4310 
4311 	if (TAILQ_EMPTY(&bbr->r_ctl.rc_map)) {
4312 		/* Nothing outstanding that we know of */
4313 		return (NULL);
4314 	}
4315 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
4316 	if (rsm == NULL) {
4317 		/* Nothing in the transmit map */
4318 		return (NULL);
4319 	}
4320 	if (tp->t_flags & TF_SENTFIN) {
4321 		/* Fin restricted, don't find anything once a fin is sent */
4322 		return (NULL);
4323 	}
4324 	if (rsm->r_flags & BBR_ACKED) {
4325 		/*
4326 		 * Ok the first one is acked (this really should not happen
4327 		 * since we remove the from the tmap once they are acked)
4328 		 */
4329 		rsm = bbr_find_lowest_rsm(bbr);
4330 		if (rsm == NULL)
4331 			return (NULL);
4332 	}
4333 	idx = rsm->r_rtr_cnt - 1;
4334 	if (SEQ_LEQ(cts, rsm->r_tim_lastsent[idx])) {
4335 		/* Send timestamp is the same or less? can't be ready */
4336 		return (NULL);
4337 	}
4338 	/* Get our RTT time */
4339 	if (bbr_is_lost(bbr, rsm, cts) &&
4340 	    ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
4341 	     (rsm->r_flags & BBR_SACK_PASSED))) {
4342 		if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4343 			rsm->r_flags |= BBR_MARKED_LOST;
4344 			bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4345 			bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4346 		}
4347 		bbr_cong_signal(tp, NULL, CC_NDUPACK, rsm);
4348 #ifdef BBR_INVARIANTS
4349 		if ((rsm->r_end - rsm->r_start) == 0)
4350 			panic("tp:%p bbr:%p rsm:%p length is 0?", tp, bbr, rsm);
4351 #endif
4352 		return (rsm);
4353 	}
4354 	return (NULL);
4355 }
4356 
4357 /*
4358  * RACK Timer, here we simply do logging and house keeping.
4359  * the normal bbr_output_wtime() function will call the
4360  * appropriate thing to check if we need to do a RACK retransmit.
4361  * We return 1, saying don't proceed with bbr_output_wtime only
4362  * when all timers have been stopped (destroyed PCB?).
4363  */
4364 static int
4365 bbr_timeout_rack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4366 {
4367 	/*
4368 	 * This timer simply provides an internal trigger to send out data.
4369 	 * The check_recovery_mode call will see if there are needed
4370 	 * retransmissions, if so we will enter fast-recovery. The output
4371 	 * call may or may not do the same thing depending on sysctl
4372 	 * settings.
4373 	 */
4374 	uint32_t lost;
4375 
4376 	if (bbr->rc_all_timers_stopped) {
4377 		return (1);
4378 	}
4379 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4380 		/* Its not time yet */
4381 		return (0);
4382 	}
4383 	BBR_STAT_INC(bbr_to_tot);
4384 	lost = bbr->r_ctl.rc_lost;
4385 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4386 		bbr_set_state(tp, bbr, 0);
4387 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_RACK);
4388 	if (bbr->r_ctl.rc_resend == NULL) {
4389 		/* Lets do the check here */
4390 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
4391 	}
4392 	if (bbr_policer_call_from_rack_to)
4393 		bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4394 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
4395 	return (0);
4396 }
4397 
4398 static __inline void
4399 bbr_clone_rsm(struct tcp_bbr *bbr, struct bbr_sendmap *nrsm, struct bbr_sendmap *rsm, uint32_t start)
4400 {
4401 	int idx;
4402 
4403 	nrsm->r_start = start;
4404 	nrsm->r_end = rsm->r_end;
4405 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4406 	nrsm->r_flags = rsm->r_flags;
4407 	/* We don't transfer forward the SYN flag */
4408 	nrsm->r_flags &= ~BBR_HAS_SYN;
4409 	/* We move forward the FIN flag, not that this should happen */
4410 	rsm->r_flags &= ~BBR_HAS_FIN;
4411 	nrsm->r_dupack = rsm->r_dupack;
4412 	nrsm->r_rtr_bytes = 0;
4413 	nrsm->r_is_gain = rsm->r_is_gain;
4414 	nrsm->r_is_drain = rsm->r_is_drain;
4415 	nrsm->r_delivered = rsm->r_delivered;
4416 	nrsm->r_ts_valid = rsm->r_ts_valid;
4417 	nrsm->r_del_ack_ts = rsm->r_del_ack_ts;
4418 	nrsm->r_del_time = rsm->r_del_time;
4419 	nrsm->r_app_limited = rsm->r_app_limited;
4420 	nrsm->r_first_sent_time = rsm->r_first_sent_time;
4421 	nrsm->r_flight_at_send = rsm->r_flight_at_send;
4422 	/* We split a piece the lower section looses any just_ret flag. */
4423 	nrsm->r_bbr_state = rsm->r_bbr_state;
4424 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4425 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4426 	}
4427 	rsm->r_end = nrsm->r_start;
4428 	idx = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
4429 	idx /= 8;
4430 	/* Check if we got too small */
4431 	if ((rsm->r_is_smallmap == 0) &&
4432 	    ((rsm->r_end - rsm->r_start) <= idx)) {
4433 		bbr->r_ctl.rc_num_small_maps_alloced++;
4434 		rsm->r_is_smallmap = 1;
4435 	}
4436 	/* Check the new one as well */
4437 	if ((nrsm->r_end - nrsm->r_start) <= idx) {
4438 		bbr->r_ctl.rc_num_small_maps_alloced++;
4439 		nrsm->r_is_smallmap = 1;
4440 	}
4441 }
4442 
4443 static int
4444 bbr_sack_mergable(struct bbr_sendmap *at,
4445 		  uint32_t start, uint32_t end)
4446 {
4447 	/*
4448 	 * Given a sack block defined by
4449 	 * start and end, and a current postion
4450 	 * at. Return 1 if either side of at
4451 	 * would show that the block is mergable
4452 	 * to that side. A block to be mergable
4453 	 * must have overlap with the start/end
4454 	 * and be in the SACK'd state.
4455 	 */
4456 	struct bbr_sendmap *l_rsm;
4457 	struct bbr_sendmap *r_rsm;
4458 
4459 	/* first get the either side blocks */
4460 	l_rsm = TAILQ_PREV(at, bbr_head, r_next);
4461 	r_rsm = TAILQ_NEXT(at, r_next);
4462 	if (l_rsm && (l_rsm->r_flags & BBR_ACKED)) {
4463 		/* Potentially mergeable */
4464 		if ((l_rsm->r_end == start) ||
4465 		    (SEQ_LT(start, l_rsm->r_end) &&
4466 		     SEQ_GT(end, l_rsm->r_end))) {
4467 			    /*
4468 			     * map blk   |------|
4469 			     * sack blk         |------|
4470 			     * <or>
4471 			     * map blk   |------|
4472 			     * sack blk      |------|
4473 			     */
4474 			    return (1);
4475 		    }
4476 	}
4477 	if (r_rsm && (r_rsm->r_flags & BBR_ACKED)) {
4478 		/* Potentially mergeable */
4479 		if ((r_rsm->r_start == end) ||
4480 		    (SEQ_LT(start, r_rsm->r_start) &&
4481 		     SEQ_GT(end, r_rsm->r_start))) {
4482 			/*
4483 			 * map blk          |---------|
4484 			 * sack blk    |----|
4485 			 * <or>
4486 			 * map blk          |---------|
4487 			 * sack blk    |-------|
4488 			 */
4489 			return (1);
4490 		}
4491 	}
4492 	return (0);
4493 }
4494 
4495 static struct bbr_sendmap *
4496 bbr_merge_rsm(struct tcp_bbr *bbr,
4497 	      struct bbr_sendmap *l_rsm,
4498 	      struct bbr_sendmap *r_rsm)
4499 {
4500 	/*
4501 	 * We are merging two ack'd RSM's,
4502 	 * the l_rsm is on the left (lower seq
4503 	 * values) and the r_rsm is on the right
4504 	 * (higher seq value). The simplest way
4505 	 * to merge these is to move the right
4506 	 * one into the left. I don't think there
4507 	 * is any reason we need to try to find
4508 	 * the oldest (or last oldest retransmitted).
4509 	 */
4510 	l_rsm->r_end = r_rsm->r_end;
4511 	if (l_rsm->r_dupack < r_rsm->r_dupack)
4512 		l_rsm->r_dupack = r_rsm->r_dupack;
4513 	if (r_rsm->r_rtr_bytes)
4514 		l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
4515 	if (r_rsm->r_in_tmap) {
4516 		/* This really should not happen */
4517 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, r_rsm, r_tnext);
4518 	}
4519 	if (r_rsm->r_app_limited)
4520 		l_rsm->r_app_limited = r_rsm->r_app_limited;
4521 	/* Now the flags */
4522 	if (r_rsm->r_flags & BBR_HAS_FIN)
4523 		l_rsm->r_flags |= BBR_HAS_FIN;
4524 	if (r_rsm->r_flags & BBR_TLP)
4525 		l_rsm->r_flags |= BBR_TLP;
4526 	if (r_rsm->r_flags & BBR_RWND_COLLAPSED)
4527 		l_rsm->r_flags |= BBR_RWND_COLLAPSED;
4528 	if (r_rsm->r_flags & BBR_MARKED_LOST) {
4529 		/* This really should not happen */
4530 		bbr->r_ctl.rc_lost_bytes -= r_rsm->r_end - r_rsm->r_start;
4531 	}
4532 	TAILQ_REMOVE(&bbr->r_ctl.rc_map, r_rsm, r_next);
4533 	if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
4534 		/* Transfer the split limit to the map we free */
4535 		r_rsm->r_limit_type = l_rsm->r_limit_type;
4536 		l_rsm->r_limit_type = 0;
4537 	}
4538 	bbr_free(bbr, r_rsm);
4539 	return(l_rsm);
4540 }
4541 
4542 /*
4543  * TLP Timer, here we simply setup what segment we want to
4544  * have the TLP expire on, the normal bbr_output_wtime() will then
4545  * send it out.
4546  *
4547  * We return 1, saying don't proceed with bbr_output_wtime only
4548  * when all timers have been stopped (destroyed PCB?).
4549  */
4550 static int
4551 bbr_timeout_tlp(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4552 {
4553 	/*
4554 	 * Tail Loss Probe.
4555 	 */
4556 	struct bbr_sendmap *rsm = NULL;
4557 	struct socket *so;
4558 	uint32_t amm;
4559 	uint32_t out, avail;
4560 	uint32_t maxseg;
4561 	int collapsed_win = 0;
4562 
4563 	if (bbr->rc_all_timers_stopped) {
4564 		return (1);
4565 	}
4566 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4567 		/* Its not time yet */
4568 		return (0);
4569 	}
4570 	if (ctf_progress_timeout_check(tp, true)) {
4571 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4572 		tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4573 		return (1);
4574 	}
4575 	/* Did we somehow get into persists? */
4576 	if (bbr->rc_in_persist) {
4577 		return (0);
4578 	}
4579 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4580 		bbr_set_state(tp, bbr, 0);
4581 	BBR_STAT_INC(bbr_tlp_tot);
4582 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4583 	/*
4584 	 * A TLP timer has expired. We have been idle for 2 rtts. So we now
4585 	 * need to figure out how to force a full MSS segment out.
4586 	 */
4587 	so = tp->t_inpcb->inp_socket;
4588 	avail = sbavail(&so->so_snd);
4589 	out = ctf_outstanding(tp);
4590 	if (out > tp->snd_wnd) {
4591 		/* special case, we need a retransmission */
4592 		collapsed_win = 1;
4593 		goto need_retran;
4594 	}
4595 	if (avail > out) {
4596 		/* New data is available */
4597 		amm = avail - out;
4598 		if (amm > maxseg) {
4599 			amm = maxseg;
4600 		} else if ((amm < maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
4601 			/* not enough to fill a MTU and no-delay is off */
4602 			goto need_retran;
4603 		}
4604 		/* Set the send-new override */
4605 		if ((out + amm) <= tp->snd_wnd) {
4606 			bbr->rc_tlp_new_data = 1;
4607 		} else {
4608 			goto need_retran;
4609 		}
4610 		bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4611 		bbr->r_ctl.rc_last_tlp_seq = tp->snd_max;
4612 		bbr->r_ctl.rc_tlp_send = NULL;
4613 		/* cap any slots */
4614 		BBR_STAT_INC(bbr_tlp_newdata);
4615 		goto send;
4616 	}
4617 need_retran:
4618 	/*
4619 	 * Ok we need to arrange the last un-acked segment to be re-sent, or
4620 	 * optionally the first un-acked segment.
4621 	 */
4622 	if (collapsed_win == 0) {
4623 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
4624 		if (rsm && (BBR_ACKED | BBR_HAS_FIN)) {
4625 			rsm = bbr_find_high_nonack(bbr, rsm);
4626 		}
4627 		if (rsm == NULL) {
4628 			goto restore;
4629 		}
4630 	} else {
4631 		/*
4632 		 * We must find the last segment
4633 		 * that was acceptable by the client.
4634 		 */
4635 		TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4636 			if ((rsm->r_flags & BBR_RWND_COLLAPSED) == 0) {
4637 				/* Found one */
4638 				break;
4639 			}
4640 		}
4641 		if (rsm == NULL) {
4642 			/* None? if so send the first */
4643 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4644 			if (rsm == NULL)
4645 				goto restore;
4646 		}
4647 	}
4648 	if ((rsm->r_end - rsm->r_start) > maxseg) {
4649 		/*
4650 		 * We need to split this the last segment in two.
4651 		 */
4652 		struct bbr_sendmap *nrsm;
4653 
4654 		nrsm = bbr_alloc_full_limit(bbr);
4655 		if (nrsm == NULL) {
4656 			/*
4657 			 * We can't get memory to split, we can either just
4658 			 * not split it. Or retransmit the whole piece, lets
4659 			 * do the large send (BTLP :-) ).
4660 			 */
4661 			goto go_for_it;
4662 		}
4663 		bbr_clone_rsm(bbr, nrsm, rsm, (rsm->r_end - maxseg));
4664 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
4665 		if (rsm->r_in_tmap) {
4666 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4667 			nrsm->r_in_tmap = 1;
4668 		}
4669 		rsm->r_flags &= (~BBR_HAS_FIN);
4670 		rsm = nrsm;
4671 	}
4672 go_for_it:
4673 	bbr->r_ctl.rc_tlp_send = rsm;
4674 	bbr->rc_tlp_rtx_out = 1;
4675 	if (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) {
4676 		bbr->r_ctl.rc_tlp_seg_send_cnt++;
4677 		tp->t_rxtshift++;
4678 	} else {
4679 		bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
4680 		bbr->r_ctl.rc_tlp_seg_send_cnt = 1;
4681 	}
4682 send:
4683 	if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
4684 		/*
4685 		 * Can't [re]/transmit a segment we have retranmitted the
4686 		 * max times. We need the retransmit timer to take over.
4687 		 */
4688 restore:
4689 		bbr->rc_tlp_new_data = 0;
4690 		bbr->r_ctl.rc_tlp_send = NULL;
4691 		if (rsm)
4692 			rsm->r_flags &= ~BBR_TLP;
4693 		BBR_STAT_INC(bbr_tlp_retran_fail);
4694 		return (0);
4695 	} else if (rsm) {
4696 		rsm->r_flags |= BBR_TLP;
4697 	}
4698 	if (rsm && (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) &&
4699 	    (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend)) {
4700 		/*
4701 		 * We have retransmitted to many times for TLP. Switch to
4702 		 * the regular RTO timer
4703 		 */
4704 		goto restore;
4705 	}
4706 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TLP);
4707 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
4708 	return (0);
4709 }
4710 
4711 /*
4712  * Delayed ack Timer, here we simply need to setup the
4713  * ACK_NOW flag and remove the DELACK flag. From there
4714  * the output routine will send the ack out.
4715  *
4716  * We only return 1, saying don't proceed, if all timers
4717  * are stopped (destroyed PCB?).
4718  */
4719 static int
4720 bbr_timeout_delack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4721 {
4722 	if (bbr->rc_all_timers_stopped) {
4723 		return (1);
4724 	}
4725 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_DELACK);
4726 	tp->t_flags &= ~TF_DELACK;
4727 	tp->t_flags |= TF_ACKNOW;
4728 	KMOD_TCPSTAT_INC(tcps_delack);
4729 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
4730 	return (0);
4731 }
4732 
4733 /*
4734  * Here we send a KEEP-ALIVE like probe to the
4735  * peer, we do not send data.
4736  *
4737  * We only return 1, saying don't proceed, if all timers
4738  * are stopped (destroyed PCB?).
4739  */
4740 static int
4741 bbr_timeout_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4742 {
4743 	struct tcptemp *t_template;
4744 	int32_t retval = 1;
4745 
4746 	if (bbr->rc_all_timers_stopped) {
4747 		return (1);
4748 	}
4749 	if (bbr->rc_in_persist == 0)
4750 		return (0);
4751 	KASSERT(tp->t_inpcb != NULL,
4752 	    ("%s: tp %p tp->t_inpcb == NULL", __func__, tp));
4753 	/*
4754 	 * Persistence timer into zero window. Force a byte to be output, if
4755 	 * possible.
4756 	 */
4757 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_PERSIST);
4758 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
4759 	KMOD_TCPSTAT_INC(tcps_persisttimeo);
4760 	/*
4761 	 * Have we exceeded the user specified progress time?
4762 	 */
4763 	if (ctf_progress_timeout_check(tp, true)) {
4764 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4765 		tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4766 		goto out;
4767 	}
4768 	/*
4769 	 * Hack: if the peer is dead/unreachable, we do not time out if the
4770 	 * window is closed.  After a full backoff, drop the connection if
4771 	 * the idle time (no responses to probes) reaches the maximum
4772 	 * backoff that we would use if retransmitting.
4773 	 */
4774 	if (tp->t_rxtshift == TCP_MAXRXTSHIFT &&
4775 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
4776 	    ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
4777 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4778 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4779 		tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4780 		goto out;
4781 	}
4782 	if ((sbavail(&bbr->rc_inp->inp_socket->so_snd) == 0) &&
4783 	    tp->snd_una == tp->snd_max) {
4784 		bbr_exit_persist(tp, bbr, cts, __LINE__);
4785 		retval = 0;
4786 		goto out;
4787 	}
4788 	/*
4789 	 * If the user has closed the socket then drop a persisting
4790 	 * connection after a much reduced timeout.
4791 	 */
4792 	if (tp->t_state > TCPS_CLOSE_WAIT &&
4793 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
4794 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4795 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4796 		tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4797 		goto out;
4798 	}
4799 	t_template = tcpip_maketemplate(bbr->rc_inp);
4800 	if (t_template) {
4801 		tcp_respond(tp, t_template->tt_ipgen,
4802 			    &t_template->tt_t, (struct mbuf *)NULL,
4803 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4804 		/* This sends an ack */
4805 		if (tp->t_flags & TF_DELACK)
4806 			tp->t_flags &= ~TF_DELACK;
4807 		free(t_template, M_TEMP);
4808 	}
4809 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
4810 		tp->t_rxtshift++;
4811 	bbr_start_hpts_timer(bbr, tp, cts, 3, 0, 0);
4812 out:
4813 	return (retval);
4814 }
4815 
4816 /*
4817  * If a keepalive goes off, we had no other timers
4818  * happening. We always return 1 here since this
4819  * routine either drops the connection or sends
4820  * out a segment with respond.
4821  */
4822 static int
4823 bbr_timeout_keepalive(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4824 {
4825 	struct tcptemp *t_template;
4826 	struct inpcb *inp;
4827 
4828 	if (bbr->rc_all_timers_stopped) {
4829 		return (1);
4830 	}
4831 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
4832 	inp = tp->t_inpcb;
4833 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_KEEP);
4834 	/*
4835 	 * Keep-alive timer went off; send something or drop connection if
4836 	 * idle for too long.
4837 	 */
4838 	KMOD_TCPSTAT_INC(tcps_keeptimeo);
4839 	if (tp->t_state < TCPS_ESTABLISHED)
4840 		goto dropit;
4841 	if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
4842 	    tp->t_state <= TCPS_CLOSING) {
4843 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
4844 			goto dropit;
4845 		/*
4846 		 * Send a packet designed to force a response if the peer is
4847 		 * up and reachable: either an ACK if the connection is
4848 		 * still alive, or an RST if the peer has closed the
4849 		 * connection due to timeout or reboot. Using sequence
4850 		 * number tp->snd_una-1 causes the transmitted zero-length
4851 		 * segment to lie outside the receive window; by the
4852 		 * protocol spec, this requires the correspondent TCP to
4853 		 * respond.
4854 		 */
4855 		KMOD_TCPSTAT_INC(tcps_keepprobe);
4856 		t_template = tcpip_maketemplate(inp);
4857 		if (t_template) {
4858 			tcp_respond(tp, t_template->tt_ipgen,
4859 			    &t_template->tt_t, (struct mbuf *)NULL,
4860 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4861 			free(t_template, M_TEMP);
4862 		}
4863 	}
4864 	bbr_start_hpts_timer(bbr, tp, cts, 4, 0, 0);
4865 	return (1);
4866 dropit:
4867 	KMOD_TCPSTAT_INC(tcps_keepdrops);
4868 	tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
4869 	tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4870 	return (1);
4871 }
4872 
4873 /*
4874  * Retransmit helper function, clear up all the ack
4875  * flags and take care of important book keeping.
4876  */
4877 static void
4878 bbr_remxt_tmr(struct tcpcb *tp)
4879 {
4880 	/*
4881 	 * The retransmit timer went off, all sack'd blocks must be
4882 	 * un-acked.
4883 	 */
4884 	struct bbr_sendmap *rsm, *trsm = NULL;
4885 	struct tcp_bbr *bbr;
4886 	uint32_t cts, lost;
4887 
4888 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4889 	cts = tcp_get_usecs(&bbr->rc_tv);
4890 	lost = bbr->r_ctl.rc_lost;
4891 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4892 		bbr_set_state(tp, bbr, 0);
4893 
4894 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
4895 		if (rsm->r_flags & BBR_ACKED) {
4896 			uint32_t old_flags;
4897 
4898 			rsm->r_dupack = 0;
4899 			if (rsm->r_in_tmap == 0) {
4900 				/* We must re-add it back to the tlist */
4901 				if (trsm == NULL) {
4902 					TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
4903 				} else {
4904 					TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, trsm, rsm, r_tnext);
4905 				}
4906 				rsm->r_in_tmap = 1;
4907 			}
4908 			old_flags = rsm->r_flags;
4909 			rsm->r_flags |= BBR_RXT_CLEARED;
4910 			rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS);
4911 			bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
4912 		} else {
4913 			if ((tp->t_state < TCPS_ESTABLISHED) &&
4914 			    (rsm->r_start == tp->snd_una)) {
4915 				/*
4916 				 * Special case for TCP FO. Where
4917 				 * we sent more data beyond the snd_max.
4918 				 * We don't mark that as lost and stop here.
4919 				 */
4920 				break;
4921 			}
4922 			if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4923 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4924 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4925 			}
4926 			if (bbr_marks_rxt_sack_passed) {
4927 				/*
4928 				 * With this option, we will rack out
4929 				 * in 1ms increments the rest of the packets.
4930 				 */
4931 				rsm->r_flags |= BBR_SACK_PASSED | BBR_MARKED_LOST;
4932 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4933 			} else {
4934 				/*
4935 				 * With this option we only mark them lost
4936 				 * and remove all sack'd markings. We will run
4937 				 * another RXT or a TLP. This will cause
4938 				 * us to eventually send more based on what
4939 				 * ack's come in.
4940 				 */
4941 				rsm->r_flags |= BBR_MARKED_LOST;
4942 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4943 				rsm->r_flags &= ~BBR_SACK_PASSED;
4944 			}
4945 		}
4946 		trsm = rsm;
4947 	}
4948 	bbr->r_ctl.rc_resend = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4949 	/* Clear the count (we just un-acked them) */
4950 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TMR);
4951 	bbr->rc_tlp_new_data = 0;
4952 	bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4953 	/* zap the behindness on a rxt */
4954 	bbr->r_ctl.rc_hptsi_agg_delay = 0;
4955 	bbr->r_agg_early_set = 0;
4956 	bbr->r_ctl.rc_agg_early = 0;
4957 	bbr->rc_tlp_rtx_out = 0;
4958 	bbr->r_ctl.rc_sacked = 0;
4959 	bbr->r_ctl.rc_sacklast = NULL;
4960 	bbr->r_timer_override = 1;
4961 	bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4962 }
4963 
4964 /*
4965  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
4966  * we will setup to retransmit the lowest seq number outstanding.
4967  */
4968 static int
4969 bbr_timeout_rxt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4970 {
4971 	int32_t rexmt;
4972 	int32_t retval = 0;
4973 	bool isipv6;
4974 
4975 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
4976 	if (bbr->rc_all_timers_stopped) {
4977 		return (1);
4978 	}
4979 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
4980 	    (tp->snd_una == tp->snd_max)) {
4981 		/* Nothing outstanding .. nothing to do */
4982 		return (0);
4983 	}
4984 	/*
4985 	 * Retransmission timer went off.  Message has not been acked within
4986 	 * retransmit interval.  Back off to a longer retransmit interval
4987 	 * and retransmit one segment.
4988 	 */
4989 	if (ctf_progress_timeout_check(tp, true)) {
4990 		retval = 1;
4991 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4992 		tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4993 		goto out;
4994 	}
4995 	bbr_remxt_tmr(tp);
4996 	if ((bbr->r_ctl.rc_resend == NULL) ||
4997 	    ((bbr->r_ctl.rc_resend->r_flags & BBR_RWND_COLLAPSED) == 0)) {
4998 		/*
4999 		 * If the rwnd collapsed on
5000 		 * the one we are retransmitting
5001 		 * it does not count against the
5002 		 * rxt count.
5003 		 */
5004 		tp->t_rxtshift++;
5005 	}
5006 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT) {
5007 		tp->t_rxtshift = TCP_MAXRXTSHIFT;
5008 		KMOD_TCPSTAT_INC(tcps_timeoutdrop);
5009 		retval = 1;
5010 		tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
5011 		tcp_set_inp_to_drop(bbr->rc_inp,
5012 		    (tp->t_softerror ? (uint16_t) tp->t_softerror : ETIMEDOUT));
5013 		goto out;
5014 	}
5015 	if (tp->t_state == TCPS_SYN_SENT) {
5016 		/*
5017 		 * If the SYN was retransmitted, indicate CWND to be limited
5018 		 * to 1 segment in cc_conn_init().
5019 		 */
5020 		tp->snd_cwnd = 1;
5021 	} else if (tp->t_rxtshift == 1) {
5022 		/*
5023 		 * first retransmit; record ssthresh and cwnd so they can be
5024 		 * recovered if this turns out to be a "bad" retransmit. A
5025 		 * retransmit is considered "bad" if an ACK for this segment
5026 		 * is received within RTT/2 interval; the assumption here is
5027 		 * that the ACK was already in flight.  See "On Estimating
5028 		 * End-to-End Network Path Properties" by Allman and Paxson
5029 		 * for more details.
5030 		 */
5031 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5032 		if (!IN_RECOVERY(tp->t_flags)) {
5033 			tp->snd_cwnd_prev = tp->snd_cwnd;
5034 			tp->snd_ssthresh_prev = tp->snd_ssthresh;
5035 			tp->snd_recover_prev = tp->snd_recover;
5036 			tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
5037 			tp->t_flags |= TF_PREVVALID;
5038 		} else {
5039 			tp->t_flags &= ~TF_PREVVALID;
5040 		}
5041 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5042 	} else {
5043 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5044 		tp->t_flags &= ~TF_PREVVALID;
5045 	}
5046 	KMOD_TCPSTAT_INC(tcps_rexmttimeo);
5047 	if ((tp->t_state == TCPS_SYN_SENT) ||
5048 	    (tp->t_state == TCPS_SYN_RECEIVED))
5049 		rexmt = USEC_2_TICKS(BBR_INITIAL_RTO) * tcp_backoff[tp->t_rxtshift];
5050 	else
5051 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
5052 	TCPT_RANGESET(tp->t_rxtcur, rexmt,
5053 	    MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms),
5054 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
5055 	/*
5056 	 * We enter the path for PLMTUD if connection is established or, if
5057 	 * connection is FIN_WAIT_1 status, reason for the last is that if
5058 	 * amount of data we send is very small, we could send it in couple
5059 	 * of packets and process straight to FIN. In that case we won't
5060 	 * catch ESTABLISHED state.
5061 	 */
5062 #ifdef INET6
5063 	isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) ? true : false;
5064 #else
5065 	isipv6 = false;
5066 #endif
5067 	if (((V_tcp_pmtud_blackhole_detect == 1) ||
5068 	    (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
5069 	    (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
5070 	    ((tp->t_state == TCPS_ESTABLISHED) ||
5071 	    (tp->t_state == TCPS_FIN_WAIT_1))) {
5072 		/*
5073 		 * Idea here is that at each stage of mtu probe (usually,
5074 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
5075 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
5076 		 * should take care of that.
5077 		 */
5078 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
5079 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
5080 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
5081 		    tp->t_rxtshift % 2 == 0)) {
5082 			/*
5083 			 * Enter Path MTU Black-hole Detection mechanism: -
5084 			 * Disable Path MTU Discovery (IP "DF" bit). -
5085 			 * Reduce MTU to lower value than what we negotiated
5086 			 * with peer.
5087 			 */
5088 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
5089 				/*
5090 				 * Record that we may have found a black
5091 				 * hole.
5092 				 */
5093 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
5094 				/* Keep track of previous MSS. */
5095 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
5096 			}
5097 			/*
5098 			 * Reduce the MSS to blackhole value or to the
5099 			 * default in an attempt to retransmit.
5100 			 */
5101 #ifdef INET6
5102 			isipv6 = bbr->r_is_v6;
5103 			if (isipv6 &&
5104 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
5105 				/* Use the sysctl tuneable blackhole MSS. */
5106 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
5107 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5108 			} else if (isipv6) {
5109 				/* Use the default MSS. */
5110 				tp->t_maxseg = V_tcp_v6mssdflt;
5111 				/*
5112 				 * Disable Path MTU Discovery when we switch
5113 				 * to minmss.
5114 				 */
5115 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5116 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5117 			}
5118 #endif
5119 #if defined(INET6) && defined(INET)
5120 			else
5121 #endif
5122 #ifdef INET
5123 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
5124 				/* Use the sysctl tuneable blackhole MSS. */
5125 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
5126 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5127 			} else {
5128 				/* Use the default MSS. */
5129 				tp->t_maxseg = V_tcp_mssdflt;
5130 				/*
5131 				 * Disable Path MTU Discovery when we switch
5132 				 * to minmss.
5133 				 */
5134 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5135 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5136 			}
5137 #endif
5138 		} else {
5139 			/*
5140 			 * If further retransmissions are still unsuccessful
5141 			 * with a lowered MTU, maybe this isn't a blackhole
5142 			 * and we restore the previous MSS and blackhole
5143 			 * detection flags. The limit '6' is determined by
5144 			 * giving each probe stage (1448, 1188, 524) 2
5145 			 * chances to recover.
5146 			 */
5147 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
5148 			    (tp->t_rxtshift >= 6)) {
5149 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
5150 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
5151 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
5152 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
5153 			}
5154 		}
5155 	}
5156 	/*
5157 	 * Disable RFC1323 and SACK if we haven't got any response to our
5158 	 * third SYN to work-around some broken terminal servers (most of
5159 	 * which have hopefully been retired) that have bad VJ header
5160 	 * compression code which trashes TCP segments containing
5161 	 * unknown-to-them TCP options.
5162 	 */
5163 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
5164 	    (tp->t_rxtshift == 3))
5165 		tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
5166 	/*
5167 	 * If we backed off this far, our srtt estimate is probably bogus.
5168 	 * Clobber it so we'll take the next rtt measurement as our srtt;
5169 	 * move the current srtt into rttvar to keep the current retransmit
5170 	 * times until then.
5171 	 */
5172 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
5173 #ifdef INET6
5174 		if (bbr->r_is_v6)
5175 			in6_losing(tp->t_inpcb);
5176 		else
5177 #endif
5178 			in_losing(tp->t_inpcb);
5179 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
5180 		tp->t_srtt = 0;
5181 	}
5182 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
5183 	tp->snd_recover = tp->snd_max;
5184 	tp->t_flags |= TF_ACKNOW;
5185 	tp->t_rtttime = 0;
5186 out:
5187 	return (retval);
5188 }
5189 
5190 static int
5191 bbr_process_timers(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, uint8_t hpts_calling)
5192 {
5193 	int32_t ret = 0;
5194 	int32_t timers = (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
5195 
5196 	if (timers == 0) {
5197 		return (0);
5198 	}
5199 	if (tp->t_state == TCPS_LISTEN) {
5200 		/* no timers on listen sockets */
5201 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
5202 			return (0);
5203 		return (1);
5204 	}
5205 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
5206 		uint32_t left;
5207 
5208 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
5209 			ret = -1;
5210 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5211 			return (0);
5212 		}
5213 		if (hpts_calling == 0) {
5214 			ret = -2;
5215 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5216 			return (0);
5217 		}
5218 		/*
5219 		 * Ok our timer went off early and we are not paced false
5220 		 * alarm, go back to sleep.
5221 		 */
5222 		left = bbr->r_ctl.rc_timer_exp - cts;
5223 		ret = -3;
5224 		bbr_log_to_processing(bbr, cts, ret, left, hpts_calling);
5225 		tcp_hpts_insert(tp->t_inpcb, HPTS_USEC_TO_SLOTS(left));
5226 		return (1);
5227 	}
5228 	bbr->rc_tmr_stopped = 0;
5229 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
5230 	if (timers & PACE_TMR_DELACK) {
5231 		ret = bbr_timeout_delack(tp, bbr, cts);
5232 	} else if (timers & PACE_TMR_PERSIT) {
5233 		ret = bbr_timeout_persist(tp, bbr, cts);
5234 	} else if (timers & PACE_TMR_RACK) {
5235 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5236 		ret = bbr_timeout_rack(tp, bbr, cts);
5237 	} else if (timers & PACE_TMR_TLP) {
5238 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5239 		ret = bbr_timeout_tlp(tp, bbr, cts);
5240 	} else if (timers & PACE_TMR_RXT) {
5241 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5242 		ret = bbr_timeout_rxt(tp, bbr, cts);
5243 	} else if (timers & PACE_TMR_KEEP) {
5244 		ret = bbr_timeout_keepalive(tp, bbr, cts);
5245 	}
5246 	bbr_log_to_processing(bbr, cts, ret, timers, hpts_calling);
5247 	return (ret);
5248 }
5249 
5250 static void
5251 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts)
5252 {
5253 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
5254 		uint8_t hpts_removed = 0;
5255 
5256 		if (bbr->rc_inp->inp_in_hpts &&
5257 		    (bbr->rc_timer_first == 1)) {
5258 			/*
5259 			 * If we are canceling timer's when we have the
5260 			 * timer ahead of the output being paced. We also
5261 			 * must remove ourselves from the hpts.
5262 			 */
5263 			hpts_removed = 1;
5264 			tcp_hpts_remove(bbr->rc_inp, HPTS_REMOVE_OUTPUT);
5265 			if (bbr->r_ctl.rc_last_delay_val) {
5266 				/* Update the last hptsi delay too */
5267 				uint32_t time_since_send;
5268 
5269 				if (TSTMP_GT(cts, bbr->rc_pacer_started))
5270 					time_since_send = cts - bbr->rc_pacer_started;
5271 				else
5272 					time_since_send = 0;
5273 				if (bbr->r_ctl.rc_last_delay_val > time_since_send) {
5274 					/* Cut down our slot time */
5275 					bbr->r_ctl.rc_last_delay_val -= time_since_send;
5276 				} else {
5277 					bbr->r_ctl.rc_last_delay_val = 0;
5278 				}
5279 				bbr->rc_pacer_started = cts;
5280 			}
5281 		}
5282 		bbr->rc_timer_first = 0;
5283 		bbr_log_to_cancel(bbr, line, cts, hpts_removed);
5284 		bbr->rc_tmr_stopped = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
5285 		bbr->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
5286 	}
5287 }
5288 
5289 static void
5290 bbr_timer_stop(struct tcpcb *tp, uint32_t timer_type)
5291 {
5292 	struct tcp_bbr *bbr;
5293 
5294 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
5295 	bbr->rc_all_timers_stopped = 1;
5296 	return;
5297 }
5298 
5299 /*
5300  * stop all timers always returning 0.
5301  */
5302 static int
5303 bbr_stopall(struct tcpcb *tp)
5304 {
5305 	return (0);
5306 }
5307 
5308 static void
5309 bbr_timer_activate(struct tcpcb *tp, uint32_t timer_type, uint32_t delta)
5310 {
5311 	return;
5312 }
5313 
5314 /*
5315  * return true if a bbr timer (rack or tlp) is active.
5316  */
5317 static int
5318 bbr_timer_active(struct tcpcb *tp, uint32_t timer_type)
5319 {
5320 	return (0);
5321 }
5322 
5323 static uint32_t
5324 bbr_get_earliest_send_outstanding(struct tcp_bbr *bbr, struct bbr_sendmap *u_rsm, uint32_t cts)
5325 {
5326 	struct bbr_sendmap *rsm;
5327 
5328 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
5329 	if ((rsm == NULL) || (u_rsm == rsm))
5330 		return (cts);
5331 	return(rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
5332 }
5333 
5334 static void
5335 bbr_update_rsm(struct tcpcb *tp, struct tcp_bbr *bbr,
5336      struct bbr_sendmap *rsm, uint32_t cts, uint32_t pacing_time)
5337 {
5338 	int32_t idx;
5339 
5340 	rsm->r_rtr_cnt++;
5341 	rsm->r_dupack = 0;
5342 	if (rsm->r_rtr_cnt > BBR_NUM_OF_RETRANS) {
5343 		rsm->r_rtr_cnt = BBR_NUM_OF_RETRANS;
5344 		rsm->r_flags |= BBR_OVERMAX;
5345 	}
5346 	if (rsm->r_flags & BBR_RWND_COLLAPSED) {
5347 		/* Take off the collapsed flag at rxt */
5348 		rsm->r_flags &= ~BBR_RWND_COLLAPSED;
5349 	}
5350 	if (rsm->r_flags & BBR_MARKED_LOST) {
5351 		/* We have retransmitted, its no longer lost */
5352 		rsm->r_flags &= ~BBR_MARKED_LOST;
5353 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
5354 	}
5355 	if (rsm->r_flags & BBR_RXT_CLEARED) {
5356 		/*
5357 		 * We hit a RXT timer on it and
5358 		 * we cleared the "acked" flag.
5359 		 * We now have it going back into
5360 		 * flight, we can remove the cleared
5361 		 * flag and possibly do accounting on
5362 		 * this piece.
5363 		 */
5364 		rsm->r_flags &= ~BBR_RXT_CLEARED;
5365 	}
5366 	if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & BBR_TLP) == 0)) {
5367 		bbr->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
5368 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
5369 	}
5370 	idx = rsm->r_rtr_cnt - 1;
5371 	rsm->r_tim_lastsent[idx] = cts;
5372 	rsm->r_pacing_delay = pacing_time;
5373 	rsm->r_delivered = bbr->r_ctl.rc_delivered;
5374 	rsm->r_ts_valid = bbr->rc_ts_valid;
5375 	if (bbr->rc_ts_valid)
5376 		rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5377 	if (bbr->r_ctl.r_app_limited_until)
5378 		rsm->r_app_limited = 1;
5379 	else
5380 		rsm->r_app_limited = 0;
5381 	if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5382 		rsm->r_bbr_state = bbr_state_val(bbr);
5383 	else
5384 		rsm->r_bbr_state = 8;
5385 	if (rsm->r_flags & BBR_ACKED) {
5386 		/* Problably MTU discovery messing with us */
5387 		uint32_t old_flags;
5388 
5389 		old_flags = rsm->r_flags;
5390 		rsm->r_flags &= ~BBR_ACKED;
5391 		bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
5392 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
5393 		if (bbr->r_ctl.rc_sacked == 0)
5394 			bbr->r_ctl.rc_sacklast = NULL;
5395 	}
5396 	if (rsm->r_in_tmap) {
5397 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5398 	}
5399 	TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5400 	rsm->r_in_tmap = 1;
5401 	if (rsm->r_flags & BBR_SACK_PASSED) {
5402 		/* We have retransmitted due to the SACK pass */
5403 		rsm->r_flags &= ~BBR_SACK_PASSED;
5404 		rsm->r_flags |= BBR_WAS_SACKPASS;
5405 	}
5406 	rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5407 	rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5408 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5409 	bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
5410 	if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5411 		rsm->r_is_gain = 1;
5412 		rsm->r_is_drain = 0;
5413 	} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5414 		rsm->r_is_drain = 1;
5415 		rsm->r_is_gain = 0;
5416 	} else {
5417 		rsm->r_is_drain = 0;
5418 		rsm->r_is_gain = 0;
5419 	}
5420 	rsm->r_del_time = bbr->r_ctl.rc_del_time; /* TEMP GOOGLE CODE */
5421 }
5422 
5423 /*
5424  * Returns 0, or the sequence where we stopped
5425  * updating. We also update the lenp to be the amount
5426  * of data left.
5427  */
5428 
5429 static uint32_t
5430 bbr_update_entry(struct tcpcb *tp, struct tcp_bbr *bbr,
5431     struct bbr_sendmap *rsm, uint32_t cts, int32_t *lenp, uint32_t pacing_time)
5432 {
5433 	/*
5434 	 * We (re-)transmitted starting at rsm->r_start for some length
5435 	 * (possibly less than r_end.
5436 	 */
5437 	struct bbr_sendmap *nrsm;
5438 	uint32_t c_end;
5439 	int32_t len;
5440 
5441 	len = *lenp;
5442 	c_end = rsm->r_start + len;
5443 	if (SEQ_GEQ(c_end, rsm->r_end)) {
5444 		/*
5445 		 * We retransmitted the whole piece or more than the whole
5446 		 * slopping into the next rsm.
5447 		 */
5448 		bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5449 		if (c_end == rsm->r_end) {
5450 			*lenp = 0;
5451 			return (0);
5452 		} else {
5453 			int32_t act_len;
5454 
5455 			/* Hangs over the end return whats left */
5456 			act_len = rsm->r_end - rsm->r_start;
5457 			*lenp = (len - act_len);
5458 			return (rsm->r_end);
5459 		}
5460 		/* We don't get out of this block. */
5461 	}
5462 	/*
5463 	 * Here we retransmitted less than the whole thing which means we
5464 	 * have to split this into what was transmitted and what was not.
5465 	 */
5466 	nrsm = bbr_alloc_full_limit(bbr);
5467 	if (nrsm == NULL) {
5468 		*lenp = 0;
5469 		return (0);
5470 	}
5471 	/*
5472 	 * So here we are going to take the original rsm and make it what we
5473 	 * retransmitted. nrsm will be the tail portion we did not
5474 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
5475 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
5476 	 * 1, 6 and the new piece will be 6, 11.
5477 	 */
5478 	bbr_clone_rsm(bbr, nrsm, rsm, c_end);
5479 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
5480 	nrsm->r_dupack = 0;
5481 	if (rsm->r_in_tmap) {
5482 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
5483 		nrsm->r_in_tmap = 1;
5484 	}
5485 	rsm->r_flags &= (~BBR_HAS_FIN);
5486 	bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5487 	*lenp = 0;
5488 	return (0);
5489 }
5490 
5491 static uint64_t
5492 bbr_get_hardware_rate(struct tcp_bbr *bbr)
5493 {
5494 	uint64_t bw;
5495 
5496 	bw = bbr_get_bw(bbr);
5497 	bw *= (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN];
5498 	bw /= (uint64_t)BBR_UNIT;
5499 	return(bw);
5500 }
5501 
5502 static void
5503 bbr_setup_less_of_rate(struct tcp_bbr *bbr, uint32_t cts,
5504 		       uint64_t act_rate, uint64_t rate_wanted)
5505 {
5506 	/*
5507 	 * We could not get a full gains worth
5508 	 * of rate.
5509 	 */
5510 	if (get_filter_value(&bbr->r_ctl.rc_delrate) >= act_rate) {
5511 		/* we can't even get the real rate */
5512 		uint64_t red;
5513 
5514 		bbr->skip_gain = 1;
5515 		bbr->gain_is_limited = 0;
5516 		red = get_filter_value(&bbr->r_ctl.rc_delrate) - act_rate;
5517 		if (red)
5518 			filter_reduce_by(&bbr->r_ctl.rc_delrate, red, cts);
5519 	} else {
5520 		/* We can use a lower gain */
5521 		bbr->skip_gain = 0;
5522 		bbr->gain_is_limited = 1;
5523 	}
5524 }
5525 
5526 static void
5527 bbr_update_hardware_pacing_rate(struct tcp_bbr *bbr, uint32_t cts)
5528 {
5529 	const struct tcp_hwrate_limit_table *nrte;
5530 	int error, rate = -1;
5531 
5532 	if (bbr->r_ctl.crte == NULL)
5533 		return;
5534 	if ((bbr->rc_inp->inp_route.ro_nh == NULL) ||
5535 	    (bbr->rc_inp->inp_route.ro_nh->nh_ifp == NULL)) {
5536 		/* Lost our routes? */
5537 		/* Clear the way for a re-attempt */
5538 		bbr->bbr_attempt_hdwr_pace = 0;
5539 lost_rate:
5540 		bbr->gain_is_limited = 0;
5541 		bbr->skip_gain = 0;
5542 		bbr->bbr_hdrw_pacing = 0;
5543 		counter_u64_add(bbr_flows_whdwr_pacing, -1);
5544 		counter_u64_add(bbr_flows_nohdwr_pacing, 1);
5545 		tcp_bbr_tso_size_check(bbr, cts);
5546 		return;
5547 	}
5548 	rate = bbr_get_hardware_rate(bbr);
5549 	nrte = tcp_chg_pacing_rate(bbr->r_ctl.crte,
5550 				   bbr->rc_tp,
5551 				   bbr->rc_inp->inp_route.ro_nh->nh_ifp,
5552 				   rate,
5553 				   (RS_PACING_GEQ|RS_PACING_SUB_OK),
5554 				   &error, NULL);
5555 	if (nrte == NULL) {
5556 		goto lost_rate;
5557 	}
5558 	if (nrte != bbr->r_ctl.crte) {
5559 		bbr->r_ctl.crte = nrte;
5560 		if (error == 0)  {
5561 			BBR_STAT_INC(bbr_hdwr_rl_mod_ok);
5562 			if (bbr->r_ctl.crte->rate < rate) {
5563 				/* We have a problem */
5564 				bbr_setup_less_of_rate(bbr, cts,
5565 						       bbr->r_ctl.crte->rate, rate);
5566 			} else {
5567 				/* We are good */
5568 				bbr->gain_is_limited = 0;
5569 				bbr->skip_gain = 0;
5570 			}
5571 		} else {
5572 			/* A failure should release the tag */
5573 			BBR_STAT_INC(bbr_hdwr_rl_mod_fail);
5574 			bbr->gain_is_limited = 0;
5575 			bbr->skip_gain = 0;
5576 			bbr->bbr_hdrw_pacing = 0;
5577 		}
5578 		bbr_type_log_hdwr_pacing(bbr,
5579 					 bbr->r_ctl.crte->ptbl->rs_ifp,
5580 					 rate,
5581 					 ((bbr->r_ctl.crte == NULL) ? 0 : bbr->r_ctl.crte->rate),
5582 					 __LINE__,
5583 					 cts,
5584 					 error);
5585 	}
5586 }
5587 
5588 static void
5589 bbr_adjust_for_hw_pacing(struct tcp_bbr *bbr, uint32_t cts)
5590 {
5591 	/*
5592 	 * If we have hardware pacing support
5593 	 * we need to factor that in for our
5594 	 * TSO size.
5595 	 */
5596 	const struct tcp_hwrate_limit_table *rlp;
5597 	uint32_t cur_delay, seg_sz, maxseg, new_tso, delta, hdwr_delay;
5598 
5599 	if ((bbr->bbr_hdrw_pacing == 0) ||
5600 	    (IN_RECOVERY(bbr->rc_tp->t_flags)) ||
5601 	    (bbr->r_ctl.crte == NULL))
5602 		return;
5603 	if (bbr->hw_pacing_set == 0) {
5604 		/* Not yet by the hdwr pacing count delay */
5605 		return;
5606 	}
5607 	if (bbr_hdwr_pace_adjust == 0) {
5608 		/* No adjustment */
5609 		return;
5610 	}
5611 	rlp = bbr->r_ctl.crte;
5612 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options)
5613 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5614 	else
5615 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5616 	/*
5617 	 * So lets first get the
5618 	 * time we will take between
5619 	 * TSO sized sends currently without
5620 	 * hardware help.
5621 	 */
5622 	cur_delay = bbr_get_pacing_delay(bbr, BBR_UNIT,
5623 		        bbr->r_ctl.rc_pace_max_segs, cts, 1);
5624 	hdwr_delay = bbr->r_ctl.rc_pace_max_segs / maxseg;
5625 	hdwr_delay *= rlp->time_between;
5626 	if (cur_delay > hdwr_delay)
5627 		delta = cur_delay - hdwr_delay;
5628 	else
5629 		delta = 0;
5630 	bbr_log_type_tsosize(bbr, cts, delta, cur_delay, hdwr_delay,
5631 			     (bbr->r_ctl.rc_pace_max_segs / maxseg),
5632 			     1);
5633 	if (delta &&
5634 	    (delta < (max(rlp->time_between,
5635 			  bbr->r_ctl.bbr_hptsi_segments_delay_tar)))) {
5636 		/*
5637 		 * Now lets divide by the pacing
5638 		 * time between each segment the
5639 		 * hardware sends rounding up and
5640 		 * derive a bytes from that. We multiply
5641 		 * that by bbr_hdwr_pace_adjust to get
5642 		 * more bang for our buck.
5643 		 *
5644 		 * The goal is to have the software pacer
5645 		 * waiting no more than an additional
5646 		 * pacing delay if we can (without the
5647 		 * compensation i.e. x bbr_hdwr_pace_adjust).
5648 		 */
5649 		seg_sz = max(((cur_delay + rlp->time_between)/rlp->time_between),
5650 			     (bbr->r_ctl.rc_pace_max_segs/maxseg));
5651 		seg_sz *= bbr_hdwr_pace_adjust;
5652 		if (bbr_hdwr_pace_floor &&
5653 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5654 			/* Currently hardware paces
5655 			 * out rs_min_seg segments at a time.
5656 			 * We need to make sure we always send at least
5657 			 * a full burst of bbr_hdwr_pace_floor down.
5658 			 */
5659 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5660 		}
5661 		seg_sz *= maxseg;
5662 	} else if (delta == 0) {
5663 		/*
5664 		 * The highest pacing rate is
5665 		 * above our b/w gained. This means
5666 		 * we probably are going quite fast at
5667 		 * the hardware highest rate. Lets just multiply
5668 		 * the calculated TSO size by the
5669 		 * multiplier factor (its probably
5670 		 * 4 segments in the default config for
5671 		 * mlx).
5672 		 */
5673 		seg_sz = bbr->r_ctl.rc_pace_max_segs * bbr_hdwr_pace_adjust;
5674 		if (bbr_hdwr_pace_floor &&
5675 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5676 			/* Currently hardware paces
5677 			 * out rs_min_seg segments at a time.
5678 			 * We need to make sure we always send at least
5679 			 * a full burst of bbr_hdwr_pace_floor down.
5680 			 */
5681 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5682 		}
5683 	} else {
5684 		/*
5685 		 * The pacing time difference is so
5686 		 * big that the hardware will
5687 		 * pace out more rapidly then we
5688 		 * really want and then we
5689 		 * will have a long delay. Lets just keep
5690 		 * the same TSO size so its as if
5691 		 * we were not using hdwr pacing (we
5692 		 * just gain a bit of spacing from the
5693 		 * hardware if seg_sz > 1).
5694 		 */
5695 		seg_sz = bbr->r_ctl.rc_pace_max_segs;
5696 	}
5697 	if (seg_sz > bbr->r_ctl.rc_pace_max_segs)
5698 		new_tso = seg_sz;
5699 	else
5700 		new_tso = bbr->r_ctl.rc_pace_max_segs;
5701 	if (new_tso >= (PACE_MAX_IP_BYTES-maxseg))
5702 		new_tso = PACE_MAX_IP_BYTES - maxseg;
5703 
5704 	if (new_tso != bbr->r_ctl.rc_pace_max_segs) {
5705 		bbr_log_type_tsosize(bbr, cts, new_tso, 0, bbr->r_ctl.rc_pace_max_segs, maxseg, 0);
5706 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5707 	}
5708 }
5709 
5710 static void
5711 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts)
5712 {
5713 	uint64_t bw;
5714 	uint32_t old_tso = 0, new_tso;
5715 	uint32_t maxseg, bytes;
5716 	uint32_t tls_seg=0;
5717 	/*
5718 	 * Google/linux uses the following algorithm to determine
5719 	 * the TSO size based on the b/w of the link (from Neal Cardwell email 9/27/18):
5720 	 *
5721 	 *  bytes = bw_in_bytes_per_second / 1000
5722 	 *  bytes = min(bytes, 64k)
5723 	 *  tso_segs = bytes / MSS
5724 	 *  if (bw < 1.2Mbs)
5725 	 *      min_tso_segs = 1
5726 	 *  else
5727 	 *	min_tso_segs = 2
5728 	 * tso_segs = max(tso_segs, min_tso_segs)
5729 	 *
5730 	 * * Note apply a device specific limit (we apply this in the
5731 	 *   tcp_m_copym).
5732 	 * Note that before the initial measurement is made google bursts out
5733 	 * a full iwnd just like new-reno/cubic.
5734 	 *
5735 	 * We do not use this algorithm. Instead we
5736 	 * use a two phased approach:
5737 	 *
5738 	 *  if ( bw <= per-tcb-cross-over)
5739 	 *     goal_tso =  calculate how much with this bw we
5740 	 *                 can send in goal-time seconds.
5741 	 *     if (goal_tso > mss)
5742 	 *         seg = goal_tso / mss
5743 	 *         tso = seg * mss
5744 	 *     else
5745          *         tso = mss
5746 	 *     if (tso > per-tcb-max)
5747 	 *         tso = per-tcb-max
5748 	 *  else if ( bw > 512Mbps)
5749 	 *     tso = max-tso (64k/mss)
5750 	 *  else
5751 	 *     goal_tso = bw / per-tcb-divsor
5752 	 *     seg = (goal_tso + mss-1)/mss
5753 	 *     tso = seg * mss
5754 	 *
5755 	 * if (tso < per-tcb-floor)
5756 	 *    tso = per-tcb-floor
5757 	 * if (tso > per-tcb-utter_max)
5758 	 *    tso = per-tcb-utter_max
5759 	 *
5760 	 * Note the default per-tcb-divisor is 1000 (same as google).
5761 	 * the goal cross over is 30Mbps however. To recreate googles
5762 	 * algorithm you need to set:
5763 	 *
5764 	 * cross-over = 23,168,000 bps
5765 	 * goal-time = 18000
5766 	 * per-tcb-max = 2
5767 	 * per-tcb-divisor = 1000
5768 	 * per-tcb-floor = 1
5769 	 *
5770 	 * This will get you "google bbr" behavior with respect to tso size.
5771 	 *
5772 	 * Note we do set anything TSO size until we are past the initial
5773 	 * window. Before that we gnerally use either a single MSS
5774 	 * or we use the full IW size (so we burst a IW at a time)
5775 	 */
5776 
5777 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options) {
5778 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5779 	} else {
5780 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5781 	}
5782 	old_tso = bbr->r_ctl.rc_pace_max_segs;
5783 	if (bbr->rc_past_init_win == 0) {
5784 		/*
5785 		 * Not enough data has been acknowledged to make a
5786 		 * judgement. Set up the initial TSO based on if we
5787 		 * are sending a full IW at once or not.
5788 		 */
5789 		if (bbr->rc_use_google)
5790 			bbr->r_ctl.rc_pace_max_segs = ((bbr->rc_tp->t_maxseg - bbr->rc_last_options) * 2);
5791 		else if (bbr->bbr_init_win_cheat)
5792 			bbr->r_ctl.rc_pace_max_segs = bbr_initial_cwnd(bbr, bbr->rc_tp);
5793 		else
5794 			bbr->r_ctl.rc_pace_max_segs = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5795 		if (bbr->r_ctl.rc_pace_min_segs != bbr->rc_tp->t_maxseg)
5796 			bbr->r_ctl.rc_pace_min_segs = bbr->rc_tp->t_maxseg;
5797 		if (bbr->r_ctl.rc_pace_max_segs == 0) {
5798 			bbr->r_ctl.rc_pace_max_segs = maxseg;
5799 		}
5800 		bbr_log_type_tsosize(bbr, cts, bbr->r_ctl.rc_pace_max_segs, tls_seg, old_tso, maxseg, 0);
5801 			bbr_adjust_for_hw_pacing(bbr, cts);
5802 		return;
5803 	}
5804 	/**
5805 	 * Now lets set the TSO goal based on our delivery rate in
5806 	 * bytes per second. Note we only do this if
5807 	 * we have acked at least the initial cwnd worth of data.
5808 	 */
5809 	bw = bbr_get_bw(bbr);
5810 	if (IN_RECOVERY(bbr->rc_tp->t_flags) &&
5811 	     (bbr->rc_use_google == 0)) {
5812 		/* We clamp to one MSS in recovery */
5813 		new_tso = maxseg;
5814 	} else if (bbr->rc_use_google) {
5815 		int min_tso_segs;
5816 
5817 		/* Google considers the gain too */
5818 		if (bbr->r_ctl.rc_bbr_hptsi_gain != BBR_UNIT) {
5819 			bw *= bbr->r_ctl.rc_bbr_hptsi_gain;
5820 			bw /= BBR_UNIT;
5821 		}
5822 		bytes = bw / 1024;
5823 		if (bytes > (64 * 1024))
5824 			bytes = 64 * 1024;
5825 		new_tso = bytes / maxseg;
5826 		if (bw < ONE_POINT_TWO_MEG)
5827 			min_tso_segs = 1;
5828 		else
5829 			min_tso_segs = 2;
5830 		if (new_tso < min_tso_segs)
5831 			new_tso = min_tso_segs;
5832 		new_tso *= maxseg;
5833 	} else if (bbr->rc_no_pacing) {
5834 		new_tso = (PACE_MAX_IP_BYTES / maxseg) * maxseg;
5835 	} else if (bw <= bbr->r_ctl.bbr_cross_over) {
5836 		/*
5837 		 * Calculate the worse case b/w TSO if we are inserting no
5838 		 * more than a delay_target number of TSO's.
5839 		 */
5840 		uint32_t tso_len, min_tso;
5841 
5842 		tso_len = bbr_get_pacing_length(bbr, BBR_UNIT, bbr->r_ctl.bbr_hptsi_segments_delay_tar, bw);
5843 		if (tso_len > maxseg) {
5844 			new_tso = tso_len / maxseg;
5845 			if (new_tso > bbr->r_ctl.bbr_hptsi_segments_max)
5846 				new_tso = bbr->r_ctl.bbr_hptsi_segments_max;
5847 			new_tso *= maxseg;
5848 		} else {
5849 			/*
5850 			 * less than a full sized frame yikes.. long rtt or
5851 			 * low bw?
5852 			 */
5853 			min_tso = bbr_minseg(bbr);
5854 			if ((tso_len > min_tso) && (bbr_all_get_min == 0))
5855 				new_tso = rounddown(tso_len, min_tso);
5856 			else
5857 				new_tso = min_tso;
5858 		}
5859 	} else if (bw > FIVETWELVE_MBPS) {
5860 		/*
5861 		 * This guy is so fast b/w wise that we can TSO as large as
5862 		 * possible of segments that the NIC will allow.
5863 		 */
5864 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5865 	} else {
5866 		/*
5867 		 * This formula is based on attempting to send a segment or
5868 		 * more every bbr_hptsi_per_second. The default is 1000
5869 		 * which means you are targeting what you can send every 1ms
5870 		 * based on the peers bw.
5871 		 *
5872 		 * If the number drops to say 500, then you are looking more
5873 		 * at 2ms and you will raise how much we send in a single
5874 		 * TSO thus saving CPU (less bbr_output_wtime() calls). The
5875 		 * trade off of course is you will send more at once and
5876 		 * thus tend to clump up the sends into larger "bursts"
5877 		 * building a queue.
5878 		 */
5879 		bw /= bbr->r_ctl.bbr_hptsi_per_second;
5880 		new_tso = roundup(bw, (uint64_t)maxseg);
5881 		/*
5882 		 * Gate the floor to match what our lower than 48Mbps
5883 		 * algorithm does. The ceiling (bbr_hptsi_segments_max) thus
5884 		 * becomes the floor for this calculation.
5885 		 */
5886 		if (new_tso < (bbr->r_ctl.bbr_hptsi_segments_max * maxseg))
5887 			new_tso = (bbr->r_ctl.bbr_hptsi_segments_max * maxseg);
5888 	}
5889 	if (bbr->r_ctl.bbr_hptsi_segments_floor && (new_tso < (maxseg * bbr->r_ctl.bbr_hptsi_segments_floor)))
5890 		new_tso = maxseg * bbr->r_ctl.bbr_hptsi_segments_floor;
5891 	if (new_tso > PACE_MAX_IP_BYTES)
5892 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5893 	/* Enforce an utter maximum. */
5894 	if (bbr->r_ctl.bbr_utter_max && (new_tso > (bbr->r_ctl.bbr_utter_max * maxseg))) {
5895 		new_tso = bbr->r_ctl.bbr_utter_max * maxseg;
5896 	}
5897 	if (old_tso != new_tso) {
5898 		/* Only log changes */
5899 		bbr_log_type_tsosize(bbr, cts, new_tso, tls_seg, old_tso, maxseg, 0);
5900 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5901 	}
5902 	/* We have hardware pacing! */
5903 	bbr_adjust_for_hw_pacing(bbr, cts);
5904 }
5905 
5906 static void
5907 bbr_log_output(struct tcp_bbr *bbr, struct tcpcb *tp, struct tcpopt *to, int32_t len,
5908     uint32_t seq_out, uint8_t th_flags, int32_t err, uint32_t cts,
5909     struct mbuf *mb, int32_t * abandon, struct bbr_sendmap *hintrsm, uint32_t delay_calc,
5910     struct sockbuf *sb)
5911 {
5912 
5913 	struct bbr_sendmap *rsm, *nrsm;
5914 	register uint32_t snd_max, snd_una;
5915 	uint32_t pacing_time;
5916 	/*
5917 	 * Add to the RACK log of packets in flight or retransmitted. If
5918 	 * there is a TS option we will use the TS echoed, if not we will
5919 	 * grab a TS.
5920 	 *
5921 	 * Retransmissions will increment the count and move the ts to its
5922 	 * proper place. Note that if options do not include TS's then we
5923 	 * won't be able to effectively use the ACK for an RTT on a retran.
5924 	 *
5925 	 * Notes about r_start and r_end. Lets consider a send starting at
5926 	 * sequence 1 for 10 bytes. In such an example the r_start would be
5927 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
5928 	 * This means that r_end is actually the first sequence for the next
5929 	 * slot (11).
5930 	 *
5931 	 */
5932 	INP_WLOCK_ASSERT(tp->t_inpcb);
5933 	if (err) {
5934 		/*
5935 		 * We don't log errors -- we could but snd_max does not
5936 		 * advance in this case either.
5937 		 */
5938 		return;
5939 	}
5940 	if (th_flags & TH_RST) {
5941 		/*
5942 		 * We don't log resets and we return immediately from
5943 		 * sending
5944 		 */
5945 		*abandon = 1;
5946 		return;
5947 	}
5948 	snd_una = tp->snd_una;
5949 	if (th_flags & (TH_SYN | TH_FIN) && (hintrsm == NULL)) {
5950 		/*
5951 		 * The call to bbr_log_output is made before bumping
5952 		 * snd_max. This means we can record one extra byte on a SYN
5953 		 * or FIN if seq_out is adding more on and a FIN is present
5954 		 * (and we are not resending).
5955 		 */
5956 		if ((th_flags & TH_SYN) && (tp->iss == seq_out))
5957 			len++;
5958 		if (th_flags & TH_FIN)
5959 			len++;
5960 	}
5961 	if (SEQ_LEQ((seq_out + len), snd_una)) {
5962 		/* Are sending an old segment to induce an ack (keep-alive)? */
5963 		return;
5964 	}
5965 	if (SEQ_LT(seq_out, snd_una)) {
5966 		/* huh? should we panic? */
5967 		uint32_t end;
5968 
5969 		end = seq_out + len;
5970 		seq_out = snd_una;
5971 		len = end - seq_out;
5972 	}
5973 	snd_max = tp->snd_max;
5974 	if (len == 0) {
5975 		/* We don't log zero window probes */
5976 		return;
5977 	}
5978 	pacing_time = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, len, cts, 1);
5979 	/* First question is it a retransmission? */
5980 	if (seq_out == snd_max) {
5981 again:
5982 		rsm = bbr_alloc(bbr);
5983 		if (rsm == NULL) {
5984 			return;
5985 		}
5986 		rsm->r_flags = 0;
5987 		if (th_flags & TH_SYN)
5988 			rsm->r_flags |= BBR_HAS_SYN;
5989 		if (th_flags & TH_FIN)
5990 			rsm->r_flags |= BBR_HAS_FIN;
5991 		rsm->r_tim_lastsent[0] = cts;
5992 		rsm->r_rtr_cnt = 1;
5993 		rsm->r_rtr_bytes = 0;
5994 		rsm->r_start = seq_out;
5995 		rsm->r_end = rsm->r_start + len;
5996 		rsm->r_dupack = 0;
5997 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
5998 		rsm->r_pacing_delay = pacing_time;
5999 		rsm->r_ts_valid = bbr->rc_ts_valid;
6000 		if (bbr->rc_ts_valid)
6001 			rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
6002 		rsm->r_del_time = bbr->r_ctl.rc_del_time;
6003 		if (bbr->r_ctl.r_app_limited_until)
6004 			rsm->r_app_limited = 1;
6005 		else
6006 			rsm->r_app_limited = 0;
6007 		rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
6008 		rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
6009 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
6010 		/*
6011 		 * Here we must also add in this rsm since snd_max
6012 		 * is updated after we return from a new send.
6013 		 */
6014 		rsm->r_flight_at_send += len;
6015 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
6016 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
6017 		rsm->r_in_tmap = 1;
6018 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
6019 			rsm->r_bbr_state = bbr_state_val(bbr);
6020 		else
6021 			rsm->r_bbr_state = 8;
6022 		if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
6023 			rsm->r_is_gain = 1;
6024 			rsm->r_is_drain = 0;
6025 		} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
6026 			rsm->r_is_drain = 1;
6027 			rsm->r_is_gain = 0;
6028 		} else {
6029 			rsm->r_is_drain = 0;
6030 			rsm->r_is_gain = 0;
6031 		}
6032 		return;
6033 	}
6034 	/*
6035 	 * If we reach here its a retransmission and we need to find it.
6036 	 */
6037 more:
6038 	if (hintrsm && (hintrsm->r_start == seq_out)) {
6039 		rsm = hintrsm;
6040 		hintrsm = NULL;
6041 	} else if (bbr->r_ctl.rc_next) {
6042 		/* We have a hint from a previous run */
6043 		rsm = bbr->r_ctl.rc_next;
6044 	} else {
6045 		/* No hints sorry */
6046 		rsm = NULL;
6047 	}
6048 	if ((rsm) && (rsm->r_start == seq_out)) {
6049 		/*
6050 		 * We used rc_next or hintrsm  to retransmit, hopefully the
6051 		 * likely case.
6052 		 */
6053 		seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6054 		if (len == 0) {
6055 			return;
6056 		} else {
6057 			goto more;
6058 		}
6059 	}
6060 	/* Ok it was not the last pointer go through it the hard way. */
6061 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6062 		if (rsm->r_start == seq_out) {
6063 			seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6064 			bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
6065 			if (len == 0) {
6066 				return;
6067 			} else {
6068 				continue;
6069 			}
6070 		}
6071 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
6072 			/* Transmitted within this piece */
6073 			/*
6074 			 * Ok we must split off the front and then let the
6075 			 * update do the rest
6076 			 */
6077 			nrsm = bbr_alloc_full_limit(bbr);
6078 			if (nrsm == NULL) {
6079 				bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
6080 				return;
6081 			}
6082 			/*
6083 			 * copy rsm to nrsm and then trim the front of rsm
6084 			 * to not include this part.
6085 			 */
6086 			bbr_clone_rsm(bbr, nrsm, rsm, seq_out);
6087 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
6088 			if (rsm->r_in_tmap) {
6089 				TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6090 				nrsm->r_in_tmap = 1;
6091 			}
6092 			rsm->r_flags &= (~BBR_HAS_FIN);
6093 			seq_out = bbr_update_entry(tp, bbr, nrsm, cts, &len, pacing_time);
6094 			if (len == 0) {
6095 				return;
6096 			}
6097 		}
6098 	}
6099 	/*
6100 	 * Hmm not found in map did they retransmit both old and on into the
6101 	 * new?
6102 	 */
6103 	if (seq_out == tp->snd_max) {
6104 		goto again;
6105 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
6106 #ifdef BBR_INVARIANTS
6107 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
6108 		    seq_out, len, tp->snd_una, tp->snd_max);
6109 		printf("Starting Dump of all rack entries\n");
6110 		TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6111 			printf("rsm:%p start:%u end:%u\n",
6112 			    rsm, rsm->r_start, rsm->r_end);
6113 		}
6114 		printf("Dump complete\n");
6115 		panic("seq_out not found rack:%p tp:%p",
6116 		    bbr, tp);
6117 #endif
6118 	} else {
6119 #ifdef BBR_INVARIANTS
6120 		/*
6121 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
6122 		 * flag)
6123 		 */
6124 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
6125 		    seq_out, len, tp->snd_max, tp);
6126 #endif
6127 	}
6128 }
6129 
6130 static void
6131 bbr_collapse_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, int32_t rtt)
6132 {
6133 	/*
6134 	 * Collapse timeout back the cum-ack moved.
6135 	 */
6136 	tp->t_rxtshift = 0;
6137 	tp->t_softerror = 0;
6138 }
6139 
6140 static void
6141 tcp_bbr_xmit_timer(struct tcp_bbr *bbr, uint32_t rtt_usecs, uint32_t rsm_send_time, uint32_t r_start, uint32_t tsin)
6142 {
6143 	bbr->rtt_valid = 1;
6144 	bbr->r_ctl.cur_rtt = rtt_usecs;
6145 	bbr->r_ctl.ts_in = tsin;
6146 	if (rsm_send_time)
6147 		bbr->r_ctl.cur_rtt_send_time = rsm_send_time;
6148 }
6149 
6150 static void
6151 bbr_make_timestamp_determination(struct tcp_bbr *bbr)
6152 {
6153 	/**
6154 	 * We have in our bbr control:
6155 	 * 1) The timestamp we started observing cum-acks (bbr->r_ctl.bbr_ts_check_tstmp).
6156 	 * 2) Our timestamp indicating when we sent that packet (bbr->r_ctl.rsm->bbr_ts_check_our_cts).
6157 	 * 3) The current timestamp that just came in (bbr->r_ctl.last_inbound_ts)
6158 	 * 4) The time that the packet that generated that ack was sent (bbr->r_ctl.cur_rtt_send_time)
6159 	 *
6160 	 * Now we can calculate the time between the sends by doing:
6161 	 *
6162 	 * delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts
6163 	 *
6164 	 * And the peer's time between receiving them by doing:
6165 	 *
6166 	 * peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp
6167 	 *
6168 	 * We want to figure out if the timestamp values are in msec, 10msec or usec.
6169 	 * We also may find that we can't use the timestamps if say we see
6170 	 * that the peer_delta indicates that though we may have taken 10ms to
6171 	 * pace out the data, it only saw 1ms between the two packets. This would
6172 	 * indicate that somewhere on the path is a batching entity that is giving
6173 	 * out time-slices of the actual b/w. This would mean we could not use
6174 	 * reliably the peers timestamps.
6175 	 *
6176 	 * We expect delta > peer_delta initially. Until we figure out the
6177 	 * timestamp difference which we will store in bbr->r_ctl.bbr_peer_tsratio.
6178 	 * If we place 1000 there then its a ms vs our usec. If we place 10000 there
6179 	 * then its 10ms vs our usec. If the peer is running a usec clock we would
6180 	 * put a 1 there. If the value is faster then ours, we will disable the
6181 	 * use of timestamps (though we could revist this later if we find it to be not
6182 	 * just an isolated one or two flows)).
6183 	 *
6184 	 * To detect the batching middle boxes we will come up with our compensation and
6185 	 * if with it in place, we find the peer is drastically off (by some margin) in
6186 	 * the smaller direction, then we will assume the worst case and disable use of timestamps.
6187 	 *
6188 	 */
6189 	uint64_t delta, peer_delta, delta_up;
6190 
6191 	delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts;
6192 	if (delta < bbr_min_usec_delta) {
6193 		/*
6194 		 * Have not seen a min amount of time
6195 		 * between our send times so we can
6196 		 * make a determination of the timestamp
6197 		 * yet.
6198 		 */
6199 		return;
6200 	}
6201 	peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp;
6202 	if (peer_delta < bbr_min_peer_delta) {
6203 		/*
6204 		 * We may have enough in the form of
6205 		 * our delta but the peers number
6206 		 * has not changed that much. It could
6207 		 * be its clock ratio is such that
6208 		 * we need more data (10ms tick) or
6209 		 * there may be other compression scenarios
6210 		 * going on. In any event we need the
6211 		 * spread to be larger.
6212 		 */
6213 		return;
6214 	}
6215 	/* Ok lets first see which way our delta is going */
6216 	if (peer_delta > delta) {
6217 		/* Very unlikely, the peer without
6218 		 * compensation shows that it saw
6219 		 * the two sends arrive further apart
6220 		 * then we saw then in micro-seconds.
6221 		 */
6222 		if (peer_delta < (delta + ((delta * (uint64_t)1000)/ (uint64_t)bbr_delta_percent))) {
6223 			/* well it looks like the peer is a micro-second clock. */
6224 			bbr->rc_ts_clock_set = 1;
6225 			bbr->r_ctl.bbr_peer_tsratio = 1;
6226 		} else {
6227 			bbr->rc_ts_cant_be_used = 1;
6228 			bbr->rc_ts_clock_set = 1;
6229 		}
6230 		return;
6231 	}
6232 	/* Ok we know that the peer_delta is smaller than our send distance */
6233 	bbr->rc_ts_clock_set = 1;
6234 	/* First question is it within the percentage that they are using usec time? */
6235 	delta_up = (peer_delta * 1000) / (uint64_t)bbr_delta_percent;
6236 	if ((peer_delta + delta_up) >= delta) {
6237 		/* Its a usec clock */
6238 		bbr->r_ctl.bbr_peer_tsratio = 1;
6239 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6240 		return;
6241 	}
6242 	/* Ok if not usec, what about 10usec (though unlikely)? */
6243 	delta_up = (peer_delta * 1000 * 10) / (uint64_t)bbr_delta_percent;
6244 	if (((peer_delta * 10) + delta_up) >= delta) {
6245 		bbr->r_ctl.bbr_peer_tsratio = 10;
6246 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6247 		return;
6248 	}
6249 	/* And what about 100usec (though again unlikely)? */
6250 	delta_up = (peer_delta * 1000 * 100) / (uint64_t)bbr_delta_percent;
6251 	if (((peer_delta * 100) + delta_up) >= delta) {
6252 		bbr->r_ctl.bbr_peer_tsratio = 100;
6253 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6254 		return;
6255 	}
6256 	/* And how about 1 msec (the most likely one)? */
6257 	delta_up = (peer_delta * 1000 * 1000) / (uint64_t)bbr_delta_percent;
6258 	if (((peer_delta * 1000) + delta_up) >= delta) {
6259 		bbr->r_ctl.bbr_peer_tsratio = 1000;
6260 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6261 		return;
6262 	}
6263 	/* Ok if not msec could it be 10 msec? */
6264 	delta_up = (peer_delta * 1000 * 10000) / (uint64_t)bbr_delta_percent;
6265 	if (((peer_delta * 10000) + delta_up) >= delta) {
6266 		bbr->r_ctl.bbr_peer_tsratio = 10000;
6267 		return;
6268 	}
6269 	/* If we fall down here the clock tick so slowly we can't use it */
6270 	bbr->rc_ts_cant_be_used = 1;
6271 	bbr->r_ctl.bbr_peer_tsratio = 0;
6272 	bbr_log_tstmp_validation(bbr, peer_delta, delta);
6273 }
6274 
6275 /*
6276  * Collect new round-trip time estimate
6277  * and update averages and current timeout.
6278  */
6279 static void
6280 tcp_bbr_xmit_timer_commit(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts)
6281 {
6282 	int32_t delta;
6283 	uint32_t rtt, tsin;
6284 	int32_t rtt_ticks;
6285 
6286 	if (bbr->rtt_valid == 0)
6287 		/* No valid sample */
6288 		return;
6289 
6290 	rtt = bbr->r_ctl.cur_rtt;
6291 	tsin = bbr->r_ctl.ts_in;
6292 	if (bbr->rc_prtt_set_ts) {
6293 		/*
6294 		 * We are to force feed the rttProp filter due
6295 		 * to an entry into PROBE_RTT. This assures
6296 		 * that the times are sync'd between when we
6297 		 * go into PROBE_RTT and the filter expiration.
6298 		 *
6299 		 * Google does not use a true filter, so they do
6300 		 * this implicitly since they only keep one value
6301 		 * and when they enter probe-rtt they update the
6302 		 * value to the newest rtt.
6303 		 */
6304 		uint32_t rtt_prop;
6305 
6306 		bbr->rc_prtt_set_ts = 0;
6307 		rtt_prop = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
6308 		if (rtt > rtt_prop)
6309 			filter_increase_by_small(&bbr->r_ctl.rc_rttprop, (rtt - rtt_prop), cts);
6310 		else
6311 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6312 	}
6313 	if (bbr->rc_ack_was_delayed)
6314 		rtt += bbr->r_ctl.rc_ack_hdwr_delay;
6315 
6316 	if (rtt < bbr->r_ctl.rc_lowest_rtt)
6317 		bbr->r_ctl.rc_lowest_rtt = rtt;
6318 	bbr_log_rtt_sample(bbr, rtt, tsin);
6319 	if (bbr->r_init_rtt) {
6320 		/*
6321 		 * The initial rtt is not-trusted, nuke it and lets get
6322 		 * our first valid measurement in.
6323 		 */
6324 		bbr->r_init_rtt = 0;
6325 		tp->t_srtt = 0;
6326 	}
6327 	if ((bbr->rc_ts_clock_set == 0) && bbr->rc_ts_valid) {
6328 		/*
6329 		 * So we have not yet figured out
6330 		 * what the peers TSTMP value is
6331 		 * in (most likely ms). We need a
6332 		 * series of cum-ack's to determine
6333 		 * this reliably.
6334 		 */
6335 		if (bbr->rc_ack_is_cumack) {
6336 			if (bbr->rc_ts_data_set) {
6337 				/* Lets attempt to determine the timestamp granularity. */
6338 				bbr_make_timestamp_determination(bbr);
6339 			} else {
6340 				bbr->rc_ts_data_set = 1;
6341 				bbr->r_ctl.bbr_ts_check_tstmp = bbr->r_ctl.last_inbound_ts;
6342 				bbr->r_ctl.bbr_ts_check_our_cts = bbr->r_ctl.cur_rtt_send_time;
6343 			}
6344 		} else {
6345 			/*
6346 			 * We have to have consecutive acks
6347 			 * reset any "filled" state to none.
6348 			 */
6349 			bbr->rc_ts_data_set = 0;
6350 		}
6351 	}
6352 	/* Round it up */
6353 	rtt_ticks = USEC_2_TICKS((rtt + (USECS_IN_MSEC - 1)));
6354 	if (rtt_ticks == 0)
6355 		rtt_ticks = 1;
6356 	if (tp->t_srtt != 0) {
6357 		/*
6358 		 * srtt is stored as fixed point with 5 bits after the
6359 		 * binary point (i.e., scaled by 8).  The following magic is
6360 		 * equivalent to the smoothing algorithm in rfc793 with an
6361 		 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6362 		 * Adjust rtt to origin 0.
6363 		 */
6364 
6365 		delta = ((rtt_ticks - 1) << TCP_DELTA_SHIFT)
6366 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6367 
6368 		tp->t_srtt += delta;
6369 		if (tp->t_srtt <= 0)
6370 			tp->t_srtt = 1;
6371 
6372 		/*
6373 		 * We accumulate a smoothed rtt variance (actually, a
6374 		 * smoothed mean difference), then set the retransmit timer
6375 		 * to smoothed rtt + 4 times the smoothed variance. rttvar
6376 		 * is stored as fixed point with 4 bits after the binary
6377 		 * point (scaled by 16).  The following is equivalent to
6378 		 * rfc793 smoothing with an alpha of .75 (rttvar =
6379 		 * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
6380 		 * wired-in beta.
6381 		 */
6382 		if (delta < 0)
6383 			delta = -delta;
6384 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6385 		tp->t_rttvar += delta;
6386 		if (tp->t_rttvar <= 0)
6387 			tp->t_rttvar = 1;
6388 		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
6389 			tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6390 	} else {
6391 		/*
6392 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
6393 		 * variance to half the rtt (so our first retransmit happens
6394 		 * at 3*rtt).
6395 		 */
6396 		tp->t_srtt = rtt_ticks << TCP_RTT_SHIFT;
6397 		tp->t_rttvar = rtt_ticks << (TCP_RTTVAR_SHIFT - 1);
6398 		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6399 	}
6400 	KMOD_TCPSTAT_INC(tcps_rttupdated);
6401 	tp->t_rttupdated++;
6402 #ifdef STATS
6403 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt_ticks));
6404 #endif
6405 	/*
6406 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
6407 	 * way we do the smoothing, srtt and rttvar will each average +1/2
6408 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
6409 	 * tick of rounding and 1 extra tick because of +-1/2 tick
6410 	 * uncertainty in the firing of the timer.  The bias will give us
6411 	 * exactly the 1.5 tick we need.  But, because the bias is
6412 	 * statistical, we have to test that we don't drop below the minimum
6413 	 * feasible timer (which is 2 ticks).
6414 	 */
6415 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6416 	    max(MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms), rtt_ticks + 2),
6417 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
6418 
6419 	/*
6420 	 * We received an ack for a packet that wasn't retransmitted; it is
6421 	 * probably safe to discard any error indications we've received
6422 	 * recently.  This isn't quite right, but close enough for now (a
6423 	 * route might have failed after we sent a segment, and the return
6424 	 * path might not be symmetrical).
6425 	 */
6426 	tp->t_softerror = 0;
6427 	rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
6428 	if (bbr->r_ctl.bbr_smallest_srtt_this_state > rtt)
6429 		bbr->r_ctl.bbr_smallest_srtt_this_state = rtt;
6430 }
6431 
6432 static void
6433 bbr_earlier_retran(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm,
6434 		   uint32_t t, uint32_t cts, int ack_type)
6435 {
6436 	/*
6437 	 * For this RSM, we acknowledged the data from a previous
6438 	 * transmission, not the last one we made. This means we did a false
6439 	 * retransmit.
6440 	 */
6441 	if (rsm->r_flags & BBR_HAS_FIN) {
6442 		/*
6443 		 * The sending of the FIN often is multiple sent when we
6444 		 * have everything outstanding ack'd. We ignore this case
6445 		 * since its over now.
6446 		 */
6447 		return;
6448 	}
6449 	if (rsm->r_flags & BBR_TLP) {
6450 		/*
6451 		 * We expect TLP's to have this occur often
6452 		 */
6453 		bbr->rc_tlp_rtx_out = 0;
6454 		return;
6455 	}
6456 	if (ack_type != BBR_CUM_ACKED) {
6457 		/*
6458 		 * If it was not a cum-ack we
6459 		 * don't really know for sure since
6460 		 * the timestamp could be from some
6461 		 * other transmission.
6462 		 */
6463 		return;
6464 	}
6465 
6466 	if (rsm->r_flags & BBR_WAS_SACKPASS) {
6467 		/*
6468 		 * We retransmitted based on a sack and the earlier
6469 		 * retransmission ack'd it - re-ordering is occuring.
6470 		 */
6471 		BBR_STAT_INC(bbr_reorder_seen);
6472 		bbr->r_ctl.rc_reorder_ts = cts;
6473 	}
6474 	/* Back down the loss count */
6475 	if (rsm->r_flags & BBR_MARKED_LOST) {
6476 		bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
6477 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
6478 		rsm->r_flags &= ~BBR_MARKED_LOST;
6479 		if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
6480 			/* LT sampling also needs adjustment */
6481 			bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
6482 	}
6483 	/***** RRS HERE ************************/
6484 	/* Do we need to do this???            */
6485 	/* bbr_reset_lt_bw_sampling(bbr, cts); */
6486 	/***** RRS HERE ************************/
6487 	BBR_STAT_INC(bbr_badfr);
6488 	BBR_STAT_ADD(bbr_badfr_bytes, (rsm->r_end - rsm->r_start));
6489 }
6490 
6491 static void
6492 bbr_set_reduced_rtt(struct tcp_bbr *bbr, uint32_t cts, uint32_t line)
6493 {
6494 	bbr->r_ctl.rc_rtt_shrinks = cts;
6495 	if (bbr_can_force_probertt &&
6496 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
6497 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
6498 		/*
6499 		 * We should enter probe-rtt its been too long
6500 		 * since we have been there.
6501 		 */
6502 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
6503 	} else
6504 		bbr_check_probe_rtt_limits(bbr, cts);
6505 }
6506 
6507 static void
6508 tcp_bbr_commit_bw(struct tcp_bbr *bbr, uint32_t cts)
6509 {
6510 	uint64_t orig_bw;
6511 
6512 	if (bbr->r_ctl.rc_bbr_cur_del_rate == 0) {
6513 		/* We never apply a zero measurment */
6514 		bbr_log_type_bbrupd(bbr, 20, cts, 0, 0,
6515 				    0, 0, 0, 0, 0, 0);
6516 		return;
6517 	}
6518 	if (bbr->r_ctl.r_measurement_count < 0xffffffff)
6519 		bbr->r_ctl.r_measurement_count++;
6520 	orig_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
6521 	apply_filter_max(&bbr->r_ctl.rc_delrate, bbr->r_ctl.rc_bbr_cur_del_rate, bbr->r_ctl.rc_pkt_epoch);
6522 	bbr_log_type_bbrupd(bbr, 21, cts, (uint32_t)orig_bw,
6523 			    (uint32_t)get_filter_value(&bbr->r_ctl.rc_delrate),
6524 			    0, 0, 0, 0, 0, 0);
6525 	if (orig_bw &&
6526 	    (orig_bw != get_filter_value(&bbr->r_ctl.rc_delrate))) {
6527 		if (bbr->bbr_hdrw_pacing) {
6528 			/*
6529 			 * Apply a new rate to the hardware
6530 			 * possibly.
6531 			 */
6532 			bbr_update_hardware_pacing_rate(bbr, cts);
6533 		}
6534 		bbr_set_state_target(bbr, __LINE__);
6535 		tcp_bbr_tso_size_check(bbr, cts);
6536 		if (bbr->r_recovery_bw)  {
6537 			bbr_setup_red_bw(bbr, cts);
6538 			bbr_log_type_bw_reduce(bbr, BBR_RED_BW_USELRBW);
6539 		}
6540 	} else if ((orig_bw == 0) && get_filter_value(&bbr->r_ctl.rc_delrate))
6541 		tcp_bbr_tso_size_check(bbr, cts);
6542 }
6543 
6544 static void
6545 bbr_nf_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6546 {
6547 	if (bbr->rc_in_persist == 0) {
6548 		/* We log only when not in persist */
6549 		/* Translate to a Bytes Per Second */
6550 		uint64_t tim, bw, ts_diff, ts_bw;
6551 		uint32_t upper, lower, delivered;
6552 
6553 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6554 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6555 		else
6556 			tim = 1;
6557 		/*
6558 		 * Now that we have processed the tim (skipping the sample
6559 		 * or possibly updating the time, go ahead and
6560 		 * calculate the cdr.
6561 		 */
6562 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6563 		bw = (uint64_t)delivered;
6564 		bw *= (uint64_t)USECS_IN_SECOND;
6565 		bw /= tim;
6566 		if (bw == 0) {
6567 			/* We must have a calculatable amount */
6568 			return;
6569 		}
6570 		upper = (bw >> 32) & 0x00000000ffffffff;
6571 		lower = bw & 0x00000000ffffffff;
6572 		/*
6573 		 * If we are using this b/w shove it in now so we
6574 		 * can see in the trace viewer if it gets over-ridden.
6575 		 */
6576 		if (rsm->r_ts_valid &&
6577 		    bbr->rc_ts_valid &&
6578 		    bbr->rc_ts_clock_set &&
6579 		    (bbr->rc_ts_cant_be_used == 0) &&
6580 		    bbr->rc_use_ts_limit) {
6581 			ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6582 			ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6583 			if ((delivered == 0) ||
6584 			    (rtt < 1000)) {
6585 				/* Can't use the ts */
6586 				bbr_log_type_bbrupd(bbr, 61, cts,
6587 						    ts_diff,
6588 						    bbr->r_ctl.last_inbound_ts,
6589 						    rsm->r_del_ack_ts, 0,
6590 						    0, 0, 0, delivered);
6591 			} else {
6592 				ts_bw = (uint64_t)delivered;
6593 				ts_bw *= (uint64_t)USECS_IN_SECOND;
6594 				ts_bw /= ts_diff;
6595 				bbr_log_type_bbrupd(bbr, 62, cts,
6596 						    (ts_bw >> 32),
6597 						    (ts_bw & 0xffffffff), 0, 0,
6598 						    0, 0, ts_diff, delivered);
6599 				if ((bbr->ts_can_raise) &&
6600 				    (ts_bw > bw)) {
6601 					bbr_log_type_bbrupd(bbr, 8, cts,
6602 							    delivered,
6603 							    ts_diff,
6604 							    (bw >> 32),
6605 							    (bw & 0x00000000ffffffff),
6606 							    0, 0, 0, 0);
6607 					bw = ts_bw;
6608 				} else if (ts_bw && (ts_bw < bw)) {
6609 					bbr_log_type_bbrupd(bbr, 7, cts,
6610 							    delivered,
6611 							    ts_diff,
6612 							    (bw >> 32),
6613 							    (bw & 0x00000000ffffffff),
6614 							    0, 0, 0, 0);
6615 					bw = ts_bw;
6616 				}
6617 			}
6618 		}
6619 		if (rsm->r_first_sent_time &&
6620 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6621 			uint64_t sbw, sti;
6622 			/*
6623 			 * We use what was in flight at the time of our
6624 			 * send  and the size of this send to figure
6625 			 * out what we have been sending at (amount).
6626 			 * For the time we take from the time of
6627 			 * the send of the first send outstanding
6628 			 * until this send plus this sends pacing
6629 			 * time. This gives us a good calculation
6630 			 * as to the rate we have been sending at.
6631 			 */
6632 
6633 			sbw = (uint64_t)(rsm->r_flight_at_send);
6634 			sbw *= (uint64_t)USECS_IN_SECOND;
6635 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6636 			sti += rsm->r_pacing_delay;
6637 			sbw /= sti;
6638 			if (sbw < bw) {
6639 				bbr_log_type_bbrupd(bbr, 6, cts,
6640 						    delivered,
6641 						    (uint32_t)sti,
6642 						    (bw >> 32),
6643 						    (uint32_t)bw,
6644 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6645 						    (uint32_t)sbw);
6646 				bw = sbw;
6647 			}
6648 		}
6649 		/* Use the google algorithm for b/w measurements */
6650 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6651 		if ((rsm->r_app_limited == 0) ||
6652 		    (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6653 			tcp_bbr_commit_bw(bbr, cts);
6654 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6655 					    0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6656 		}
6657 	}
6658 }
6659 
6660 static void
6661 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6662 {
6663 	if (bbr->rc_in_persist == 0) {
6664 		/* We log only when not in persist */
6665 		/* Translate to a Bytes Per Second */
6666 		uint64_t tim, bw;
6667 		uint32_t upper, lower, delivered;
6668 		int no_apply = 0;
6669 
6670 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6671 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6672 		else
6673 			tim = 1;
6674 		/*
6675 		 * Now that we have processed the tim (skipping the sample
6676 		 * or possibly updating the time, go ahead and
6677 		 * calculate the cdr.
6678 		 */
6679 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6680 		bw = (uint64_t)delivered;
6681 		bw *= (uint64_t)USECS_IN_SECOND;
6682 		bw /= tim;
6683 		if (tim < bbr->r_ctl.rc_lowest_rtt) {
6684 			bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6685 					    tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6686 
6687 			no_apply = 1;
6688 		}
6689 		upper = (bw >> 32) & 0x00000000ffffffff;
6690 		lower = bw & 0x00000000ffffffff;
6691 		/*
6692 		 * If we are using this b/w shove it in now so we
6693 		 * can see in the trace viewer if it gets over-ridden.
6694 		 */
6695 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6696 		/* Gate by the sending rate */
6697 		if (rsm->r_first_sent_time &&
6698 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6699 			uint64_t sbw, sti;
6700 			/*
6701 			 * We use what was in flight at the time of our
6702 			 * send  and the size of this send to figure
6703 			 * out what we have been sending at (amount).
6704 			 * For the time we take from the time of
6705 			 * the send of the first send outstanding
6706 			 * until this send plus this sends pacing
6707 			 * time. This gives us a good calculation
6708 			 * as to the rate we have been sending at.
6709 			 */
6710 
6711 			sbw = (uint64_t)(rsm->r_flight_at_send);
6712 			sbw *= (uint64_t)USECS_IN_SECOND;
6713 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6714 			sti += rsm->r_pacing_delay;
6715 			sbw /= sti;
6716 			if (sbw < bw) {
6717 				bbr_log_type_bbrupd(bbr, 6, cts,
6718 						    delivered,
6719 						    (uint32_t)sti,
6720 						    (bw >> 32),
6721 						    (uint32_t)bw,
6722 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6723 						    (uint32_t)sbw);
6724 				bw = sbw;
6725 			}
6726 			if ((sti > tim) &&
6727 			    (sti < bbr->r_ctl.rc_lowest_rtt)) {
6728 				bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6729 						    (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6730 				no_apply = 1;
6731 			} else
6732 				no_apply = 0;
6733 		}
6734 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6735 		if ((no_apply == 0) &&
6736 		    ((rsm->r_app_limited == 0) ||
6737 		     (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6738 			tcp_bbr_commit_bw(bbr, cts);
6739 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6740 					    0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6741 		}
6742 	}
6743 }
6744 
6745 static void
6746 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6747     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6748 {
6749 	uint64_t old_rttprop;
6750 
6751 	/* Update our delivery time and amount */
6752 	bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6753 	bbr->r_ctl.rc_del_time = cts;
6754 	if (rtt == 0) {
6755 		/*
6756 		 * 0 means its a retransmit, for now we don't use these for
6757 		 * the rest of BBR.
6758 		 */
6759 		return;
6760 	}
6761 	if ((bbr->rc_use_google == 0) &&
6762 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6763 	    (match != BBR_RTT_BY_TIMESTAMP)){
6764 		/*
6765 		 * We get a lot of rtt updates, lets not pay attention to
6766 		 * any that are not an exact match. That way we don't have
6767 		 * to worry about timestamps and the whole nonsense of
6768 		 * unsure if its a retransmission etc (if we ever had the
6769 		 * timestamp fixed to always have the last thing sent this
6770 		 * would not be a issue).
6771 		 */
6772 		return;
6773 	}
6774 	if ((bbr_no_retran && bbr->rc_use_google) &&
6775 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6776 	    (match != BBR_RTT_BY_TIMESTAMP)){
6777 		/*
6778 		 * We only do measurements in google mode
6779 		 * with bbr_no_retran on for sure things.
6780 		 */
6781 		return;
6782 	}
6783 	/* Only update srtt if we know by exact match */
6784 	tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6785 	if (ack_type == BBR_CUM_ACKED)
6786 		bbr->rc_ack_is_cumack = 1;
6787 	else
6788 		bbr->rc_ack_is_cumack = 0;
6789 	old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6790         /*
6791 	 * Note the following code differs to the original
6792 	 * BBR spec. It calls for <= not <. However after a
6793 	 * long discussion in email with Neal, he acknowledged
6794 	 * that it should be < than so that we will have flows
6795 	 * going into probe-rtt (we were seeing cases where that
6796 	 * did not happen and caused ugly things to occur). We
6797 	 * have added this agreed upon fix to our code base.
6798 	 */
6799 	if (rtt < old_rttprop) {
6800 		/* Update when we last saw a rtt drop */
6801 		bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6802 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
6803 	}
6804 	bbr_log_type_bbrrttprop(bbr, rtt, (rsm ? rsm->r_end : 0), uts, cts,
6805 	    match, rsm->r_start, rsm->r_flags);
6806 	apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6807 	if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6808 		/*
6809 		 * The RTT-prop moved, reset the target (may be a
6810 		 * nop for some states).
6811 		 */
6812 		bbr_set_state_target(bbr, __LINE__);
6813 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6814 			bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6815 					    __LINE__, BBR_RTTS_NEW_TARGET, 0);
6816 		else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6817 			/* It went up */
6818 			bbr_check_probe_rtt_limits(bbr, cts);
6819 	}
6820 	if ((bbr->rc_use_google == 0) &&
6821 	    (match == BBR_RTT_BY_TIMESTAMP)) {
6822 		/*
6823 		 * We don't do b/w update with
6824 		 * these since they are not really
6825 		 * reliable.
6826 		 */
6827 		return;
6828 	}
6829 	if (bbr->r_ctl.r_app_limited_until &&
6830 	    (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6831 		/* We are no longer app-limited */
6832 		bbr->r_ctl.r_app_limited_until = 0;
6833 	}
6834 	if (bbr->rc_use_google) {
6835 		bbr_google_measurement(bbr, rsm, rtt, cts);
6836 	} else {
6837 		bbr_nf_measurement(bbr, rsm, rtt, cts);
6838 	}
6839 }
6840 
6841 /*
6842  * Convert a timestamp that the main stack
6843  * uses (milliseconds) into one that bbr uses
6844  * (microseconds). Return that converted timestamp.
6845  */
6846 static uint32_t
6847 bbr_ts_convert(uint32_t cts) {
6848 	uint32_t sec, msec;
6849 
6850 	sec = cts / MS_IN_USEC;
6851 	msec = cts - (MS_IN_USEC * sec);
6852 	return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6853 }
6854 
6855 /*
6856  * Return 0 if we did not update the RTT time, return
6857  * 1 if we did.
6858  */
6859 static int
6860 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6861     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6862 {
6863 	int32_t i;
6864 	uint32_t t, uts = 0;
6865 
6866 	if ((rsm->r_flags & BBR_ACKED) ||
6867 	    (rsm->r_flags & BBR_WAS_RENEGED) ||
6868 	    (rsm->r_flags & BBR_RXT_CLEARED)) {
6869 		/* Already done */
6870 		return (0);
6871 	}
6872 	if (rsm->r_rtr_cnt == 1) {
6873 		/*
6874 		 * Only one transmit. Hopefully the normal case.
6875 		 */
6876 		if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6877 			t = cts - rsm->r_tim_lastsent[0];
6878 		else
6879 			t = 1;
6880 		if ((int)t <= 0)
6881 			t = 1;
6882 		bbr->r_ctl.rc_last_rtt = t;
6883 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6884 				    BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6885 		return (1);
6886 	}
6887 	/* Convert to usecs */
6888 	if ((bbr_can_use_ts_for_rtt == 1) &&
6889 	    (bbr->rc_use_google == 1) &&
6890 	    (ack_type == BBR_CUM_ACKED) &&
6891 	    (to->to_flags & TOF_TS) &&
6892 	    (to->to_tsecr != 0)) {
6893 		t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
6894 		if (t < 1)
6895 			t = 1;
6896 		t *= MS_IN_USEC;
6897 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6898 				    BBR_RTT_BY_TIMESTAMP,
6899 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
6900 				    ack_type, to);
6901 		return (1);
6902 	}
6903 	uts = bbr_ts_convert(to->to_tsecr);
6904 	if ((to->to_flags & TOF_TS) &&
6905 	    (to->to_tsecr != 0) &&
6906 	    (ack_type == BBR_CUM_ACKED) &&
6907 	    ((rsm->r_flags & BBR_OVERMAX) == 0)) {
6908 		/*
6909 		 * Now which timestamp does it match? In this block the ACK
6910 		 * may be coming from a previous transmission.
6911 		 */
6912 		uint32_t fudge;
6913 
6914 		fudge = BBR_TIMER_FUDGE;
6915 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
6916 			if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
6917 			    (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
6918 				if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6919 					t = cts - rsm->r_tim_lastsent[i];
6920 				else
6921 					t = 1;
6922 				if ((int)t <= 0)
6923 					t = 1;
6924 				bbr->r_ctl.rc_last_rtt = t;
6925 				bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
6926 						    rsm->r_tim_lastsent[i], ack_type, to);
6927 				if ((i + 1) < rsm->r_rtr_cnt) {
6928 					/* Likely */
6929 					bbr_earlier_retran(tp, bbr, rsm, t, cts, ack_type);
6930 				} else if (rsm->r_flags & BBR_TLP) {
6931 					bbr->rc_tlp_rtx_out = 0;
6932 				}
6933 				return (1);
6934 			}
6935 		}
6936 		/* Fall through if we can't find a matching timestamp */
6937 	}
6938 	/*
6939 	 * Ok its a SACK block that we retransmitted. or a windows
6940 	 * machine without timestamps. We can tell nothing from the
6941 	 * time-stamp since its not there or the time the peer last
6942 	 * recieved a segment that moved forward its cum-ack point.
6943 	 *
6944 	 * Lets look at the last retransmit and see what we can tell
6945 	 * (with BBR for space we only keep 2 note we have to keep
6946 	 * at least 2 so the map can not be condensed more).
6947 	 */
6948 	i = rsm->r_rtr_cnt - 1;
6949 	if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6950 		t = cts - rsm->r_tim_lastsent[i];
6951 	else
6952 		goto not_sure;
6953 	if (t < bbr->r_ctl.rc_lowest_rtt) {
6954 		/*
6955 		 * We retransmitted and the ack came back in less
6956 		 * than the smallest rtt we have observed in the
6957 		 * windowed rtt. We most likey did an improper
6958 		 * retransmit as outlined in 4.2 Step 3 point 2 in
6959 		 * the rack-draft.
6960 		 *
6961 		 * Use the prior transmission to update all the
6962 		 * information as long as there is only one prior
6963 		 * transmission.
6964 		 */
6965 		if ((rsm->r_flags & BBR_OVERMAX) == 0) {
6966 #ifdef BBR_INVARIANTS
6967 			if (rsm->r_rtr_cnt == 1)
6968 				panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
6969 #endif
6970 			i = rsm->r_rtr_cnt - 2;
6971 			if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6972 				t = cts - rsm->r_tim_lastsent[i];
6973 			else
6974 				t = 1;
6975 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
6976 					    rsm->r_tim_lastsent[i], ack_type, to);
6977 			bbr_earlier_retran(tp, bbr, rsm, t, cts, ack_type);
6978 		} else {
6979 			/*
6980 			 * Too many prior transmissions, just
6981 			 * updated BBR delivered
6982 			 */
6983 not_sure:
6984 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6985 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6986 		}
6987 	} else {
6988 		/*
6989 		 * We retransmitted it and the retransmit did the
6990 		 * job.
6991 		 */
6992 		if (rsm->r_flags & BBR_TLP)
6993 			bbr->rc_tlp_rtx_out = 0;
6994 		if ((rsm->r_flags & BBR_OVERMAX) == 0)
6995 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
6996 					    BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
6997 		else
6998 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6999 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
7000 		return (1);
7001 	}
7002 	return (0);
7003 }
7004 
7005 /*
7006  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
7007  */
7008 static void
7009 bbr_log_sack_passed(struct tcpcb *tp,
7010     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
7011 {
7012 	struct bbr_sendmap *nrsm;
7013 
7014 	nrsm = rsm;
7015 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
7016 	    bbr_head, r_tnext) {
7017 		if (nrsm == rsm) {
7018 			/* Skip orginal segment he is acked */
7019 			continue;
7020 		}
7021 		if (nrsm->r_flags & BBR_ACKED) {
7022 			/* Skip ack'd segments */
7023 			continue;
7024 		}
7025 		if (nrsm->r_flags & BBR_SACK_PASSED) {
7026 			/*
7027 			 * We found one that is already marked
7028 			 * passed, we have been here before and
7029 			 * so all others below this are marked.
7030 			 */
7031 			break;
7032 		}
7033 		BBR_STAT_INC(bbr_sack_passed);
7034 		nrsm->r_flags |= BBR_SACK_PASSED;
7035 		if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
7036 		    bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
7037 			bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
7038 			bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
7039 			nrsm->r_flags |= BBR_MARKED_LOST;
7040 		}
7041 		nrsm->r_flags &= ~BBR_WAS_SACKPASS;
7042 	}
7043 }
7044 
7045 /*
7046  * Returns the number of bytes that were
7047  * newly ack'd by sack blocks.
7048  */
7049 static uint32_t
7050 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
7051     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
7052 {
7053 	int32_t times = 0;
7054 	uint32_t start, end, maxseg, changed = 0;
7055 	struct bbr_sendmap *rsm, *nrsm;
7056 	int32_t used_ref = 1;
7057 	uint8_t went_back = 0, went_fwd = 0;
7058 
7059 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7060 	start = sack->start;
7061 	end = sack->end;
7062 	rsm = *prsm;
7063 	if (rsm == NULL)
7064 		used_ref = 0;
7065 
7066 	/* Do we locate the block behind where we last were? */
7067 	if (rsm && SEQ_LT(start, rsm->r_start)) {
7068 		went_back = 1;
7069 		TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
7070 			if (SEQ_GEQ(start, rsm->r_start) &&
7071 			    SEQ_LT(start, rsm->r_end)) {
7072 				goto do_rest_ofb;
7073 			}
7074 		}
7075 	}
7076 start_at_beginning:
7077 	went_fwd = 1;
7078 	/*
7079 	 * Ok lets locate the block where this guy is fwd from rsm (if its
7080 	 * set)
7081 	 */
7082 	TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
7083 		if (SEQ_GEQ(start, rsm->r_start) &&
7084 		    SEQ_LT(start, rsm->r_end)) {
7085 			break;
7086 		}
7087 	}
7088 do_rest_ofb:
7089 	if (rsm == NULL) {
7090 		/*
7091 		 * This happens when we get duplicate sack blocks with the
7092 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
7093 		 * will not change there location so we would just start at
7094 		 * the end of the first one and get lost.
7095 		 */
7096 		if (tp->t_flags & TF_SENTFIN) {
7097 			/*
7098 			 * Check to see if we have not logged the FIN that
7099 			 * went out.
7100 			 */
7101 			nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7102 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
7103 				/*
7104 				 * Ok we did not get the FIN logged.
7105 				 */
7106 				nrsm->r_end++;
7107 				rsm = nrsm;
7108 				goto do_rest_ofb;
7109 			}
7110 		}
7111 		if (times == 1) {
7112 #ifdef BBR_INVARIANTS
7113 			panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7114 			    tp, bbr, sack, to, prsm);
7115 #else
7116 			goto out;
7117 #endif
7118 		}
7119 		times++;
7120 		BBR_STAT_INC(bbr_sack_proc_restart);
7121 		rsm = NULL;
7122 		goto start_at_beginning;
7123 	}
7124 	/* Ok we have an ACK for some piece of rsm */
7125 	if (rsm->r_start != start) {
7126 		/*
7127 		 * Need to split this in two pieces the before and after.
7128 		 */
7129 		if (bbr_sack_mergable(rsm, start, end))
7130 			nrsm = bbr_alloc_full_limit(bbr);
7131 		else
7132 			nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7133 		if (nrsm == NULL) {
7134 			/* We could not allocate ignore the sack */
7135 			struct sackblk blk;
7136 
7137 			blk.start = start;
7138 			blk.end = end;
7139 			sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7140 			goto out;
7141 		}
7142 		bbr_clone_rsm(bbr, nrsm, rsm, start);
7143 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7144 		if (rsm->r_in_tmap) {
7145 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7146 			nrsm->r_in_tmap = 1;
7147 		}
7148 		rsm->r_flags &= (~BBR_HAS_FIN);
7149 		rsm = nrsm;
7150 	}
7151 	if (SEQ_GEQ(end, rsm->r_end)) {
7152 		/*
7153 		 * The end of this block is either beyond this guy or right
7154 		 * at this guy.
7155 		 */
7156 		if ((rsm->r_flags & BBR_ACKED) == 0) {
7157 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7158 			changed += (rsm->r_end - rsm->r_start);
7159 			bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7160 			bbr_log_sack_passed(tp, bbr, rsm);
7161 			if (rsm->r_flags & BBR_MARKED_LOST) {
7162 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7163 			}
7164 			/* Is Reordering occuring? */
7165 			if (rsm->r_flags & BBR_SACK_PASSED) {
7166 				BBR_STAT_INC(bbr_reorder_seen);
7167 				bbr->r_ctl.rc_reorder_ts = cts;
7168 				if (rsm->r_flags & BBR_MARKED_LOST) {
7169 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7170 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7171 						/* LT sampling also needs adjustment */
7172 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7173 				}
7174 			}
7175 			rsm->r_flags |= BBR_ACKED;
7176 			rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7177 			if (rsm->r_in_tmap) {
7178 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7179 				rsm->r_in_tmap = 0;
7180 			}
7181 		}
7182 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7183 		if (end == rsm->r_end) {
7184 			/* This block only - done */
7185 			goto out;
7186 		}
7187 		/* There is more not coverend by this rsm move on */
7188 		start = rsm->r_end;
7189 		nrsm = TAILQ_NEXT(rsm, r_next);
7190 		rsm = nrsm;
7191 		times = 0;
7192 		goto do_rest_ofb;
7193 	}
7194 	if (rsm->r_flags & BBR_ACKED) {
7195 		/* Been here done that */
7196 		goto out;
7197 	}
7198 	/* Ok we need to split off this one at the tail */
7199 	if (bbr_sack_mergable(rsm, start, end))
7200 		nrsm = bbr_alloc_full_limit(bbr);
7201 	else
7202 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7203 	if (nrsm == NULL) {
7204 		/* failed XXXrrs what can we do but loose the sack info? */
7205 		struct sackblk blk;
7206 
7207 		blk.start = start;
7208 		blk.end = end;
7209 		sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7210 		goto out;
7211 	}
7212 	/* Clone it */
7213 	bbr_clone_rsm(bbr, nrsm, rsm, end);
7214 	/* The sack block does not cover this guy fully */
7215 	rsm->r_flags &= (~BBR_HAS_FIN);
7216 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7217 	if (rsm->r_in_tmap) {
7218 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7219 		nrsm->r_in_tmap = 1;
7220 	}
7221 	nrsm->r_dupack = 0;
7222 	bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7223 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7224 	changed += (rsm->r_end - rsm->r_start);
7225 	bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7226 	bbr_log_sack_passed(tp, bbr, rsm);
7227 	/* Is Reordering occuring? */
7228 	if (rsm->r_flags & BBR_MARKED_LOST) {
7229 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7230 	}
7231 	if (rsm->r_flags & BBR_SACK_PASSED) {
7232 		BBR_STAT_INC(bbr_reorder_seen);
7233 		bbr->r_ctl.rc_reorder_ts = cts;
7234 		if (rsm->r_flags & BBR_MARKED_LOST) {
7235 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7236 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7237 				/* LT sampling also needs adjustment */
7238 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7239 		}
7240 	}
7241 	rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7242 	rsm->r_flags |= BBR_ACKED;
7243 	if (rsm->r_in_tmap) {
7244 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7245 		rsm->r_in_tmap = 0;
7246 	}
7247 out:
7248 	if (rsm && (rsm->r_flags & BBR_ACKED)) {
7249 		/*
7250 		 * Now can we merge this newly acked
7251 		 * block with either the previous or
7252 		 * next block?
7253 		 */
7254 		nrsm = TAILQ_NEXT(rsm, r_next);
7255 		if (nrsm &&
7256 		    (nrsm->r_flags & BBR_ACKED)) {
7257 			/* yep this and next can be merged */
7258 			rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7259 		}
7260 		/* Now what about the previous? */
7261 		nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7262 		if (nrsm &&
7263 		    (nrsm->r_flags & BBR_ACKED)) {
7264 			/* yep the previous and this can be merged */
7265 			rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7266 		}
7267 	}
7268 	if (used_ref == 0) {
7269 		BBR_STAT_INC(bbr_sack_proc_all);
7270 	} else {
7271 		BBR_STAT_INC(bbr_sack_proc_short);
7272 	}
7273 	if (went_fwd && went_back) {
7274 		BBR_STAT_INC(bbr_sack_search_both);
7275 	} else if (went_fwd) {
7276 		BBR_STAT_INC(bbr_sack_search_fwd);
7277 	} else if (went_back) {
7278 		BBR_STAT_INC(bbr_sack_search_back);
7279 	}
7280 	/* Save off where the next seq is */
7281 	if (rsm)
7282 		bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7283 	else
7284 		bbr->r_ctl.rc_sacklast = NULL;
7285 	*prsm = rsm;
7286 	return (changed);
7287 }
7288 
7289 static void inline
7290 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7291 {
7292 	struct bbr_sendmap *tmap;
7293 
7294 	BBR_STAT_INC(bbr_reneges_seen);
7295 	tmap = NULL;
7296 	while (rsm && (rsm->r_flags & BBR_ACKED)) {
7297 		/* Its no longer sacked, mark it so */
7298 		uint32_t oflags;
7299 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7300 #ifdef BBR_INVARIANTS
7301 		if (rsm->r_in_tmap) {
7302 			panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7303 			    bbr, rsm, rsm->r_flags);
7304 		}
7305 #endif
7306 		oflags = rsm->r_flags;
7307 		if (rsm->r_flags & BBR_MARKED_LOST) {
7308 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7309 			bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7310 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7311 				/* LT sampling also needs adjustment */
7312 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7313 		}
7314 		rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7315 		rsm->r_flags |= BBR_WAS_RENEGED;
7316 		rsm->r_flags |= BBR_RXT_CLEARED;
7317 		bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7318 		/* Rebuild it into our tmap */
7319 		if (tmap == NULL) {
7320 			TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7321 			tmap = rsm;
7322 		} else {
7323 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7324 			tmap = rsm;
7325 		}
7326 		tmap->r_in_tmap = 1;
7327 		/*
7328 		 * XXXrrs Delivered? Should we do anything here?
7329 		 *
7330 		 * Of course we don't on a rxt timeout so maybe its ok that
7331 		 * we don't?
7332 		 *
7333 		 * For now lets not.
7334 		 */
7335 		rsm = TAILQ_NEXT(rsm, r_next);
7336 	}
7337 	/*
7338 	 * Now lets possibly clear the sack filter so we start recognizing
7339 	 * sacks that cover this area.
7340 	 */
7341 	sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7342 }
7343 
7344 static void
7345 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7346 {
7347 	struct tcp_bbr *bbr;
7348 	struct bbr_sendmap *rsm;
7349 	uint32_t cts;
7350 
7351 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7352 	cts = bbr->r_ctl.rc_rcvtime;
7353 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7354 	if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7355 		if ((rsm->r_end - rsm->r_start) <= 1) {
7356 			/* Log out the SYN completely */
7357 			bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7358 			rsm->r_rtr_bytes = 0;
7359 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7360 			if (rsm->r_in_tmap) {
7361 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7362 				rsm->r_in_tmap = 0;
7363 			}
7364 			if (bbr->r_ctl.rc_next == rsm) {
7365 				/* scoot along the marker */
7366 				bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7367 			}
7368 			if (to != NULL)
7369 				bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7370 			bbr_free(bbr, rsm);
7371 		} else {
7372 			/* There is more (Fast open)? strip out SYN. */
7373 			rsm->r_flags &= ~BBR_HAS_SYN;
7374 			rsm->r_start++;
7375 		}
7376 	}
7377 }
7378 
7379 /*
7380  * Returns the number of bytes that were
7381  * acknowledged by SACK blocks.
7382  */
7383 
7384 static uint32_t
7385 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7386     uint32_t *prev_acked)
7387 {
7388 	uint32_t changed, last_seq, entered_recovery = 0;
7389 	struct tcp_bbr *bbr;
7390 	struct bbr_sendmap *rsm;
7391 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7392 	register uint32_t th_ack;
7393 	int32_t i, j, k, new_sb, num_sack_blks = 0;
7394 	uint32_t cts, acked, ack_point, sack_changed = 0;
7395 	uint32_t p_maxseg, maxseg, p_acked = 0;
7396 
7397 	INP_WLOCK_ASSERT(tp->t_inpcb);
7398 	if (th->th_flags & TH_RST) {
7399 		/* We don't log resets */
7400 		return (0);
7401 	}
7402 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7403 	cts = bbr->r_ctl.rc_rcvtime;
7404 
7405 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7406 	changed = 0;
7407 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7408 	p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7409 	th_ack = th->th_ack;
7410 	if (SEQ_GT(th_ack, tp->snd_una)) {
7411 		acked = th_ack - tp->snd_una;
7412 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7413 		bbr->rc_tp->t_acktime = ticks;
7414 	} else
7415 		acked = 0;
7416 	if (SEQ_LEQ(th_ack, tp->snd_una)) {
7417 		/* Only sent here for sack processing */
7418 		goto proc_sack;
7419 	}
7420 	if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7421 		changed = th_ack - rsm->r_start;
7422 	} else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7423 		/*
7424 		 * For the SYN incoming case we will not have called
7425 		 * tcp_output for the sending of the SYN, so there will be
7426 		 * no map. All other cases should probably be a panic.
7427 		 */
7428 		if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7429 			/*
7430 			 * We have a timestamp that can be used to generate
7431 			 * an initial RTT.
7432 			 */
7433 			uint32_t ts, now, rtt;
7434 
7435 			ts = bbr_ts_convert(to->to_tsecr);
7436 			now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7437 			rtt = now - ts;
7438 			if (rtt < 1)
7439 				rtt = 1;
7440 			bbr_log_type_bbrrttprop(bbr, rtt,
7441 						tp->iss, 0, cts,
7442 						BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7443 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7444 			changed = 1;
7445 			bbr->r_wanted_output = 1;
7446 			goto out;
7447 		}
7448 		goto proc_sack;
7449 	} else if (rsm == NULL) {
7450 		goto out;
7451 	}
7452 	if (changed) {
7453 		/*
7454 		 * The ACK point is advancing to th_ack, we must drop off
7455 		 * the packets in the rack log and calculate any eligble
7456 		 * RTT's.
7457 		 */
7458 		bbr->r_wanted_output = 1;
7459 more:
7460 		if (rsm == NULL) {
7461 			if (tp->t_flags & TF_SENTFIN) {
7462 				/* if we send a FIN we will not hav a map */
7463 				goto proc_sack;
7464 			}
7465 #ifdef BBR_INVARIANTS
7466 			panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7467 			    tp,
7468 			    th, tp->t_state, bbr,
7469 			    tp->snd_una, tp->snd_max, changed);
7470 #endif
7471 			goto proc_sack;
7472 		}
7473 	}
7474 	if (SEQ_LT(th_ack, rsm->r_start)) {
7475 		/* Huh map is missing this */
7476 #ifdef BBR_INVARIANTS
7477 		printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7478 		    rsm->r_start,
7479 		    th_ack, tp->t_state,
7480 		    bbr->r_state, bbr);
7481 		panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7482 #endif
7483 		goto proc_sack;
7484 	} else if (th_ack == rsm->r_start) {
7485 		/* None here to ack */
7486 		goto proc_sack;
7487 	}
7488 	/*
7489 	 * Clear the dup ack counter, it will
7490 	 * either be freed or if there is some
7491 	 * remaining we need to start it at zero.
7492 	 */
7493 	rsm->r_dupack = 0;
7494 	/* Now do we consume the whole thing? */
7495 	if (SEQ_GEQ(th_ack, rsm->r_end)) {
7496 		/* Its all consumed. */
7497 		uint32_t left;
7498 
7499 		if (rsm->r_flags & BBR_ACKED) {
7500 			/*
7501 			 * It was acked on the scoreboard -- remove it from
7502 			 * total
7503 			 */
7504 			p_acked += (rsm->r_end - rsm->r_start);
7505 			bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7506 			if (bbr->r_ctl.rc_sacked == 0)
7507 				bbr->r_ctl.rc_sacklast = NULL;
7508 		} else {
7509 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7510 			if (rsm->r_flags & BBR_MARKED_LOST) {
7511 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7512 			}
7513 			if (rsm->r_flags & BBR_SACK_PASSED) {
7514 				/*
7515 				 * There are acked segments ACKED on the
7516 				 * scoreboard further up. We are seeing
7517 				 * reordering.
7518 				 */
7519 				BBR_STAT_INC(bbr_reorder_seen);
7520 				bbr->r_ctl.rc_reorder_ts = cts;
7521 				if (rsm->r_flags & BBR_MARKED_LOST) {
7522 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7523 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7524 						/* LT sampling also needs adjustment */
7525 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7526 				}
7527 			}
7528 			rsm->r_flags &= ~BBR_MARKED_LOST;
7529 		}
7530 		bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7531 		rsm->r_rtr_bytes = 0;
7532 		TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7533 		if (rsm->r_in_tmap) {
7534 			TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7535 			rsm->r_in_tmap = 0;
7536 		}
7537 		if (bbr->r_ctl.rc_next == rsm) {
7538 			/* scoot along the marker */
7539 			bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7540 		}
7541 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7542 		/* Adjust the packet counts */
7543 		left = th_ack - rsm->r_end;
7544 		/* Free back to zone */
7545 		bbr_free(bbr, rsm);
7546 		if (left) {
7547 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7548 			goto more;
7549 		}
7550 		goto proc_sack;
7551 	}
7552 	if (rsm->r_flags & BBR_ACKED) {
7553 		/*
7554 		 * It was acked on the scoreboard -- remove it from total
7555 		 * for the part being cum-acked.
7556 		 */
7557 		p_acked += (rsm->r_end - rsm->r_start);
7558 		bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7559 		if (bbr->r_ctl.rc_sacked == 0)
7560 			bbr->r_ctl.rc_sacklast = NULL;
7561 	} else {
7562 		/*
7563 		 * It was acked up to th_ack point for the first time
7564 		 */
7565 		struct bbr_sendmap lrsm;
7566 
7567 		memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7568 		lrsm.r_end = th_ack;
7569 		bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7570 	}
7571 	if ((rsm->r_flags & BBR_MARKED_LOST) &&
7572 	    ((rsm->r_flags & BBR_ACKED) == 0)) {
7573 		/*
7574 		 * It was marked lost and partly ack'd now
7575 		 * for the first time. We lower the rc_lost_bytes
7576 		 * and still leave it MARKED.
7577 		 */
7578 		bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7579 	}
7580 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7581 	bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7582 	rsm->r_rtr_bytes = 0;
7583 	/* adjust packet count */
7584 	rsm->r_start = th_ack;
7585 proc_sack:
7586 	/* Check for reneging */
7587 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7588 	if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7589 		/*
7590 		 * The peer has moved snd_una up to the edge of this send,
7591 		 * i.e. one that it had previously acked. The only way that
7592 		 * can be true if the peer threw away data (space issues)
7593 		 * that it had previously sacked (else it would have given
7594 		 * us snd_una up to (rsm->r_end). We need to undo the acked
7595 		 * markings here.
7596 		 *
7597 		 * Note we have to look to make sure th_ack is our
7598 		 * rsm->r_start in case we get an old ack where th_ack is
7599 		 * behind snd_una.
7600 		 */
7601 		bbr_peer_reneges(bbr, rsm, th->th_ack);
7602 	}
7603 	if ((to->to_flags & TOF_SACK) == 0) {
7604 		/* We are done nothing left to log */
7605 		goto out;
7606 	}
7607 	rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7608 	if (rsm) {
7609 		last_seq = rsm->r_end;
7610 	} else {
7611 		last_seq = tp->snd_max;
7612 	}
7613 	/* Sack block processing */
7614 	if (SEQ_GT(th_ack, tp->snd_una))
7615 		ack_point = th_ack;
7616 	else
7617 		ack_point = tp->snd_una;
7618 	for (i = 0; i < to->to_nsacks; i++) {
7619 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
7620 		    &sack, sizeof(sack));
7621 		sack.start = ntohl(sack.start);
7622 		sack.end = ntohl(sack.end);
7623 		if (SEQ_GT(sack.end, sack.start) &&
7624 		    SEQ_GT(sack.start, ack_point) &&
7625 		    SEQ_LT(sack.start, tp->snd_max) &&
7626 		    SEQ_GT(sack.end, ack_point) &&
7627 		    SEQ_LEQ(sack.end, tp->snd_max)) {
7628 			if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7629 			    (SEQ_LT(sack.end, last_seq)) &&
7630 			    ((sack.end - sack.start) < (p_maxseg / 8))) {
7631 				/*
7632 				 * Not the last piece and its smaller than
7633 				 * 1/8th of a p_maxseg. We ignore this.
7634 				 */
7635 				BBR_STAT_INC(bbr_runt_sacks);
7636 				continue;
7637 			}
7638 			sack_blocks[num_sack_blks] = sack;
7639 			num_sack_blks++;
7640 #ifdef NETFLIX_STATS
7641 		} else if (SEQ_LEQ(sack.start, th_ack) &&
7642 		    SEQ_LEQ(sack.end, th_ack)) {
7643 			/*
7644 			 * Its a D-SACK block.
7645 			 */
7646 			tcp_record_dsack(sack.start, sack.end);
7647 #endif
7648 		}
7649 	}
7650 	if (num_sack_blks == 0)
7651 		goto out;
7652 	/*
7653 	 * Sort the SACK blocks so we can update the rack scoreboard with
7654 	 * just one pass.
7655 	 */
7656 	new_sb = sack_filter_blks(&bbr->r_ctl.bbr_sf, sack_blocks,
7657 				  num_sack_blks, th->th_ack);
7658 	ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7659 	BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7660 	BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7661 	num_sack_blks = new_sb;
7662 	if (num_sack_blks < 2) {
7663 		goto do_sack_work;
7664 	}
7665 	/* Sort the sacks */
7666 	for (i = 0; i < num_sack_blks; i++) {
7667 		for (j = i + 1; j < num_sack_blks; j++) {
7668 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7669 				sack = sack_blocks[i];
7670 				sack_blocks[i] = sack_blocks[j];
7671 				sack_blocks[j] = sack;
7672 			}
7673 		}
7674 	}
7675 	/*
7676 	 * Now are any of the sack block ends the same (yes some
7677 	 * implememtations send these)?
7678 	 */
7679 again:
7680 	if (num_sack_blks > 1) {
7681 		for (i = 0; i < num_sack_blks; i++) {
7682 			for (j = i + 1; j < num_sack_blks; j++) {
7683 				if (sack_blocks[i].end == sack_blocks[j].end) {
7684 					/*
7685 					 * Ok these two have the same end we
7686 					 * want the smallest end and then
7687 					 * throw away the larger and start
7688 					 * again.
7689 					 */
7690 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7691 						/*
7692 						 * The second block covers
7693 						 * more area use that
7694 						 */
7695 						sack_blocks[i].start = sack_blocks[j].start;
7696 					}
7697 					/*
7698 					 * Now collapse out the dup-sack and
7699 					 * lower the count
7700 					 */
7701 					for (k = (j + 1); k < num_sack_blks; k++) {
7702 						sack_blocks[j].start = sack_blocks[k].start;
7703 						sack_blocks[j].end = sack_blocks[k].end;
7704 						j++;
7705 					}
7706 					num_sack_blks--;
7707 					goto again;
7708 				}
7709 			}
7710 		}
7711 	}
7712 do_sack_work:
7713 	rsm = bbr->r_ctl.rc_sacklast;
7714 	for (i = 0; i < num_sack_blks; i++) {
7715 		acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7716 		if (acked) {
7717 			bbr->r_wanted_output = 1;
7718 			changed += acked;
7719 			sack_changed += acked;
7720 		}
7721 	}
7722 out:
7723 	*prev_acked = p_acked;
7724 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7725 		/*
7726 		 * Ok we have a high probability that we need to go in to
7727 		 * recovery since we have data sack'd
7728 		 */
7729 		struct bbr_sendmap *rsm;
7730 
7731 		rsm = bbr_check_recovery_mode(tp, bbr, cts);
7732 		if (rsm) {
7733 			/* Enter recovery */
7734 			entered_recovery = 1;
7735 			bbr->r_wanted_output = 1;
7736 			/*
7737 			 * When we enter recovery we need to assure we send
7738 			 * one packet.
7739 			 */
7740 			if (bbr->r_ctl.rc_resend == NULL) {
7741 				bbr->r_ctl.rc_resend = rsm;
7742 			}
7743 		}
7744 	}
7745 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7746 		/*
7747 		 * See if we need to rack-retransmit anything if so set it
7748 		 * up as the thing to resend assuming something else is not
7749 		 * already in that position.
7750 		 */
7751 		if (bbr->r_ctl.rc_resend == NULL) {
7752 			bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7753 		}
7754 	}
7755 	/*
7756 	 * We return the amount that changed via sack, this is used by the
7757 	 * ack-received code to augment what was changed between th_ack <->
7758 	 * snd_una.
7759 	 */
7760 	return (sack_changed);
7761 }
7762 
7763 static void
7764 bbr_strike_dupack(struct tcp_bbr *bbr)
7765 {
7766 	struct bbr_sendmap *rsm;
7767 
7768 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7769 	if (rsm && (rsm->r_dupack < 0xff)) {
7770 		rsm->r_dupack++;
7771 		if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7772 			bbr->r_wanted_output = 1;
7773 	}
7774 }
7775 
7776 /*
7777  * Return value of 1, we do not need to call bbr_process_data().
7778  * return value of 0, bbr_process_data can be called.
7779  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7780  * its unlocked and probably unsafe to touch the TCB.
7781  */
7782 static int
7783 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7784     struct tcpcb *tp, struct tcpopt *to,
7785     uint32_t tiwin, int32_t tlen,
7786     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7787 {
7788 	int32_t ourfinisacked = 0;
7789 	int32_t acked_amount;
7790 	uint16_t nsegs;
7791 	int32_t acked;
7792 	uint32_t lost, sack_changed = 0;
7793 	struct mbuf *mfree;
7794 	struct tcp_bbr *bbr;
7795 	uint32_t prev_acked = 0;
7796 
7797 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7798 	lost = bbr->r_ctl.rc_lost;
7799 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
7800 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
7801 		ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7802 		bbr->r_wanted_output = 1;
7803 		return (1);
7804 	}
7805 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7806 		/* Process the ack */
7807 		if (bbr->rc_in_persist)
7808 			tp->t_rxtshift = 0;
7809 		if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7810 		        bbr_strike_dupack(bbr);
7811 		sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7812 	}
7813 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7814 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7815 		/*
7816 		 * Old ack, behind the last one rcv'd or a duplicate ack
7817 		 * with SACK info.
7818 		 */
7819 		if (th->th_ack == tp->snd_una) {
7820 			bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7821 			if (bbr->r_state == TCPS_SYN_SENT) {
7822 				/*
7823 				 * Special case on where we sent SYN. When
7824 				 * the SYN-ACK is processed in syn_sent
7825 				 * state it bumps the snd_una. This causes
7826 				 * us to hit here even though we did ack 1
7827 				 * byte.
7828 				 *
7829 				 * Go through the nothing left case so we
7830 				 * send data.
7831 				 */
7832 				goto nothing_left;
7833 			}
7834 		}
7835 		return (0);
7836 	}
7837 	/*
7838 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7839 	 * something we sent.
7840 	 */
7841 	if (tp->t_flags & TF_NEEDSYN) {
7842 		/*
7843 		 * T/TCP: Connection was half-synchronized, and our SYN has
7844 		 * been ACK'd (so connection is now fully synchronized).  Go
7845 		 * to non-starred state, increment snd_una for ACK of SYN,
7846 		 * and check if we can do window scaling.
7847 		 */
7848 		tp->t_flags &= ~TF_NEEDSYN;
7849 		tp->snd_una++;
7850 		/* Do window scaling? */
7851 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7852 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7853 			tp->rcv_scale = tp->request_r_scale;
7854 			/* Send window already scaled. */
7855 		}
7856 	}
7857 	INP_WLOCK_ASSERT(tp->t_inpcb);
7858 
7859 	acked = BYTES_THIS_ACK(tp, th);
7860 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7861 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
7862 
7863 	/*
7864 	 * If we just performed our first retransmit, and the ACK arrives
7865 	 * within our recovery window, then it was a mistake to do the
7866 	 * retransmit in the first place.  Recover our original cwnd and
7867 	 * ssthresh, and proceed to transmit where we left off.
7868 	 */
7869 	if (tp->t_flags & TF_PREVVALID) {
7870 		tp->t_flags &= ~TF_PREVVALID;
7871 		if (tp->t_rxtshift == 1 &&
7872 		    (int)(ticks - tp->t_badrxtwin) < 0)
7873 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7874 	}
7875 	SOCKBUF_LOCK(&so->so_snd);
7876 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
7877 	tp->snd_wnd -= acked_amount;
7878 	mfree = sbcut_locked(&so->so_snd, acked_amount);
7879 	SOCKBUF_UNLOCK(&so->so_snd);
7880 	tp->t_flags |= TF_WAKESOW;
7881 	m_freem(mfree);
7882 	if (SEQ_GT(th->th_ack, tp->snd_una)) {
7883 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
7884 	}
7885 	tp->snd_una = th->th_ack;
7886 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
7887 	if (IN_RECOVERY(tp->t_flags)) {
7888 		if (SEQ_LT(th->th_ack, tp->snd_recover) &&
7889 		    (SEQ_LT(th->th_ack, tp->snd_max))) {
7890 			tcp_bbr_partialack(tp);
7891 		} else {
7892 			bbr_post_recovery(tp);
7893 		}
7894 	}
7895 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
7896 		tp->snd_recover = tp->snd_una;
7897 	}
7898 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
7899 		tp->snd_nxt = tp->snd_max;
7900 	}
7901 	if (tp->snd_una == tp->snd_max) {
7902 		/* Nothing left outstanding */
7903 nothing_left:
7904 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
7905 		if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
7906 			bbr->rc_tp->t_acktime = 0;
7907 		if ((sbused(&so->so_snd) == 0) &&
7908 		    (tp->t_flags & TF_SENTFIN)) {
7909 			ourfinisacked = 1;
7910 		}
7911 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
7912 		if (bbr->rc_in_persist == 0) {
7913 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
7914 		}
7915 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
7916 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
7917 		/*
7918 		 * We invalidate the last ack here since we
7919 		 * don't want to transfer forward the time
7920 		 * for our sum's calculations.
7921 		 */
7922 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
7923 		    (sbavail(&so->so_snd) == 0) &&
7924 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
7925 			/*
7926 			 * The socket was gone and the peer sent data, time
7927 			 * to reset him.
7928 			 */
7929 			*ret_val = 1;
7930 			tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
7931 			/* tcp_close will kill the inp pre-log the Reset */
7932 			tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
7933 			tp = tcp_close(tp);
7934 			ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
7935 			BBR_STAT_INC(bbr_dropped_af_data);
7936 			return (1);
7937 		}
7938 		/* Set need output so persist might get set */
7939 		bbr->r_wanted_output = 1;
7940 	}
7941 	if (ofia)
7942 		*ofia = ourfinisacked;
7943 	return (0);
7944 }
7945 
7946 static void
7947 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7948 {
7949 	if (bbr->rc_in_persist == 0) {
7950 		bbr_timer_cancel(bbr, __LINE__, cts);
7951 		bbr->r_ctl.rc_last_delay_val = 0;
7952 		tp->t_rxtshift = 0;
7953 		bbr->rc_in_persist = 1;
7954 		bbr->r_ctl.rc_went_idle_time = cts;
7955 		/* We should be capped when rw went to 0 but just in case */
7956 		bbr_log_type_pesist(bbr, cts, 0, line, 1);
7957 		/* Time freezes for the state, so do the accounting now */
7958 		if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
7959 			uint32_t time_in;
7960 
7961 			time_in = cts - bbr->r_ctl.rc_bbr_state_time;
7962 			if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7963 				int32_t idx;
7964 
7965 				idx = bbr_state_val(bbr);
7966 				counter_u64_add(bbr_state_time[(idx + 5)], time_in);
7967 			} else {
7968 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
7969 			}
7970 		}
7971 		bbr->r_ctl.rc_bbr_state_time = cts;
7972 	}
7973 }
7974 
7975 static void
7976 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
7977 {
7978 	/*
7979 	 * Note that if idle time does not exceed our
7980 	 * threshold, we do nothing continuing the state
7981 	 * transitions we were last walking through.
7982 	 */
7983 	if (idle_time >= bbr_idle_restart_threshold) {
7984 		if (bbr->rc_use_idle_restart) {
7985 			bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
7986 			/*
7987 			 * Set our target using BBR_UNIT, so
7988 			 * we increase at a dramatic rate but
7989 			 * we stop when we get the pipe
7990 			 * full again for our current b/w estimate.
7991 			 */
7992 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
7993 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
7994 			bbr_set_state_target(bbr, __LINE__);
7995 			/* Now setup our gains to ramp up */
7996 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
7997 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
7998 			bbr_log_type_statechange(bbr, cts, __LINE__);
7999 		} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
8000 			bbr_substate_change(bbr, cts, __LINE__, 1);
8001 		}
8002 	}
8003 }
8004 
8005 static void
8006 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
8007 {
8008 	uint32_t idle_time;
8009 
8010 	if (bbr->rc_in_persist == 0)
8011 		return;
8012 	idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
8013 	bbr->rc_in_persist = 0;
8014 	bbr->rc_hit_state_1 = 0;
8015 	bbr->r_ctl.rc_del_time = cts;
8016 	/*
8017 	 * We invalidate the last ack here since we
8018 	 * don't want to transfer forward the time
8019 	 * for our sum's calculations.
8020 	 */
8021 	if (bbr->rc_inp->inp_in_hpts) {
8022 		tcp_hpts_remove(bbr->rc_inp, HPTS_REMOVE_OUTPUT);
8023 		bbr->rc_timer_first = 0;
8024 		bbr->r_ctl.rc_hpts_flags = 0;
8025 		bbr->r_ctl.rc_last_delay_val = 0;
8026 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
8027 		bbr->r_agg_early_set = 0;
8028 		bbr->r_ctl.rc_agg_early = 0;
8029 	}
8030 	bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
8031 	if (idle_time >= bbr_rtt_probe_time) {
8032 		/*
8033 		 * This qualifies as a RTT_PROBE session since we drop the
8034 		 * data outstanding to nothing and waited more than
8035 		 * bbr_rtt_probe_time.
8036 		 */
8037 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
8038 		bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
8039 	}
8040 	tp->t_rxtshift = 0;
8041 	/*
8042 	 * If in probeBW and we have persisted more than an RTT lets do
8043 	 * special handling.
8044 	 */
8045 	/* Force a time based epoch */
8046 	bbr_set_epoch(bbr, cts, __LINE__);
8047 	/*
8048 	 * Setup the lost so we don't count anything against the guy
8049 	 * we have been stuck with during persists.
8050 	 */
8051 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
8052 	/* Time un-freezes for the state */
8053 	bbr->r_ctl.rc_bbr_state_time = cts;
8054 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
8055 	    (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
8056 		/*
8057 		 * If we are going back to probe-bw
8058 		 * or probe_rtt, we may need to possibly
8059 		 * do a fast restart.
8060 		 */
8061 		bbr_restart_after_idle(bbr, cts, idle_time);
8062 	}
8063 }
8064 
8065 static void
8066 bbr_collapsed_window(struct tcp_bbr *bbr)
8067 {
8068 	/*
8069 	 * Now we must walk the
8070 	 * send map and divide the
8071 	 * ones left stranded. These
8072 	 * guys can't cause us to abort
8073 	 * the connection and are really
8074 	 * "unsent". However if a buggy
8075 	 * client actually did keep some
8076 	 * of the data i.e. collapsed the win
8077 	 * and refused to ack and then opened
8078 	 * the win and acked that data. We would
8079 	 * get into an ack war, the simplier
8080 	 * method then of just pretending we
8081 	 * did not send those segments something
8082 	 * won't work.
8083 	 */
8084 	struct bbr_sendmap *rsm, *nrsm;
8085 	tcp_seq max_seq;
8086 	uint32_t maxseg;
8087 	int can_split = 0;
8088 	int fnd = 0;
8089 
8090 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
8091 	max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
8092 	bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
8093 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
8094 		/* Find the first seq past or at maxseq */
8095 		if (rsm->r_flags & BBR_RWND_COLLAPSED)
8096 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8097 		if (SEQ_GEQ(max_seq, rsm->r_start) &&
8098 		    SEQ_GEQ(rsm->r_end, max_seq)) {
8099 			fnd = 1;
8100 			break;
8101 		}
8102 	}
8103 	bbr->rc_has_collapsed = 0;
8104 	if (!fnd) {
8105 		/* Nothing to do strange */
8106 		return;
8107 	}
8108 	/*
8109 	 * Now can we split?
8110 	 *
8111 	 * We don't want to split if splitting
8112 	 * would generate too many small segments
8113 	 * less we let an attacker fragment our
8114 	 * send_map and leave us out of memory.
8115 	 */
8116 	if ((max_seq != rsm->r_start) &&
8117 	    (max_seq != rsm->r_end)){
8118 		/* can we split? */
8119 		int res1, res2;
8120 
8121 		res1 = max_seq - rsm->r_start;
8122 		res2 = rsm->r_end - max_seq;
8123 		if ((res1 >= (maxseg/8)) &&
8124 		    (res2 >= (maxseg/8))) {
8125 			/* No small pieces here */
8126 			can_split = 1;
8127 		} else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8128 			/* We are under the limit */
8129 			can_split = 1;
8130 		}
8131 	}
8132 	/* Ok do we need to split this rsm? */
8133 	if (max_seq == rsm->r_start) {
8134 		/* It's this guy no split required */
8135 		nrsm = rsm;
8136 	} else if (max_seq == rsm->r_end) {
8137 		/* It's the next one no split required. */
8138 		nrsm = TAILQ_NEXT(rsm, r_next);
8139 		if (nrsm == NULL) {
8140 			/* Huh? */
8141 			return;
8142 		}
8143 	} else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8144 		/* yep we need to split it */
8145 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8146 		if (nrsm == NULL) {
8147 			/* failed XXXrrs what can we do mark the whole? */
8148 			nrsm = rsm;
8149 			goto no_split;
8150 		}
8151 		/* Clone it */
8152 		bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8153 		bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8154 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8155 		if (rsm->r_in_tmap) {
8156 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8157 			nrsm->r_in_tmap = 1;
8158 		}
8159 	} else {
8160 		/*
8161 		 * Split not allowed just start here just
8162 		 * use this guy.
8163 		 */
8164 		nrsm = rsm;
8165 	}
8166 no_split:
8167 	BBR_STAT_INC(bbr_collapsed_win);
8168 	/* reuse fnd as a count */
8169 	fnd = 0;
8170 	TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8171 		nrsm->r_flags |= BBR_RWND_COLLAPSED;
8172 		fnd++;
8173 		bbr->rc_has_collapsed = 1;
8174 	}
8175 	bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8176 }
8177 
8178 static void
8179 bbr_un_collapse_window(struct tcp_bbr *bbr)
8180 {
8181 	struct bbr_sendmap *rsm;
8182 	int cleared = 0;
8183 
8184 	TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8185 		if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8186 			/* Clear the flag */
8187 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8188 			cleared++;
8189 		} else
8190 			break;
8191 	}
8192 	bbr_log_type_rwnd_collapse(bbr,
8193 				   (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8194 	bbr->rc_has_collapsed = 0;
8195 }
8196 
8197 /*
8198  * Return value of 1, the TCB is unlocked and most
8199  * likely gone, return value of 0, the TCB is still
8200  * locked.
8201  */
8202 static int
8203 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8204     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8205     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8206 {
8207 	/*
8208 	 * Update window information. Don't look at window if no ACK: TAC's
8209 	 * send garbage on first SYN.
8210 	 */
8211 	uint16_t nsegs;
8212 	int32_t tfo_syn;
8213 	struct tcp_bbr *bbr;
8214 
8215 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8216 	INP_WLOCK_ASSERT(tp->t_inpcb);
8217 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8218 	if ((thflags & TH_ACK) &&
8219 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8220 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8221 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8222 		/* keep track of pure window updates */
8223 		if (tlen == 0 &&
8224 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8225 			KMOD_TCPSTAT_INC(tcps_rcvwinupd);
8226 		tp->snd_wnd = tiwin;
8227 		tp->snd_wl1 = th->th_seq;
8228 		tp->snd_wl2 = th->th_ack;
8229 		if (tp->snd_wnd > tp->max_sndwnd)
8230 			tp->max_sndwnd = tp->snd_wnd;
8231 		bbr->r_wanted_output = 1;
8232 	} else if (thflags & TH_ACK) {
8233 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8234 			tp->snd_wnd = tiwin;
8235 			tp->snd_wl1 = th->th_seq;
8236 			tp->snd_wl2 = th->th_ack;
8237 		}
8238 	}
8239 	if (tp->snd_wnd < ctf_outstanding(tp))
8240 		/* The peer collapsed its window on us */
8241 		bbr_collapsed_window(bbr);
8242  	else if (bbr->rc_has_collapsed)
8243 		bbr_un_collapse_window(bbr);
8244 	/* Was persist timer active and now we have window space? */
8245 	if ((bbr->rc_in_persist != 0) &&
8246 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8247 				bbr_minseg(bbr)))) {
8248 		/*
8249 		 * Make the rate persist at end of persist mode if idle long
8250 		 * enough
8251 		 */
8252 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8253 
8254 		/* Make sure we output to start the timer */
8255 		bbr->r_wanted_output = 1;
8256 	}
8257 	/* Do we need to enter persist? */
8258 	if ((bbr->rc_in_persist == 0) &&
8259 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8260 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8261 	    (tp->snd_max == tp->snd_una) &&
8262 	    sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
8263 	    (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
8264 		/* No send window.. we must enter persist */
8265 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8266 	}
8267 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8268 		m_freem(m);
8269 		return (0);
8270 	}
8271 	/*
8272 	 * We don't support urgent data but
8273 	 * drag along the up just to make sure
8274 	 * if there is a stack switch no one
8275 	 * is surprised.
8276 	 */
8277 	tp->rcv_up = tp->rcv_nxt;
8278 	INP_WLOCK_ASSERT(tp->t_inpcb);
8279 
8280 	/*
8281 	 * Process the segment text, merging it into the TCP sequencing
8282 	 * queue, and arranging for acknowledgment of receipt if necessary.
8283 	 * This process logically involves adjusting tp->rcv_wnd as data is
8284 	 * presented to the user (this happens in tcp_usrreq.c, case
8285 	 * PRU_RCVD).  If a FIN has already been received on this connection
8286 	 * then we just ignore the text.
8287 	 */
8288 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8289 		   IS_FASTOPEN(tp->t_flags));
8290 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
8291 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8292 		tcp_seq save_start = th->th_seq;
8293 		tcp_seq save_rnxt  = tp->rcv_nxt;
8294 		int     save_tlen  = tlen;
8295 
8296 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8297 		/*
8298 		 * Insert segment which includes th into TCP reassembly
8299 		 * queue with control block tp.  Set thflags to whether
8300 		 * reassembly now includes a segment with FIN.  This handles
8301 		 * the common case inline (segment is the next to be
8302 		 * received on an established connection, and the queue is
8303 		 * empty), avoiding linkage into and removal from the queue
8304 		 * and repetition of various conversions. Set DELACK for
8305 		 * segments received in order, but ack immediately when
8306 		 * segments are out of order (so fast retransmit can work).
8307 		 */
8308 		if (th->th_seq == tp->rcv_nxt &&
8309 		    SEGQ_EMPTY(tp) &&
8310 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
8311 		    tfo_syn)) {
8312 #ifdef NETFLIX_SB_LIMITS
8313 			u_int mcnt, appended;
8314 
8315 			if (so->so_rcv.sb_shlim) {
8316 				mcnt = m_memcnt(m);
8317 				appended = 0;
8318 				if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8319 				    CFO_NOSLEEP, NULL) == false) {
8320 					counter_u64_add(tcp_sb_shlim_fails, 1);
8321 					m_freem(m);
8322 					return (0);
8323 				}
8324 			}
8325 
8326 #endif
8327 			if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8328 				bbr->bbr_segs_rcvd += max(1, nsegs);
8329 				tp->t_flags |= TF_DELACK;
8330 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8331 			} else {
8332 				bbr->r_wanted_output = 1;
8333 				tp->t_flags |= TF_ACKNOW;
8334 			}
8335 			tp->rcv_nxt += tlen;
8336 			if (tlen &&
8337 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8338 			    (tp->t_fbyte_in == 0)) {
8339 				tp->t_fbyte_in = ticks;
8340 				if (tp->t_fbyte_in == 0)
8341 					tp->t_fbyte_in = 1;
8342 				if (tp->t_fbyte_out && tp->t_fbyte_in)
8343 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8344 			}
8345 			thflags = th->th_flags & TH_FIN;
8346 			KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8347 			KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8348 			SOCKBUF_LOCK(&so->so_rcv);
8349 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8350 				m_freem(m);
8351 			else
8352 #ifdef NETFLIX_SB_LIMITS
8353 				appended =
8354 #endif
8355 					sbappendstream_locked(&so->so_rcv, m, 0);
8356 			SOCKBUF_UNLOCK(&so->so_rcv);
8357 			tp->t_flags |= TF_WAKESOR;
8358 #ifdef NETFLIX_SB_LIMITS
8359 			if (so->so_rcv.sb_shlim && appended != mcnt)
8360 				counter_fo_release(so->so_rcv.sb_shlim,
8361 				    mcnt - appended);
8362 #endif
8363 		} else {
8364 			/*
8365 			 * XXX: Due to the header drop above "th" is
8366 			 * theoretically invalid by now.  Fortunately
8367 			 * m_adj() doesn't actually frees any mbufs when
8368 			 * trimming from the head.
8369 			 */
8370 			tcp_seq temp = save_start;
8371 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
8372 			tp->t_flags |= TF_ACKNOW;
8373 		}
8374 		if ((tp->t_flags & TF_SACK_PERMIT) &&
8375 		    (save_tlen > 0) &&
8376 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
8377 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8378 				/*
8379 				 * DSACK actually handled in the fastpath
8380 				 * above.
8381 				 */
8382 				tcp_update_sack_list(tp, save_start,
8383 				    save_start + save_tlen);
8384 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8385 				if ((tp->rcv_numsacks >= 1) &&
8386 				    (tp->sackblks[0].end == save_start)) {
8387 					/*
8388 					 * Partial overlap, recorded at todrop
8389 					 * above.
8390 					 */
8391 					tcp_update_sack_list(tp,
8392 					    tp->sackblks[0].start,
8393 					    tp->sackblks[0].end);
8394 				} else {
8395 					tcp_update_dsack_list(tp, save_start,
8396 					    save_start + save_tlen);
8397 				}
8398 			} else if (tlen >= save_tlen) {
8399 				/* Update of sackblks. */
8400 				tcp_update_dsack_list(tp, save_start,
8401 				    save_start + save_tlen);
8402 			} else if (tlen > 0) {
8403 				tcp_update_dsack_list(tp, save_start,
8404 				    save_start + tlen);
8405 			}
8406 		}
8407 	} else {
8408 		m_freem(m);
8409 		thflags &= ~TH_FIN;
8410 	}
8411 
8412 	/*
8413 	 * If FIN is received ACK the FIN and let the user know that the
8414 	 * connection is closing.
8415 	 */
8416 	if (thflags & TH_FIN) {
8417 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8418 			socantrcvmore(so);
8419 			/* The socket upcall is handled by socantrcvmore. */
8420 			tp->t_flags &= ~TF_WAKESOR;
8421 			/*
8422 			 * If connection is half-synchronized (ie NEEDSYN
8423 			 * flag on) then delay ACK, so it may be piggybacked
8424 			 * when SYN is sent. Otherwise, since we received a
8425 			 * FIN then no more input can be expected, send ACK
8426 			 * now.
8427 			 */
8428 			if (tp->t_flags & TF_NEEDSYN) {
8429 				tp->t_flags |= TF_DELACK;
8430 				bbr_timer_cancel(bbr,
8431 				    __LINE__, bbr->r_ctl.rc_rcvtime);
8432 			} else {
8433 				tp->t_flags |= TF_ACKNOW;
8434 			}
8435 			tp->rcv_nxt++;
8436 		}
8437 		switch (tp->t_state) {
8438 			/*
8439 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
8440 			 * CLOSE_WAIT state.
8441 			 */
8442 		case TCPS_SYN_RECEIVED:
8443 			tp->t_starttime = ticks;
8444 			/* FALLTHROUGH */
8445 		case TCPS_ESTABLISHED:
8446 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
8447 			break;
8448 
8449 			/*
8450 			 * If still in FIN_WAIT_1 STATE FIN has not been
8451 			 * acked so enter the CLOSING state.
8452 			 */
8453 		case TCPS_FIN_WAIT_1:
8454 			tcp_state_change(tp, TCPS_CLOSING);
8455 			break;
8456 
8457 			/*
8458 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
8459 			 * starting the time-wait timer, turning off the
8460 			 * other standard timers.
8461 			 */
8462 		case TCPS_FIN_WAIT_2:
8463 			bbr->rc_timer_first = 1;
8464 			bbr_timer_cancel(bbr,
8465 			    __LINE__, bbr->r_ctl.rc_rcvtime);
8466 			INP_WLOCK_ASSERT(tp->t_inpcb);
8467 			tcp_twstart(tp);
8468 			return (1);
8469 		}
8470 	}
8471 	/*
8472 	 * Return any desired output.
8473 	 */
8474 	if ((tp->t_flags & TF_ACKNOW) ||
8475 	    (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8476 		bbr->r_wanted_output = 1;
8477 	}
8478 	INP_WLOCK_ASSERT(tp->t_inpcb);
8479 	return (0);
8480 }
8481 
8482 /*
8483  * Here nothing is really faster, its just that we
8484  * have broken out the fast-data path also just like
8485  * the fast-ack. Return 1 if we processed the packet
8486  * return 0 if you need to take the "slow-path".
8487  */
8488 static int
8489 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8490     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8491     uint32_t tiwin, int32_t nxt_pkt)
8492 {
8493 	uint16_t nsegs;
8494 	int32_t newsize = 0;	/* automatic sockbuf scaling */
8495 	struct tcp_bbr *bbr;
8496 #ifdef NETFLIX_SB_LIMITS
8497 	u_int mcnt, appended;
8498 #endif
8499 #ifdef TCPDEBUG
8500 	/*
8501 	 * The size of tcp_saveipgen must be the size of the max ip header,
8502 	 * now IPv6.
8503 	 */
8504 	u_char tcp_saveipgen[IP6_HDR_LEN];
8505 	struct tcphdr tcp_savetcp;
8506 	short ostate = 0;
8507 
8508 #endif
8509 	/* On the hpts and we would have called output */
8510 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8511 
8512 	/*
8513 	 * If last ACK falls within this segment's sequence numbers, record
8514 	 * the timestamp. NOTE that the test is modified according to the
8515 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8516 	 */
8517 	if (bbr->r_ctl.rc_resend != NULL) {
8518 		return (0);
8519 	}
8520 	if (tiwin && tiwin != tp->snd_wnd) {
8521 		return (0);
8522 	}
8523 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8524 		return (0);
8525 	}
8526 	if (__predict_false((to->to_flags & TOF_TS) &&
8527 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8528 		return (0);
8529 	}
8530 	if (__predict_false((th->th_ack != tp->snd_una))) {
8531 		return (0);
8532 	}
8533 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8534 		return (0);
8535 	}
8536 	if ((to->to_flags & TOF_TS) != 0 &&
8537 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8538 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8539 		tp->ts_recent = to->to_tsval;
8540 	}
8541 	/*
8542 	 * This is a pure, in-sequence data packet with nothing on the
8543 	 * reassembly queue and we have enough buffer space to take it.
8544 	 */
8545 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8546 
8547 #ifdef NETFLIX_SB_LIMITS
8548 	if (so->so_rcv.sb_shlim) {
8549 		mcnt = m_memcnt(m);
8550 		appended = 0;
8551 		if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8552 		    CFO_NOSLEEP, NULL) == false) {
8553 			counter_u64_add(tcp_sb_shlim_fails, 1);
8554 			m_freem(m);
8555 			return (1);
8556 		}
8557 	}
8558 #endif
8559 	/* Clean receiver SACK report if present */
8560 	if (tp->rcv_numsacks)
8561 		tcp_clean_sackreport(tp);
8562 	KMOD_TCPSTAT_INC(tcps_preddat);
8563 	tp->rcv_nxt += tlen;
8564 	if (tlen &&
8565 	    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8566 	    (tp->t_fbyte_in == 0)) {
8567 		tp->t_fbyte_in = ticks;
8568 		if (tp->t_fbyte_in == 0)
8569 			tp->t_fbyte_in = 1;
8570 		if (tp->t_fbyte_out && tp->t_fbyte_in)
8571 			tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8572 	}
8573 	/*
8574 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8575 	 */
8576 	tp->snd_wl1 = th->th_seq;
8577 	/*
8578 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8579 	 */
8580 	tp->rcv_up = tp->rcv_nxt;
8581 	KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8582 	KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8583 #ifdef TCPDEBUG
8584 	if (so->so_options & SO_DEBUG)
8585 		tcp_trace(TA_INPUT, ostate, tp,
8586 		    (void *)tcp_saveipgen, &tcp_savetcp, 0);
8587 #endif
8588 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8589 
8590 	/* Add data to socket buffer. */
8591 	SOCKBUF_LOCK(&so->so_rcv);
8592 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8593 		m_freem(m);
8594 	} else {
8595 		/*
8596 		 * Set new socket buffer size. Give up when limit is
8597 		 * reached.
8598 		 */
8599 		if (newsize)
8600 			if (!sbreserve_locked(&so->so_rcv,
8601 			    newsize, so, NULL))
8602 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8603 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8604 
8605 #ifdef NETFLIX_SB_LIMITS
8606 		appended =
8607 #endif
8608 			sbappendstream_locked(&so->so_rcv, m, 0);
8609 		ctf_calc_rwin(so, tp);
8610 	}
8611 	SOCKBUF_UNLOCK(&so->so_rcv);
8612 	tp->t_flags |= TF_WAKESOR;
8613 #ifdef NETFLIX_SB_LIMITS
8614 	if (so->so_rcv.sb_shlim && mcnt != appended)
8615 		counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8616 #endif
8617 	if (DELAY_ACK(tp, bbr, nsegs)) {
8618 		bbr->bbr_segs_rcvd += max(1, nsegs);
8619 		tp->t_flags |= TF_DELACK;
8620 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8621 	} else {
8622 		bbr->r_wanted_output = 1;
8623 		tp->t_flags |= TF_ACKNOW;
8624 	}
8625 	return (1);
8626 }
8627 
8628 /*
8629  * This subfunction is used to try to highly optimize the
8630  * fast path. We again allow window updates that are
8631  * in sequence to remain in the fast-path. We also add
8632  * in the __predict's to attempt to help the compiler.
8633  * Note that if we return a 0, then we can *not* process
8634  * it and the caller should push the packet into the
8635  * slow-path. If we return 1, then all is well and
8636  * the packet is fully processed.
8637  */
8638 static int
8639 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8640     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8641     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
8642 {
8643 	int32_t acked;
8644 	uint16_t nsegs;
8645 	uint32_t sack_changed;
8646 #ifdef TCPDEBUG
8647 	/*
8648 	 * The size of tcp_saveipgen must be the size of the max ip header,
8649 	 * now IPv6.
8650 	 */
8651 	u_char tcp_saveipgen[IP6_HDR_LEN];
8652 	struct tcphdr tcp_savetcp;
8653 	short ostate = 0;
8654 
8655 #endif
8656 	uint32_t prev_acked = 0;
8657 	struct tcp_bbr *bbr;
8658 
8659 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8660 		/* Old ack, behind (or duplicate to) the last one rcv'd */
8661 		return (0);
8662 	}
8663 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8664 		/* Above what we have sent? */
8665 		return (0);
8666 	}
8667 	if (__predict_false(tiwin == 0)) {
8668 		/* zero window */
8669 		return (0);
8670 	}
8671 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8672 		/* We need a SYN or a FIN, unlikely.. */
8673 		return (0);
8674 	}
8675 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8676 		/* Timestamp is behind .. old ack with seq wrap? */
8677 		return (0);
8678 	}
8679 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8680 		/* Still recovering */
8681 		return (0);
8682 	}
8683 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8684 	if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8685 		/* We are retransmitting */
8686 		return (0);
8687 	}
8688 	if (__predict_false(bbr->rc_in_persist != 0)) {
8689 		/* In persist mode */
8690 		return (0);
8691 	}
8692 	if (bbr->r_ctl.rc_sacked) {
8693 		/* We have sack holes on our scoreboard */
8694 		return (0);
8695 	}
8696 	/* Ok if we reach here, we can process a fast-ack */
8697 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8698 	sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8699 	/*
8700 	 * We never detect loss in fast ack [we can't
8701 	 * have a sack and can't be in recovery so
8702 	 * we always pass 0 (nothing detected)].
8703 	 */
8704 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8705 	/* Did the window get updated? */
8706 	if (tiwin != tp->snd_wnd) {
8707 		tp->snd_wnd = tiwin;
8708 		tp->snd_wl1 = th->th_seq;
8709 		if (tp->snd_wnd > tp->max_sndwnd)
8710 			tp->max_sndwnd = tp->snd_wnd;
8711 	}
8712 	/* Do we need to exit persists? */
8713 	if ((bbr->rc_in_persist != 0) &&
8714 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8715 			       bbr_minseg(bbr)))) {
8716 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8717 		bbr->r_wanted_output = 1;
8718 	}
8719 	/* Do we need to enter persists? */
8720 	if ((bbr->rc_in_persist == 0) &&
8721 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8722 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8723 	    (tp->snd_max == tp->snd_una) &&
8724 	    sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
8725 	    (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
8726 		/* No send window.. we must enter persist */
8727 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8728 	}
8729 	/*
8730 	 * If last ACK falls within this segment's sequence numbers, record
8731 	 * the timestamp. NOTE that the test is modified according to the
8732 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8733 	 */
8734 	if ((to->to_flags & TOF_TS) != 0 &&
8735 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8736 		tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8737 		tp->ts_recent = to->to_tsval;
8738 	}
8739 	/*
8740 	 * This is a pure ack for outstanding data.
8741 	 */
8742 	KMOD_TCPSTAT_INC(tcps_predack);
8743 
8744 	/*
8745 	 * "bad retransmit" recovery.
8746 	 */
8747 	if (tp->t_flags & TF_PREVVALID) {
8748 		tp->t_flags &= ~TF_PREVVALID;
8749 		if (tp->t_rxtshift == 1 &&
8750 		    (int)(ticks - tp->t_badrxtwin) < 0)
8751 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8752 	}
8753 	/*
8754 	 * Recalculate the transmit timer / rtt.
8755 	 *
8756 	 * Some boxes send broken timestamp replies during the SYN+ACK
8757 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
8758 	 * and blow up the retransmit timer.
8759 	 */
8760 	acked = BYTES_THIS_ACK(tp, th);
8761 
8762 #ifdef TCP_HHOOK
8763 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8764 	hhook_run_tcp_est_in(tp, th, to);
8765 #endif
8766 
8767 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8768 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
8769 	sbdrop(&so->so_snd, acked);
8770 
8771 	if (SEQ_GT(th->th_ack, tp->snd_una))
8772 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8773 	tp->snd_una = th->th_ack;
8774 	if (tp->snd_wnd < ctf_outstanding(tp))
8775 		/* The peer collapsed its window on us */
8776 		bbr_collapsed_window(bbr);
8777 	else if (bbr->rc_has_collapsed)
8778 		bbr_un_collapse_window(bbr);
8779 
8780 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8781 		tp->snd_recover = tp->snd_una;
8782 	}
8783 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8784 	/*
8785 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8786 	 */
8787 	tp->snd_wl2 = th->th_ack;
8788 	m_freem(m);
8789 	/*
8790 	 * If all outstanding data are acked, stop retransmit timer,
8791 	 * otherwise restart timer using current (possibly backed-off)
8792 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
8793 	 * If data are ready to send, let tcp_output decide between more
8794 	 * output or persist.
8795 	 */
8796 #ifdef TCPDEBUG
8797 	if (so->so_options & SO_DEBUG)
8798 		tcp_trace(TA_INPUT, ostate, tp,
8799 		    (void *)tcp_saveipgen,
8800 		    &tcp_savetcp, 0);
8801 #endif
8802 	/* Wake up the socket if we have room to write more */
8803 	tp->t_flags |= TF_WAKESOW;
8804 	if (tp->snd_una == tp->snd_max) {
8805 		/* Nothing left outstanding */
8806 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8807 		if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
8808 			bbr->rc_tp->t_acktime = 0;
8809 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8810 		if (bbr->rc_in_persist == 0) {
8811 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8812 		}
8813 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8814 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8815 		/*
8816 		 * We invalidate the last ack here since we
8817 		 * don't want to transfer forward the time
8818 		 * for our sum's calculations.
8819 		 */
8820 		bbr->r_wanted_output = 1;
8821 	}
8822 	if (sbavail(&so->so_snd)) {
8823 		bbr->r_wanted_output = 1;
8824 	}
8825 	return (1);
8826 }
8827 
8828 /*
8829  * Return value of 1, the TCB is unlocked and most
8830  * likely gone, return value of 0, the TCB is still
8831  * locked.
8832  */
8833 static int
8834 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8835     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8836     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8837 {
8838 	int32_t todrop;
8839 	int32_t ourfinisacked = 0;
8840 	struct tcp_bbr *bbr;
8841 	int32_t ret_val = 0;
8842 
8843 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8844 	ctf_calc_rwin(so, tp);
8845 	/*
8846 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
8847 	 * SYN, drop the input. if seg contains a RST, then drop the
8848 	 * connection. if seg does not contain SYN, then drop it. Otherwise
8849 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
8850 	 * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8851 	 * not support ECN so we will not say we are capable. if SYN has
8852 	 * been acked change to ESTABLISHED else SYN_RCVD state arrange for
8853 	 * segment to be acked (eventually) continue processing rest of
8854 	 * data/controls, beginning with URG
8855 	 */
8856 	if ((thflags & TH_ACK) &&
8857 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
8858 	    SEQ_GT(th->th_ack, tp->snd_max))) {
8859 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8860 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8861 		return (1);
8862 	}
8863 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
8864 		TCP_PROBE5(connect__refused, NULL, tp,
8865 		    mtod(m, const char *), tp, th);
8866 		tp = tcp_drop(tp, ECONNREFUSED);
8867 		ctf_do_drop(m, tp);
8868 		return (1);
8869 	}
8870 	if (thflags & TH_RST) {
8871 		ctf_do_drop(m, tp);
8872 		return (1);
8873 	}
8874 	if (!(thflags & TH_SYN)) {
8875 		ctf_do_drop(m, tp);
8876 		return (1);
8877 	}
8878 	tp->irs = th->th_seq;
8879 	tcp_rcvseqinit(tp);
8880 	if (thflags & TH_ACK) {
8881 		int tfo_partial = 0;
8882 
8883 		KMOD_TCPSTAT_INC(tcps_connects);
8884 		soisconnected(so);
8885 #ifdef MAC
8886 		mac_socketpeer_set_from_mbuf(m, so);
8887 #endif
8888 		/* Do window scaling on this connection? */
8889 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
8890 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
8891 			tp->rcv_scale = tp->request_r_scale;
8892 		}
8893 		tp->rcv_adv += min(tp->rcv_wnd,
8894 		    TCP_MAXWIN << tp->rcv_scale);
8895 		/*
8896 		 * If not all the data that was sent in the TFO SYN
8897 		 * has been acked, resend the remainder right away.
8898 		 */
8899 		if (IS_FASTOPEN(tp->t_flags) &&
8900 		    (tp->snd_una != tp->snd_max)) {
8901 			tp->snd_nxt = th->th_ack;
8902 			tfo_partial = 1;
8903 		}
8904 		/*
8905 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
8906 		 * will be turned on later.
8907 		 */
8908 		if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && !tfo_partial) {
8909 			bbr->bbr_segs_rcvd += 1;
8910 			tp->t_flags |= TF_DELACK;
8911 			bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8912 		} else {
8913 			bbr->r_wanted_output = 1;
8914 			tp->t_flags |= TF_ACKNOW;
8915 		}
8916 		if (SEQ_GT(th->th_ack, tp->iss)) {
8917 			/*
8918 			 * The SYN is acked
8919 			 * handle it specially.
8920 			 */
8921 			bbr_log_syn(tp, to);
8922 		}
8923 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
8924 			/*
8925 			 * We advance snd_una for the
8926 			 * fast open case. If th_ack is
8927 			 * acknowledging data beyond
8928 			 * snd_una we can't just call
8929 			 * ack-processing since the
8930 			 * data stream in our send-map
8931 			 * will start at snd_una + 1 (one
8932 			 * beyond the SYN). If its just
8933 			 * equal we don't need to do that
8934 			 * and there is no send_map.
8935 			 */
8936 			tp->snd_una++;
8937 		}
8938 		/*
8939 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
8940 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
8941 		 */
8942 		tp->t_starttime = ticks;
8943 		if (tp->t_flags & TF_NEEDFIN) {
8944 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
8945 			tp->t_flags &= ~TF_NEEDFIN;
8946 			thflags &= ~TH_SYN;
8947 		} else {
8948 			tcp_state_change(tp, TCPS_ESTABLISHED);
8949 			TCP_PROBE5(connect__established, NULL, tp,
8950 			    mtod(m, const char *), tp, th);
8951 			cc_conn_init(tp);
8952 		}
8953 	} else {
8954 		/*
8955 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
8956 		 * open.  If segment contains CC option and there is a
8957 		 * cached CC, apply TAO test. If it succeeds, connection is *
8958 		 * half-synchronized. Otherwise, do 3-way handshake:
8959 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
8960 		 * there was no CC option, clear cached CC value.
8961 		 */
8962 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
8963 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
8964 	}
8965 	INP_WLOCK_ASSERT(tp->t_inpcb);
8966 	/*
8967 	 * Advance th->th_seq to correspond to first data byte. If data,
8968 	 * trim to stay within window, dropping FIN if necessary.
8969 	 */
8970 	th->th_seq++;
8971 	if (tlen > tp->rcv_wnd) {
8972 		todrop = tlen - tp->rcv_wnd;
8973 		m_adj(m, -todrop);
8974 		tlen = tp->rcv_wnd;
8975 		thflags &= ~TH_FIN;
8976 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
8977 		KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
8978 	}
8979 	tp->snd_wl1 = th->th_seq - 1;
8980 	tp->rcv_up = th->th_seq;
8981 	/*
8982 	 * Client side of transaction: already sent SYN and data. If the
8983 	 * remote host used T/TCP to validate the SYN, our data will be
8984 	 * ACK'd; if so, enter normal data segment processing in the middle
8985 	 * of step 5, ack processing. Otherwise, goto step 6.
8986 	 */
8987 	if (thflags & TH_ACK) {
8988 		if ((to->to_flags & TOF_TS) != 0) {
8989 			uint32_t t, rtt;
8990 
8991 			t = tcp_tv_to_mssectick(&bbr->rc_tv);
8992 			if (TSTMP_GEQ(t, to->to_tsecr)) {
8993 				rtt = t - to->to_tsecr;
8994 				if (rtt == 0) {
8995 					rtt = 1;
8996 				}
8997 				rtt *= MS_IN_USEC;
8998 				tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
8999 				apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
9000 						       rtt, bbr->r_ctl.rc_rcvtime);
9001 			}
9002 		}
9003 		if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
9004 			return (ret_val);
9005 		/* We may have changed to FIN_WAIT_1 above */
9006 		if (tp->t_state == TCPS_FIN_WAIT_1) {
9007 			/*
9008 			 * In FIN_WAIT_1 STATE in addition to the processing
9009 			 * for the ESTABLISHED state if our FIN is now
9010 			 * acknowledged then enter FIN_WAIT_2.
9011 			 */
9012 			if (ourfinisacked) {
9013 				/*
9014 				 * If we can't receive any more data, then
9015 				 * closing user can proceed. Starting the
9016 				 * timer is contrary to the specification,
9017 				 * but if we don't get a FIN we'll hang
9018 				 * forever.
9019 				 *
9020 				 * XXXjl: we should release the tp also, and
9021 				 * use a compressed state.
9022 				 */
9023 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9024 					soisdisconnected(so);
9025 					tcp_timer_activate(tp, TT_2MSL,
9026 					    (tcp_fast_finwait2_recycle ?
9027 					    tcp_finwait2_timeout :
9028 					    TP_MAXIDLE(tp)));
9029 				}
9030 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
9031 			}
9032 		}
9033 	}
9034 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9035 	    tiwin, thflags, nxt_pkt));
9036 }
9037 
9038 /*
9039  * Return value of 1, the TCB is unlocked and most
9040  * likely gone, return value of 0, the TCB is still
9041  * locked.
9042  */
9043 static int
9044 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
9045 		struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9046 		uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9047 {
9048 	int32_t ourfinisacked = 0;
9049 	int32_t ret_val;
9050 	struct tcp_bbr *bbr;
9051 
9052 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9053 	ctf_calc_rwin(so, tp);
9054 	if ((thflags & TH_ACK) &&
9055 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
9056 	     SEQ_GT(th->th_ack, tp->snd_max))) {
9057 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9058 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9059 		return (1);
9060 	}
9061 	if (IS_FASTOPEN(tp->t_flags)) {
9062 		/*
9063 		 * When a TFO connection is in SYN_RECEIVED, the only valid
9064 		 * packets are the initial SYN, a retransmit/copy of the
9065 		 * initial SYN (possibly with a subset of the original
9066 		 * data), a valid ACK, a FIN, or a RST.
9067 		 */
9068 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
9069 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9070 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9071 			return (1);
9072 		} else if (thflags & TH_SYN) {
9073 			/* non-initial SYN is ignored */
9074 			if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
9075 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
9076 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
9077 				ctf_do_drop(m, NULL);
9078 				return (0);
9079 			}
9080 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
9081 			ctf_do_drop(m, NULL);
9082 			return (0);
9083 		}
9084 	}
9085 	if ((thflags & TH_RST) ||
9086 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9087 		return (ctf_process_rst(m, th, so, tp));
9088 	/*
9089 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9090 	 * it's less than ts_recent, drop it.
9091 	 */
9092 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9093 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9094 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9095 			return (ret_val);
9096 	}
9097 	/*
9098 	 * In the SYN-RECEIVED state, validate that the packet belongs to
9099 	 * this connection before trimming the data to fit the receive
9100 	 * window.  Check the sequence number versus IRS since we know the
9101 	 * sequence numbers haven't wrapped.  This is a partial fix for the
9102 	 * "LAND" DoS attack.
9103 	 */
9104 	if (SEQ_LT(th->th_seq, tp->irs)) {
9105 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9106 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9107 		return (1);
9108 	}
9109 	INP_WLOCK_ASSERT(tp->t_inpcb);
9110 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9111 		return (ret_val);
9112 	}
9113 	/*
9114 	 * If last ACK falls within this segment's sequence numbers, record
9115 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9116 	 * from the latest proposal of the tcplw@cray.com list (Braden
9117 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9118 	 * with our earlier PAWS tests, so this check should be solely
9119 	 * predicated on the sequence space of this segment. 3) That we
9120 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9121 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9122 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9123 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9124 	 * p.869. In such cases, we can still calculate the RTT correctly
9125 	 * when RCV.NXT == Last.ACK.Sent.
9126 	 */
9127 	if ((to->to_flags & TOF_TS) != 0 &&
9128 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9129 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9130 		    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9131 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9132 		tp->ts_recent = to->to_tsval;
9133 	}
9134 	tp->snd_wnd = tiwin;
9135 	/*
9136 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9137 	 * is on (half-synchronized state), then queue data for later
9138 	 * processing; else drop segment and return.
9139 	 */
9140 	if ((thflags & TH_ACK) == 0) {
9141 		if (IS_FASTOPEN(tp->t_flags)) {
9142 			cc_conn_init(tp);
9143 		}
9144 		return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9145 					 tiwin, thflags, nxt_pkt));
9146 	}
9147 	KMOD_TCPSTAT_INC(tcps_connects);
9148 	soisconnected(so);
9149 	/* Do window scaling? */
9150 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9151 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9152 		tp->rcv_scale = tp->request_r_scale;
9153 	}
9154 	/*
9155 	 * ok for the first time in lets see if we can use the ts to figure
9156 	 * out what the initial RTT was.
9157 	 */
9158 	if ((to->to_flags & TOF_TS) != 0) {
9159 		uint32_t t, rtt;
9160 
9161 		t = tcp_tv_to_mssectick(&bbr->rc_tv);
9162 		if (TSTMP_GEQ(t, to->to_tsecr)) {
9163 			rtt = t - to->to_tsecr;
9164 			if (rtt == 0) {
9165 				rtt = 1;
9166 			}
9167 			rtt *= MS_IN_USEC;
9168 			tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9169 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9170 		}
9171 	}
9172 	/* Drop off any SYN in the send map (probably not there)  */
9173 	if (thflags & TH_ACK)
9174 		bbr_log_syn(tp, to);
9175 	if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
9176 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9177 		tp->t_tfo_pending = NULL;
9178 	}
9179 	/*
9180 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9181 	 * FIN-WAIT-1
9182 	 */
9183 	tp->t_starttime = ticks;
9184 	if (tp->t_flags & TF_NEEDFIN) {
9185 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
9186 		tp->t_flags &= ~TF_NEEDFIN;
9187 	} else {
9188 		tcp_state_change(tp, TCPS_ESTABLISHED);
9189 		TCP_PROBE5(accept__established, NULL, tp,
9190 			   mtod(m, const char *), tp, th);
9191 		/*
9192 		 * TFO connections call cc_conn_init() during SYN
9193 		 * processing.  Calling it again here for such connections
9194 		 * is not harmless as it would undo the snd_cwnd reduction
9195 		 * that occurs when a TFO SYN|ACK is retransmitted.
9196 		 */
9197 		if (!IS_FASTOPEN(tp->t_flags))
9198 			cc_conn_init(tp);
9199 	}
9200 	/*
9201 	 * Account for the ACK of our SYN prior to
9202 	 * regular ACK processing below, except for
9203 	 * simultaneous SYN, which is handled later.
9204 	 */
9205 	if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
9206 		tp->snd_una++;
9207 	/*
9208 	 * If segment contains data or ACK, will call tcp_reass() later; if
9209 	 * not, do so now to pass queued data to user.
9210 	 */
9211 	if (tlen == 0 && (thflags & TH_FIN) == 0)
9212 		(void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9213 			(struct mbuf *)0);
9214 	tp->snd_wl1 = th->th_seq - 1;
9215 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9216 		return (ret_val);
9217 	}
9218 	if (tp->t_state == TCPS_FIN_WAIT_1) {
9219 		/* We could have went to FIN_WAIT_1 (or EST) above */
9220 		/*
9221 		 * In FIN_WAIT_1 STATE in addition to the processing for the
9222 		 * ESTABLISHED state if our FIN is now acknowledged then
9223 		 * enter FIN_WAIT_2.
9224 		 */
9225 		if (ourfinisacked) {
9226 			/*
9227 			 * If we can't receive any more data, then closing
9228 			 * user can proceed. Starting the timer is contrary
9229 			 * to the specification, but if we don't get a FIN
9230 			 * we'll hang forever.
9231 			 *
9232 			 * XXXjl: we should release the tp also, and use a
9233 			 * compressed state.
9234 			 */
9235 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9236 				soisdisconnected(so);
9237 				tcp_timer_activate(tp, TT_2MSL,
9238 						   (tcp_fast_finwait2_recycle ?
9239 						    tcp_finwait2_timeout :
9240 						    TP_MAXIDLE(tp)));
9241 			}
9242 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
9243 		}
9244 	}
9245 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9246 				 tiwin, thflags, nxt_pkt));
9247 }
9248 
9249 /*
9250  * Return value of 1, the TCB is unlocked and most
9251  * likely gone, return value of 0, the TCB is still
9252  * locked.
9253  */
9254 static int
9255 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9256     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9257     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9258 {
9259 	struct tcp_bbr *bbr;
9260 	int32_t ret_val;
9261 
9262 	/*
9263 	 * Header prediction: check for the two common cases of a
9264 	 * uni-directional data xfer.  If the packet has no control flags,
9265 	 * is in-sequence, the window didn't change and we're not
9266 	 * retransmitting, it's a candidate.  If the length is zero and the
9267 	 * ack moved forward, we're the sender side of the xfer.  Just free
9268 	 * the data acked & wake any higher level process that was blocked
9269 	 * waiting for space.  If the length is non-zero and the ack didn't
9270 	 * move, we're the receiver side.  If we're getting packets in-order
9271 	 * (the reassembly queue is empty), add the data toc The socket
9272 	 * buffer and note that we need a delayed ack. Make sure that the
9273 	 * hidden state-flags are also off. Since we check for
9274 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9275 	 */
9276 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9277 	if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9278 		/*
9279 		 * If we have delived under 4 segments increase the initial
9280 		 * window if raised by the peer. We use this to determine
9281 		 * dynamic and static rwnd's at the end of a connection.
9282 		 */
9283 		bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9284 	}
9285 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9286 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9287 	    __predict_true(SEGQ_EMPTY(tp)) &&
9288 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
9289 		if (tlen == 0) {
9290 			if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9291 			    tiwin, nxt_pkt, iptos)) {
9292 				return (0);
9293 			}
9294 		} else {
9295 			if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9296 			    tiwin, nxt_pkt)) {
9297 				return (0);
9298 			}
9299 		}
9300 	}
9301 	ctf_calc_rwin(so, tp);
9302 
9303 	if ((thflags & TH_RST) ||
9304 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9305 		return (ctf_process_rst(m, th, so, tp));
9306 	/*
9307 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9308 	 * synchronized state.
9309 	 */
9310 	if (thflags & TH_SYN) {
9311 		ctf_challenge_ack(m, th, tp, &ret_val);
9312 		return (ret_val);
9313 	}
9314 	/*
9315 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9316 	 * it's less than ts_recent, drop it.
9317 	 */
9318 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9319 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9320 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9321 			return (ret_val);
9322 	}
9323 	INP_WLOCK_ASSERT(tp->t_inpcb);
9324 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9325 		return (ret_val);
9326 	}
9327 	/*
9328 	 * If last ACK falls within this segment's sequence numbers, record
9329 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9330 	 * from the latest proposal of the tcplw@cray.com list (Braden
9331 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9332 	 * with our earlier PAWS tests, so this check should be solely
9333 	 * predicated on the sequence space of this segment. 3) That we
9334 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9335 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9336 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9337 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9338 	 * p.869. In such cases, we can still calculate the RTT correctly
9339 	 * when RCV.NXT == Last.ACK.Sent.
9340 	 */
9341 	if ((to->to_flags & TOF_TS) != 0 &&
9342 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9343 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9344 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9345 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9346 		tp->ts_recent = to->to_tsval;
9347 	}
9348 	/*
9349 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9350 	 * is on (half-synchronized state), then queue data for later
9351 	 * processing; else drop segment and return.
9352 	 */
9353 	if ((thflags & TH_ACK) == 0) {
9354 		if (tp->t_flags & TF_NEEDSYN) {
9355 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9356 			    tiwin, thflags, nxt_pkt));
9357 		} else if (tp->t_flags & TF_ACKNOW) {
9358 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9359 			bbr->r_wanted_output = 1;
9360 			return (ret_val);
9361 		} else {
9362 			ctf_do_drop(m, NULL);
9363 			return (0);
9364 		}
9365 	}
9366 	/*
9367 	 * Ack processing.
9368 	 */
9369 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9370 		return (ret_val);
9371 	}
9372 	if (sbavail(&so->so_snd)) {
9373 		if (ctf_progress_timeout_check(tp, true)) {
9374 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9375 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9376 			return (1);
9377 		}
9378 	}
9379 	/* State changes only happen in bbr_process_data() */
9380 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9381 	    tiwin, thflags, nxt_pkt));
9382 }
9383 
9384 /*
9385  * Return value of 1, the TCB is unlocked and most
9386  * likely gone, return value of 0, the TCB is still
9387  * locked.
9388  */
9389 static int
9390 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9391     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9392     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9393 {
9394 	struct tcp_bbr *bbr;
9395 	int32_t ret_val;
9396 
9397 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9398 	ctf_calc_rwin(so, tp);
9399 	if ((thflags & TH_RST) ||
9400 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9401 		return (ctf_process_rst(m, th, so, tp));
9402 	/*
9403 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9404 	 * synchronized state.
9405 	 */
9406 	if (thflags & TH_SYN) {
9407 		ctf_challenge_ack(m, th, tp, &ret_val);
9408 		return (ret_val);
9409 	}
9410 	/*
9411 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9412 	 * it's less than ts_recent, drop it.
9413 	 */
9414 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9415 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9416 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9417 			return (ret_val);
9418 	}
9419 	INP_WLOCK_ASSERT(tp->t_inpcb);
9420 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9421 		return (ret_val);
9422 	}
9423 	/*
9424 	 * If last ACK falls within this segment's sequence numbers, record
9425 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9426 	 * from the latest proposal of the tcplw@cray.com list (Braden
9427 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9428 	 * with our earlier PAWS tests, so this check should be solely
9429 	 * predicated on the sequence space of this segment. 3) That we
9430 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9431 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9432 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9433 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9434 	 * p.869. In such cases, we can still calculate the RTT correctly
9435 	 * when RCV.NXT == Last.ACK.Sent.
9436 	 */
9437 	if ((to->to_flags & TOF_TS) != 0 &&
9438 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9439 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9440 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9441 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9442 		tp->ts_recent = to->to_tsval;
9443 	}
9444 	/*
9445 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9446 	 * is on (half-synchronized state), then queue data for later
9447 	 * processing; else drop segment and return.
9448 	 */
9449 	if ((thflags & TH_ACK) == 0) {
9450 		if (tp->t_flags & TF_NEEDSYN) {
9451 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9452 			    tiwin, thflags, nxt_pkt));
9453 		} else if (tp->t_flags & TF_ACKNOW) {
9454 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9455 			bbr->r_wanted_output = 1;
9456 			return (ret_val);
9457 		} else {
9458 			ctf_do_drop(m, NULL);
9459 			return (0);
9460 		}
9461 	}
9462 	/*
9463 	 * Ack processing.
9464 	 */
9465 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9466 		return (ret_val);
9467 	}
9468 	if (sbavail(&so->so_snd)) {
9469 		if (ctf_progress_timeout_check(tp, true)) {
9470 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9471 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9472 			return (1);
9473 		}
9474 	}
9475 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9476 	    tiwin, thflags, nxt_pkt));
9477 }
9478 
9479 static int
9480 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9481     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9482 {
9483 
9484 	if (bbr->rc_allow_data_af_clo == 0) {
9485 close_now:
9486 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
9487 		/* tcp_close will kill the inp pre-log the Reset */
9488 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
9489 		tp = tcp_close(tp);
9490 		KMOD_TCPSTAT_INC(tcps_rcvafterclose);
9491 		ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9492 		return (1);
9493 	}
9494 	if (sbavail(&so->so_snd) == 0)
9495 		goto close_now;
9496 	/* Ok we allow data that is ignored and a followup reset */
9497 	tp->rcv_nxt = th->th_seq + *tlen;
9498 	tp->t_flags2 |= TF2_DROP_AF_DATA;
9499 	bbr->r_wanted_output = 1;
9500 	*tlen = 0;
9501 	return (0);
9502 }
9503 
9504 /*
9505  * Return value of 1, the TCB is unlocked and most
9506  * likely gone, return value of 0, the TCB is still
9507  * locked.
9508  */
9509 static int
9510 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9511     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9512     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9513 {
9514 	int32_t ourfinisacked = 0;
9515 	int32_t ret_val;
9516 	struct tcp_bbr *bbr;
9517 
9518 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9519 	ctf_calc_rwin(so, tp);
9520 	if ((thflags & TH_RST) ||
9521 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9522 		return (ctf_process_rst(m, th, so, tp));
9523 	/*
9524 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9525 	 * synchronized state.
9526 	 */
9527 	if (thflags & TH_SYN) {
9528 		ctf_challenge_ack(m, th, tp, &ret_val);
9529 		return (ret_val);
9530 	}
9531 	/*
9532 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9533 	 * it's less than ts_recent, drop it.
9534 	 */
9535 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9536 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9537 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9538 			return (ret_val);
9539 	}
9540 	INP_WLOCK_ASSERT(tp->t_inpcb);
9541 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9542 		return (ret_val);
9543 	}
9544 	/*
9545 	 * If new data are received on a connection after the user processes
9546 	 * are gone, then RST the other end.
9547 	 */
9548 	if ((so->so_state & SS_NOFDREF) && tlen) {
9549 		/*
9550 		 * We call a new function now so we might continue and setup
9551 		 * to reset at all data being ack'd.
9552 		 */
9553 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9554 			return (1);
9555 	}
9556 	/*
9557 	 * If last ACK falls within this segment's sequence numbers, record
9558 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9559 	 * from the latest proposal of the tcplw@cray.com list (Braden
9560 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9561 	 * with our earlier PAWS tests, so this check should be solely
9562 	 * predicated on the sequence space of this segment. 3) That we
9563 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9564 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9565 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9566 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9567 	 * p.869. In such cases, we can still calculate the RTT correctly
9568 	 * when RCV.NXT == Last.ACK.Sent.
9569 	 */
9570 	if ((to->to_flags & TOF_TS) != 0 &&
9571 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9572 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9573 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9574 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9575 		tp->ts_recent = to->to_tsval;
9576 	}
9577 	/*
9578 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9579 	 * is on (half-synchronized state), then queue data for later
9580 	 * processing; else drop segment and return.
9581 	 */
9582 	if ((thflags & TH_ACK) == 0) {
9583 		if (tp->t_flags & TF_NEEDSYN) {
9584 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9585 			    tiwin, thflags, nxt_pkt));
9586 		} else if (tp->t_flags & TF_ACKNOW) {
9587 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9588 			bbr->r_wanted_output = 1;
9589 			return (ret_val);
9590 		} else {
9591 			ctf_do_drop(m, NULL);
9592 			return (0);
9593 		}
9594 	}
9595 	/*
9596 	 * Ack processing.
9597 	 */
9598 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9599 		return (ret_val);
9600 	}
9601 	if (ourfinisacked) {
9602 		/*
9603 		 * If we can't receive any more data, then closing user can
9604 		 * proceed. Starting the timer is contrary to the
9605 		 * specification, but if we don't get a FIN we'll hang
9606 		 * forever.
9607 		 *
9608 		 * XXXjl: we should release the tp also, and use a
9609 		 * compressed state.
9610 		 */
9611 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9612 			soisdisconnected(so);
9613 			tcp_timer_activate(tp, TT_2MSL,
9614 			    (tcp_fast_finwait2_recycle ?
9615 			    tcp_finwait2_timeout :
9616 			    TP_MAXIDLE(tp)));
9617 		}
9618 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
9619 	}
9620 	if (sbavail(&so->so_snd)) {
9621 		if (ctf_progress_timeout_check(tp, true)) {
9622 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9623 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9624 			return (1);
9625 		}
9626 	}
9627 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9628 	    tiwin, thflags, nxt_pkt));
9629 }
9630 
9631 /*
9632  * Return value of 1, the TCB is unlocked and most
9633  * likely gone, return value of 0, the TCB is still
9634  * locked.
9635  */
9636 static int
9637 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9638     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9639     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9640 {
9641 	int32_t ourfinisacked = 0;
9642 	int32_t ret_val;
9643 	struct tcp_bbr *bbr;
9644 
9645 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9646 	ctf_calc_rwin(so, tp);
9647 	if ((thflags & TH_RST) ||
9648 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9649 		return (ctf_process_rst(m, th, so, tp));
9650 	/*
9651 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9652 	 * synchronized state.
9653 	 */
9654 	if (thflags & TH_SYN) {
9655 		ctf_challenge_ack(m, th, tp, &ret_val);
9656 		return (ret_val);
9657 	}
9658 	/*
9659 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9660 	 * it's less than ts_recent, drop it.
9661 	 */
9662 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9663 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9664 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9665 			return (ret_val);
9666 	}
9667 	INP_WLOCK_ASSERT(tp->t_inpcb);
9668 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9669 		return (ret_val);
9670 	}
9671 	/*
9672 	 * If new data are received on a connection after the user processes
9673 	 * are gone, then RST the other end.
9674 	 */
9675 	if ((so->so_state & SS_NOFDREF) && tlen) {
9676 		/*
9677 		 * We call a new function now so we might continue and setup
9678 		 * to reset at all data being ack'd.
9679 		 */
9680 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9681 			return (1);
9682 	}
9683 	/*
9684 	 * If last ACK falls within this segment's sequence numbers, record
9685 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9686 	 * from the latest proposal of the tcplw@cray.com list (Braden
9687 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9688 	 * with our earlier PAWS tests, so this check should be solely
9689 	 * predicated on the sequence space of this segment. 3) That we
9690 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9691 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9692 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9693 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9694 	 * p.869. In such cases, we can still calculate the RTT correctly
9695 	 * when RCV.NXT == Last.ACK.Sent.
9696 	 */
9697 	if ((to->to_flags & TOF_TS) != 0 &&
9698 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9699 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9700 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9701 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9702 		tp->ts_recent = to->to_tsval;
9703 	}
9704 	/*
9705 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9706 	 * is on (half-synchronized state), then queue data for later
9707 	 * processing; else drop segment and return.
9708 	 */
9709 	if ((thflags & TH_ACK) == 0) {
9710 		if (tp->t_flags & TF_NEEDSYN) {
9711 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9712 			    tiwin, thflags, nxt_pkt));
9713 		} else if (tp->t_flags & TF_ACKNOW) {
9714 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9715 			bbr->r_wanted_output = 1;
9716 			return (ret_val);
9717 		} else {
9718 			ctf_do_drop(m, NULL);
9719 			return (0);
9720 		}
9721 	}
9722 	/*
9723 	 * Ack processing.
9724 	 */
9725 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9726 		return (ret_val);
9727 	}
9728 	if (ourfinisacked) {
9729 		tcp_twstart(tp);
9730 		m_freem(m);
9731 		return (1);
9732 	}
9733 	if (sbavail(&so->so_snd)) {
9734 		if (ctf_progress_timeout_check(tp, true)) {
9735 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9736 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9737 			return (1);
9738 		}
9739 	}
9740 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9741 	    tiwin, thflags, nxt_pkt));
9742 }
9743 
9744 /*
9745  * Return value of 1, the TCB is unlocked and most
9746  * likely gone, return value of 0, the TCB is still
9747  * locked.
9748  */
9749 static int
9750 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9751     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9752     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9753 {
9754 	int32_t ourfinisacked = 0;
9755 	int32_t ret_val;
9756 	struct tcp_bbr *bbr;
9757 
9758 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9759 	ctf_calc_rwin(so, tp);
9760 	if ((thflags & TH_RST) ||
9761 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9762 		return (ctf_process_rst(m, th, so, tp));
9763 	/*
9764 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9765 	 * synchronized state.
9766 	 */
9767 	if (thflags & TH_SYN) {
9768 		ctf_challenge_ack(m, th, tp, &ret_val);
9769 		return (ret_val);
9770 	}
9771 	/*
9772 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9773 	 * it's less than ts_recent, drop it.
9774 	 */
9775 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9776 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9777 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9778 			return (ret_val);
9779 	}
9780 	INP_WLOCK_ASSERT(tp->t_inpcb);
9781 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9782 		return (ret_val);
9783 	}
9784 	/*
9785 	 * If new data are received on a connection after the user processes
9786 	 * are gone, then RST the other end.
9787 	 */
9788 	if ((so->so_state & SS_NOFDREF) && tlen) {
9789 		/*
9790 		 * We call a new function now so we might continue and setup
9791 		 * to reset at all data being ack'd.
9792 		 */
9793 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9794 			return (1);
9795 	}
9796 	/*
9797 	 * If last ACK falls within this segment's sequence numbers, record
9798 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9799 	 * from the latest proposal of the tcplw@cray.com list (Braden
9800 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9801 	 * with our earlier PAWS tests, so this check should be solely
9802 	 * predicated on the sequence space of this segment. 3) That we
9803 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9804 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9805 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9806 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9807 	 * p.869. In such cases, we can still calculate the RTT correctly
9808 	 * when RCV.NXT == Last.ACK.Sent.
9809 	 */
9810 	if ((to->to_flags & TOF_TS) != 0 &&
9811 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9812 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9813 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9814 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9815 		tp->ts_recent = to->to_tsval;
9816 	}
9817 	/*
9818 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9819 	 * is on (half-synchronized state), then queue data for later
9820 	 * processing; else drop segment and return.
9821 	 */
9822 	if ((thflags & TH_ACK) == 0) {
9823 		if (tp->t_flags & TF_NEEDSYN) {
9824 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9825 			    tiwin, thflags, nxt_pkt));
9826 		} else if (tp->t_flags & TF_ACKNOW) {
9827 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9828 			bbr->r_wanted_output = 1;
9829 			return (ret_val);
9830 		} else {
9831 			ctf_do_drop(m, NULL);
9832 			return (0);
9833 		}
9834 	}
9835 	/*
9836 	 * case TCPS_LAST_ACK: Ack processing.
9837 	 */
9838 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9839 		return (ret_val);
9840 	}
9841 	if (ourfinisacked) {
9842 		tp = tcp_close(tp);
9843 		ctf_do_drop(m, tp);
9844 		return (1);
9845 	}
9846 	if (sbavail(&so->so_snd)) {
9847 		if (ctf_progress_timeout_check(tp, true)) {
9848 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9849 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9850 			return (1);
9851 		}
9852 	}
9853 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9854 	    tiwin, thflags, nxt_pkt));
9855 }
9856 
9857 /*
9858  * Return value of 1, the TCB is unlocked and most
9859  * likely gone, return value of 0, the TCB is still
9860  * locked.
9861  */
9862 static int
9863 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9864     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9865     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9866 {
9867 	int32_t ourfinisacked = 0;
9868 	int32_t ret_val;
9869 	struct tcp_bbr *bbr;
9870 
9871 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9872 	ctf_calc_rwin(so, tp);
9873 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
9874 	if ((thflags & TH_RST) ||
9875 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9876 		return (ctf_process_rst(m, th, so, tp));
9877 
9878 	/*
9879 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9880 	 * synchronized state.
9881 	 */
9882 	if (thflags & TH_SYN) {
9883 		ctf_challenge_ack(m, th, tp, &ret_val);
9884 		return (ret_val);
9885 	}
9886 	INP_WLOCK_ASSERT(tp->t_inpcb);
9887 	/*
9888 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9889 	 * it's less than ts_recent, drop it.
9890 	 */
9891 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9892 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9893 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9894 			return (ret_val);
9895 	}
9896 	INP_WLOCK_ASSERT(tp->t_inpcb);
9897 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9898 		return (ret_val);
9899 	}
9900 	/*
9901 	 * If new data are received on a connection after the user processes
9902 	 * are gone, then we may RST the other end depending on the outcome
9903 	 * of bbr_check_data_after_close.
9904 	 */
9905 	if ((so->so_state & SS_NOFDREF) &&
9906 	    tlen) {
9907 		/*
9908 		 * We call a new function now so we might continue and setup
9909 		 * to reset at all data being ack'd.
9910 		 */
9911 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9912 			return (1);
9913 	}
9914 	INP_WLOCK_ASSERT(tp->t_inpcb);
9915 	/*
9916 	 * If last ACK falls within this segment's sequence numbers, record
9917 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9918 	 * from the latest proposal of the tcplw@cray.com list (Braden
9919 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9920 	 * with our earlier PAWS tests, so this check should be solely
9921 	 * predicated on the sequence space of this segment. 3) That we
9922 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9923 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9924 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9925 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9926 	 * p.869. In such cases, we can still calculate the RTT correctly
9927 	 * when RCV.NXT == Last.ACK.Sent.
9928 	 */
9929 	INP_WLOCK_ASSERT(tp->t_inpcb);
9930 	if ((to->to_flags & TOF_TS) != 0 &&
9931 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9932 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9933 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9934 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9935 		tp->ts_recent = to->to_tsval;
9936 	}
9937 	/*
9938 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9939 	 * is on (half-synchronized state), then queue data for later
9940 	 * processing; else drop segment and return.
9941 	 */
9942 	if ((thflags & TH_ACK) == 0) {
9943 		if (tp->t_flags & TF_NEEDSYN) {
9944 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9945 			    tiwin, thflags, nxt_pkt));
9946 		} else if (tp->t_flags & TF_ACKNOW) {
9947 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9948 			bbr->r_wanted_output = 1;
9949 			return (ret_val);
9950 		} else {
9951 			ctf_do_drop(m, NULL);
9952 			return (0);
9953 		}
9954 	}
9955 	/*
9956 	 * Ack processing.
9957 	 */
9958 	INP_WLOCK_ASSERT(tp->t_inpcb);
9959 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9960 		return (ret_val);
9961 	}
9962 	if (sbavail(&so->so_snd)) {
9963 		if (ctf_progress_timeout_check(tp, true)) {
9964 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9965 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9966 			return (1);
9967 		}
9968 	}
9969 	INP_WLOCK_ASSERT(tp->t_inpcb);
9970 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9971 	    tiwin, thflags, nxt_pkt));
9972 }
9973 
9974 static void
9975 bbr_stop_all_timers(struct tcpcb *tp)
9976 {
9977 	struct tcp_bbr *bbr;
9978 
9979 	/*
9980 	 * Assure no timers are running.
9981 	 */
9982 	if (tcp_timer_active(tp, TT_PERSIST)) {
9983 		/* We enter in persists, set the flag appropriately */
9984 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9985 		bbr->rc_in_persist = 1;
9986 	}
9987 	tcp_timer_suspend(tp, TT_PERSIST);
9988 	tcp_timer_suspend(tp, TT_REXMT);
9989 	tcp_timer_suspend(tp, TT_KEEP);
9990 	tcp_timer_suspend(tp, TT_DELACK);
9991 }
9992 
9993 static void
9994 bbr_google_mode_on(struct tcp_bbr *bbr)
9995 {
9996 	bbr->rc_use_google = 1;
9997 	bbr->rc_no_pacing = 0;
9998 	bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9999 	bbr->r_use_policer = bbr_policer_detection_enabled;
10000 	bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10001 	bbr->bbr_use_rack_cheat = 0;
10002 	bbr->r_ctl.rc_incr_tmrs = 0;
10003 	bbr->r_ctl.rc_inc_tcp_oh = 0;
10004 	bbr->r_ctl.rc_inc_ip_oh = 0;
10005 	bbr->r_ctl.rc_inc_enet_oh = 0;
10006 	reset_time(&bbr->r_ctl.rc_delrate,
10007 		   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10008 	reset_time_small(&bbr->r_ctl.rc_rttprop,
10009 			 (11 * USECS_IN_SECOND));
10010 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
10011 }
10012 
10013 static void
10014 bbr_google_mode_off(struct tcp_bbr *bbr)
10015 {
10016 	bbr->rc_use_google = 0;
10017 	bbr->r_ctl.bbr_google_discount = 0;
10018 	bbr->no_pacing_until = bbr_no_pacing_until;
10019 	bbr->r_use_policer = 0;
10020 	if (bbr->no_pacing_until)
10021 		bbr->rc_no_pacing = 1;
10022 	else
10023 		bbr->rc_no_pacing = 0;
10024 	if (bbr_use_rack_resend_cheat)
10025 		bbr->bbr_use_rack_cheat = 1;
10026 	else
10027 		bbr->bbr_use_rack_cheat = 0;
10028 	if (bbr_incr_timers)
10029 		bbr->r_ctl.rc_incr_tmrs = 1;
10030 	else
10031 		bbr->r_ctl.rc_incr_tmrs = 0;
10032 	if (bbr_include_tcp_oh)
10033 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10034 	else
10035 		bbr->r_ctl.rc_inc_tcp_oh = 0;
10036 	if (bbr_include_ip_oh)
10037 		bbr->r_ctl.rc_inc_ip_oh = 1;
10038 	else
10039 		bbr->r_ctl.rc_inc_ip_oh = 0;
10040 	if (bbr_include_enet_oh)
10041 		bbr->r_ctl.rc_inc_enet_oh = 1;
10042 	else
10043 		bbr->r_ctl.rc_inc_enet_oh = 0;
10044 	bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10045 	reset_time(&bbr->r_ctl.rc_delrate,
10046 		   bbr_num_pktepo_for_del_limit);
10047 	reset_time_small(&bbr->r_ctl.rc_rttprop,
10048 			 (bbr_filter_len_sec * USECS_IN_SECOND));
10049 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
10050 }
10051 /*
10052  * Return 0 on success, non-zero on failure
10053  * which indicates the error (usually no memory).
10054  */
10055 static int
10056 bbr_init(struct tcpcb *tp)
10057 {
10058 	struct tcp_bbr *bbr = NULL;
10059 	struct inpcb *inp;
10060 	uint32_t cts;
10061 
10062 	tp->t_fb_ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
10063 	if (tp->t_fb_ptr == NULL) {
10064 		/*
10065 		 * We need to allocate memory but cant. The INP and INP_INFO
10066 		 * locks and they are recusive (happens during setup. So a
10067 		 * scheme to drop the locks fails :(
10068 		 *
10069 		 */
10070 		return (ENOMEM);
10071 	}
10072 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10073 	bbr->rtt_valid = 0;
10074 	inp = tp->t_inpcb;
10075 	inp->inp_flags2 |= INP_CANNOT_DO_ECN;
10076 	inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
10077 	TAILQ_INIT(&bbr->r_ctl.rc_map);
10078 	TAILQ_INIT(&bbr->r_ctl.rc_free);
10079 	TAILQ_INIT(&bbr->r_ctl.rc_tmap);
10080 	bbr->rc_tp = tp;
10081 	if (tp->t_inpcb) {
10082 		bbr->rc_inp = tp->t_inpcb;
10083 	}
10084 	cts = tcp_get_usecs(&bbr->rc_tv);
10085 	tp->t_acktime = 0;
10086 	bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
10087 	bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
10088 	bbr->rc_tlp_threshold = bbr_tlp_thresh;
10089 	bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
10090 	bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
10091 	bbr->r_ctl.rc_min_to = bbr_min_to;
10092 	bbr->rc_bbr_state = BBR_STATE_STARTUP;
10093 	bbr->r_ctl.bbr_lost_at_state = 0;
10094 	bbr->r_ctl.rc_lost_at_startup = 0;
10095 	bbr->rc_all_timers_stopped = 0;
10096 	bbr->r_ctl.rc_bbr_lastbtlbw = 0;
10097 	bbr->r_ctl.rc_pkt_epoch_del = 0;
10098 	bbr->r_ctl.rc_pkt_epoch = 0;
10099 	bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
10100 	bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
10101 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
10102 	bbr->r_ctl.rc_went_idle_time = cts;
10103 	bbr->rc_pacer_started = cts;
10104 	bbr->r_ctl.rc_pkt_epoch_time = cts;
10105 	bbr->r_ctl.rc_rcvtime = cts;
10106 	bbr->r_ctl.rc_bbr_state_time = cts;
10107 	bbr->r_ctl.rc_del_time = cts;
10108 	bbr->r_ctl.rc_tlp_rxt_last_time = cts;
10109 	bbr->r_ctl.last_in_probertt = cts;
10110 	bbr->skip_gain = 0;
10111 	bbr->gain_is_limited = 0;
10112 	bbr->no_pacing_until = bbr_no_pacing_until;
10113 	if (bbr->no_pacing_until)
10114 		bbr->rc_no_pacing = 1;
10115 	if (bbr_use_google_algo) {
10116 		bbr->rc_no_pacing = 0;
10117 		bbr->rc_use_google = 1;
10118 		bbr->r_ctl.bbr_google_discount = bbr_google_discount;
10119 		bbr->r_use_policer = bbr_policer_detection_enabled;
10120 	} else {
10121 		bbr->rc_use_google = 0;
10122 		bbr->r_ctl.bbr_google_discount = 0;
10123 		bbr->r_use_policer = 0;
10124 	}
10125 	if (bbr_ts_limiting)
10126 		bbr->rc_use_ts_limit = 1;
10127 	else
10128 		bbr->rc_use_ts_limit = 0;
10129 	if (bbr_ts_can_raise)
10130 		bbr->ts_can_raise = 1;
10131 	else
10132 		bbr->ts_can_raise = 0;
10133 	if (V_tcp_delack_enabled == 1)
10134 		tp->t_delayed_ack = 2;
10135 	else if (V_tcp_delack_enabled == 0)
10136 		tp->t_delayed_ack = 0;
10137 	else if (V_tcp_delack_enabled < 100)
10138 		tp->t_delayed_ack = V_tcp_delack_enabled;
10139 	else
10140 		tp->t_delayed_ack = 2;
10141 	if (bbr->rc_use_google == 0)
10142 		bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10143 	else
10144 		bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10145 	bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10146 	bbr->rc_max_rto_sec = bbr_rto_max_sec;
10147 	bbr->rc_init_win = bbr_def_init_win;
10148 	if (tp->t_flags & TF_REQ_TSTMP)
10149 		bbr->rc_last_options = TCP_TS_OVERHEAD;
10150 	bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10151 	bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10152 	bbr->r_init_rtt = 1;
10153 
10154 	counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10155 	if (bbr_allow_hdwr_pacing)
10156 		bbr->bbr_hdw_pace_ena = 1;
10157 	else
10158 		bbr->bbr_hdw_pace_ena = 0;
10159 	if (bbr_sends_full_iwnd)
10160 		bbr->bbr_init_win_cheat = 1;
10161 	else
10162 		bbr->bbr_init_win_cheat = 0;
10163 	bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10164 	bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10165 	bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10166 	bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10167 	bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10168 	bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10169 	bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10170 	bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10171 	bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10172 	bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10173 	bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10174 	bbr->r_ctl.rc_rtt_shrinks = cts;
10175 	if (bbr->rc_use_google) {
10176 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10177 				  FILTER_TYPE_MAX,
10178 				  BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10179 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10180 					FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10181 	} else {
10182 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10183 				  FILTER_TYPE_MAX,
10184 				  bbr_num_pktepo_for_del_limit);
10185 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10186 					FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10187 	}
10188 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10189 	if (bbr_uses_idle_restart)
10190 		bbr->rc_use_idle_restart = 1;
10191 	else
10192 		bbr->rc_use_idle_restart = 0;
10193 	bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10194 	bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10195 	if (bbr_resends_use_tso)
10196 		bbr->rc_resends_use_tso = 1;
10197 #ifdef NETFLIX_PEAKRATE
10198 	tp->t_peakrate_thr = tp->t_maxpeakrate;
10199 #endif
10200 	if (tp->snd_una != tp->snd_max) {
10201 		/* Create a send map for the current outstanding data */
10202 		struct bbr_sendmap *rsm;
10203 
10204 		rsm = bbr_alloc(bbr);
10205 		if (rsm == NULL) {
10206 			uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10207 			tp->t_fb_ptr = NULL;
10208 			return (ENOMEM);
10209 		}
10210 		rsm->r_flags = BBR_OVERMAX;
10211 		rsm->r_tim_lastsent[0] = cts;
10212 		rsm->r_rtr_cnt = 1;
10213 		rsm->r_rtr_bytes = 0;
10214 		rsm->r_start = tp->snd_una;
10215 		rsm->r_end = tp->snd_max;
10216 		rsm->r_dupack = 0;
10217 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
10218 		rsm->r_ts_valid = 0;
10219 		rsm->r_del_ack_ts = tp->ts_recent;
10220 		rsm->r_del_time = cts;
10221 		if (bbr->r_ctl.r_app_limited_until)
10222 			rsm->r_app_limited = 1;
10223 		else
10224 			rsm->r_app_limited = 0;
10225 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10226 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10227 		rsm->r_in_tmap = 1;
10228 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10229 			rsm->r_bbr_state = bbr_state_val(bbr);
10230 		else
10231 			rsm->r_bbr_state = 8;
10232 	}
10233 	if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10234 		bbr->bbr_use_rack_cheat = 1;
10235 	if (bbr_incr_timers && (bbr->rc_use_google == 0))
10236 		bbr->r_ctl.rc_incr_tmrs = 1;
10237 	if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10238 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10239 	if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10240 		bbr->r_ctl.rc_inc_ip_oh = 1;
10241 	if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10242 		bbr->r_ctl.rc_inc_enet_oh = 1;
10243 
10244 	bbr_log_type_statechange(bbr, cts, __LINE__);
10245 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10246 	    (tp->t_srtt)) {
10247 		uint32_t rtt;
10248 
10249 		rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10250 		apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10251 	}
10252 	/* announce the settings and state */
10253 	bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10254 	tcp_bbr_tso_size_check(bbr, cts);
10255 	/*
10256 	 * Now call the generic function to start a timer. This will place
10257 	 * the TCB on the hptsi wheel if a timer is needed with appropriate
10258 	 * flags.
10259 	 */
10260 	bbr_stop_all_timers(tp);
10261 	bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10262 	return (0);
10263 }
10264 
10265 /*
10266  * Return 0 if we can accept the connection. Return
10267  * non-zero if we can't handle the connection. A EAGAIN
10268  * means you need to wait until the connection is up.
10269  * a EADDRNOTAVAIL means we can never handle the connection
10270  * (no SACK).
10271  */
10272 static int
10273 bbr_handoff_ok(struct tcpcb *tp)
10274 {
10275 	if ((tp->t_state == TCPS_CLOSED) ||
10276 	    (tp->t_state == TCPS_LISTEN)) {
10277 		/* Sure no problem though it may not stick */
10278 		return (0);
10279 	}
10280 	if ((tp->t_state == TCPS_SYN_SENT) ||
10281 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
10282 		/*
10283 		 * We really don't know you have to get to ESTAB or beyond
10284 		 * to tell.
10285 		 */
10286 		return (EAGAIN);
10287 	}
10288 	if (tp->t_flags & TF_SENTFIN)
10289 		return (EINVAL);
10290 	if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10291 		return (0);
10292 	}
10293 	/*
10294 	 * If we reach here we don't do SACK on this connection so we can
10295 	 * never do rack.
10296 	 */
10297 	return (EINVAL);
10298 }
10299 
10300 static void
10301 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10302 {
10303 	if (tp->t_fb_ptr) {
10304 		uint32_t calc;
10305 		struct tcp_bbr *bbr;
10306 		struct bbr_sendmap *rsm;
10307 
10308 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10309 		if (bbr->r_ctl.crte)
10310 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10311 		bbr_log_flowend(bbr);
10312 		bbr->rc_tp = NULL;
10313 		if (tp->t_inpcb) {
10314 			/* Backout any flags2 we applied */
10315 			tp->t_inpcb->inp_flags2 &= ~INP_CANNOT_DO_ECN;
10316 			tp->t_inpcb->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
10317 			tp->t_inpcb->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
10318 		}
10319 		if (bbr->bbr_hdrw_pacing)
10320 			counter_u64_add(bbr_flows_whdwr_pacing, -1);
10321 		else
10322 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10323 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10324 		while (rsm) {
10325 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10326 			uma_zfree(bbr_zone, rsm);
10327 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10328 		}
10329 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10330 		while (rsm) {
10331 			TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10332 			uma_zfree(bbr_zone, rsm);
10333 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10334 		}
10335 		calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10336 		if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10337 			BBR_STAT_INC(bbr_dynamic_rwnd);
10338 		else
10339 			BBR_STAT_INC(bbr_static_rwnd);
10340 		bbr->r_ctl.rc_free_cnt = 0;
10341 		uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10342 		tp->t_fb_ptr = NULL;
10343 	}
10344 	/* Make sure snd_nxt is correctly set */
10345 	tp->snd_nxt = tp->snd_max;
10346 }
10347 
10348 static void
10349 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10350 {
10351 	switch (tp->t_state) {
10352 	case TCPS_SYN_SENT:
10353 		bbr->r_state = TCPS_SYN_SENT;
10354 		bbr->r_substate = bbr_do_syn_sent;
10355 		break;
10356 	case TCPS_SYN_RECEIVED:
10357 		bbr->r_state = TCPS_SYN_RECEIVED;
10358 		bbr->r_substate = bbr_do_syn_recv;
10359 		break;
10360 	case TCPS_ESTABLISHED:
10361 		bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10362 		bbr->r_state = TCPS_ESTABLISHED;
10363 		bbr->r_substate = bbr_do_established;
10364 		break;
10365 	case TCPS_CLOSE_WAIT:
10366 		bbr->r_state = TCPS_CLOSE_WAIT;
10367 		bbr->r_substate = bbr_do_close_wait;
10368 		break;
10369 	case TCPS_FIN_WAIT_1:
10370 		bbr->r_state = TCPS_FIN_WAIT_1;
10371 		bbr->r_substate = bbr_do_fin_wait_1;
10372 		break;
10373 	case TCPS_CLOSING:
10374 		bbr->r_state = TCPS_CLOSING;
10375 		bbr->r_substate = bbr_do_closing;
10376 		break;
10377 	case TCPS_LAST_ACK:
10378 		bbr->r_state = TCPS_LAST_ACK;
10379 		bbr->r_substate = bbr_do_lastack;
10380 		break;
10381 	case TCPS_FIN_WAIT_2:
10382 		bbr->r_state = TCPS_FIN_WAIT_2;
10383 		bbr->r_substate = bbr_do_fin_wait_2;
10384 		break;
10385 	case TCPS_LISTEN:
10386 	case TCPS_CLOSED:
10387 	case TCPS_TIME_WAIT:
10388 	default:
10389 		break;
10390 	};
10391 }
10392 
10393 static void
10394 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10395 {
10396 	/*
10397 	 * Now what state are we going into now? Is there adjustments
10398 	 * needed?
10399 	 */
10400 	int32_t old_state, old_gain;
10401 
10402 	old_state = bbr_state_val(bbr);
10403 	old_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
10404 	if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10405 		/* Save the lowest srtt we saw in our end of the sub-state */
10406 		bbr->rc_hit_state_1 = 0;
10407 		if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10408 			bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10409 	}
10410 	bbr->rc_bbr_substate++;
10411 	if (bbr->rc_bbr_substate >= BBR_SUBSTATE_COUNT) {
10412 		/* Cycle back to first state-> gain */
10413 		bbr->rc_bbr_substate = 0;
10414 	}
10415 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10416 		/*
10417 		 * We enter the gain(5/4) cycle (possibly less if
10418 		 * shallow buffer detection is enabled)
10419 		 */
10420 		if (bbr->skip_gain) {
10421 			/*
10422 			 * Hardware pacing has set our rate to
10423 			 * the max and limited our b/w just
10424 			 * do level i.e. no gain.
10425 			 */
10426 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10427 		} else if (bbr->gain_is_limited &&
10428 			   bbr->bbr_hdrw_pacing &&
10429 			   bbr->r_ctl.crte) {
10430 			/*
10431 			 * We can't gain above the hardware pacing
10432 			 * rate which is less than our rate + the gain
10433 			 * calculate the gain needed to reach the hardware
10434 			 * pacing rate..
10435 			 */
10436 			uint64_t bw, rate, gain_calc;
10437 
10438 			bw = bbr_get_bw(bbr);
10439 			rate = bbr->r_ctl.crte->rate;
10440 			if ((rate > bw) &&
10441 			    (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10442 				gain_calc = (rate * BBR_UNIT) / bw;
10443 				if (gain_calc < BBR_UNIT)
10444 					gain_calc = BBR_UNIT;
10445 				bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10446 			} else {
10447 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10448 			}
10449 		} else
10450 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10451 		if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10452 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10453 		} else
10454 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10455 	} else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10456 		bbr->rc_hit_state_1 = 1;
10457 		bbr->r_ctl.rc_exta_time_gd = 0;
10458 		bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10459 						     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10460 		if (bbr_state_drain_2_tar) {
10461 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10462 		} else
10463 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10464 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10465 	} else {
10466 		/* All other cycles hit here 2-7 */
10467 		if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10468 			if (bbr_sub_drain_slam_cwnd &&
10469 			    (bbr->rc_use_google == 0) &&
10470 			    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10471 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10472 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10473 			}
10474 			if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10475 				bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10476 							       bbr_get_rtt(bbr, BBR_RTT_PROP));
10477 			else
10478 				bbr->r_ctl.rc_exta_time_gd = 0;
10479 			if (bbr->r_ctl.rc_exta_time_gd) {
10480 				bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10481 				/* Now chop up the time for each state (div by 7) */
10482 				bbr->r_ctl.rc_level_state_extra /= 7;
10483 				if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10484 					/* Add a randomization */
10485 					bbr_randomize_extra_state_time(bbr);
10486 				}
10487 			}
10488 		}
10489 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10490 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10491 	}
10492 	if (bbr->rc_use_google) {
10493 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10494 	}
10495 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10496 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10497 	if (dolog)
10498 		bbr_log_type_statechange(bbr, cts, line);
10499 
10500 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10501 		uint32_t time_in;
10502 
10503 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10504 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10505 			counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10506 		} else {
10507 			counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10508 		}
10509 	}
10510 	bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10511 	bbr_set_state_target(bbr, __LINE__);
10512 	if (bbr_sub_drain_slam_cwnd &&
10513 	    (bbr->rc_use_google == 0) &&
10514 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10515 		/* Slam down the cwnd */
10516 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10517 		bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10518 		if (bbr_sub_drain_app_limit) {
10519 			/* Go app limited if we are on a long drain */
10520 			bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10521 							  ctf_flight_size(bbr->rc_tp,
10522 							      (bbr->r_ctl.rc_sacked +
10523 							       bbr->r_ctl.rc_lost_bytes)));
10524 		}
10525 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10526 	}
10527 	if (bbr->rc_lt_use_bw) {
10528 		/* In policed mode we clamp pacing_gain to BBR_UNIT */
10529 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10530 	}
10531 	/* Google changes TSO size every cycle */
10532 	if (bbr->rc_use_google)
10533 		tcp_bbr_tso_size_check(bbr, cts);
10534 	bbr->r_ctl.gain_epoch = cts;
10535 	bbr->r_ctl.rc_bbr_state_time = cts;
10536 	bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10537 }
10538 
10539 static void
10540 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10541 {
10542 	if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10543 	    (google_allow_early_out == 1) &&
10544 	    (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10545 		/* We have reached out target flight size possibly early */
10546 		goto change_state;
10547 	}
10548 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10549 		return;
10550 	}
10551 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10552 		/*
10553 		 * Must be a rttProp movement forward before
10554 		 * we can change states.
10555 		 */
10556 		return;
10557 	}
10558 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10559 		/*
10560 		 * The needed time has passed but for
10561 		 * the gain cycle extra rules apply:
10562 		 * 1) If we have seen loss, we exit
10563 		 * 2) If we have not reached the target
10564 		 *    we stay in GAIN (gain-to-target).
10565 		 */
10566 		if (google_consider_lost && losses)
10567 			goto change_state;
10568 		if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10569 			return;
10570 		}
10571 	}
10572 change_state:
10573 	/* For gain we must reach our target, all others last 1 rttProp */
10574 	bbr_substate_change(bbr, cts, __LINE__, 1);
10575 }
10576 
10577 static void
10578 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10579 {
10580 	uint32_t flight, bbr_cur_cycle_time;
10581 
10582 	if (bbr->rc_use_google) {
10583 		bbr_set_probebw_google_gains(bbr, cts, losses);
10584 		return;
10585 	}
10586 	if (cts == 0) {
10587 		/*
10588 		 * Never alow cts to be 0 we
10589 		 * do this so we can judge if
10590 		 * we have set a timestamp.
10591 		 */
10592 		cts = 1;
10593 	}
10594 	if (bbr_state_is_pkt_epoch)
10595 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10596 	else
10597 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10598 
10599 	if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10600 		if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10601 			flight = ctf_flight_size(bbr->rc_tp,
10602 				     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10603 			if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10604 				/* Keep it slam down */
10605 				if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10606 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10607 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10608 				}
10609 				if (bbr_sub_drain_app_limit) {
10610 					/* Go app limited if we are on a long drain */
10611 					bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10612 				}
10613 			}
10614 			if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10615 			    (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10616 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
10617 				/*
10618 				 * Still here after the same time as
10619 				 * the gain. We need to drain harder
10620 				 * for the next srtt. Reduce by a set amount
10621 				 * the gain drop is capped at DRAIN states
10622 				 * value (88).
10623 				 */
10624 				bbr->r_ctl.flightsize_at_drain = flight;
10625 				if (bbr_drain_drop_mul &&
10626 				    bbr_drain_drop_div &&
10627 				    (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10628 					/* Use your specific drop value (def 4/5 = 20%) */
10629 					bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10630 					bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10631 				} else {
10632 					/* You get drop of 20% */
10633 					bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10634 					bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10635 				}
10636 				if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10637 					/* Reduce our gain again to the bottom  */
10638 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10639 				}
10640 				bbr_log_exit_gain(bbr, cts, 4);
10641 				/*
10642 				 * Extend out so we wait another
10643 				 * epoch before dropping again.
10644 				 */
10645 				bbr->r_ctl.gain_epoch = cts;
10646 			}
10647 			if (flight <= bbr->r_ctl.rc_target_at_state) {
10648 				if (bbr_sub_drain_slam_cwnd &&
10649 				    (bbr->rc_use_google == 0) &&
10650 				    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10651 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10652 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10653 				}
10654 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10655 				bbr_log_exit_gain(bbr, cts, 3);
10656 			}
10657 		} else {
10658 			/* Its a gain  */
10659 			if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10660 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10661 				goto change_state;
10662 			}
10663 			if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10664 			    ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10665 			     bbr->rc_tp->snd_wnd)) {
10666 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10667 				bbr_log_exit_gain(bbr, cts, 2);
10668 			}
10669 		}
10670 		/**
10671 		 * We fall through and return always one of two things has
10672 		 * occurred.
10673 		 * 1) We are still not at target
10674 		 *    <or>
10675 		 * 2) We reached the target and set rc_bbr_state_atflight
10676 		 *    which means we no longer hit this block
10677 		 *    next time we are called.
10678 		 */
10679 		return;
10680 	}
10681 change_state:
10682 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10683 		return;
10684 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10685 		/* Less than a full time-period has passed */
10686 		return;
10687 	}
10688 	if (bbr->r_ctl.rc_level_state_extra &&
10689 	    (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10690 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10691 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10692 		/* Less than a full time-period + extra has passed */
10693 		return;
10694 	}
10695 	if (bbr_gain_gets_extra_too &&
10696 	    bbr->r_ctl.rc_level_state_extra &&
10697 	    (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10698 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10699 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10700 		/* Less than a full time-period + extra has passed */
10701 		return;
10702 	}
10703 	bbr_substate_change(bbr, cts, __LINE__, 1);
10704 }
10705 
10706 static uint32_t
10707 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10708 {
10709 	uint32_t mss, tar;
10710 
10711 	if (bbr->rc_use_google) {
10712 		/* Google just uses the cwnd target */
10713 		tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10714 	} else {
10715 		mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10716 			  bbr->r_ctl.rc_pace_max_segs);
10717 		/* Get the base cwnd with gain rounded to a mss */
10718 		tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10719 						      gain), mss);
10720 		/* Make sure it is within our min */
10721 		if (tar < get_min_cwnd(bbr))
10722 			return (get_min_cwnd(bbr));
10723 	}
10724 	return (tar);
10725 }
10726 
10727 static void
10728 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10729 {
10730 	uint32_t tar, meth;
10731 
10732 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10733 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10734 		/* Special case using old probe-rtt method */
10735 		tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10736 		meth = 1;
10737 	} else {
10738 		/* Non-probe-rtt case and reduced probe-rtt  */
10739 		if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10740 		    (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10741 			/* For gain cycle we use the hptsi gain */
10742 			tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10743 			meth = 2;
10744 		} else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10745 			/*
10746 			 * If configured, or for google all other states
10747 			 * get BBR_UNIT.
10748 			 */
10749 			tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10750 			meth = 3;
10751 		} else {
10752 			/*
10753 			 * Or we set a target based on the pacing gain
10754 			 * for non-google mode and default (non-configured).
10755 			 * Note we don't set a target goal below drain (192).
10756 			 */
10757 			if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10758 				tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10759 				meth = 4;
10760 			} else {
10761 				tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10762 				meth = 5;
10763 			}
10764 		}
10765 	}
10766 	bbr_log_set_of_state_target(bbr, tar, line, meth);
10767 	bbr->r_ctl.rc_target_at_state = tar;
10768 }
10769 
10770 static void
10771 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10772 {
10773 	/* Change to probe_rtt */
10774 	uint32_t time_in;
10775 
10776 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10777 	bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10778 					     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10779 	bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10780 					  + bbr->r_ctl.rc_delivered);
10781 	/* Setup so we force feed the filter */
10782 	if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10783 		bbr->rc_prtt_set_ts = 1;
10784 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10785 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10786 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10787 	}
10788 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10789 	bbr->r_ctl.rc_rtt_shrinks = cts;
10790 	bbr->r_ctl.last_in_probertt = cts;
10791 	bbr->r_ctl.rc_probertt_srttchktim = cts;
10792 	bbr->r_ctl.rc_bbr_state_time = cts;
10793 	bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10794 	/* We need to force the filter to update */
10795 
10796 	if ((bbr_sub_drain_slam_cwnd) &&
10797 	    bbr->rc_hit_state_1 &&
10798 	    (bbr->rc_use_google == 0) &&
10799 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10800 		if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10801 			bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10802 	} else
10803 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10804 	/* Update the lost */
10805 	bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10806 	if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10807 		/* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10808 		bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10809 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10810 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10811 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10812 		bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10813 		bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10814 	} else {
10815 		/*
10816 		 * We bring it down slowly by using a hptsi gain that is
10817 		 * probably 75%. This will slowly float down our outstanding
10818 		 * without tampering with the cwnd.
10819 		 */
10820 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10821 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10822 		bbr_set_state_target(bbr, __LINE__);
10823 		if (bbr_prtt_slam_cwnd &&
10824 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10825 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10826 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10827 		}
10828 	}
10829 	if (ctf_flight_size(bbr->rc_tp,
10830 		(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10831 	    bbr->r_ctl.rc_target_at_state) {
10832 		/* We are at target */
10833 		bbr->r_ctl.rc_bbr_enters_probertt = cts;
10834 	} else {
10835 		/* We need to come down to reach target before our time begins */
10836 		bbr->r_ctl.rc_bbr_enters_probertt = 0;
10837 	}
10838 	bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10839 	BBR_STAT_INC(bbr_enter_probertt);
10840 	bbr_log_exit_gain(bbr, cts, 0);
10841 	bbr_log_type_statechange(bbr, cts, line);
10842 }
10843 
10844 static void
10845 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10846 {
10847 	/*
10848 	 * Sanity check on probe-rtt intervals.
10849 	 * In crazy situations where we are competing
10850 	 * against new-reno flows with huge buffers
10851 	 * our rtt-prop interval could come to dominate
10852 	 * things if we can't get through a full set
10853 	 * of cycles, we need to adjust it.
10854 	 */
10855 	if (bbr_can_adjust_probertt &&
10856 	    (bbr->rc_use_google == 0)) {
10857 		uint16_t val = 0;
10858 		uint32_t cur_rttp, fval, newval, baseval;
10859 
10860 		/* Are we to small and go into probe-rtt to often? */
10861 		baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10862 		cur_rttp = roundup(baseval, USECS_IN_SECOND);
10863 		fval = bbr_filter_len_sec * USECS_IN_SECOND;
10864 		if (bbr_is_ratio == 0) {
10865 			if (fval > bbr_rtt_probe_limit)
10866 				newval = cur_rttp + (fval - bbr_rtt_probe_limit);
10867 			else
10868 				newval = cur_rttp;
10869 		} else {
10870 			int mul;
10871 
10872 			mul = fval / bbr_rtt_probe_limit;
10873 			newval = cur_rttp * mul;
10874 		}
10875 		if (cur_rttp > 	bbr->r_ctl.rc_probertt_int) {
10876 			bbr->r_ctl.rc_probertt_int = cur_rttp;
10877 			reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10878 			val = 1;
10879 		} else {
10880 			/*
10881 			 * No adjustments were made
10882 			 * do we need to shrink it?
10883 			 */
10884 			if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
10885 				if (cur_rttp <= bbr_rtt_probe_limit) {
10886 					/*
10887 					 * Things have calmed down lets
10888 					 * shrink all the way to default
10889 					 */
10890 					bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10891 					reset_time_small(&bbr->r_ctl.rc_rttprop,
10892 							 (bbr_filter_len_sec * USECS_IN_SECOND));
10893 					cur_rttp = bbr_rtt_probe_limit;
10894 					newval = (bbr_filter_len_sec * USECS_IN_SECOND);
10895 					val = 2;
10896 				} else {
10897 					/*
10898 					 * Well does some adjustment make sense?
10899 					 */
10900 					if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
10901 						/* We can reduce interval time some */
10902 						bbr->r_ctl.rc_probertt_int = cur_rttp;
10903 						reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10904 						val = 3;
10905 					}
10906 				}
10907 			}
10908 		}
10909 		if (val)
10910 			bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
10911 	}
10912 }
10913 
10914 static void
10915 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
10916 {
10917 	/* Exit probe-rtt */
10918 
10919 	if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
10920 		tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10921 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10922 	}
10923 	bbr_log_exit_gain(bbr, cts, 1);
10924 	bbr->rc_hit_state_1 = 0;
10925 	bbr->r_ctl.rc_rtt_shrinks = cts;
10926 	bbr->r_ctl.last_in_probertt = cts;
10927 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
10928 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10929 	bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
10930 					      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
10931 					  bbr->r_ctl.rc_delivered);
10932 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10933 		uint32_t time_in;
10934 
10935 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10936 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10937 	}
10938 	if (bbr->rc_filled_pipe) {
10939 		/* Switch to probe_bw */
10940 		bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
10941 		bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
10942 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10943 		bbr_substate_change(bbr, cts, __LINE__, 0);
10944 		bbr_log_type_statechange(bbr, cts, __LINE__);
10945 	} else {
10946 		/* Back to startup */
10947 		bbr->rc_bbr_state = BBR_STATE_STARTUP;
10948 		bbr->r_ctl.rc_bbr_state_time = cts;
10949 		/*
10950 		 * We don't want to give a complete free 3
10951 		 * measurements until we exit, so we use
10952 		 * the number of pe's we were in probe-rtt
10953 		 * to add to the startup_epoch. That way
10954 		 * we will still retain the old state.
10955 		 */
10956 		bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
10957 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10958 		/* Make sure to use the lower pg when shifting back in */
10959 		if (bbr->r_ctl.rc_lost &&
10960 		    bbr_use_lower_gain_in_startup &&
10961 		    (bbr->rc_use_google == 0))
10962 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10963 		else
10964 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
10965 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
10966 		/* Probably not needed but set it anyway */
10967 		bbr_set_state_target(bbr, __LINE__);
10968 		bbr_log_type_statechange(bbr, cts, __LINE__);
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, 0);
10971 	}
10972 	bbr_check_probe_rtt_limits(bbr, cts);
10973 }
10974 
10975 static int32_t inline
10976 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
10977 {
10978 	if ((bbr->rc_past_init_win == 1) &&
10979 	    (bbr->rc_in_persist == 0) &&
10980 	    (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
10981 		return (1);
10982 	}
10983 	if (bbr_can_force_probertt &&
10984 	    (bbr->rc_in_persist == 0) &&
10985 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
10986 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
10987 		return (1);
10988 	}
10989 	return (0);
10990 }
10991 
10992 static int32_t
10993 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
10994 {
10995 	uint64_t btlbw, gain;
10996 	if (pkt_epoch == 0) {
10997 		/*
10998 		 * Need to be on a pkt-epoch to continue.
10999 		 */
11000 		return (0);
11001 	}
11002 	btlbw = bbr_get_full_bw(bbr);
11003 	gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11004 		 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11005 	if (btlbw >= gain) {
11006 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
11007 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11008 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
11009 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
11010 	}
11011 	if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
11012 		return (1);
11013 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11014 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11015 	return(0);
11016 }
11017 
11018 static int32_t inline
11019 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
11020 {
11021 	/* Have we gained 25% in the last 3 packet based epoch's? */
11022 	uint64_t btlbw, gain;
11023 	int do_exit;
11024 	int delta, rtt_gain;
11025 
11026 	if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11027 	    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11028 		/*
11029 		 * This qualifies as a RTT_PROBE session since we drop the
11030 		 * data outstanding to nothing and waited more than
11031 		 * bbr_rtt_probe_time.
11032 		 */
11033 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11034 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
11035 	}
11036 	if (bbr_should_enter_probe_rtt(bbr, cts)) {
11037 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
11038 		return (0);
11039 	}
11040 	if (bbr->rc_use_google)
11041 		return (bbr_google_startup(bbr, cts,  pkt_epoch));
11042 
11043 	if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11044 	    (bbr_use_lower_gain_in_startup)) {
11045 		/* Drop to a lower gain 1.5 x since we saw loss */
11046 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
11047 	}
11048 	if (pkt_epoch == 0) {
11049 		/*
11050 		 * Need to be on a pkt-epoch to continue.
11051 		 */
11052 		return (0);
11053 	}
11054 	if (bbr_rtt_gain_thresh) {
11055 		/*
11056 		 * Do we allow a flow to stay
11057 		 * in startup with no loss and no
11058 		 * gain in rtt over a set threshold?
11059 		 */
11060 		if (bbr->r_ctl.rc_pkt_epoch_rtt &&
11061 		    bbr->r_ctl.startup_last_srtt &&
11062 		    (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
11063 			delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
11064 			rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
11065 		} else
11066 			rtt_gain = 0;
11067 		if ((bbr->r_ctl.startup_last_srtt == 0)  ||
11068 		    (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
11069 			/* First time or new lower value */
11070 			bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
11071 
11072 		if ((bbr->r_ctl.rc_lost == 0) &&
11073 		    (rtt_gain < bbr_rtt_gain_thresh)) {
11074 			/*
11075 			 * No loss, and we are under
11076 			 * our gain threhold for
11077 			 * increasing RTT.
11078 			 */
11079 			if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11080 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
11081 			bbr_log_startup_event(bbr, cts, rtt_gain,
11082 					      delta, bbr->r_ctl.startup_last_srtt, 10);
11083 			return (0);
11084 		}
11085 	}
11086 	if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
11087 	    (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
11088 	    (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
11089 		/*
11090 		 * We only assess if we have a new measurment when
11091 		 * we have no loss and are not in recovery.
11092 		 * Drag up by one our last_startup epoch so we will hold
11093 		 * the number of non-gain we have already accumulated.
11094 		 */
11095 		if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11096 			bbr->r_ctl.rc_bbr_last_startup_epoch++;
11097 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11098 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 9);
11099 		return (0);
11100 	}
11101 	/* Case where we reduced the lost (bad retransmit) */
11102 	if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
11103 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11104 	bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
11105 	btlbw = bbr_get_full_bw(bbr);
11106 	if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
11107 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11108 			 (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11109 	else
11110 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11111 			 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11112 	do_exit = 0;
11113 	if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
11114 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
11115 	if (btlbw >= gain) {
11116 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
11117 		/* Update the lost so we won't exit in next set of tests */
11118 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11119 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11120 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
11121 	}
11122 	if ((bbr->rc_loss_exit &&
11123 	     (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11124 	     (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
11125 	    ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
11126 		/*
11127 		 * If we had no gain,  we had loss and that loss was above
11128 		 * our threshould, the rwnd is not constrained, and we have
11129 		 * had at least 3 packet epochs exit. Note that this is
11130 		 * switched off by sysctl. Google does not do this by the
11131 		 * way.
11132 		 */
11133 		if ((ctf_flight_size(bbr->rc_tp,
11134 			 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11135 		     (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11136 			do_exit = 1;
11137 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11138 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11139 		} else {
11140 			/* Just record an updated loss value */
11141 			bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11142 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11143 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11144 		}
11145 	} else
11146 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11147 	if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11148 	    do_exit) {
11149 		/* Return 1 to exit the startup state. */
11150 		return (1);
11151 	}
11152 	/* Stay in startup */
11153 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11154 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11155 	return (0);
11156 }
11157 
11158 static void
11159 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11160 {
11161 	/*
11162 	 * A tick occurred in the rtt epoch do we need to do anything?
11163 	 */
11164 #ifdef BBR_INVARIANTS
11165 	if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11166 	    (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11167 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11168 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11169 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11170 		/* Debug code? */
11171 		panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11172 	}
11173 #endif
11174 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11175 		/* Do we exit the startup state? */
11176 		if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11177 			uint32_t time_in;
11178 
11179 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11180 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11181 			bbr->rc_filled_pipe = 1;
11182 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11183 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11184 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11185 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11186 			} else
11187 				time_in = 0;
11188 			if (bbr->rc_no_pacing)
11189 				bbr->rc_no_pacing = 0;
11190 			bbr->r_ctl.rc_bbr_state_time = cts;
11191 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11192 			bbr->rc_bbr_state = BBR_STATE_DRAIN;
11193 			bbr_set_state_target(bbr, __LINE__);
11194 			if ((bbr->rc_use_google == 0) &&
11195 			    bbr_slam_cwnd_in_main_drain) {
11196 				/* Here we don't have to worry about probe-rtt */
11197 				bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
11198 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11199 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11200 			}
11201 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11202 			bbr_log_type_statechange(bbr, cts, __LINE__);
11203 			if (ctf_flight_size(bbr->rc_tp,
11204 			        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11205 			    bbr->r_ctl.rc_target_at_state) {
11206 				/*
11207 				 * Switch to probe_bw if we are already
11208 				 * there
11209 				 */
11210 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11211 				bbr_substate_change(bbr, cts, __LINE__, 0);
11212 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11213 				bbr_log_type_statechange(bbr, cts, __LINE__);
11214 			}
11215 		}
11216 	} else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11217 		uint32_t inflight;
11218 		struct tcpcb *tp;
11219 
11220 		tp = bbr->rc_tp;
11221 		inflight = ctf_flight_size(tp,
11222 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11223 		if (inflight >= bbr->r_ctl.rc_target_at_state) {
11224 			/* We have reached a flight of the cwnd target */
11225 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11226 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11227 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11228 			bbr_set_state_target(bbr, __LINE__);
11229 			/*
11230 			 * Rig it so we don't do anything crazy and
11231 			 * start fresh with a new randomization.
11232 			 */
11233 			bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11234 			bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11235 			bbr_substate_change(bbr, cts, __LINE__, 1);
11236 		}
11237 	} else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11238 		/* Has in-flight reached the bdp (or less)? */
11239 		uint32_t inflight;
11240 		struct tcpcb *tp;
11241 
11242 		tp = bbr->rc_tp;
11243 		inflight = ctf_flight_size(tp,
11244 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11245 		if ((bbr->rc_use_google == 0) &&
11246 		    bbr_slam_cwnd_in_main_drain &&
11247 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11248 			/*
11249 			 * Here we don't have to worry about probe-rtt
11250 			 * re-slam it, but keep it slammed down.
11251 			 */
11252 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11253 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11254 		}
11255 		if (inflight <= bbr->r_ctl.rc_target_at_state) {
11256 			/* We have drained */
11257 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11258 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11259 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11260 				uint32_t time_in;
11261 
11262 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11263 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11264 			}
11265 			if ((bbr->rc_use_google == 0) &&
11266 			    bbr_slam_cwnd_in_main_drain &&
11267 			    (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11268 				/* Restore the cwnd */
11269 				tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11270 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11271 			}
11272 			/* Setup probe-rtt has being done now RRS-HERE */
11273 			bbr->r_ctl.rc_rtt_shrinks = cts;
11274 			bbr->r_ctl.last_in_probertt = cts;
11275 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11276 			/* Randomly pick a sub-state */
11277 			bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11278 			bbr_substate_change(bbr, cts, __LINE__, 0);
11279 			bbr_log_type_statechange(bbr, cts, __LINE__);
11280 		}
11281 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11282 		uint32_t flight;
11283 
11284 		flight = ctf_flight_size(bbr->rc_tp,
11285 			     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11286 		bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11287 		if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11288 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11289 			/*
11290 			 * We must keep cwnd at the desired MSS.
11291 			 */
11292 			bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11293 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11294 		} else if ((bbr_prtt_slam_cwnd) &&
11295 			   (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11296 			/* Re-slam it */
11297 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11298 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11299 		}
11300 		if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11301 			/* Has outstanding reached our target? */
11302 			if (flight <= bbr->r_ctl.rc_target_at_state) {
11303 				bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11304 				bbr->r_ctl.rc_bbr_enters_probertt = cts;
11305 				/* If time is exactly 0, be 1usec off */
11306 				if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11307 					bbr->r_ctl.rc_bbr_enters_probertt = 1;
11308 				if (bbr->rc_use_google == 0) {
11309 					/*
11310 					 * Restore any lowering that as occurred to
11311 					 * reach here
11312 					 */
11313 					if (bbr->r_ctl.bbr_rttprobe_gain_val)
11314 						bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11315 					else
11316 						bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11317 				}
11318 			}
11319 			if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11320 			    (bbr->rc_use_google == 0) &&
11321 			    bbr->r_ctl.bbr_rttprobe_gain_val &&
11322 			    (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11323 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
11324 				/*
11325 				 * We have doddled with our current hptsi
11326 				 * gain an srtt and have still not made it
11327 				 * to target, or we have increased our flight.
11328 				 * Lets reduce the gain by xx%
11329 				 * flooring the reduce at DRAIN (based on
11330 				 * mul/div)
11331 				 */
11332 				int red;
11333 
11334 				bbr->r_ctl.flightsize_at_drain = flight;
11335 				bbr->r_ctl.rc_probertt_srttchktim = cts;
11336 				red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11337 				if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11338 					/* Reduce our gain again */
11339 					bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11340 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11341 				} else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11342 					/* one more chance before we give up */
11343 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11344 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11345 				} else {
11346 					/* At the very bottom */
11347 					bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11348 				}
11349 			}
11350 		}
11351 		if (bbr->r_ctl.rc_bbr_enters_probertt &&
11352 		    (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11353 		    ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11354 			/* Time to exit probe RTT normally */
11355 			bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11356 		}
11357 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11358 		if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11359 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11360 			/*
11361 			 * This qualifies as a RTT_PROBE session since we
11362 			 * drop the data outstanding to nothing and waited
11363 			 * more than bbr_rtt_probe_time.
11364 			 */
11365 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11366 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
11367 		}
11368 		if (bbr_should_enter_probe_rtt(bbr, cts)) {
11369 			bbr_enter_probe_rtt(bbr, cts, __LINE__);
11370 		} else {
11371 			bbr_set_probebw_gains(bbr, cts, losses);
11372 		}
11373 	}
11374 }
11375 
11376 static void
11377 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11378 {
11379 	int32_t epoch = 0;
11380 
11381 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11382 		bbr_set_epoch(bbr, cts, line);
11383 		/* At each epoch doe lt bw sampling */
11384 		epoch = 1;
11385 	}
11386 	bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11387 }
11388 
11389 static int
11390 bbr_do_segment_nounlock(struct mbuf *m, struct tcphdr *th, struct socket *so,
11391     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos,
11392     int32_t nxt_pkt, struct timeval *tv)
11393 {
11394 	int32_t thflags, retval;
11395 	uint32_t cts, lcts;
11396 	uint32_t tiwin;
11397 	struct tcpopt to;
11398 	struct tcp_bbr *bbr;
11399 	struct bbr_sendmap *rsm;
11400 	struct timeval ltv;
11401 	int32_t did_out = 0;
11402 	int32_t in_recovery;
11403 	uint16_t nsegs;
11404 	int32_t prev_state;
11405 	uint32_t lost;
11406 
11407 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
11408 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11409 	/* add in our stats */
11410 	kern_prefetch(bbr, &prev_state);
11411 	prev_state = 0;
11412 	thflags = th->th_flags;
11413 	/*
11414 	 * If this is either a state-changing packet or current state isn't
11415 	 * established, we require a write lock on tcbinfo.  Otherwise, we
11416 	 * allow the tcbinfo to be in either alocked or unlocked, as the
11417 	 * caller may have unnecessarily acquired a write lock due to a
11418 	 * race.
11419 	 */
11420 	INP_WLOCK_ASSERT(tp->t_inpcb);
11421 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11422 	    __func__));
11423 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11424 	    __func__));
11425 
11426 	tp->t_rcvtime = ticks;
11427 	/*
11428 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
11429 	 * the scale is zero.
11430 	 */
11431 	tiwin = th->th_win << tp->snd_scale;
11432 #ifdef STATS
11433 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11434 #endif
11435 
11436 	if (m->m_flags & M_TSTMP) {
11437 		/* Prefer the hardware timestamp if present */
11438 		struct timespec ts;
11439 
11440 		mbuf_tstmp2timespec(m, &ts);
11441 		bbr->rc_tv.tv_sec = ts.tv_sec;
11442 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11443 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11444 	} else if (m->m_flags & M_TSTMP_LRO) {
11445 		/* Next the arrival timestamp */
11446 		struct timespec ts;
11447 
11448 		mbuf_tstmp2timespec(m, &ts);
11449 		bbr->rc_tv.tv_sec = ts.tv_sec;
11450 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11451 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11452 	} else {
11453 		/*
11454 		 * Ok just get the current time.
11455 		 */
11456 		bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11457 	}
11458 	/*
11459 	 * Parse options on any incoming segment.
11460 	 */
11461 	tcp_dooptions(&to, (u_char *)(th + 1),
11462 	    (th->th_off << 2) - sizeof(struct tcphdr),
11463 	    (thflags & TH_SYN) ? TO_SYN : 0);
11464 
11465 	/*
11466 	 * If timestamps were negotiated during SYN/ACK and a
11467 	 * segment without a timestamp is received, silently drop
11468 	 * the segment, unless it is a RST segment or missing timestamps are
11469 	 * tolerated.
11470 	 * See section 3.2 of RFC 7323.
11471 	 */
11472 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
11473 	    ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
11474 		retval = 0;
11475 		goto done_with_input;
11476 	}
11477 	/*
11478 	 * If echoed timestamp is later than the current time, fall back to
11479 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
11480 	 * were used when this connection was established.
11481 	 */
11482 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
11483 		to.to_tsecr -= tp->ts_offset;
11484 		if (TSTMP_GT(to.to_tsecr, tcp_tv_to_mssectick(&bbr->rc_tv)))
11485 			to.to_tsecr = 0;
11486 	}
11487 	/*
11488 	 * If its the first time in we need to take care of options and
11489 	 * verify we can do SACK for rack!
11490 	 */
11491 	if (bbr->r_state == 0) {
11492 		/*
11493 		 * Process options only when we get SYN/ACK back. The SYN
11494 		 * case for incoming connections is handled in tcp_syncache.
11495 		 * According to RFC1323 the window field in a SYN (i.e., a
11496 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
11497 		 * this is traditional behavior, may need to be cleaned up.
11498 		 */
11499 		if (bbr->rc_inp == NULL) {
11500 			bbr->rc_inp = tp->t_inpcb;
11501 		}
11502 		/*
11503 		 * We need to init rc_inp here since its not init'd when
11504 		 * bbr_init is called
11505 		 */
11506 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
11507 			if ((to.to_flags & TOF_SCALE) &&
11508 			    (tp->t_flags & TF_REQ_SCALE)) {
11509 				tp->t_flags |= TF_RCVD_SCALE;
11510 				tp->snd_scale = to.to_wscale;
11511 			} else
11512 				tp->t_flags &= ~TF_REQ_SCALE;
11513 			/*
11514 			 * Initial send window.  It will be updated with the
11515 			 * next incoming segment to the scaled value.
11516 			 */
11517 			tp->snd_wnd = th->th_win;
11518 			if ((to.to_flags & TOF_TS) &&
11519 			    (tp->t_flags & TF_REQ_TSTMP)) {
11520 				tp->t_flags |= TF_RCVD_TSTMP;
11521 				tp->ts_recent = to.to_tsval;
11522 				tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
11523 			} else
11524 			    tp->t_flags &= ~TF_REQ_TSTMP;
11525 			if (to.to_flags & TOF_MSS)
11526 				tcp_mss(tp, to.to_mss);
11527 			if ((tp->t_flags & TF_SACK_PERMIT) &&
11528 			    (to.to_flags & TOF_SACKPERM) == 0)
11529 				tp->t_flags &= ~TF_SACK_PERMIT;
11530 			if (IS_FASTOPEN(tp->t_flags)) {
11531 				if (to.to_flags & TOF_FASTOPEN) {
11532 					uint16_t mss;
11533 
11534 					if (to.to_flags & TOF_MSS)
11535 						mss = to.to_mss;
11536 					else
11537 						if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
11538 							mss = TCP6_MSS;
11539 						else
11540 							mss = TCP_MSS;
11541 					tcp_fastopen_update_cache(tp, mss,
11542 					    to.to_tfo_len, to.to_tfo_cookie);
11543 				} else
11544 					tcp_fastopen_disable_path(tp);
11545 			}
11546 		}
11547 		/*
11548 		 * At this point we are at the initial call. Here we decide
11549 		 * if we are doing RACK or not. We do this by seeing if
11550 		 * TF_SACK_PERMIT is set, if not rack is *not* possible and
11551 		 * we switch to the default code.
11552 		 */
11553 		if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
11554 			/* Bail */
11555 			tcp_switch_back_to_default(tp);
11556 			(*tp->t_fb->tfb_tcp_do_segment) (m, th, so, tp, drop_hdrlen,
11557 			    tlen, iptos);
11558 			return (1);
11559 		}
11560 		/* Set the flag */
11561 		bbr->r_is_v6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
11562 		tcp_set_hpts(tp->t_inpcb);
11563 		sack_filter_clear(&bbr->r_ctl.bbr_sf, th->th_ack);
11564 	}
11565 	if (thflags & TH_ACK) {
11566 		/* Track ack types */
11567 		if (to.to_flags & TOF_SACK)
11568 			BBR_STAT_INC(bbr_acks_with_sacks);
11569 		else
11570 			BBR_STAT_INC(bbr_plain_acks);
11571 	}
11572 	/*
11573 	 * This is the one exception case where we set the rack state
11574 	 * always. All other times (timers etc) we must have a rack-state
11575 	 * set (so we assure we have done the checks above for SACK).
11576 	 */
11577 	if (thflags & TH_FIN)
11578 		tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
11579 	if (bbr->r_state != tp->t_state)
11580 		bbr_set_state(tp, bbr, tiwin);
11581 
11582 	if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map)) != NULL)
11583 		kern_prefetch(rsm, &prev_state);
11584 	prev_state = bbr->r_state;
11585 	bbr->rc_ack_was_delayed = 0;
11586 	lost = bbr->r_ctl.rc_lost;
11587 	bbr->rc_is_pkt_epoch_now = 0;
11588 	if (m->m_flags & (M_TSTMP|M_TSTMP_LRO)) {
11589 		/* Get the real time into lcts and figure the real delay */
11590 		lcts = tcp_get_usecs(&ltv);
11591 		if (TSTMP_GT(lcts, cts)) {
11592 			bbr->r_ctl.rc_ack_hdwr_delay = lcts - cts;
11593 			bbr->rc_ack_was_delayed = 1;
11594 			if (TSTMP_GT(bbr->r_ctl.rc_ack_hdwr_delay,
11595 				     bbr->r_ctl.highest_hdwr_delay))
11596 				bbr->r_ctl.highest_hdwr_delay = bbr->r_ctl.rc_ack_hdwr_delay;
11597 		} else {
11598 			bbr->r_ctl.rc_ack_hdwr_delay = 0;
11599 			bbr->rc_ack_was_delayed = 0;
11600 		}
11601 	} else {
11602 		bbr->r_ctl.rc_ack_hdwr_delay = 0;
11603 		bbr->rc_ack_was_delayed = 0;
11604 	}
11605 	bbr_log_ack_event(bbr, th, &to, tlen, nsegs, cts, nxt_pkt, m);
11606 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
11607 		retval = 0;
11608 		m_freem(m);
11609                 goto done_with_input;
11610         }
11611         /*
11612          * If a segment with the ACK-bit set arrives in the SYN-SENT state
11613          * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
11614          */
11615         if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
11616             (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
11617 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11618 		ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11619                 return (1);
11620         }
11621 	in_recovery = IN_RECOVERY(tp->t_flags);
11622 	if (tiwin > bbr->r_ctl.rc_high_rwnd)
11623 		bbr->r_ctl.rc_high_rwnd = tiwin;
11624 #ifdef BBR_INVARIANTS
11625 	if ((tp->t_inpcb->inp_flags & INP_DROPPED) ||
11626 	    (tp->t_inpcb->inp_flags2 & INP_FREED)) {
11627 		panic("tp:%p bbr:%p given a dropped inp:%p",
11628 		    tp, bbr, tp->t_inpcb);
11629 	}
11630 #endif
11631 	bbr->r_ctl.rc_flight_at_input = ctf_flight_size(tp,
11632 					    (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11633 	bbr->rtt_valid = 0;
11634 	if (to.to_flags & TOF_TS) {
11635 		bbr->rc_ts_valid = 1;
11636 		bbr->r_ctl.last_inbound_ts = to.to_tsval;
11637 	} else {
11638 		bbr->rc_ts_valid = 0;
11639 		bbr->r_ctl.last_inbound_ts = 0;
11640 	}
11641 	retval = (*bbr->r_substate) (m, th, so,
11642 	    tp, &to, drop_hdrlen,
11643 	    tlen, tiwin, thflags, nxt_pkt, iptos);
11644 #ifdef BBR_INVARIANTS
11645 	if ((retval == 0) &&
11646 	    (tp->t_inpcb == NULL)) {
11647 		panic("retval:%d tp:%p t_inpcb:NULL state:%d",
11648 		    retval, tp, prev_state);
11649 	}
11650 #endif
11651 	if (nxt_pkt == 0)
11652 		BBR_STAT_INC(bbr_rlock_left_ret0);
11653 	else
11654 		BBR_STAT_INC(bbr_rlock_left_ret1);
11655 	if (retval == 0) {
11656 		/*
11657 		 * If retval is 1 the tcb is unlocked and most likely the tp
11658 		 * is gone.
11659 		 */
11660 		INP_WLOCK_ASSERT(tp->t_inpcb);
11661 		tcp_bbr_xmit_timer_commit(bbr, tp, cts);
11662 		if (bbr->rc_is_pkt_epoch_now)
11663 			bbr_set_pktepoch(bbr, cts, __LINE__);
11664 		bbr_check_bbr_for_state(bbr, cts, __LINE__, (bbr->r_ctl.rc_lost - lost));
11665 		if (nxt_pkt == 0) {
11666 			if (bbr->r_wanted_output != 0) {
11667 				bbr->rc_output_starts_timer = 0;
11668 				did_out = 1;
11669 				(void)tp->t_fb->tfb_tcp_output(tp);
11670 			} else
11671 				bbr_start_hpts_timer(bbr, tp, cts, 6, 0, 0);
11672 		}
11673 		if ((nxt_pkt == 0) &&
11674 		    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
11675 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
11676 		     (tp->t_flags & TF_DELACK) ||
11677 		     ((V_tcp_always_keepalive || bbr->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
11678 		      (tp->t_state <= TCPS_CLOSING)))) {
11679 			/*
11680 			 * We could not send (probably in the hpts but
11681 			 * stopped the timer)?
11682 			 */
11683 			if ((tp->snd_max == tp->snd_una) &&
11684 			    ((tp->t_flags & TF_DELACK) == 0) &&
11685 			    (bbr->rc_inp->inp_in_hpts) &&
11686 			    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11687 				/*
11688 				 * keep alive not needed if we are hptsi
11689 				 * output yet
11690 				 */
11691 				;
11692 			} else {
11693 				if (bbr->rc_inp->inp_in_hpts) {
11694 					tcp_hpts_remove(bbr->rc_inp, HPTS_REMOVE_OUTPUT);
11695 					if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11696 					    (TSTMP_GT(lcts, bbr->rc_pacer_started))) {
11697 						uint32_t del;
11698 
11699 						del = lcts - bbr->rc_pacer_started;
11700 						if (bbr->r_ctl.rc_last_delay_val > del) {
11701 							BBR_STAT_INC(bbr_force_timer_start);
11702 							bbr->r_ctl.rc_last_delay_val -= del;
11703 							bbr->rc_pacer_started = lcts;
11704 						} else {
11705 							/* We are late */
11706 							bbr->r_ctl.rc_last_delay_val = 0;
11707 							BBR_STAT_INC(bbr_force_output);
11708 							(void)tp->t_fb->tfb_tcp_output(tp);
11709 						}
11710 					}
11711 				}
11712 				bbr_start_hpts_timer(bbr, tp, cts, 8, bbr->r_ctl.rc_last_delay_val,
11713 				    0);
11714 			}
11715 		} else if ((bbr->rc_output_starts_timer == 0) && (nxt_pkt == 0)) {
11716 			/* Do we have the correct timer running? */
11717 			bbr_timer_audit(tp, bbr, lcts, &so->so_snd);
11718 		}
11719 		/* Do we have a new state */
11720 		if (bbr->r_state != tp->t_state)
11721 			bbr_set_state(tp, bbr, tiwin);
11722 done_with_input:
11723 		bbr_log_doseg_done(bbr, cts, nxt_pkt, did_out);
11724 		if (did_out)
11725 			bbr->r_wanted_output = 0;
11726 #ifdef BBR_INVARIANTS
11727 		if (tp->t_inpcb == NULL) {
11728 			panic("OP:%d retval:%d tp:%p t_inpcb:NULL state:%d",
11729 			    did_out,
11730 			    retval, tp, prev_state);
11731 		}
11732 #endif
11733 	}
11734 	return (retval);
11735 }
11736 
11737 static void
11738 bbr_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
11739     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
11740 {
11741 	struct timeval tv;
11742 	int retval;
11743 
11744 	/* First lets see if we have old packets */
11745 	if (tp->t_in_pkt) {
11746 		if (ctf_do_queued_segments(so, tp, 1)) {
11747 			m_freem(m);
11748 			return;
11749 		}
11750 	}
11751 	if (m->m_flags & M_TSTMP_LRO) {
11752 		tv.tv_sec = m->m_pkthdr.rcv_tstmp /1000000000;
11753 		tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000)/1000;
11754 	} else {
11755 		/* Should not be should we kassert instead? */
11756 		tcp_get_usecs(&tv);
11757 	}
11758 	retval = bbr_do_segment_nounlock(m, th, so, tp,
11759 					 drop_hdrlen, tlen, iptos, 0, &tv);
11760 	if (retval == 0) {
11761 		tcp_handle_wakeup(tp, so);
11762 		INP_WUNLOCK(tp->t_inpcb);
11763 	}
11764 }
11765 
11766 /*
11767  * Return how much data can be sent without violating the
11768  * cwnd or rwnd.
11769  */
11770 
11771 static inline uint32_t
11772 bbr_what_can_we_send(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t sendwin,
11773     uint32_t avail, int32_t sb_offset, uint32_t cts)
11774 {
11775 	uint32_t len;
11776 
11777 	if (ctf_outstanding(tp) >= tp->snd_wnd) {
11778 		/* We never want to go over our peers rcv-window */
11779 		len = 0;
11780 	} else {
11781 		uint32_t flight;
11782 
11783 		flight = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11784 		if (flight >= sendwin) {
11785 			/*
11786 			 * We have in flight what we are allowed by cwnd (if
11787 			 * it was rwnd blocking it would have hit above out
11788 			 * >= tp->snd_wnd).
11789 			 */
11790 			return (0);
11791 		}
11792 		len = sendwin - flight;
11793 		if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
11794 			/* We would send too much (beyond the rwnd) */
11795 			len = tp->snd_wnd - ctf_outstanding(tp);
11796 		}
11797 		if ((len + sb_offset) > avail) {
11798 			/*
11799 			 * We don't have that much in the SB, how much is
11800 			 * there?
11801 			 */
11802 			len = avail - sb_offset;
11803 		}
11804 	}
11805 	return (len);
11806 }
11807 
11808 static inline void
11809 bbr_do_error_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11810 {
11811 #ifdef NETFLIX_STATS
11812 	KMOD_TCPSTAT_INC(tcps_sndpack_error);
11813 	KMOD_TCPSTAT_ADD(tcps_sndbyte_error, len);
11814 #endif
11815 }
11816 
11817 static inline void
11818 bbr_do_send_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11819 {
11820 	if (error) {
11821 		bbr_do_error_accounting(tp, bbr, rsm, len, error);
11822 		return;
11823 	}
11824 	if (rsm) {
11825 		if (rsm->r_flags & BBR_TLP) {
11826 			/*
11827 			 * TLP should not count in retran count, but in its
11828 			 * own bin
11829 			 */
11830 #ifdef NETFLIX_STATS
11831 			tp->t_sndtlppack++;
11832 			tp->t_sndtlpbyte += len;
11833 			KMOD_TCPSTAT_INC(tcps_tlpresends);
11834 			KMOD_TCPSTAT_ADD(tcps_tlpresend_bytes, len);
11835 #endif
11836 		} else {
11837 			/* Retransmit */
11838 			tp->t_sndrexmitpack++;
11839 			KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
11840 			KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
11841 #ifdef STATS
11842 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
11843 			    len);
11844 #endif
11845 		}
11846 		/*
11847 		 * Logs in 0 - 8, 8 is all non probe_bw states 0-7 is
11848 		 * sub-state
11849 		 */
11850 		counter_u64_add(bbr_state_lost[rsm->r_bbr_state], len);
11851 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_BW) {
11852 			/* Non probe_bw log in 1, 2, or 4. */
11853 			counter_u64_add(bbr_state_resend[bbr->rc_bbr_state], len);
11854 		} else {
11855 			/*
11856 			 * Log our probe state 3, and log also 5-13 to show
11857 			 * us the recovery sub-state for the send. This
11858 			 * means that 3 == (5+6+7+8+9+10+11+12+13)
11859 			 */
11860 			counter_u64_add(bbr_state_resend[BBR_STATE_PROBE_BW], len);
11861 			counter_u64_add(bbr_state_resend[(bbr_state_val(bbr) + 5)], len);
11862 		}
11863 		/* Place in both 16's the totals of retransmitted */
11864 		counter_u64_add(bbr_state_lost[16], len);
11865 		counter_u64_add(bbr_state_resend[16], len);
11866 		/* Place in 17's the total sent */
11867 		counter_u64_add(bbr_state_resend[17], len);
11868 		counter_u64_add(bbr_state_lost[17], len);
11869 
11870 	} else {
11871 		/* New sends */
11872 		KMOD_TCPSTAT_INC(tcps_sndpack);
11873 		KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
11874 		/* Place in 17's the total sent */
11875 		counter_u64_add(bbr_state_resend[17], len);
11876 		counter_u64_add(bbr_state_lost[17], len);
11877 #ifdef STATS
11878 		stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
11879 		    len);
11880 #endif
11881 	}
11882 }
11883 
11884 static void
11885 bbr_cwnd_limiting(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t in_level)
11886 {
11887 	if (bbr->rc_filled_pipe && bbr_target_cwnd_mult_limit && (bbr->rc_use_google == 0)) {
11888 		/*
11889 		 * Limit the cwnd to not be above N x the target plus whats
11890 		 * is outstanding. The target is based on the current b/w
11891 		 * estimate.
11892 		 */
11893 		uint32_t target;
11894 
11895 		target = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), BBR_UNIT);
11896 		target += ctf_outstanding(tp);
11897 		target *= bbr_target_cwnd_mult_limit;
11898 		if (tp->snd_cwnd > target)
11899 			tp->snd_cwnd = target;
11900 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 10, 0, 0, __LINE__);
11901 	}
11902 }
11903 
11904 static int
11905 bbr_window_update_needed(struct tcpcb *tp, struct socket *so, uint32_t recwin, int32_t maxseg)
11906 {
11907 	/*
11908 	 * "adv" is the amount we could increase the window, taking into
11909 	 * account that we are limited by TCP_MAXWIN << tp->rcv_scale.
11910 	 */
11911 	int32_t adv;
11912 	int32_t oldwin;
11913 
11914 	adv = recwin;
11915 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
11916 		oldwin = (tp->rcv_adv - tp->rcv_nxt);
11917 		if (adv > oldwin)
11918 			adv -= oldwin;
11919 		else {
11920 			/* We can't increase the window */
11921 			adv = 0;
11922 		}
11923 	} else
11924 		oldwin = 0;
11925 
11926 	/*
11927 	 * If the new window size ends up being the same as or less
11928 	 * than the old size when it is scaled, then don't force
11929 	 * a window update.
11930 	 */
11931 	if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
11932 		return (0);
11933 
11934 	if (adv >= (2 * maxseg) &&
11935 	    (adv >= (so->so_rcv.sb_hiwat / 4) ||
11936 	    recwin <= (so->so_rcv.sb_hiwat / 8) ||
11937 	    so->so_rcv.sb_hiwat <= 8 * maxseg)) {
11938 		return (1);
11939 	}
11940 	if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
11941 		return (1);
11942 	return (0);
11943 }
11944 
11945 /*
11946  * Return 0 on success and a errno on failure to send.
11947  * Note that a 0 return may not mean we sent anything
11948  * if the TCB was on the hpts. A non-zero return
11949  * does indicate the error we got from ip[6]_output.
11950  */
11951 static int
11952 bbr_output_wtime(struct tcpcb *tp, const struct timeval *tv)
11953 {
11954 	struct socket *so;
11955 	int32_t len;
11956 	uint32_t cts;
11957 	uint32_t recwin, sendwin;
11958 	int32_t sb_offset;
11959 	int32_t flags, abandon, error = 0;
11960 	struct tcp_log_buffer *lgb = NULL;
11961 	struct mbuf *m;
11962 	struct mbuf *mb;
11963 	uint32_t if_hw_tsomaxsegcount = 0;
11964 	uint32_t if_hw_tsomaxsegsize = 0;
11965 	uint32_t if_hw_tsomax = 0;
11966 	struct ip *ip = NULL;
11967 #ifdef TCPDEBUG
11968 	struct ipovly *ipov = NULL;
11969 #endif
11970 	struct tcp_bbr *bbr;
11971 	struct tcphdr *th;
11972 #ifdef NETFLIX_TCPOUDP
11973 	struct udphdr *udp = NULL;
11974 #endif
11975 	u_char opt[TCP_MAXOLEN];
11976 	unsigned ipoptlen, optlen, hdrlen;
11977 #ifdef NETFLIX_TCPOUDP
11978 	unsigned ulen;
11979 #endif
11980 	uint32_t bbr_seq;
11981 	uint32_t delay_calc=0;
11982 	uint8_t doing_tlp = 0;
11983 	uint8_t local_options;
11984 #ifdef BBR_INVARIANTS
11985 	uint8_t doing_retran_from = 0;
11986 	uint8_t picked_up_retran = 0;
11987 #endif
11988 	uint8_t wanted_cookie = 0;
11989 	uint8_t more_to_rxt=0;
11990 	int32_t prefetch_so_done = 0;
11991 	int32_t prefetch_rsm = 0;
11992  	uint32_t what_we_can = 0;
11993 	uint32_t tot_len = 0;
11994 	uint32_t rtr_cnt = 0;
11995 	uint32_t maxseg, pace_max_segs, p_maxseg;
11996 	int32_t csum_flags;
11997  	int32_t hw_tls;
11998 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
11999 	unsigned ipsec_optlen = 0;
12000 
12001 #endif
12002 	volatile int32_t sack_rxmit;
12003 	struct bbr_sendmap *rsm = NULL;
12004 	int32_t tso, mtu;
12005 	struct tcpopt to;
12006 	int32_t slot = 0;
12007 	struct inpcb *inp;
12008 	struct sockbuf *sb;
12009 	uint32_t hpts_calling;
12010 #ifdef INET6
12011 	struct ip6_hdr *ip6 = NULL;
12012 	int32_t isipv6;
12013 #endif
12014 	uint8_t app_limited = BBR_JR_SENT_DATA;
12015 	uint8_t filled_all = 0;
12016 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
12017 	/* We take a cache hit here */
12018 	memcpy(&bbr->rc_tv, tv, sizeof(struct timeval));
12019 	cts = tcp_tv_to_usectick(&bbr->rc_tv);
12020 	inp = bbr->rc_inp;
12021 	so = inp->inp_socket;
12022 	sb = &so->so_snd;
12023  	if (sb->sb_flags & SB_TLS_IFNET)
12024  		hw_tls = 1;
12025  	else
12026  		hw_tls = 0;
12027 	kern_prefetch(sb, &maxseg);
12028 	maxseg = tp->t_maxseg - bbr->rc_last_options;
12029 	if (bbr_minseg(bbr) < maxseg) {
12030 		tcp_bbr_tso_size_check(bbr, cts);
12031 	}
12032 	/* Remove any flags that indicate we are pacing on the inp  */
12033 	pace_max_segs = bbr->r_ctl.rc_pace_max_segs;
12034 	p_maxseg = min(maxseg, pace_max_segs);
12035 	INP_WLOCK_ASSERT(inp);
12036 #ifdef TCP_OFFLOAD
12037 	if (tp->t_flags & TF_TOE)
12038 		return (tcp_offload_output(tp));
12039 #endif
12040 
12041 #ifdef INET6
12042 	if (bbr->r_state) {
12043 		/* Use the cache line loaded if possible */
12044 		isipv6 = bbr->r_is_v6;
12045 	} else {
12046 		isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
12047 	}
12048 #endif
12049 	if (((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
12050 	    inp->inp_in_hpts) {
12051 		/*
12052 		 * We are on the hpts for some timer but not hptsi output.
12053 		 * Possibly remove from the hpts so we can send/recv etc.
12054 		 */
12055 		if ((tp->t_flags & TF_ACKNOW) == 0) {
12056 			/*
12057 			 * No immediate demand right now to send an ack, but
12058 			 * the user may have read, making room for new data
12059 			 * (a window update). If so we may want to cancel
12060 			 * whatever timer is running (KEEP/DEL-ACK?) and
12061 			 * continue to send out a window update. Or we may
12062 			 * have gotten more data into the socket buffer to
12063 			 * send.
12064 			 */
12065 			recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12066 				      (long)TCP_MAXWIN << tp->rcv_scale);
12067 			if ((bbr_window_update_needed(tp, so, recwin, maxseg) == 0) &&
12068 			    ((tcp_outflags[tp->t_state] & TH_RST) == 0) &&
12069 			    ((sbavail(sb) + ((tcp_outflags[tp->t_state] & TH_FIN) ? 1 : 0)) <=
12070 			    (tp->snd_max - tp->snd_una))) {
12071 				/*
12072 				 * Nothing new to send and no window update
12073 				 * is needed to send. Lets just return and
12074 				 * let the timer-run off.
12075 				 */
12076 				return (0);
12077 			}
12078 		}
12079 		tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12080 		bbr_timer_cancel(bbr, __LINE__, cts);
12081 	}
12082 	if (bbr->r_ctl.rc_last_delay_val) {
12083 		/* Calculate a rough delay for early escape to sending  */
12084 		if (SEQ_GT(cts, bbr->rc_pacer_started))
12085 			delay_calc = cts - bbr->rc_pacer_started;
12086 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12087 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
12088 		else
12089 			delay_calc = 0;
12090 	}
12091 	/* Mark that we have called bbr_output(). */
12092 	if ((bbr->r_timer_override) ||
12093 	    (tp->t_state < TCPS_ESTABLISHED)) {
12094 		/* Timeouts or early states are exempt */
12095 		if (inp->inp_in_hpts)
12096 			tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12097 	} else if (inp->inp_in_hpts) {
12098 		if ((bbr->r_ctl.rc_last_delay_val) &&
12099 		    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
12100 		    delay_calc) {
12101 			/*
12102 			 * We were being paced for output and the delay has
12103 			 * already exceeded when we were supposed to be
12104 			 * called, lets go ahead and pull out of the hpts
12105 			 * and call output.
12106 			 */
12107 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_LATE], 1);
12108 			bbr->r_ctl.rc_last_delay_val = 0;
12109 			tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12110 		} else if (tp->t_state == TCPS_CLOSED) {
12111 			bbr->r_ctl.rc_last_delay_val = 0;
12112 			tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12113 		} else {
12114 			/*
12115 			 * On the hpts, you shall not pass! even if ACKNOW
12116 			 * is on, we will when the hpts fires, unless of
12117 			 * course we are overdue.
12118 			 */
12119 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_INPACE], 1);
12120 			return (0);
12121 		}
12122 	}
12123 	bbr->rc_cwnd_limited = 0;
12124 	if (bbr->r_ctl.rc_last_delay_val) {
12125 		/* recalculate the real delay and deal with over/under  */
12126 		if (SEQ_GT(cts, bbr->rc_pacer_started))
12127 			delay_calc = cts - bbr->rc_pacer_started;
12128 		else
12129 			delay_calc = 0;
12130 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12131 			/* Setup the delay which will be added in */
12132 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
12133 		else {
12134 			/*
12135 			 * We are early setup to adjust
12136 			 * our slot time.
12137 			 */
12138 			uint64_t merged_val;
12139 
12140 			bbr->r_ctl.rc_agg_early += (bbr->r_ctl.rc_last_delay_val - delay_calc);
12141 			bbr->r_agg_early_set = 1;
12142 			if (bbr->r_ctl.rc_hptsi_agg_delay) {
12143 				if (bbr->r_ctl.rc_hptsi_agg_delay >= bbr->r_ctl.rc_agg_early) {
12144 					/* Nope our previous late cancels out the early */
12145 					bbr->r_ctl.rc_hptsi_agg_delay -= bbr->r_ctl.rc_agg_early;
12146 					bbr->r_agg_early_set = 0;
12147 					bbr->r_ctl.rc_agg_early = 0;
12148 				} else {
12149 					bbr->r_ctl.rc_agg_early -= bbr->r_ctl.rc_hptsi_agg_delay;
12150 					bbr->r_ctl.rc_hptsi_agg_delay = 0;
12151 				}
12152 			}
12153 			merged_val = bbr->rc_pacer_started;
12154 			merged_val <<= 32;
12155 			merged_val |= bbr->r_ctl.rc_last_delay_val;
12156 			bbr_log_pacing_delay_calc(bbr, inp->inp_hpts_calls,
12157 						 bbr->r_ctl.rc_agg_early, cts, delay_calc, merged_val,
12158 						 bbr->r_agg_early_set, 3);
12159 			bbr->r_ctl.rc_last_delay_val = 0;
12160 			BBR_STAT_INC(bbr_early);
12161 			delay_calc = 0;
12162 		}
12163 	} else {
12164 		/* We were not delayed due to hptsi */
12165 		if (bbr->r_agg_early_set)
12166 			bbr->r_ctl.rc_agg_early = 0;
12167 		bbr->r_agg_early_set = 0;
12168 		delay_calc = 0;
12169 	}
12170 	if (delay_calc) {
12171 		/*
12172 		 * We had a hptsi delay which means we are falling behind on
12173 		 * sending at the expected rate. Calculate an extra amount
12174 		 * of data we can send, if any, to put us back on track.
12175 		 */
12176 		if ((bbr->r_ctl.rc_hptsi_agg_delay + delay_calc) < bbr->r_ctl.rc_hptsi_agg_delay)
12177 			bbr->r_ctl.rc_hptsi_agg_delay = 0xffffffff;
12178 		else
12179 			bbr->r_ctl.rc_hptsi_agg_delay += delay_calc;
12180 	}
12181 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12182 	if ((tp->snd_una == tp->snd_max) &&
12183 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
12184 	    (sbavail(sb))) {
12185 		/*
12186 		 * Ok we have been idle with nothing outstanding
12187 		 * we possibly need to start fresh with either a new
12188 		 * suite of states or a fast-ramp up.
12189 		 */
12190 		bbr_restart_after_idle(bbr,
12191 				       cts, bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time));
12192 	}
12193 	/*
12194 	 * Now was there a hptsi delay where we are behind? We only count
12195 	 * being behind if: a) We are not in recovery. b) There was a delay.
12196 	 * <and> c) We had room to send something.
12197 	 *
12198 	 */
12199 	hpts_calling = inp->inp_hpts_calls;
12200 	inp->inp_hpts_calls = 0;
12201 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
12202 		if (bbr_process_timers(tp, bbr, cts, hpts_calling)) {
12203 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_ATIMER], 1);
12204 			return (0);
12205 		}
12206 	}
12207 	bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
12208 	if (hpts_calling &&
12209 	    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
12210 		bbr->r_ctl.rc_last_delay_val = 0;
12211 	}
12212 	bbr->r_timer_override = 0;
12213 	bbr->r_wanted_output = 0;
12214 	/*
12215 	 * For TFO connections in SYN_RECEIVED, only allow the initial
12216 	 * SYN|ACK and those sent by the retransmit timer.
12217 	 */
12218 	if (IS_FASTOPEN(tp->t_flags) &&
12219 	    ((tp->t_state == TCPS_SYN_RECEIVED) ||
12220 	     (tp->t_state == TCPS_SYN_SENT)) &&
12221 	    SEQ_GT(tp->snd_max, tp->snd_una) &&	/* initial SYN or SYN|ACK sent */
12222 	    (tp->t_rxtshift == 0)) {	/* not a retransmit */
12223 		len = 0;
12224 		goto just_return_nolock;
12225 	}
12226 	/*
12227 	 * Before sending anything check for a state update. For hpts
12228 	 * calling without input this is important. If its input calling
12229 	 * then this was already done.
12230 	 */
12231 	if (bbr->rc_use_google == 0)
12232 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12233 again:
12234 	/*
12235 	 * If we've recently taken a timeout, snd_max will be greater than
12236 	 * snd_max. BBR in general does not pay much attention to snd_nxt
12237 	 * for historic reasons the persist timer still uses it. This means
12238 	 * we have to look at it. All retransmissions that are not persits
12239 	 * use the rsm that needs to be sent so snd_nxt is ignored. At the
12240 	 * end of this routine we pull snd_nxt always up to snd_max.
12241 	 */
12242 	doing_tlp = 0;
12243 #ifdef BBR_INVARIANTS
12244 	doing_retran_from = picked_up_retran = 0;
12245 #endif
12246 	error = 0;
12247 	tso = 0;
12248 	slot = 0;
12249 	mtu = 0;
12250 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12251 	sb_offset = tp->snd_max - tp->snd_una;
12252 	flags = tcp_outflags[tp->t_state];
12253 	sack_rxmit = 0;
12254 	len = 0;
12255 	rsm = NULL;
12256 	if (flags & TH_RST) {
12257 		SOCKBUF_LOCK(sb);
12258 		goto send;
12259 	}
12260 recheck_resend:
12261 	while (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
12262 		/* We need to always have one in reserve */
12263 		rsm = bbr_alloc(bbr);
12264 		if (rsm == NULL) {
12265 			error = ENOMEM;
12266 			/* Lie to get on the hpts */
12267 			tot_len = tp->t_maxseg;
12268 			if (hpts_calling)
12269 				/* Retry in a ms */
12270 				slot = 1001;
12271 			goto just_return_nolock;
12272 		}
12273 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
12274 		bbr->r_ctl.rc_free_cnt++;
12275 		rsm = NULL;
12276 	}
12277 	/* What do we send, a resend? */
12278 	if (bbr->r_ctl.rc_resend == NULL) {
12279 		/* Check for rack timeout */
12280 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
12281 		if (bbr->r_ctl.rc_resend) {
12282 #ifdef BBR_INVARIANTS
12283 			picked_up_retran = 1;
12284 #endif
12285 			bbr_cong_signal(tp, NULL, CC_NDUPACK, bbr->r_ctl.rc_resend);
12286 		}
12287 	}
12288 	if (bbr->r_ctl.rc_resend) {
12289 		rsm = bbr->r_ctl.rc_resend;
12290 #ifdef BBR_INVARIANTS
12291 		doing_retran_from = 1;
12292 #endif
12293 		/* Remove any TLP flags its a RACK or T-O */
12294 		rsm->r_flags &= ~BBR_TLP;
12295 		bbr->r_ctl.rc_resend = NULL;
12296 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
12297 #ifdef BBR_INVARIANTS
12298 			panic("Huh, tp:%p bbr:%p rsm:%p start:%u < snd_una:%u\n",
12299 			    tp, bbr, rsm, rsm->r_start, tp->snd_una);
12300 			goto recheck_resend;
12301 #else
12302 			/* TSNH */
12303 			rsm = NULL;
12304 			goto recheck_resend;
12305 #endif
12306 		}
12307 		rtr_cnt++;
12308 		if (rsm->r_flags & BBR_HAS_SYN) {
12309 			/* Only retransmit a SYN by itself */
12310 			len = 0;
12311 			if ((flags & TH_SYN) == 0) {
12312 				/* Huh something is wrong */
12313 				rsm->r_start++;
12314 				if (rsm->r_start == rsm->r_end) {
12315 					/* Clean it up, somehow we missed the ack? */
12316 					bbr_log_syn(tp, NULL);
12317 				} else {
12318 					/* TFO with data? */
12319 					rsm->r_flags &= ~BBR_HAS_SYN;
12320 					len = rsm->r_end - rsm->r_start;
12321 				}
12322 			} else {
12323 				/* Retransmitting SYN */
12324 				rsm = NULL;
12325 				SOCKBUF_LOCK(sb);
12326 				goto send;
12327 			}
12328 		} else
12329 			len = rsm->r_end - rsm->r_start;
12330 		if ((bbr->rc_resends_use_tso == 0) &&
12331 		    (len > maxseg)) {
12332 			len = maxseg;
12333 			more_to_rxt = 1;
12334 		}
12335 		sb_offset = rsm->r_start - tp->snd_una;
12336 		if (len > 0) {
12337 			sack_rxmit = 1;
12338 			KMOD_TCPSTAT_INC(tcps_sack_rexmits);
12339 			KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
12340 			    min(len, maxseg));
12341 		} else {
12342 			/* I dont think this can happen */
12343 			rsm = NULL;
12344 			goto recheck_resend;
12345 		}
12346 		BBR_STAT_INC(bbr_resends_set);
12347 	} else if (bbr->r_ctl.rc_tlp_send) {
12348 		/*
12349 		 * Tail loss probe
12350 		 */
12351 		doing_tlp = 1;
12352 		rsm = bbr->r_ctl.rc_tlp_send;
12353 		bbr->r_ctl.rc_tlp_send = NULL;
12354 		sack_rxmit = 1;
12355 		len = rsm->r_end - rsm->r_start;
12356 		rtr_cnt++;
12357 		if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12358 			len = maxseg;
12359 
12360 		if (SEQ_GT(tp->snd_una, rsm->r_start)) {
12361 #ifdef BBR_INVARIANTS
12362 			panic("tp:%p bbc:%p snd_una:%u rsm:%p r_start:%u",
12363 			    tp, bbr, tp->snd_una, rsm, rsm->r_start);
12364 #else
12365 			/* TSNH */
12366 			rsm = NULL;
12367 			goto recheck_resend;
12368 #endif
12369 		}
12370 		sb_offset = rsm->r_start - tp->snd_una;
12371 		BBR_STAT_INC(bbr_tlp_set);
12372 	}
12373 	/*
12374 	 * Enforce a connection sendmap count limit if set
12375 	 * as long as we are not retransmiting.
12376 	 */
12377 	if ((rsm == NULL) &&
12378 	    (V_tcp_map_entries_limit > 0) &&
12379 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
12380 		BBR_STAT_INC(bbr_alloc_limited);
12381 		if (!bbr->alloc_limit_reported) {
12382 			bbr->alloc_limit_reported = 1;
12383 			BBR_STAT_INC(bbr_alloc_limited_conns);
12384 		}
12385 		goto just_return_nolock;
12386 	}
12387 #ifdef BBR_INVARIANTS
12388 	if (rsm && SEQ_LT(rsm->r_start, tp->snd_una)) {
12389 		panic("tp:%p bbr:%p rsm:%p sb_offset:%u len:%u",
12390 		    tp, bbr, rsm, sb_offset, len);
12391 	}
12392 #endif
12393 	/*
12394 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
12395 	 * state flags.
12396 	 */
12397 	if (tp->t_flags & TF_NEEDFIN && (rsm == NULL))
12398 		flags |= TH_FIN;
12399 	if (tp->t_flags & TF_NEEDSYN)
12400 		flags |= TH_SYN;
12401 
12402 	if (rsm && (rsm->r_flags & BBR_HAS_FIN)) {
12403 		/* we are retransmitting the fin */
12404 		len--;
12405 		if (len) {
12406 			/*
12407 			 * When retransmitting data do *not* include the
12408 			 * FIN. This could happen from a TLP probe if we
12409 			 * allowed data with a FIN.
12410 			 */
12411 			flags &= ~TH_FIN;
12412 		}
12413 	} else if (rsm) {
12414 		if (flags & TH_FIN)
12415 			flags &= ~TH_FIN;
12416 	}
12417 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
12418 		void *end_rsm;
12419 
12420 		end_rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
12421 		if (end_rsm)
12422 			kern_prefetch(end_rsm, &prefetch_rsm);
12423 		prefetch_rsm = 1;
12424 	}
12425 	SOCKBUF_LOCK(sb);
12426 	/*
12427 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
12428 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
12429 	 * negative length.  This can also occur when TCP opens up its
12430 	 * congestion window while receiving additional duplicate acks after
12431 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
12432 	 * the fast-retransmit.
12433 	 *
12434 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
12435 	 * set to snd_una, the sb_offset will be 0, and the length may wind
12436 	 * up 0.
12437 	 *
12438 	 * If sack_rxmit is true we are retransmitting from the scoreboard
12439 	 * in which case len is already set.
12440 	 */
12441 	if (sack_rxmit == 0) {
12442 		uint32_t avail;
12443 
12444 		avail = sbavail(sb);
12445 		if (SEQ_GT(tp->snd_max, tp->snd_una))
12446 			sb_offset = tp->snd_max - tp->snd_una;
12447 		else
12448 			sb_offset = 0;
12449 		if (bbr->rc_tlp_new_data) {
12450 			/* TLP is forcing out new data */
12451 			uint32_t tlplen;
12452 
12453 			doing_tlp = 1;
12454 			tlplen = maxseg;
12455 
12456 			if (tlplen > (uint32_t)(avail - sb_offset)) {
12457 				tlplen = (uint32_t)(avail - sb_offset);
12458 			}
12459 			if (tlplen > tp->snd_wnd) {
12460 				len = tp->snd_wnd;
12461 			} else {
12462 				len = tlplen;
12463 			}
12464 			bbr->rc_tlp_new_data = 0;
12465 		} else {
12466 			what_we_can = len = bbr_what_can_we_send(tp, bbr, sendwin, avail, sb_offset, cts);
12467 			if ((len < p_maxseg) &&
12468 			    (bbr->rc_in_persist == 0) &&
12469 			    (ctf_outstanding(tp) >= (2 * p_maxseg)) &&
12470 			    ((avail - sb_offset) >= p_maxseg)) {
12471 				/*
12472 				 * We are not completing whats in the socket
12473 				 * buffer (i.e. there is at least a segment
12474 				 * waiting to send) and we have 2 or more
12475 				 * segments outstanding. There is no sense
12476 				 * of sending a little piece. Lets defer and
12477 				 * and wait until we can send a whole
12478 				 * segment.
12479 				 */
12480 				len = 0;
12481 			}
12482 			if (bbr->rc_in_persist) {
12483 				/*
12484 				 * We are in persists, figure out if
12485 				 * a retransmit is available (maybe the previous
12486 				 * persists we sent) or if we have to send new
12487 				 * data.
12488 				 */
12489 				rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
12490 				if (rsm) {
12491 					len = rsm->r_end - rsm->r_start;
12492 					if (rsm->r_flags & BBR_HAS_FIN)
12493 						len--;
12494 					if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12495 						len = maxseg;
12496 					if (len > 1)
12497 						BBR_STAT_INC(bbr_persist_reneg);
12498 					/*
12499 					 * XXXrrs we could force the len to
12500 					 * 1 byte here to cause the chunk to
12501 					 * split apart.. but that would then
12502 					 * mean we always retransmit it as
12503 					 * one byte even after the window
12504 					 * opens.
12505 					 */
12506 					sack_rxmit = 1;
12507 					sb_offset = rsm->r_start - tp->snd_una;
12508 				} else {
12509 					/*
12510 					 * First time through in persists or peer
12511 					 * acked our one byte. Though we do have
12512 					 * to have something in the sb.
12513 					 */
12514 					len = 1;
12515 					sb_offset = 0;
12516 					if (avail == 0)
12517 					    len = 0;
12518 				}
12519 			}
12520 		}
12521 	}
12522 	if (prefetch_so_done == 0) {
12523 		kern_prefetch(so, &prefetch_so_done);
12524 		prefetch_so_done = 1;
12525 	}
12526 	/*
12527 	 * Lop off SYN bit if it has already been sent.  However, if this is
12528 	 * SYN-SENT state and if segment contains data and if we don't know
12529 	 * that foreign host supports TAO, suppress sending segment.
12530 	 */
12531 	if ((flags & TH_SYN) && (rsm == NULL) &&
12532 	    SEQ_GT(tp->snd_max, tp->snd_una)) {
12533 		if (tp->t_state != TCPS_SYN_RECEIVED)
12534 			flags &= ~TH_SYN;
12535 		/*
12536 		 * When sending additional segments following a TFO SYN|ACK,
12537 		 * do not include the SYN bit.
12538 		 */
12539 		if (IS_FASTOPEN(tp->t_flags) &&
12540 		    (tp->t_state == TCPS_SYN_RECEIVED))
12541 			flags &= ~TH_SYN;
12542 		sb_offset--, len++;
12543 		if (sbavail(sb) == 0)
12544 			len = 0;
12545 	} else if ((flags & TH_SYN) && rsm) {
12546 		/*
12547 		 * Subtract one from the len for the SYN being
12548 		 * retransmitted.
12549 		 */
12550 		len--;
12551 	}
12552 	/*
12553 	 * Be careful not to send data and/or FIN on SYN segments. This
12554 	 * measure is needed to prevent interoperability problems with not
12555 	 * fully conformant TCP implementations.
12556 	 */
12557 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
12558 		len = 0;
12559 		flags &= ~TH_FIN;
12560 	}
12561 	/*
12562 	 * On TFO sockets, ensure no data is sent in the following cases:
12563 	 *
12564 	 *  - When retransmitting SYN|ACK on a passively-created socket
12565 	 *  - When retransmitting SYN on an actively created socket
12566 	 *  - When sending a zero-length cookie (cookie request) on an
12567 	 *    actively created socket
12568 	 *  - When the socket is in the CLOSED state (RST is being sent)
12569 	 */
12570 	if (IS_FASTOPEN(tp->t_flags) &&
12571 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
12572 	     ((tp->t_state == TCPS_SYN_SENT) &&
12573 	      (tp->t_tfo_client_cookie_len == 0)) ||
12574 	     (flags & TH_RST))) {
12575 		len = 0;
12576 		sack_rxmit = 0;
12577 		rsm = NULL;
12578 	}
12579 	/* Without fast-open there should never be data sent on a SYN */
12580 	if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags)))
12581 		len = 0;
12582 	if (len <= 0) {
12583 		/*
12584 		 * If FIN has been sent but not acked, but we haven't been
12585 		 * called to retransmit, len will be < 0.  Otherwise, window
12586 		 * shrank after we sent into it.  If window shrank to 0,
12587 		 * cancel pending retransmit, pull snd_nxt back to (closed)
12588 		 * window, and set the persist timer if it isn't already
12589 		 * going.  If the window didn't close completely, just wait
12590 		 * for an ACK.
12591 		 *
12592 		 * We also do a general check here to ensure that we will
12593 		 * set the persist timer when we have data to send, but a
12594 		 * 0-byte window. This makes sure the persist timer is set
12595 		 * even if the packet hits one of the "goto send" lines
12596 		 * below.
12597 		 */
12598 		len = 0;
12599 		if ((tp->snd_wnd == 0) &&
12600 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12601 		    (tp->snd_una == tp->snd_max) &&
12602 		    (sb_offset < (int)sbavail(sb))) {
12603 			/*
12604 			 * Not enough room in the rwnd to send
12605 			 * a paced segment out.
12606 			 */
12607 			bbr_enter_persist(tp, bbr, cts, __LINE__);
12608 		}
12609 	} else if ((rsm == NULL) &&
12610 		   (doing_tlp == 0) &&
12611 		   (len < bbr->r_ctl.rc_pace_max_segs)) {
12612 		/*
12613 		 * We are not sending a full segment for
12614 		 * some reason. Should we not send anything (think
12615 		 * sws or persists)?
12616 		 */
12617 		if ((tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12618 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12619 		    (len < (int)(sbavail(sb) - sb_offset))) {
12620 			/*
12621 			 * Here the rwnd is less than
12622 			 * the pacing size, this is not a retransmit,
12623 			 * we are established and
12624 			 * the send is not the last in the socket buffer
12625 			 * lets not send, and possibly enter persists.
12626 			 */
12627 			len = 0;
12628 			if (tp->snd_max == tp->snd_una)
12629 				bbr_enter_persist(tp, bbr, cts, __LINE__);
12630 		} else if ((tp->snd_cwnd >= bbr->r_ctl.rc_pace_max_segs) &&
12631 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12632 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12633 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12634 			   (len < bbr_minseg(bbr))) {
12635 			/*
12636 			 * Here we are not retransmitting, and
12637 			 * the cwnd is not so small that we could
12638 			 * not send at least a min size (rxt timer
12639 			 * not having gone off), We have 2 segments or
12640 			 * more already in flight, its not the tail end
12641 			 * of the socket buffer  and the cwnd is blocking
12642 			 * us from sending out minimum pacing segment size.
12643 			 * Lets not send anything.
12644 			 */
12645 			bbr->rc_cwnd_limited = 1;
12646 			len = 0;
12647 		} else if (((tp->snd_wnd - ctf_outstanding(tp)) <
12648 			    min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12649 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12650 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12651 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12652 			   (TCPS_HAVEESTABLISHED(tp->t_state))) {
12653 			/*
12654 			 * Here we have a send window but we have
12655 			 * filled it up and we can't send another pacing segment.
12656 			 * We also have in flight more than 2 segments
12657 			 * and we are not completing the sb i.e. we allow
12658 			 * the last bytes of the sb to go out even if
12659 			 * its not a full pacing segment.
12660 			 */
12661 			len = 0;
12662 		}
12663 	}
12664 	/* len will be >= 0 after this point. */
12665 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
12666 	tcp_sndbuf_autoscale(tp, so, sendwin);
12667 	/*
12668 	 *
12669 	 */
12670 	if (bbr->rc_in_persist &&
12671 	    len &&
12672 	    (rsm == NULL) &&
12673 	    (len < min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs))) {
12674 		/*
12675 		 * We are in persist, not doing a retransmit and don't have enough space
12676 		 * yet to send a full TSO. So is it at the end of the sb
12677 		 * if so we need to send else nuke to 0 and don't send.
12678 		 */
12679 		int sbleft;
12680 		if (sbavail(sb) > sb_offset)
12681 			sbleft = sbavail(sb) - sb_offset;
12682 		else
12683 			sbleft = 0;
12684 		if (sbleft >= min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs)) {
12685 			/* not at end of sb lets not send */
12686 			len = 0;
12687 		}
12688 	}
12689 	/*
12690 	 * Decide if we can use TCP Segmentation Offloading (if supported by
12691 	 * hardware).
12692 	 *
12693 	 * TSO may only be used if we are in a pure bulk sending state.  The
12694 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
12695 	 * options prevent using TSO.  With TSO the TCP header is the same
12696 	 * (except for the sequence number) for all generated packets.  This
12697 	 * makes it impossible to transmit any options which vary per
12698 	 * generated segment or packet.
12699 	 *
12700 	 * IPv4 handling has a clear separation of ip options and ip header
12701 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen()
12702 	 * does the right thing below to provide length of just ip options
12703 	 * and thus checking for ipoptlen is enough to decide if ip options
12704 	 * are present.
12705 	 */
12706 #ifdef INET6
12707 	if (isipv6)
12708 		ipoptlen = ip6_optlen(inp);
12709 	else
12710 #endif
12711 	if (inp->inp_options)
12712 		ipoptlen = inp->inp_options->m_len -
12713 		    offsetof(struct ipoption, ipopt_list);
12714 	else
12715 		ipoptlen = 0;
12716 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12717 	/*
12718 	 * Pre-calculate here as we save another lookup into the darknesses
12719 	 * of IPsec that way and can actually decide if TSO is ok.
12720 	 */
12721 #ifdef INET6
12722 	if (isipv6 && IPSEC_ENABLED(ipv6))
12723 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
12724 #ifdef INET
12725 	else
12726 #endif
12727 #endif				/* INET6 */
12728 #ifdef INET
12729 	if (IPSEC_ENABLED(ipv4))
12730 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
12731 #endif				/* INET */
12732 #endif				/* IPSEC */
12733 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12734 	ipoptlen += ipsec_optlen;
12735 #endif
12736 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
12737 	    (len > maxseg) &&
12738 	    (tp->t_port == 0) &&
12739 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
12740 	    tp->rcv_numsacks == 0 &&
12741 	    ipoptlen == 0)
12742 		tso = 1;
12743 
12744 	recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12745 	    (long)TCP_MAXWIN << tp->rcv_scale);
12746 	/*
12747 	 * Sender silly window avoidance.   We transmit under the following
12748 	 * conditions when len is non-zero:
12749 	 *
12750 	 * - We have a full segment (or more with TSO) - This is the last
12751 	 * buffer in a write()/send() and we are either idle or running
12752 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
12753 	 * then 1/2 the maximum send window's worth of data (receiver may be
12754 	 * limited the window size) - we need to retransmit
12755 	 */
12756 	if (rsm)
12757 		goto send;
12758 	if (len) {
12759 		if (sack_rxmit)
12760 			goto send;
12761 		if (len >= p_maxseg)
12762 			goto send;
12763 		/*
12764 		 * NOTE! on localhost connections an 'ack' from the remote
12765 		 * end may occur synchronously with the output and cause us
12766 		 * to flush a buffer queued with moretocome.  XXX
12767 		 *
12768 		 */
12769 		if (((tp->t_flags & TF_MORETOCOME) == 0) &&	/* normal case */
12770 		    ((tp->t_flags & TF_NODELAY) ||
12771 		    ((uint32_t)len + (uint32_t)sb_offset) >= sbavail(&so->so_snd)) &&
12772 		    (tp->t_flags & TF_NOPUSH) == 0) {
12773 			goto send;
12774 		}
12775 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
12776 			goto send;
12777 		}
12778 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
12779 			goto send;
12780 		}
12781 	}
12782 	/*
12783 	 * Sending of standalone window updates.
12784 	 *
12785 	 * Window updates are important when we close our window due to a
12786 	 * full socket buffer and are opening it again after the application
12787 	 * reads data from it.  Once the window has opened again and the
12788 	 * remote end starts to send again the ACK clock takes over and
12789 	 * provides the most current window information.
12790 	 *
12791 	 * We must avoid the silly window syndrome whereas every read from
12792 	 * the receive buffer, no matter how small, causes a window update
12793 	 * to be sent.  We also should avoid sending a flurry of window
12794 	 * updates when the socket buffer had queued a lot of data and the
12795 	 * application is doing small reads.
12796 	 *
12797 	 * Prevent a flurry of pointless window updates by only sending an
12798 	 * update when we can increase the advertized window by more than
12799 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
12800 	 * full or is very small be more aggressive and send an update
12801 	 * whenever we can increase by two mss sized segments. In all other
12802 	 * situations the ACK's to new incoming data will carry further
12803 	 * window increases.
12804 	 *
12805 	 * Don't send an independent window update if a delayed ACK is
12806 	 * pending (it will get piggy-backed on it) or the remote side
12807 	 * already has done a half-close and won't send more data.  Skip
12808 	 * this if the connection is in T/TCP half-open state.
12809 	 */
12810 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
12811 	    !(tp->t_flags & TF_DELACK) &&
12812 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
12813 		/* Check to see if we should do a window update */
12814 		if (bbr_window_update_needed(tp, so, recwin, maxseg))
12815 			goto send;
12816 	}
12817 	/*
12818 	 * Send if we owe the peer an ACK, RST, SYN.  ACKNOW
12819 	 * is also a catch-all for the retransmit timer timeout case.
12820 	 */
12821 	if (tp->t_flags & TF_ACKNOW) {
12822 		goto send;
12823 	}
12824 	if (flags & TH_RST) {
12825 		/* Always send a RST if one is due */
12826 		goto send;
12827 	}
12828 	if ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0) {
12829 		goto send;
12830 	}
12831 	/*
12832 	 * If our state indicates that FIN should be sent and we have not
12833 	 * yet done so, then we need to send.
12834 	 */
12835 	if (flags & TH_FIN &&
12836 	    ((tp->t_flags & TF_SENTFIN) == 0)) {
12837 		goto send;
12838 	}
12839 	/*
12840 	 * No reason to send a segment, just return.
12841 	 */
12842 just_return:
12843 	SOCKBUF_UNLOCK(sb);
12844 just_return_nolock:
12845 	if (tot_len)
12846 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
12847 	if (bbr->rc_no_pacing)
12848 		slot = 0;
12849 	if (tot_len == 0) {
12850 		if ((ctf_outstanding(tp) + min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) >=
12851 		    tp->snd_wnd) {
12852 			BBR_STAT_INC(bbr_rwnd_limited);
12853 			app_limited = BBR_JR_RWND_LIMITED;
12854 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12855 			if ((bbr->rc_in_persist == 0) &&
12856 			    TCPS_HAVEESTABLISHED(tp->t_state) &&
12857 			    (tp->snd_max == tp->snd_una) &&
12858 			    sbavail(&tp->t_inpcb->inp_socket->so_snd)) {
12859 				/* No send window.. we must enter persist */
12860 				bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
12861 			}
12862 		} else if (ctf_outstanding(tp) >= sbavail(sb)) {
12863 			BBR_STAT_INC(bbr_app_limited);
12864 			app_limited = BBR_JR_APP_LIMITED;
12865 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12866 		} else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12867 						 bbr->r_ctl.rc_lost_bytes)) + p_maxseg) >= tp->snd_cwnd) {
12868 			BBR_STAT_INC(bbr_cwnd_limited);
12869  			app_limited = BBR_JR_CWND_LIMITED;
12870 			bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12871 									bbr->r_ctl.rc_lost_bytes)));
12872 			bbr->rc_cwnd_limited = 1;
12873 		} else {
12874 			BBR_STAT_INC(bbr_app_limited);
12875 			app_limited = BBR_JR_APP_LIMITED;
12876 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12877 		}
12878 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
12879 		bbr->r_agg_early_set = 0;
12880 		bbr->r_ctl.rc_agg_early = 0;
12881 		bbr->r_ctl.rc_last_delay_val = 0;
12882 	} else if (bbr->rc_use_google == 0)
12883 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12884 	/* Are we app limited? */
12885 	if ((app_limited == BBR_JR_APP_LIMITED) ||
12886 	    (app_limited == BBR_JR_RWND_LIMITED)) {
12887 		/**
12888 		 * We are application limited.
12889 		 */
12890 		bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12891 								       bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_delivered);
12892 	}
12893 	if (tot_len == 0)
12894 		counter_u64_add(bbr_out_size[TCP_MSS_ACCT_JUSTRET], 1);
12895 	/* Dont update the time if we did not send */
12896 	bbr->r_ctl.rc_last_delay_val = 0;
12897 	bbr->rc_output_starts_timer = 1;
12898 	bbr_start_hpts_timer(bbr, tp, cts, 9, slot, tot_len);
12899 	bbr_log_type_just_return(bbr, cts, tot_len, hpts_calling, app_limited, p_maxseg, len);
12900 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
12901 		/* Make sure snd_nxt is drug up */
12902 		tp->snd_nxt = tp->snd_max;
12903 	}
12904 	return (error);
12905 
12906 send:
12907 	if (doing_tlp == 0) {
12908 		/*
12909 		 * Data not a TLP, and its not the rxt firing. If it is the
12910 		 * rxt firing, we want to leave the tlp_in_progress flag on
12911 		 * so we don't send another TLP. It has to be a rack timer
12912 		 * or normal send (response to acked data) to clear the tlp
12913 		 * in progress flag.
12914 		 */
12915 		bbr->rc_tlp_in_progress = 0;
12916 		bbr->rc_tlp_rtx_out = 0;
12917 	} else {
12918 		/*
12919 		 * Its a TLP.
12920 		 */
12921 		bbr->rc_tlp_in_progress = 1;
12922 	}
12923 	bbr_timer_cancel(bbr, __LINE__, cts);
12924 	if (rsm == NULL) {
12925 		if (sbused(sb) > 0) {
12926 			/*
12927 			 * This is sub-optimal. We only send a stand alone
12928 			 * FIN on its own segment.
12929 			 */
12930 			if (flags & TH_FIN) {
12931 				flags &= ~TH_FIN;
12932 				if ((len == 0) && ((tp->t_flags & TF_ACKNOW) == 0)) {
12933 					/* Lets not send this */
12934 					slot = 0;
12935 					goto just_return;
12936 				}
12937 			}
12938 		}
12939 	} else {
12940 		/*
12941 		 * We do *not* send a FIN on a retransmit if it has data.
12942 		 * The if clause here where len > 1 should never come true.
12943 		 */
12944 		if ((len > 0) &&
12945 		    (((rsm->r_flags & BBR_HAS_FIN) == 0) &&
12946 		    (flags & TH_FIN))) {
12947 			flags &= ~TH_FIN;
12948 			len--;
12949 		}
12950 	}
12951 	SOCKBUF_LOCK_ASSERT(sb);
12952 	if (len > 0) {
12953 		if ((tp->snd_una == tp->snd_max) &&
12954 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
12955 			/*
12956 			 * This qualifies as a RTT_PROBE session since we
12957 			 * drop the data outstanding to nothing and waited
12958 			 * more than bbr_rtt_probe_time.
12959 			 */
12960 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
12961 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
12962 		}
12963 		if (len >= maxseg)
12964 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
12965 		else
12966 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
12967 	}
12968 	/*
12969 	 * Before ESTABLISHED, force sending of initial options unless TCP
12970 	 * set not to do any options. NOTE: we assume that the IP/TCP header
12971 	 * plus TCP options always fit in a single mbuf, leaving room for a
12972 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
12973 	 * + optlen <= MCLBYTES
12974 	 */
12975 	optlen = 0;
12976 #ifdef INET6
12977 	if (isipv6)
12978 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
12979 	else
12980 #endif
12981 		hdrlen = sizeof(struct tcpiphdr);
12982 
12983 	/*
12984 	 * Compute options for segment. We only have to care about SYN and
12985 	 * established connection segments.  Options for SYN-ACK segments
12986 	 * are handled in TCP syncache.
12987 	 */
12988 	to.to_flags = 0;
12989 	local_options = 0;
12990 	if ((tp->t_flags & TF_NOOPT) == 0) {
12991 		/* Maximum segment size. */
12992 		if (flags & TH_SYN) {
12993 			to.to_mss = tcp_mssopt(&inp->inp_inc);
12994 #ifdef NETFLIX_TCPOUDP
12995 			if (tp->t_port)
12996 				to.to_mss -= V_tcp_udp_tunneling_overhead;
12997 #endif
12998 			to.to_flags |= TOF_MSS;
12999 			/*
13000 			 * On SYN or SYN|ACK transmits on TFO connections,
13001 			 * only include the TFO option if it is not a
13002 			 * retransmit, as the presence of the TFO option may
13003 			 * have caused the original SYN or SYN|ACK to have
13004 			 * been dropped by a middlebox.
13005 			 */
13006 			if (IS_FASTOPEN(tp->t_flags) &&
13007 			    (tp->t_rxtshift == 0)) {
13008 				if (tp->t_state == TCPS_SYN_RECEIVED) {
13009 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
13010 					to.to_tfo_cookie =
13011 					    (u_int8_t *)&tp->t_tfo_cookie.server;
13012 					to.to_flags |= TOF_FASTOPEN;
13013 					wanted_cookie = 1;
13014 				} else if (tp->t_state == TCPS_SYN_SENT) {
13015 					to.to_tfo_len =
13016 					    tp->t_tfo_client_cookie_len;
13017 					to.to_tfo_cookie =
13018 					    tp->t_tfo_cookie.client;
13019 					to.to_flags |= TOF_FASTOPEN;
13020 					wanted_cookie = 1;
13021 				}
13022 			}
13023 		}
13024 		/* Window scaling. */
13025 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
13026 			to.to_wscale = tp->request_r_scale;
13027 			to.to_flags |= TOF_SCALE;
13028 		}
13029 		/* Timestamps. */
13030 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
13031 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
13032 			to.to_tsval = 	tcp_tv_to_mssectick(&bbr->rc_tv) + tp->ts_offset;
13033 			to.to_tsecr = tp->ts_recent;
13034 			to.to_flags |= TOF_TS;
13035 			local_options += TCPOLEN_TIMESTAMP + 2;
13036 		}
13037 		/* Set receive buffer autosizing timestamp. */
13038 		if (tp->rfbuf_ts == 0 &&
13039 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
13040 			tp->rfbuf_ts = 	tcp_tv_to_mssectick(&bbr->rc_tv);
13041 		/* Selective ACK's. */
13042 		if (flags & TH_SYN)
13043 			to.to_flags |= TOF_SACKPERM;
13044 		else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13045 		    tp->rcv_numsacks > 0) {
13046 			to.to_flags |= TOF_SACK;
13047 			to.to_nsacks = tp->rcv_numsacks;
13048 			to.to_sacks = (u_char *)tp->sackblks;
13049 		}
13050 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13051 		/* TCP-MD5 (RFC2385). */
13052 		if (tp->t_flags & TF_SIGNATURE)
13053 			to.to_flags |= TOF_SIGNATURE;
13054 #endif				/* TCP_SIGNATURE */
13055 
13056 		/* Processing the options. */
13057 		hdrlen += (optlen = tcp_addoptions(&to, opt));
13058 		/*
13059 		 * If we wanted a TFO option to be added, but it was unable
13060 		 * to fit, ensure no data is sent.
13061 		 */
13062 		if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
13063 		    !(to.to_flags & TOF_FASTOPEN))
13064 			len = 0;
13065 	}
13066 #ifdef NETFLIX_TCPOUDP
13067 	if (tp->t_port) {
13068 		if (V_tcp_udp_tunneling_port == 0) {
13069 			/* The port was removed?? */
13070 			SOCKBUF_UNLOCK(&so->so_snd);
13071 			return (EHOSTUNREACH);
13072 		}
13073 		hdrlen += sizeof(struct udphdr);
13074 	}
13075 #endif
13076 #ifdef INET6
13077 	if (isipv6)
13078 		ipoptlen = ip6_optlen(tp->t_inpcb);
13079 	else
13080 #endif
13081 	if (tp->t_inpcb->inp_options)
13082 		ipoptlen = tp->t_inpcb->inp_options->m_len -
13083 		    offsetof(struct ipoption, ipopt_list);
13084 	else
13085 		ipoptlen = 0;
13086 	ipoptlen = 0;
13087 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
13088 	ipoptlen += ipsec_optlen;
13089 #endif
13090 	if (bbr->rc_last_options != local_options) {
13091 		/*
13092 		 * Cache the options length this generally does not change
13093 		 * on a connection. We use this to calculate TSO.
13094 		 */
13095 		bbr->rc_last_options = local_options;
13096 	}
13097 	maxseg = tp->t_maxseg - (ipoptlen + optlen);
13098 	p_maxseg = min(maxseg, pace_max_segs);
13099 	/*
13100 	 * Adjust data length if insertion of options will bump the packet
13101 	 * length beyond the t_maxseg length. Clear the FIN bit because we
13102 	 * cut off the tail of the segment.
13103 	 */
13104 	if (len > maxseg) {
13105 		if (len != 0 && (flags & TH_FIN)) {
13106 			flags &= ~TH_FIN;
13107 		}
13108 		if (tso) {
13109 			uint32_t moff;
13110 			int32_t max_len;
13111 
13112 			/* extract TSO information */
13113 			if_hw_tsomax = tp->t_tsomax;
13114 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
13115 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
13116 			KASSERT(ipoptlen == 0,
13117 			    ("%s: TSO can't do IP options", __func__));
13118 
13119 			/*
13120 			 * Check if we should limit by maximum payload
13121 			 * length:
13122 			 */
13123 			if (if_hw_tsomax != 0) {
13124 				/* compute maximum TSO length */
13125 				max_len = (if_hw_tsomax - hdrlen -
13126 				    max_linkhdr);
13127 				if (max_len <= 0) {
13128 					len = 0;
13129 				} else if (len > max_len) {
13130 					len = max_len;
13131 				}
13132 			}
13133 			/*
13134 			 * Prevent the last segment from being fractional
13135 			 * unless the send sockbuf can be emptied:
13136 			 */
13137 			if ((sb_offset + len) < sbavail(sb)) {
13138 				moff = len % (uint32_t)maxseg;
13139 				if (moff != 0) {
13140 					len -= moff;
13141 				}
13142 			}
13143 			/*
13144 			 * In case there are too many small fragments don't
13145 			 * use TSO:
13146 			 */
13147 			if (len <= maxseg) {
13148 				len = maxseg;
13149 				tso = 0;
13150 			}
13151 		} else {
13152 			/* Not doing TSO */
13153 			if (optlen + ipoptlen >= tp->t_maxseg) {
13154 				/*
13155 				 * Since we don't have enough space to put
13156 				 * the IP header chain and the TCP header in
13157 				 * one packet as required by RFC 7112, don't
13158 				 * send it. Also ensure that at least one
13159 				 * byte of the payload can be put into the
13160 				 * TCP segment.
13161 				 */
13162 				SOCKBUF_UNLOCK(&so->so_snd);
13163 				error = EMSGSIZE;
13164 				sack_rxmit = 0;
13165 				goto out;
13166 			}
13167 			len = maxseg;
13168 		}
13169 	} else {
13170 		/* Not doing TSO */
13171 		if_hw_tsomaxsegcount = 0;
13172 		tso = 0;
13173 	}
13174 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
13175 	    ("%s: len > IP_MAXPACKET", __func__));
13176 #ifdef DIAGNOSTIC
13177 #ifdef INET6
13178 	if (max_linkhdr + hdrlen > MCLBYTES)
13179 #else
13180 	if (max_linkhdr + hdrlen > MHLEN)
13181 #endif
13182 		panic("tcphdr too big");
13183 #endif
13184 	/*
13185 	 * This KASSERT is here to catch edge cases at a well defined place.
13186 	 * Before, those had triggered (random) panic conditions further
13187 	 * down.
13188 	 */
13189 #ifdef BBR_INVARIANTS
13190 	if (sack_rxmit) {
13191 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
13192 			panic("RSM:%p TP:%p bbr:%p start:%u is < snd_una:%u",
13193 			    rsm, tp, bbr, rsm->r_start, tp->snd_una);
13194 		}
13195 	}
13196 #endif
13197 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
13198 	if ((len == 0) &&
13199 	    (flags & TH_FIN) &&
13200 	    (sbused(sb))) {
13201 		/*
13202 		 * We have outstanding data, don't send a fin by itself!.
13203 		 */
13204 		slot = 0;
13205 		goto just_return;
13206 	}
13207 	/*
13208 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
13209 	 * and initialize the header from the template for sends on this
13210 	 * connection.
13211 	 */
13212 	if (len) {
13213 		uint32_t moff;
13214 		uint32_t orig_len;
13215 
13216 		/*
13217 		 * We place a limit on sending with hptsi.
13218 		 */
13219 		if ((rsm == NULL) && len > pace_max_segs)
13220 			len = pace_max_segs;
13221 		if (len <= maxseg)
13222 			tso = 0;
13223 #ifdef INET6
13224 		if (MHLEN < hdrlen + max_linkhdr)
13225 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
13226 		else
13227 #endif
13228 			m = m_gethdr(M_NOWAIT, MT_DATA);
13229 
13230 		if (m == NULL) {
13231 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13232 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13233 			SOCKBUF_UNLOCK(sb);
13234 			error = ENOBUFS;
13235 			sack_rxmit = 0;
13236 			goto out;
13237 		}
13238 		m->m_data += max_linkhdr;
13239 		m->m_len = hdrlen;
13240 		/*
13241 		 * Start the m_copy functions from the closest mbuf to the
13242 		 * sb_offset in the socket buffer chain.
13243 		 */
13244 		if ((sb_offset > sbavail(sb)) || ((len + sb_offset) > sbavail(sb))) {
13245 #ifdef BBR_INVARIANTS
13246 			if ((len + sb_offset) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0)))
13247 				panic("tp:%p bbr:%p len:%u sb_offset:%u sbavail:%u rsm:%p %u:%u:%u",
13248 				    tp, bbr, len, sb_offset, sbavail(sb), rsm,
13249 				    doing_retran_from,
13250 				    picked_up_retran,
13251 				    doing_tlp);
13252 
13253 #endif
13254 			/*
13255 			 * In this messed up situation we have two choices,
13256 			 * a) pretend the send worked, and just start timers
13257 			 * and what not (not good since that may lead us
13258 			 * back here a lot). <or> b) Send the lowest segment
13259 			 * in the map. <or> c) Drop the connection. Lets do
13260 			 * <b> which if it continues to happen will lead to
13261 			 * <c> via timeouts.
13262 			 */
13263 			BBR_STAT_INC(bbr_offset_recovery);
13264 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
13265 			sb_offset = 0;
13266 			if (rsm == NULL) {
13267 				sack_rxmit = 0;
13268 				len = sbavail(sb);
13269 			} else {
13270 				sack_rxmit = 1;
13271 				if (rsm->r_start != tp->snd_una) {
13272 					/*
13273 					 * Things are really messed up, <c>
13274 					 * is the only thing to do.
13275 					 */
13276 					BBR_STAT_INC(bbr_offset_drop);
13277 					tcp_set_inp_to_drop(inp, EFAULT);
13278 					SOCKBUF_UNLOCK(sb);
13279 					(void)m_free(m);
13280 					return (0);
13281 				}
13282 				len = rsm->r_end - rsm->r_start;
13283 			}
13284 			if (len > sbavail(sb))
13285 				len = sbavail(sb);
13286 			if (len > maxseg)
13287 				len = maxseg;
13288 		}
13289 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
13290 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
13291 			m_copydata(mb, moff, (int)len,
13292 			    mtod(m, caddr_t)+hdrlen);
13293 			if (rsm == NULL)
13294 				sbsndptr_adv(sb, mb, len);
13295 			m->m_len += len;
13296 		} else {
13297 			struct sockbuf *msb;
13298 
13299 			if (rsm)
13300 				msb = NULL;
13301 			else
13302 				msb = sb;
13303 #ifdef BBR_INVARIANTS
13304 			if ((len + moff) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0))) {
13305 				if (rsm) {
13306 					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 ",
13307 					    tp, bbr, len, moff,
13308 					    sbavail(sb), rsm,
13309 					    tp->snd_una, rsm->r_flags, rsm->r_start,
13310 					    doing_retran_from,
13311 					    picked_up_retran,
13312 					    doing_tlp, sack_rxmit);
13313 				} else {
13314 					panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u sb_offset:%u snd_una:%u",
13315 					    tp, bbr, len, moff, sbavail(sb), sb_offset, tp->snd_una);
13316 				}
13317 			}
13318 #endif
13319 			orig_len = len;
13320 			m->m_next = tcp_m_copym(
13321 				mb, moff, &len,
13322 				if_hw_tsomaxsegcount,
13323 				if_hw_tsomaxsegsize, msb,
13324 				((rsm == NULL) ? hw_tls : 0)
13325 #ifdef NETFLIX_COPY_ARGS
13326 				, &filled_all
13327 #endif
13328 				);
13329 			if (len <= maxseg) {
13330 				/*
13331 				 * Must have ran out of mbufs for the copy
13332 				 * shorten it to no longer need tso. Lets
13333 				 * not put on sendalot since we are low on
13334 				 * mbufs.
13335 				 */
13336 				tso = 0;
13337 			}
13338 			if (m->m_next == NULL) {
13339 				SOCKBUF_UNLOCK(sb);
13340 				(void)m_free(m);
13341 				error = ENOBUFS;
13342 				sack_rxmit = 0;
13343 				goto out;
13344 			}
13345 		}
13346 #ifdef BBR_INVARIANTS
13347 		if (tso && len < maxseg) {
13348 			panic("tp:%p tso on, but len:%d < maxseg:%d",
13349 			    tp, len, maxseg);
13350 		}
13351 		if (tso && if_hw_tsomaxsegcount) {
13352 			int32_t seg_cnt = 0;
13353 			struct mbuf *foo;
13354 
13355 			foo = m;
13356 			while (foo) {
13357 				seg_cnt++;
13358 				foo = foo->m_next;
13359 			}
13360 			if (seg_cnt > if_hw_tsomaxsegcount) {
13361 				panic("seg_cnt:%d > max:%d", seg_cnt, if_hw_tsomaxsegcount);
13362 			}
13363 		}
13364 #endif
13365 		/*
13366 		 * If we're sending everything we've got, set PUSH. (This
13367 		 * will keep happy those implementations which only give
13368 		 * data to the user when a buffer fills or a PUSH comes in.)
13369 		 */
13370 		if (sb_offset + len == sbused(sb) &&
13371 		    sbused(sb) &&
13372 		    !(flags & TH_SYN)) {
13373 			flags |= TH_PUSH;
13374 		}
13375 		SOCKBUF_UNLOCK(sb);
13376 	} else {
13377 		SOCKBUF_UNLOCK(sb);
13378 		if (tp->t_flags & TF_ACKNOW)
13379 			KMOD_TCPSTAT_INC(tcps_sndacks);
13380 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
13381 			KMOD_TCPSTAT_INC(tcps_sndctrl);
13382 		else
13383 			KMOD_TCPSTAT_INC(tcps_sndwinup);
13384 
13385 		m = m_gethdr(M_NOWAIT, MT_DATA);
13386 		if (m == NULL) {
13387 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13388 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13389 			error = ENOBUFS;
13390 			/* Fudge the send time since we could not send */
13391 			sack_rxmit = 0;
13392 			goto out;
13393 		}
13394 #ifdef INET6
13395 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
13396 		    MHLEN >= hdrlen) {
13397 			M_ALIGN(m, hdrlen);
13398 		} else
13399 #endif
13400 			m->m_data += max_linkhdr;
13401 		m->m_len = hdrlen;
13402 	}
13403 	SOCKBUF_UNLOCK_ASSERT(sb);
13404 	m->m_pkthdr.rcvif = (struct ifnet *)0;
13405 #ifdef MAC
13406 	mac_inpcb_create_mbuf(inp, m);
13407 #endif
13408 #ifdef INET6
13409 	if (isipv6) {
13410 		ip6 = mtod(m, struct ip6_hdr *);
13411 #ifdef NETFLIX_TCPOUDP
13412 		if (tp->t_port) {
13413 			udp = (struct udphdr *)((caddr_t)ip6 + ipoptlen + sizeof(struct ip6_hdr));
13414 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13415 			udp->uh_dport = tp->t_port;
13416 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
13417 			udp->uh_ulen = htons(ulen);
13418 			th = (struct tcphdr *)(udp + 1);
13419 		} else {
13420 #endif
13421 			th = (struct tcphdr *)(ip6 + 1);
13422 
13423 #ifdef NETFLIX_TCPOUDP
13424 		}
13425 #endif
13426 		tcpip_fillheaders(inp,
13427 #ifdef NETFLIX_TCPOUDP
13428 				  tp->t_port,
13429 #endif
13430 				  ip6, th);
13431 	} else
13432 #endif				/* INET6 */
13433 	{
13434 		ip = mtod(m, struct ip *);
13435 #ifdef TCPDEBUG
13436 		ipov = (struct ipovly *)ip;
13437 #endif
13438 #ifdef NETFLIX_TCPOUDP
13439 		if (tp->t_port) {
13440 			udp = (struct udphdr *)((caddr_t)ip + ipoptlen + sizeof(struct ip));
13441 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13442 			udp->uh_dport = tp->t_port;
13443 			ulen = hdrlen + len - sizeof(struct ip);
13444 			udp->uh_ulen = htons(ulen);
13445 			th = (struct tcphdr *)(udp + 1);
13446 		} else
13447 #endif
13448 			th = (struct tcphdr *)(ip + 1);
13449 		tcpip_fillheaders(inp,
13450 #ifdef NETFLIX_TCPOUDP
13451 				  tp->t_port,
13452 #endif
13453 				  ip, th);
13454 	}
13455 	/*
13456 	 * If we are doing retransmissions, then snd_nxt will not reflect
13457 	 * the first unsent octet.  For ACK only packets, we do not want the
13458 	 * sequence number of the retransmitted packet, we want the sequence
13459 	 * number of the next unsent octet.  So, if there is no data (and no
13460 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
13461 	 * ti_seq.  But if we are in persist state, snd_max might reflect
13462 	 * one byte beyond the right edge of the window, so use snd_nxt in
13463 	 * that case, since we know we aren't doing a retransmission.
13464 	 * (retransmit and persist are mutually exclusive...)
13465 	 */
13466 	if (sack_rxmit == 0) {
13467 		if (len && ((flags & (TH_FIN | TH_SYN | TH_RST)) == 0)) {
13468 			/* New data (including new persists) */
13469 			th->th_seq = htonl(tp->snd_max);
13470 			bbr_seq = tp->snd_max;
13471 		} else if (flags & TH_SYN) {
13472 			/* Syn's always send from iss */
13473 			th->th_seq = htonl(tp->iss);
13474 			bbr_seq = tp->iss;
13475 		} else if (flags & TH_FIN) {
13476 			if (flags & TH_FIN && tp->t_flags & TF_SENTFIN) {
13477 				/*
13478 				 * If we sent the fin already its 1 minus
13479 				 * snd_max
13480 				 */
13481 				th->th_seq = (htonl(tp->snd_max - 1));
13482 				bbr_seq = (tp->snd_max - 1);
13483 			} else {
13484 				/* First time FIN use snd_max */
13485 				th->th_seq = htonl(tp->snd_max);
13486 				bbr_seq = tp->snd_max;
13487 			}
13488 		} else if (flags & TH_RST) {
13489 			/*
13490 			 * For a Reset send the last cum ack in sequence
13491 			 * (this like any other choice may still generate a
13492 			 * challenge ack, if a ack-update packet is in
13493 			 * flight).
13494 			 */
13495 			th->th_seq = htonl(tp->snd_una);
13496 			bbr_seq = tp->snd_una;
13497 		} else {
13498 			/*
13499 			 * len == 0 and not persist we use snd_max, sending
13500 			 * an ack unless we have sent the fin then its 1
13501 			 * minus.
13502 			 */
13503 			/*
13504 			 * XXXRRS Question if we are in persists and we have
13505 			 * nothing outstanding to send and we have not sent
13506 			 * a FIN, we will send an ACK. In such a case it
13507 			 * might be better to send (tp->snd_una - 1) which
13508 			 * would force the peer to ack.
13509 			 */
13510 			if (tp->t_flags & TF_SENTFIN) {
13511 				th->th_seq = htonl(tp->snd_max - 1);
13512 				bbr_seq = (tp->snd_max - 1);
13513 			} else {
13514 				th->th_seq = htonl(tp->snd_max);
13515 				bbr_seq = tp->snd_max;
13516 			}
13517 		}
13518 	} else {
13519 		/* All retransmits use the rsm to guide the send */
13520 		th->th_seq = htonl(rsm->r_start);
13521 		bbr_seq = rsm->r_start;
13522 	}
13523 	th->th_ack = htonl(tp->rcv_nxt);
13524 	if (optlen) {
13525 		bcopy(opt, th + 1, optlen);
13526 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
13527 	}
13528 	th->th_flags = flags;
13529 	/*
13530 	 * Calculate receive window.  Don't shrink window, but avoid silly
13531 	 * window syndrome.
13532 	 */
13533 	if ((flags & TH_RST) || ((recwin < (so->so_rcv.sb_hiwat / 4) &&
13534 				  recwin < maxseg)))
13535 		recwin = 0;
13536 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
13537 	    recwin < (tp->rcv_adv - tp->rcv_nxt))
13538 		recwin = (tp->rcv_adv - tp->rcv_nxt);
13539 	if (recwin > TCP_MAXWIN << tp->rcv_scale)
13540 		recwin = TCP_MAXWIN << tp->rcv_scale;
13541 
13542 	/*
13543 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
13544 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
13545 	 * handled in syncache.
13546 	 */
13547 	if (flags & TH_SYN)
13548 		th->th_win = htons((u_short)
13549 		    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
13550 	else {
13551 		/* Avoid shrinking window with window scaling. */
13552 		recwin = roundup2(recwin, 1 << tp->rcv_scale);
13553 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
13554 	}
13555 	/*
13556 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
13557 	 * window.  This may cause the remote transmitter to stall.  This
13558 	 * flag tells soreceive() to disable delayed acknowledgements when
13559 	 * draining the buffer.  This can occur if the receiver is
13560 	 * attempting to read more data than can be buffered prior to
13561 	 * transmitting on the connection.
13562 	 */
13563 	if (th->th_win == 0) {
13564 		tp->t_sndzerowin++;
13565 		tp->t_flags |= TF_RXWIN0SENT;
13566 	} else
13567 		tp->t_flags &= ~TF_RXWIN0SENT;
13568 	/*
13569 	 * We don't support urgent data, but drag along
13570 	 * the pointer in case of a stack switch.
13571 	 */
13572 	tp->snd_up = tp->snd_una;
13573 
13574 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13575 	if (to.to_flags & TOF_SIGNATURE) {
13576 		/*
13577 		 * Calculate MD5 signature and put it into the place
13578 		 * determined before. NOTE: since TCP options buffer doesn't
13579 		 * point into mbuf's data, calculate offset and use it.
13580 		 */
13581 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
13582 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
13583 			/*
13584 			 * Do not send segment if the calculation of MD5
13585 			 * digest has failed.
13586 			 */
13587 			goto out;
13588 		}
13589 	}
13590 #endif
13591 
13592 	/*
13593 	 * Put TCP length in extended header, and then checksum extended
13594 	 * header and data.
13595 	 */
13596 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
13597 #ifdef INET6
13598 	if (isipv6) {
13599 		/*
13600 		 * ip6_plen is not need to be filled now, and will be filled
13601 		 * in ip6_output.
13602 		 */
13603 #ifdef NETFLIX_TCPOUDP
13604 		if (tp->t_port) {
13605 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
13606 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13607 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
13608 			th->th_sum = htons(0);
13609 			UDPSTAT_INC(udps_opackets);
13610 		} else {
13611 #endif
13612 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
13613 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13614 			th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
13615 			    optlen + len, IPPROTO_TCP, 0);
13616 #ifdef NETFLIX_TCPOUDP
13617 		}
13618 #endif
13619 	}
13620 #endif
13621 #if defined(INET6) && defined(INET)
13622 	else
13623 #endif
13624 #ifdef INET
13625 	{
13626 #ifdef NETFLIX_TCPOUDP
13627 		if (tp->t_port) {
13628 			m->m_pkthdr.csum_flags = CSUM_UDP;
13629 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13630 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
13631 			    ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
13632 			th->th_sum = htons(0);
13633 			UDPSTAT_INC(udps_opackets);
13634 		} else {
13635 #endif
13636 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP;
13637 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13638 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
13639 			    ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
13640 			    IPPROTO_TCP + len + optlen));
13641 #ifdef NETFLIX_TCPOUDP
13642 		}
13643 #endif
13644 		/* IP version must be set here for ipv4/ipv6 checking later */
13645 		KASSERT(ip->ip_v == IPVERSION,
13646 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
13647 	}
13648 #endif
13649 
13650 	/*
13651 	 * Enable TSO and specify the size of the segments. The TCP pseudo
13652 	 * header checksum is always provided. XXX: Fixme: This is currently
13653 	 * not the case for IPv6.
13654 	 */
13655 	if (tso) {
13656 		KASSERT(len > maxseg,
13657 		    ("%s: len:%d <= tso_segsz:%d", __func__, len, maxseg));
13658 		m->m_pkthdr.csum_flags |= CSUM_TSO;
13659 		csum_flags |= CSUM_TSO;
13660 		m->m_pkthdr.tso_segsz = maxseg;
13661 	}
13662 	KASSERT(len + hdrlen == m_length(m, NULL),
13663 	    ("%s: mbuf chain different than expected: %d + %u != %u",
13664 	    __func__, len, hdrlen, m_length(m, NULL)));
13665 
13666 #ifdef TCP_HHOOK
13667 	/* Run HHOOK_TC_ESTABLISHED_OUT helper hooks. */
13668 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
13669 #endif
13670 #ifdef TCPDEBUG
13671 	/*
13672 	 * Trace.
13673 	 */
13674 	if (so->so_options & SO_DEBUG) {
13675 		u_short save = 0;
13676 
13677 #ifdef INET6
13678 		if (!isipv6)
13679 #endif
13680 		{
13681 			save = ipov->ih_len;
13682 			ipov->ih_len = htons(m->m_pkthdr.len	/* - hdrlen +
13683 			      * (th->th_off << 2) */ );
13684 		}
13685 		tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
13686 #ifdef INET6
13687 		if (!isipv6)
13688 #endif
13689 			ipov->ih_len = save;
13690 	}
13691 #endif				/* TCPDEBUG */
13692 
13693 	/* Log to the black box */
13694 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
13695 		union tcp_log_stackspecific log;
13696 
13697 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
13698 		/* Record info on type of transmission */
13699 		log.u_bbr.flex1 = bbr->r_ctl.rc_hptsi_agg_delay;
13700 		log.u_bbr.flex2 = (bbr->r_recovery_bw << 3);
13701 		log.u_bbr.flex3 = maxseg;
13702 		log.u_bbr.flex4 = delay_calc;
13703 		/* Encode filled_all into the upper flex5 bit */
13704 		log.u_bbr.flex5 = bbr->rc_past_init_win;
13705 		log.u_bbr.flex5 <<= 1;
13706 		log.u_bbr.flex5 |= bbr->rc_no_pacing;
13707 		log.u_bbr.flex5 <<= 29;
13708 		if (filled_all)
13709 			log.u_bbr.flex5 |= 0x80000000;
13710 		log.u_bbr.flex5 |= tp->t_maxseg;
13711 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_max_segs;
13712 		log.u_bbr.flex7 = (bbr->rc_bbr_state << 8) | bbr_state_val(bbr);
13713 		/* lets poke in the low and the high here for debugging */
13714 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
13715 		if (rsm || sack_rxmit) {
13716 			if (doing_tlp)
13717 				log.u_bbr.flex8 = 2;
13718 			else
13719 				log.u_bbr.flex8 = 1;
13720 		} else {
13721 			log.u_bbr.flex8 = 0;
13722 		}
13723 		lgb = tcp_log_event_(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
13724 		    len, &log, false, NULL, NULL, 0, tv);
13725 	} else {
13726 		lgb = NULL;
13727 	}
13728 	/*
13729 	 * Fill in IP length and desired time to live and send to IP level.
13730 	 * There should be a better way to handle ttl and tos; we could keep
13731 	 * them in the template, but need a way to checksum without them.
13732 	 */
13733 	/*
13734 	 * m->m_pkthdr.len should have been set before cksum calcuration,
13735 	 * because in6_cksum() need it.
13736 	 */
13737 #ifdef INET6
13738 	if (isipv6) {
13739 		/*
13740 		 * we separately set hoplimit for every segment, since the
13741 		 * user might want to change the value via setsockopt. Also,
13742 		 * desired default hop limit might be changed via Neighbor
13743 		 * Discovery.
13744 		 */
13745 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
13746 
13747 		/*
13748 		 * Set the packet size here for the benefit of DTrace
13749 		 * probes. ip6_output() will set it properly; it's supposed
13750 		 * to include the option header lengths as well.
13751 		 */
13752 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
13753 
13754 		if (V_path_mtu_discovery && maxseg > V_tcp_minmss)
13755 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13756 		else
13757 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13758 
13759 		if (tp->t_state == TCPS_SYN_SENT)
13760 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
13761 
13762 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
13763 		/* TODO: IPv6 IP6TOS_ECT bit on */
13764 		error = ip6_output(m, inp->in6p_outputopts,
13765 		    &inp->inp_route6,
13766 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
13767 		    NULL, NULL, inp);
13768 
13769 		if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
13770 			mtu = inp->inp_route6.ro_nh->nh_mtu;
13771 	}
13772 #endif				/* INET6 */
13773 #if defined(INET) && defined(INET6)
13774 	else
13775 #endif
13776 #ifdef INET
13777 	{
13778 		ip->ip_len = htons(m->m_pkthdr.len);
13779 #ifdef INET6
13780 		if (isipv6)
13781 			ip->ip_ttl = in6_selecthlim(inp, NULL);
13782 #endif				/* INET6 */
13783 		/*
13784 		 * If we do path MTU discovery, then we set DF on every
13785 		 * packet. This might not be the best thing to do according
13786 		 * to RFC3390 Section 2. However the tcp hostcache migitates
13787 		 * the problem so it affects only the first tcp connection
13788 		 * with a host.
13789 		 *
13790 		 * NB: Don't set DF on small MTU/MSS to have a safe
13791 		 * fallback.
13792 		 */
13793 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
13794 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13795 			if (tp->t_port == 0 || len < V_tcp_minmss) {
13796 				ip->ip_off |= htons(IP_DF);
13797 			}
13798 		} else {
13799 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13800 		}
13801 
13802 		if (tp->t_state == TCPS_SYN_SENT)
13803 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
13804 
13805 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
13806 
13807 		error = ip_output(m, inp->inp_options, &inp->inp_route,
13808 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
13809 		    inp);
13810 		if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
13811 			mtu = inp->inp_route.ro_nh->nh_mtu;
13812 	}
13813 #endif				/* INET */
13814 out:
13815 
13816 	if (lgb) {
13817 		lgb->tlb_errno = error;
13818 		lgb = NULL;
13819 	}
13820 	/*
13821 	 * In transmit state, time the transmission and arrange for the
13822 	 * retransmit.  In persist state, just set snd_max.
13823 	 */
13824 	if (error == 0) {
13825 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13826 		    (tp->t_flags & TF_SACK_PERMIT) &&
13827 		    tp->rcv_numsacks > 0)
13828 			tcp_clean_dsack_blocks(tp);
13829 		/* We sent an ack clear the bbr_segs_rcvd count */
13830 		bbr->output_error_seen = 0;
13831 		bbr->oerror_cnt = 0;
13832 		bbr->bbr_segs_rcvd = 0;
13833 		if (len == 0)
13834 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_SNDACK], 1);
13835 		/* Do accounting for new sends */
13836 		if ((len > 0) && (rsm == NULL)) {
13837 			int idx;
13838 			if (tp->snd_una == tp->snd_max) {
13839 				/*
13840 				 * Special case to match google, when
13841 				 * nothing is in flight the delivered
13842 				 * time does get updated to the current
13843 				 * time (see tcp_rate_bsd.c).
13844 				 */
13845 				bbr->r_ctl.rc_del_time = cts;
13846 			}
13847 			if (len >= maxseg) {
13848 				idx = (len / maxseg) + 3;
13849 				if (idx >= TCP_MSS_ACCT_ATIMER)
13850 					counter_u64_add(bbr_out_size[(TCP_MSS_ACCT_ATIMER - 1)], 1);
13851 				else
13852 					counter_u64_add(bbr_out_size[idx], 1);
13853 			} else {
13854 				/* smaller than a MSS */
13855 				idx = len / (bbr_hptsi_bytes_min - bbr->rc_last_options);
13856 				if (idx >= TCP_MSS_SMALL_MAX_SIZE_DIV)
13857 					idx = (TCP_MSS_SMALL_MAX_SIZE_DIV - 1);
13858 				counter_u64_add(bbr_out_size[(idx + TCP_MSS_SMALL_SIZE_OFF)], 1);
13859 			}
13860 		}
13861 	}
13862 	abandon = 0;
13863 	/*
13864 	 * We must do the send accounting before we log the output,
13865 	 * otherwise the state of the rsm could change and we account to the
13866 	 * wrong bucket.
13867 	 */
13868 	if (len > 0) {
13869 		bbr_do_send_accounting(tp, bbr, rsm, len, error);
13870 		if (error == 0) {
13871 			if (tp->snd_una == tp->snd_max)
13872 				bbr->r_ctl.rc_tlp_rxt_last_time = cts;
13873 		}
13874 	}
13875 	bbr_log_output(bbr, tp, &to, len, bbr_seq, (uint8_t) flags, error,
13876 	    cts, mb, &abandon, rsm, 0, sb);
13877 	if (abandon) {
13878 		/*
13879 		 * If bbr_log_output destroys the TCB or sees a TH_RST being
13880 		 * sent we should hit this condition.
13881 		 */
13882 		return (0);
13883 	}
13884 	if (bbr->rc_in_persist == 0) {
13885 		/*
13886 		 * Advance snd_nxt over sequence space of this segment.
13887 		 */
13888 		if (error)
13889 			/* We don't log or do anything with errors */
13890 			goto skip_upd;
13891 
13892 		if (tp->snd_una == tp->snd_max &&
13893 		    (len || (flags & (TH_SYN | TH_FIN)))) {
13894 			/*
13895 			 * Update the time we just added data since none was
13896 			 * outstanding.
13897 			 */
13898 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13899 			bbr->rc_tp->t_acktime  = ticks;
13900 		}
13901 		if (flags & (TH_SYN | TH_FIN) && (rsm == NULL)) {
13902 			if (flags & TH_SYN) {
13903 				/*
13904 				 * Smack the snd_max to iss + 1
13905 				 * if its a FO we will add len below.
13906 				 */
13907 				tp->snd_max = tp->iss + 1;
13908 			}
13909 			if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13910 				tp->snd_max++;
13911 				tp->t_flags |= TF_SENTFIN;
13912 			}
13913 		}
13914 		if (sack_rxmit == 0)
13915 			tp->snd_max += len;
13916 skip_upd:
13917 		if ((error == 0) && len)
13918 			tot_len += len;
13919 	} else {
13920 		/* Persists case */
13921 		int32_t xlen = len;
13922 
13923 		if (error)
13924 			goto nomore;
13925 
13926 		if (flags & TH_SYN)
13927 			++xlen;
13928 		if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13929 			++xlen;
13930 			tp->t_flags |= TF_SENTFIN;
13931 		}
13932 		if (xlen && (tp->snd_una == tp->snd_max)) {
13933 			/*
13934 			 * Update the time we just added data since none was
13935 			 * outstanding.
13936 			 */
13937 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13938 			bbr->rc_tp->t_acktime = ticks;
13939 		}
13940 		if (sack_rxmit == 0)
13941 			tp->snd_max += xlen;
13942 		tot_len += (len + optlen + ipoptlen);
13943 	}
13944 nomore:
13945 	if (error) {
13946 		/*
13947 		 * Failures do not advance the seq counter above. For the
13948 		 * case of ENOBUFS we will fall out and become ack-clocked.
13949 		 * capping the cwnd at the current flight.
13950 		 * Everything else will just have to retransmit with the timer
13951 		 * (no pacer).
13952 		 */
13953 		SOCKBUF_UNLOCK_ASSERT(sb);
13954 		BBR_STAT_INC(bbr_saw_oerr);
13955 		/* Clear all delay/early tracks */
13956 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
13957 		bbr->r_ctl.rc_agg_early = 0;
13958 		bbr->r_agg_early_set = 0;
13959 		bbr->output_error_seen = 1;
13960 		if (bbr->oerror_cnt < 0xf)
13961 			bbr->oerror_cnt++;
13962 		if (bbr_max_net_error_cnt && (bbr->oerror_cnt >= bbr_max_net_error_cnt)) {
13963 			/* drop the session */
13964 			tcp_set_inp_to_drop(inp, ENETDOWN);
13965 		}
13966 		switch (error) {
13967 		case ENOBUFS:
13968 			/*
13969 			 * Make this guy have to get ack's to send
13970 			 * more but lets make sure we don't
13971 			 * slam him below a T-O (1MSS).
13972 			 */
13973 			if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
13974 				tp->snd_cwnd = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13975 								    bbr->r_ctl.rc_lost_bytes)) - maxseg;
13976 				if (tp->snd_cwnd < maxseg)
13977 					tp->snd_cwnd = maxseg;
13978 			}
13979 			slot = (bbr_error_base_paceout + 1) << bbr->oerror_cnt;
13980 			BBR_STAT_INC(bbr_saw_enobuf);
13981 			if (bbr->bbr_hdrw_pacing)
13982 				counter_u64_add(bbr_hdwr_pacing_enobuf, 1);
13983 			else
13984 				counter_u64_add(bbr_nohdwr_pacing_enobuf, 1);
13985 			/*
13986 			 * Here even in the enobuf's case we want to do our
13987 			 * state update. The reason being we may have been
13988 			 * called by the input function. If so we have had
13989 			 * things change.
13990 			 */
13991 			error = 0;
13992 			goto enobufs;
13993 		case EMSGSIZE:
13994 			/*
13995 			 * For some reason the interface we used initially
13996 			 * to send segments changed to another or lowered
13997 			 * its MTU. If TSO was active we either got an
13998 			 * interface without TSO capabilits or TSO was
13999 			 * turned off. If we obtained mtu from ip_output()
14000 			 * then update it and try again.
14001 			 */
14002 			/* Turn on tracing (or try to) */
14003 			{
14004 				int old_maxseg;
14005 
14006 				old_maxseg = tp->t_maxseg;
14007 				BBR_STAT_INC(bbr_saw_emsgsiz);
14008 				bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, csum_flags, tso, cts);
14009 				if (mtu != 0)
14010 					tcp_mss_update(tp, -1, mtu, NULL, NULL);
14011 				if (old_maxseg <= tp->t_maxseg) {
14012 					/* Huh it did not shrink? */
14013 					tp->t_maxseg = old_maxseg - 40;
14014 					bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
14015 				}
14016 				/*
14017 				 * Nuke all other things that can interfere
14018 				 * with slot
14019 				 */
14020 				if ((tot_len + len) && (len >= tp->t_maxseg)) {
14021 					slot = bbr_get_pacing_delay(bbr,
14022 					    bbr->r_ctl.rc_bbr_hptsi_gain,
14023 					    (tot_len + len), cts, 0);
14024 					if (slot < bbr_error_base_paceout)
14025 						slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
14026 				} else
14027 					slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
14028 				bbr->rc_output_starts_timer = 1;
14029 				bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
14030 				    tot_len);
14031 				return (error);
14032 			}
14033 		case EPERM:
14034 			tp->t_softerror = error;
14035 			/* Fall through */
14036 		case EHOSTDOWN:
14037 		case EHOSTUNREACH:
14038 		case ENETDOWN:
14039 		case ENETUNREACH:
14040 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
14041 				tp->t_softerror = error;
14042 			}
14043 			/* FALLTHROUGH */
14044 		default:
14045 			slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
14046 			bbr->rc_output_starts_timer = 1;
14047 			bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
14048 			return (error);
14049 		}
14050 #ifdef STATS
14051 	} else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
14052 		    len &&
14053 		    (rsm == NULL) &&
14054 	    (bbr->rc_in_persist == 0)) {
14055 		tp->gput_seq = bbr_seq;
14056 		tp->gput_ack = bbr_seq +
14057 		    min(sbavail(&so->so_snd) - sb_offset, sendwin);
14058 		tp->gput_ts = cts;
14059 		tp->t_flags |= TF_GPUTINPROG;
14060 #endif
14061 	}
14062 	KMOD_TCPSTAT_INC(tcps_sndtotal);
14063 	if ((bbr->bbr_hdw_pace_ena) &&
14064 	    (bbr->bbr_attempt_hdwr_pace == 0) &&
14065 	    (bbr->rc_past_init_win) &&
14066 	    (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
14067 	    (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
14068 	    (inp->inp_route.ro_nh &&
14069 	     inp->inp_route.ro_nh->nh_ifp)) {
14070 		/*
14071 		 * We are past the initial window and
14072 		 * have at least one measurement so we
14073 		 * could use hardware pacing if its available.
14074 		 * We have an interface and we have not attempted
14075 		 * to setup hardware pacing, lets try to now.
14076 		 */
14077 		uint64_t rate_wanted;
14078 		int err = 0;
14079 
14080 		rate_wanted = bbr_get_hardware_rate(bbr);
14081 		bbr->bbr_attempt_hdwr_pace = 1;
14082 		bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp,
14083 						      inp->inp_route.ro_nh->nh_ifp,
14084 						      rate_wanted,
14085 						      (RS_PACING_GEQ|RS_PACING_SUB_OK),
14086 						      &err, NULL);
14087 		if (bbr->r_ctl.crte) {
14088 			bbr_type_log_hdwr_pacing(bbr,
14089 						 bbr->r_ctl.crte->ptbl->rs_ifp,
14090 						 rate_wanted,
14091 						 bbr->r_ctl.crte->rate,
14092 						 __LINE__, cts, err);
14093 			BBR_STAT_INC(bbr_hdwr_rl_add_ok);
14094 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
14095 			counter_u64_add(bbr_flows_whdwr_pacing, 1);
14096 			bbr->bbr_hdrw_pacing = 1;
14097 			/* Now what is our gain status? */
14098 			if (bbr->r_ctl.crte->rate < rate_wanted) {
14099 				/* We have a problem */
14100 				bbr_setup_less_of_rate(bbr, cts,
14101 						       bbr->r_ctl.crte->rate, rate_wanted);
14102 			} else {
14103 				/* We are good */
14104 				bbr->gain_is_limited = 0;
14105 				bbr->skip_gain = 0;
14106 			}
14107 			tcp_bbr_tso_size_check(bbr, cts);
14108 		} else {
14109 			bbr_type_log_hdwr_pacing(bbr,
14110 						 inp->inp_route.ro_nh->nh_ifp,
14111 						 rate_wanted,
14112 						 0,
14113 						 __LINE__, cts, err);
14114 			BBR_STAT_INC(bbr_hdwr_rl_add_fail);
14115 		}
14116 	}
14117 	if (bbr->bbr_hdrw_pacing) {
14118 		/*
14119 		 * Worry about cases where the route
14120 		 * changes or something happened that we
14121 		 * lost our hardware pacing possibly during
14122 		 * the last ip_output call.
14123 		 */
14124 		if (inp->inp_snd_tag == NULL) {
14125 			/* A change during ip output disabled hw pacing? */
14126 			bbr->bbr_hdrw_pacing = 0;
14127 		} else if ((inp->inp_route.ro_nh == NULL) ||
14128 		    (inp->inp_route.ro_nh->nh_ifp != inp->inp_snd_tag->ifp)) {
14129 			/*
14130 			 * We had an interface or route change,
14131 			 * detach from the current hdwr pacing
14132 			 * and setup to re-attempt next go
14133 			 * round.
14134 			 */
14135 			bbr->bbr_hdrw_pacing = 0;
14136 			bbr->bbr_attempt_hdwr_pace = 0;
14137 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
14138 			tcp_bbr_tso_size_check(bbr, cts);
14139 		}
14140 	}
14141 	/*
14142 	 * Data sent (as far as we can tell). If this advertises a larger
14143 	 * window than any other segment, then remember the size of the
14144 	 * advertised window. Any pending ACK has now been sent.
14145 	 */
14146 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
14147 		tp->rcv_adv = tp->rcv_nxt + recwin;
14148 
14149 	tp->last_ack_sent = tp->rcv_nxt;
14150 	if ((error == 0) &&
14151 	    (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
14152 	    (doing_tlp == 0) &&
14153 	    (tso == 0) &&
14154 	    (len > 0) &&
14155 	    ((flags & TH_RST) == 0) &&
14156 	    ((flags & TH_SYN) == 0) &&
14157 	    (IN_RECOVERY(tp->t_flags) == 0) &&
14158 	    (bbr->rc_in_persist == 0) &&
14159 	    (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
14160 		/*
14161 		 * For non-tso we need to goto again until we have sent out
14162 		 * enough data to match what we are hptsi out every hptsi
14163 		 * interval.
14164 		 */
14165 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14166 			/* Make sure snd_nxt is drug up */
14167 			tp->snd_nxt = tp->snd_max;
14168 		}
14169 		if (rsm != NULL) {
14170 			rsm = NULL;
14171 			goto skip_again;
14172 		}
14173 		rsm = NULL;
14174 		sack_rxmit = 0;
14175 		tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
14176 		goto again;
14177 	}
14178 skip_again:
14179 	if ((error == 0) && (flags & TH_FIN))
14180 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
14181 	if ((error == 0) && (flags & TH_RST))
14182 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
14183 	if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
14184 		/*
14185 		 * Calculate/Re-Calculate the hptsi slot in usecs based on
14186 		 * what we have sent so far
14187 		 */
14188 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
14189 		if (bbr->rc_no_pacing)
14190 			slot = 0;
14191 	}
14192 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
14193 enobufs:
14194 	if (bbr->rc_use_google == 0)
14195 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
14196 	bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
14197 							bbr->r_ctl.rc_lost_bytes)));
14198 	bbr->rc_output_starts_timer = 1;
14199 	if (bbr->bbr_use_rack_cheat &&
14200 	    (more_to_rxt ||
14201 	     ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
14202 		/* Rack cheats and shotguns out all rxt's 1ms apart */
14203 		if (slot > 1000)
14204 			slot = 1000;
14205 	}
14206 	if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
14207 		/*
14208 		 * We don't change the tso size until some number of sends
14209 		 * to give the hardware commands time to get down
14210 		 * to the interface.
14211 		 */
14212 		bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
14213 		if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
14214 			bbr->hw_pacing_set = 1;
14215 			tcp_bbr_tso_size_check(bbr, cts);
14216 		}
14217 	}
14218 	bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
14219 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14220 		/* Make sure snd_nxt is drug up */
14221 		tp->snd_nxt = tp->snd_max;
14222 	}
14223 	return (error);
14224 
14225 }
14226 
14227 /*
14228  * See bbr_output_wtime() for return values.
14229  */
14230 static int
14231 bbr_output(struct tcpcb *tp)
14232 {
14233 	int32_t ret;
14234 	struct timeval tv;
14235 	struct tcp_bbr *bbr;
14236 
14237 	NET_EPOCH_ASSERT();
14238 
14239 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14240 	INP_WLOCK_ASSERT(tp->t_inpcb);
14241 	(void)tcp_get_usecs(&tv);
14242 	ret = bbr_output_wtime(tp, &tv);
14243 	return (ret);
14244 }
14245 
14246 static void
14247 bbr_mtu_chg(struct tcpcb *tp)
14248 {
14249 	struct tcp_bbr *bbr;
14250 	struct bbr_sendmap *rsm, *frsm = NULL;
14251 	uint32_t maxseg;
14252 
14253 	/*
14254 	 * The MTU has changed. a) Clear the sack filter. b) Mark everything
14255 	 * over the current size as SACK_PASS so a retransmit will occur.
14256 	 */
14257 
14258 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14259 	maxseg = tp->t_maxseg - bbr->rc_last_options;
14260 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14261 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14262 		/* Don't mess with ones acked (by sack?) */
14263 		if (rsm->r_flags & BBR_ACKED)
14264 			continue;
14265 		if ((rsm->r_end - rsm->r_start) > maxseg) {
14266 			/*
14267 			 * We mark sack-passed on all the previous large
14268 			 * sends we did. This will force them to retransmit.
14269 			 */
14270 			rsm->r_flags |= BBR_SACK_PASSED;
14271 			if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14272 			    bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14273 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14274 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14275 				rsm->r_flags |= BBR_MARKED_LOST;
14276 			}
14277 			if (frsm == NULL)
14278 				frsm = rsm;
14279 		}
14280 	}
14281 	if (frsm) {
14282 		bbr->r_ctl.rc_resend = frsm;
14283 	}
14284 }
14285 
14286 /*
14287  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14288  * socket option arguments.  When it re-acquires the lock after the copy, it
14289  * has to revalidate that the connection is still valid for the socket
14290  * option.
14291  */
14292 static int
14293 bbr_set_sockopt(struct socket *so, struct sockopt *sopt,
14294 		struct inpcb *inp, struct tcpcb *tp, struct tcp_bbr *bbr)
14295 {
14296 	struct epoch_tracker et;
14297 	int32_t error = 0, optval;
14298 
14299 	switch (sopt->sopt_name) {
14300 	case TCP_RACK_PACE_MAX_SEG:
14301 	case TCP_RACK_MIN_TO:
14302 	case TCP_RACK_REORD_THRESH:
14303 	case TCP_RACK_REORD_FADE:
14304 	case TCP_RACK_TLP_THRESH:
14305 	case TCP_RACK_PKT_DELAY:
14306 	case TCP_BBR_ALGORITHM:
14307 	case TCP_BBR_TSLIMITS:
14308 	case TCP_BBR_IWINTSO:
14309 	case TCP_BBR_RECFORCE:
14310 	case TCP_BBR_STARTUP_PG:
14311 	case TCP_BBR_DRAIN_PG:
14312 	case TCP_BBR_RWND_IS_APP:
14313 	case TCP_BBR_PROBE_RTT_INT:
14314 	case TCP_BBR_PROBE_RTT_GAIN:
14315 	case TCP_BBR_PROBE_RTT_LEN:
14316 	case TCP_BBR_STARTUP_LOSS_EXIT:
14317 	case TCP_BBR_USEDEL_RATE:
14318 	case TCP_BBR_MIN_RTO:
14319 	case TCP_BBR_MAX_RTO:
14320 	case TCP_BBR_PACE_PER_SEC:
14321 	case TCP_DELACK:
14322 	case TCP_BBR_PACE_DEL_TAR:
14323 	case TCP_BBR_SEND_IWND_IN_TSO:
14324 	case TCP_BBR_EXTRA_STATE:
14325 	case TCP_BBR_UTTER_MAX_TSO:
14326 	case TCP_BBR_MIN_TOPACEOUT:
14327 	case TCP_BBR_FLOOR_MIN_TSO:
14328 	case TCP_BBR_TSTMP_RAISES:
14329 	case TCP_BBR_POLICER_DETECT:
14330 	case TCP_BBR_USE_RACK_CHEAT:
14331 	case TCP_DATA_AFTER_CLOSE:
14332 	case TCP_BBR_HDWR_PACE:
14333 	case TCP_BBR_PACE_SEG_MAX:
14334 	case TCP_BBR_PACE_SEG_MIN:
14335 	case TCP_BBR_PACE_CROSS:
14336 	case TCP_BBR_PACE_OH:
14337 #ifdef NETFLIX_PEAKRATE
14338 	case TCP_MAXPEAKRATE:
14339 #endif
14340 	case TCP_BBR_TMR_PACE_OH:
14341 	case TCP_BBR_RACK_RTT_USE:
14342 	case TCP_BBR_RETRAN_WTSO:
14343 		break;
14344 	default:
14345 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14346 		break;
14347 	}
14348 	INP_WUNLOCK(inp);
14349 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14350 	if (error)
14351 		return (error);
14352 	INP_WLOCK(inp);
14353 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
14354 		INP_WUNLOCK(inp);
14355 		return (ECONNRESET);
14356 	}
14357 	tp = intotcpcb(inp);
14358 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14359 	switch (sopt->sopt_name) {
14360 	case TCP_BBR_PACE_PER_SEC:
14361 		BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14362 		bbr->r_ctl.bbr_hptsi_per_second = optval;
14363 		break;
14364 	case TCP_BBR_PACE_DEL_TAR:
14365 		BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14366 		bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14367 		break;
14368 	case TCP_BBR_PACE_SEG_MAX:
14369 		BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14370 		bbr->r_ctl.bbr_hptsi_segments_max = optval;
14371 		break;
14372 	case TCP_BBR_PACE_SEG_MIN:
14373 		BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14374 		bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14375 		break;
14376 	case TCP_BBR_PACE_CROSS:
14377 		BBR_OPTS_INC(tcp_bbr_pace_cross);
14378 		bbr->r_ctl.bbr_cross_over = optval;
14379 		break;
14380 	case TCP_BBR_ALGORITHM:
14381 		BBR_OPTS_INC(tcp_bbr_algorithm);
14382 		if (optval && (bbr->rc_use_google == 0)) {
14383 			/* Turn on the google mode */
14384 			bbr_google_mode_on(bbr);
14385 			if ((optval > 3) && (optval < 500)) {
14386 				/*
14387 				 * Must be at least greater than .3%
14388 				 * and must be less than 50.0%.
14389 				 */
14390 				bbr->r_ctl.bbr_google_discount = optval;
14391 			}
14392 		} else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14393 			/* Turn off the google mode */
14394 			bbr_google_mode_off(bbr);
14395 		}
14396 		break;
14397 	case TCP_BBR_TSLIMITS:
14398 		BBR_OPTS_INC(tcp_bbr_tslimits);
14399 		if (optval == 1)
14400 			bbr->rc_use_ts_limit = 1;
14401 		else if (optval == 0)
14402 			bbr->rc_use_ts_limit = 0;
14403 		else
14404 			error = EINVAL;
14405 		break;
14406 
14407 	case TCP_BBR_IWINTSO:
14408 		BBR_OPTS_INC(tcp_bbr_iwintso);
14409 		if ((optval >= 0) && (optval < 128)) {
14410 			uint32_t twin;
14411 
14412 			bbr->rc_init_win = optval;
14413 			twin = bbr_initial_cwnd(bbr, tp);
14414 			if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14415 				tp->snd_cwnd = twin;
14416 			else
14417 				error = EBUSY;
14418 		} else
14419 			error = EINVAL;
14420 		break;
14421 	case TCP_BBR_STARTUP_PG:
14422 		BBR_OPTS_INC(tcp_bbr_startup_pg);
14423 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14424 			bbr->r_ctl.rc_startup_pg = optval;
14425 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14426 				bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14427 			}
14428 		} else
14429 			error = EINVAL;
14430 		break;
14431 	case TCP_BBR_DRAIN_PG:
14432 		BBR_OPTS_INC(tcp_bbr_drain_pg);
14433 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14434 			bbr->r_ctl.rc_drain_pg = optval;
14435 		else
14436 			error = EINVAL;
14437 		break;
14438 	case TCP_BBR_PROBE_RTT_LEN:
14439 		BBR_OPTS_INC(tcp_bbr_probertt_len);
14440 		if (optval <= 1)
14441 			reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14442 		else
14443 			error = EINVAL;
14444 		break;
14445 	case TCP_BBR_PROBE_RTT_GAIN:
14446 		BBR_OPTS_INC(tcp_bbr_probertt_gain);
14447 		if (optval <= BBR_UNIT)
14448 			bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14449 		else
14450 			error = EINVAL;
14451 		break;
14452 	case TCP_BBR_PROBE_RTT_INT:
14453 		BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14454 		if (optval > 1000)
14455 			bbr->r_ctl.rc_probertt_int = optval;
14456 		else
14457 			error = EINVAL;
14458 		break;
14459 	case TCP_BBR_MIN_TOPACEOUT:
14460 		BBR_OPTS_INC(tcp_bbr_topaceout);
14461 		if (optval == 0) {
14462 			bbr->no_pacing_until = 0;
14463 			bbr->rc_no_pacing = 0;
14464 		} else if (optval <= 0x00ff) {
14465 			bbr->no_pacing_until = optval;
14466 			if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14467 			    (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14468 				/* Turn on no pacing */
14469 				bbr->rc_no_pacing = 1;
14470 			}
14471 		} else
14472 			error = EINVAL;
14473 		break;
14474 	case TCP_BBR_STARTUP_LOSS_EXIT:
14475 		BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14476 		bbr->rc_loss_exit = optval;
14477 		break;
14478 	case TCP_BBR_USEDEL_RATE:
14479 		error = EINVAL;
14480 		break;
14481 	case TCP_BBR_MIN_RTO:
14482 		BBR_OPTS_INC(tcp_bbr_min_rto);
14483 		bbr->r_ctl.rc_min_rto_ms = optval;
14484 		break;
14485 	case TCP_BBR_MAX_RTO:
14486 		BBR_OPTS_INC(tcp_bbr_max_rto);
14487 		bbr->rc_max_rto_sec = optval;
14488 		break;
14489 	case TCP_RACK_MIN_TO:
14490 		/* Minimum time between rack t-o's in ms */
14491 		BBR_OPTS_INC(tcp_rack_min_to);
14492 		bbr->r_ctl.rc_min_to = optval;
14493 		break;
14494 	case TCP_RACK_REORD_THRESH:
14495 		/* RACK reorder threshold (shift amount) */
14496 		BBR_OPTS_INC(tcp_rack_reord_thresh);
14497 		if ((optval > 0) && (optval < 31))
14498 			bbr->r_ctl.rc_reorder_shift = optval;
14499 		else
14500 			error = EINVAL;
14501 		break;
14502 	case TCP_RACK_REORD_FADE:
14503 		/* Does reordering fade after ms time */
14504 		BBR_OPTS_INC(tcp_rack_reord_fade);
14505 		bbr->r_ctl.rc_reorder_fade = optval;
14506 		break;
14507 	case TCP_RACK_TLP_THRESH:
14508 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14509 		BBR_OPTS_INC(tcp_rack_tlp_thresh);
14510 		if (optval)
14511 			bbr->rc_tlp_threshold = optval;
14512 		else
14513 			error = EINVAL;
14514 		break;
14515 	case TCP_BBR_USE_RACK_CHEAT:
14516 		BBR_OPTS_INC(tcp_use_rackcheat);
14517 		if (bbr->rc_use_google) {
14518 			error = EINVAL;
14519 			break;
14520 		}
14521 		BBR_OPTS_INC(tcp_rack_cheat);
14522 		if (optval)
14523 			bbr->bbr_use_rack_cheat = 1;
14524 		else
14525 			bbr->bbr_use_rack_cheat = 0;
14526 		break;
14527 	case TCP_BBR_FLOOR_MIN_TSO:
14528 		BBR_OPTS_INC(tcp_utter_max_tso);
14529 		if ((optval >= 0) && (optval < 40))
14530 			bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14531 		else
14532 			error = EINVAL;
14533 		break;
14534 	case TCP_BBR_UTTER_MAX_TSO:
14535 		BBR_OPTS_INC(tcp_utter_max_tso);
14536 		if ((optval >= 0) && (optval < 0xffff))
14537 			bbr->r_ctl.bbr_utter_max = optval;
14538 		else
14539 			error = EINVAL;
14540 		break;
14541 
14542 	case TCP_BBR_EXTRA_STATE:
14543 		BBR_OPTS_INC(tcp_extra_state);
14544 		if (optval)
14545 			bbr->rc_use_idle_restart = 1;
14546 		else
14547 			bbr->rc_use_idle_restart = 0;
14548 		break;
14549 	case TCP_BBR_SEND_IWND_IN_TSO:
14550 		BBR_OPTS_INC(tcp_iwnd_tso);
14551 		if (optval) {
14552 			bbr->bbr_init_win_cheat = 1;
14553 			if (bbr->rc_past_init_win == 0) {
14554 				uint32_t cts;
14555 				cts = tcp_get_usecs(&bbr->rc_tv);
14556 				tcp_bbr_tso_size_check(bbr, cts);
14557 			}
14558 		} else
14559 			bbr->bbr_init_win_cheat = 0;
14560 		break;
14561 	case TCP_BBR_HDWR_PACE:
14562 		BBR_OPTS_INC(tcp_hdwr_pacing);
14563 		if (optval){
14564 			bbr->bbr_hdw_pace_ena = 1;
14565 			bbr->bbr_attempt_hdwr_pace = 0;
14566 		} else {
14567 			bbr->bbr_hdw_pace_ena = 0;
14568 #ifdef RATELIMIT
14569 			if (bbr->bbr_hdrw_pacing) {
14570 				bbr->bbr_hdrw_pacing = 0;
14571 				in_pcbdetach_txrtlmt(bbr->rc_inp);
14572 			}
14573 #endif
14574 		}
14575 		break;
14576 
14577 	case TCP_DELACK:
14578 		BBR_OPTS_INC(tcp_delack);
14579 		if (optval < 100) {
14580 			if (optval == 0) /* off */
14581 				tp->t_delayed_ack = 0;
14582 			else if (optval == 1) /* on which is 2 */
14583 				tp->t_delayed_ack = 2;
14584 			else /* higher than 2 and less than 100 */
14585 				tp->t_delayed_ack = optval;
14586 			if (tp->t_flags & TF_DELACK) {
14587 				tp->t_flags &= ~TF_DELACK;
14588 				tp->t_flags |= TF_ACKNOW;
14589 				NET_EPOCH_ENTER(et);
14590 				bbr_output(tp);
14591 				NET_EPOCH_EXIT(et);
14592 			}
14593 		} else
14594 			error = EINVAL;
14595 		break;
14596 	case TCP_RACK_PKT_DELAY:
14597 		/* RACK added ms i.e. rack-rtt + reord + N */
14598 		BBR_OPTS_INC(tcp_rack_pkt_delay);
14599 		bbr->r_ctl.rc_pkt_delay = optval;
14600 		break;
14601 #ifdef NETFLIX_PEAKRATE
14602 	case TCP_MAXPEAKRATE:
14603 		BBR_OPTS_INC(tcp_maxpeak);
14604 		error = tcp_set_maxpeakrate(tp, optval);
14605 		if (!error)
14606 			tp->t_peakrate_thr = tp->t_maxpeakrate;
14607 		break;
14608 #endif
14609 	case TCP_BBR_RETRAN_WTSO:
14610 		BBR_OPTS_INC(tcp_retran_wtso);
14611 		if (optval)
14612 			bbr->rc_resends_use_tso = 1;
14613 		else
14614 			bbr->rc_resends_use_tso = 0;
14615 		break;
14616 	case TCP_DATA_AFTER_CLOSE:
14617 		BBR_OPTS_INC(tcp_data_ac);
14618 		if (optval)
14619 			bbr->rc_allow_data_af_clo = 1;
14620 		else
14621 			bbr->rc_allow_data_af_clo = 0;
14622 		break;
14623 	case TCP_BBR_POLICER_DETECT:
14624 		BBR_OPTS_INC(tcp_policer_det);
14625 		if (bbr->rc_use_google == 0)
14626 			error = EINVAL;
14627 		else if (optval)
14628 			bbr->r_use_policer = 1;
14629 		else
14630 			bbr->r_use_policer = 0;
14631 		break;
14632 
14633 	case TCP_BBR_TSTMP_RAISES:
14634 		BBR_OPTS_INC(tcp_ts_raises);
14635 		if (optval)
14636 			bbr->ts_can_raise = 1;
14637 		else
14638 			bbr->ts_can_raise = 0;
14639 		break;
14640 	case TCP_BBR_TMR_PACE_OH:
14641 		BBR_OPTS_INC(tcp_pacing_oh_tmr);
14642 		if (bbr->rc_use_google) {
14643 			error = EINVAL;
14644 		} else {
14645 			if (optval)
14646 				bbr->r_ctl.rc_incr_tmrs = 1;
14647 			else
14648 				bbr->r_ctl.rc_incr_tmrs = 0;
14649 		}
14650 		break;
14651 	case TCP_BBR_PACE_OH:
14652 		BBR_OPTS_INC(tcp_pacing_oh);
14653 		if (bbr->rc_use_google) {
14654 			error = EINVAL;
14655 		} else {
14656 			if (optval > (BBR_INCL_TCP_OH|
14657 				      BBR_INCL_IP_OH|
14658 				      BBR_INCL_ENET_OH)) {
14659 				error = EINVAL;
14660 				break;
14661 			}
14662 			if (optval & BBR_INCL_TCP_OH)
14663 				bbr->r_ctl.rc_inc_tcp_oh = 1;
14664 			else
14665 				bbr->r_ctl.rc_inc_tcp_oh = 0;
14666 			if (optval & BBR_INCL_IP_OH)
14667 				bbr->r_ctl.rc_inc_ip_oh = 1;
14668 			else
14669 				bbr->r_ctl.rc_inc_ip_oh = 0;
14670 			if (optval & BBR_INCL_ENET_OH)
14671 				bbr->r_ctl.rc_inc_enet_oh = 1;
14672 			else
14673 				bbr->r_ctl.rc_inc_enet_oh = 0;
14674 		}
14675 		break;
14676 	default:
14677 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14678 		break;
14679 	}
14680 #ifdef NETFLIX_STATS
14681 	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14682 #endif
14683 	INP_WUNLOCK(inp);
14684 	return (error);
14685 }
14686 
14687 /*
14688  * return 0 on success, error-num on failure
14689  */
14690 static int
14691 bbr_get_sockopt(struct socket *so, struct sockopt *sopt,
14692     struct inpcb *inp, struct tcpcb *tp, struct tcp_bbr *bbr)
14693 {
14694 	int32_t error, optval;
14695 
14696 	/*
14697 	 * Because all our options are either boolean or an int, we can just
14698 	 * pull everything into optval and then unlock and copy. If we ever
14699 	 * add a option that is not a int, then this will have quite an
14700 	 * impact to this routine.
14701 	 */
14702 	switch (sopt->sopt_name) {
14703 	case TCP_BBR_PACE_PER_SEC:
14704 		optval = bbr->r_ctl.bbr_hptsi_per_second;
14705 		break;
14706 	case TCP_BBR_PACE_DEL_TAR:
14707 		optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14708 		break;
14709 	case TCP_BBR_PACE_SEG_MAX:
14710 		optval = bbr->r_ctl.bbr_hptsi_segments_max;
14711 		break;
14712 	case TCP_BBR_MIN_TOPACEOUT:
14713 		optval = bbr->no_pacing_until;
14714 		break;
14715 	case TCP_BBR_PACE_SEG_MIN:
14716 		optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14717 		break;
14718 	case TCP_BBR_PACE_CROSS:
14719 		optval = bbr->r_ctl.bbr_cross_over;
14720 		break;
14721 	case TCP_BBR_ALGORITHM:
14722 		optval = bbr->rc_use_google;
14723 		break;
14724 	case TCP_BBR_TSLIMITS:
14725 		optval = bbr->rc_use_ts_limit;
14726 		break;
14727 	case TCP_BBR_IWINTSO:
14728 		optval = bbr->rc_init_win;
14729 		break;
14730 	case TCP_BBR_STARTUP_PG:
14731 		optval = bbr->r_ctl.rc_startup_pg;
14732 		break;
14733 	case TCP_BBR_DRAIN_PG:
14734 		optval = bbr->r_ctl.rc_drain_pg;
14735 		break;
14736 	case TCP_BBR_PROBE_RTT_INT:
14737 		optval = bbr->r_ctl.rc_probertt_int;
14738 		break;
14739 	case TCP_BBR_PROBE_RTT_LEN:
14740 		optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14741 		break;
14742 	case TCP_BBR_PROBE_RTT_GAIN:
14743 		optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14744 		break;
14745 	case TCP_BBR_STARTUP_LOSS_EXIT:
14746 		optval = bbr->rc_loss_exit;
14747 		break;
14748 	case TCP_BBR_USEDEL_RATE:
14749 		error = EINVAL;
14750 		break;
14751 	case TCP_BBR_MIN_RTO:
14752 		optval = bbr->r_ctl.rc_min_rto_ms;
14753 		break;
14754 	case TCP_BBR_MAX_RTO:
14755 		optval = bbr->rc_max_rto_sec;
14756 		break;
14757 	case TCP_RACK_PACE_MAX_SEG:
14758 		/* Max segments in a pace */
14759 		optval = bbr->r_ctl.rc_pace_max_segs;
14760 		break;
14761 	case TCP_RACK_MIN_TO:
14762 		/* Minimum time between rack t-o's in ms */
14763 		optval = bbr->r_ctl.rc_min_to;
14764 		break;
14765 	case TCP_RACK_REORD_THRESH:
14766 		/* RACK reorder threshold (shift amount) */
14767 		optval = bbr->r_ctl.rc_reorder_shift;
14768 		break;
14769 	case TCP_RACK_REORD_FADE:
14770 		/* Does reordering fade after ms time */
14771 		optval = bbr->r_ctl.rc_reorder_fade;
14772 		break;
14773 	case TCP_BBR_USE_RACK_CHEAT:
14774 		/* Do we use the rack cheat for rxt */
14775 		optval = bbr->bbr_use_rack_cheat;
14776 		break;
14777 	case TCP_BBR_FLOOR_MIN_TSO:
14778 		optval = bbr->r_ctl.bbr_hptsi_segments_floor;
14779 		break;
14780 	case TCP_BBR_UTTER_MAX_TSO:
14781 		optval = bbr->r_ctl.bbr_utter_max;
14782 		break;
14783 	case TCP_BBR_SEND_IWND_IN_TSO:
14784 		/* Do we send TSO size segments initially */
14785 		optval = bbr->bbr_init_win_cheat;
14786 		break;
14787 	case TCP_BBR_EXTRA_STATE:
14788 		optval = bbr->rc_use_idle_restart;
14789 		break;
14790 	case TCP_RACK_TLP_THRESH:
14791 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14792 		optval = bbr->rc_tlp_threshold;
14793 		break;
14794 	case TCP_RACK_PKT_DELAY:
14795 		/* RACK added ms i.e. rack-rtt + reord + N */
14796 		optval = bbr->r_ctl.rc_pkt_delay;
14797 		break;
14798 	case TCP_BBR_RETRAN_WTSO:
14799 		optval = bbr->rc_resends_use_tso;
14800 		break;
14801 	case TCP_DATA_AFTER_CLOSE:
14802 		optval = bbr->rc_allow_data_af_clo;
14803 		break;
14804 	case TCP_DELACK:
14805 		optval = tp->t_delayed_ack;
14806 		break;
14807 	case TCP_BBR_HDWR_PACE:
14808 		optval = bbr->bbr_hdw_pace_ena;
14809 		break;
14810 	case TCP_BBR_POLICER_DETECT:
14811 		optval = bbr->r_use_policer;
14812 		break;
14813 	case TCP_BBR_TSTMP_RAISES:
14814 		optval = bbr->ts_can_raise;
14815 		break;
14816 	case TCP_BBR_TMR_PACE_OH:
14817 		optval = bbr->r_ctl.rc_incr_tmrs;
14818 		break;
14819 	case TCP_BBR_PACE_OH:
14820 		optval = 0;
14821 		if (bbr->r_ctl.rc_inc_tcp_oh)
14822 			optval |= BBR_INCL_TCP_OH;
14823 		if (bbr->r_ctl.rc_inc_ip_oh)
14824 			optval |= BBR_INCL_IP_OH;
14825 		if (bbr->r_ctl.rc_inc_enet_oh)
14826 			optval |= BBR_INCL_ENET_OH;
14827 		break;
14828 	default:
14829 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14830 		break;
14831 	}
14832 	INP_WUNLOCK(inp);
14833 	error = sooptcopyout(sopt, &optval, sizeof optval);
14834 	return (error);
14835 }
14836 
14837 /*
14838  * return 0 on success, error-num on failure
14839  */
14840 static int
14841 bbr_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp, struct tcpcb *tp)
14842 {
14843 	int32_t error = EINVAL;
14844 	struct tcp_bbr *bbr;
14845 
14846 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14847 	if (bbr == NULL) {
14848 		/* Huh? */
14849 		goto out;
14850 	}
14851 	if (sopt->sopt_dir == SOPT_SET) {
14852 		return (bbr_set_sockopt(so, sopt, inp, tp, bbr));
14853 	} else if (sopt->sopt_dir == SOPT_GET) {
14854 		return (bbr_get_sockopt(so, sopt, inp, tp, bbr));
14855 	}
14856 out:
14857 	INP_WUNLOCK(inp);
14858 	return (error);
14859 }
14860 
14861 static int
14862 bbr_pru_options(struct tcpcb *tp, int flags)
14863 {
14864 	if (flags & PRUS_OOB)
14865 		return (EOPNOTSUPP);
14866 	return (0);
14867 }
14868 
14869 struct tcp_function_block __tcp_bbr = {
14870 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
14871 	.tfb_tcp_output = bbr_output,
14872 	.tfb_do_queued_segments = ctf_do_queued_segments,
14873 	.tfb_do_segment_nounlock = bbr_do_segment_nounlock,
14874 	.tfb_tcp_do_segment = bbr_do_segment,
14875 	.tfb_tcp_ctloutput = bbr_ctloutput,
14876 	.tfb_tcp_fb_init = bbr_init,
14877 	.tfb_tcp_fb_fini = bbr_fini,
14878 	.tfb_tcp_timer_stop_all = bbr_stopall,
14879 	.tfb_tcp_timer_activate = bbr_timer_activate,
14880 	.tfb_tcp_timer_active = bbr_timer_active,
14881 	.tfb_tcp_timer_stop = bbr_timer_stop,
14882 	.tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
14883 	.tfb_tcp_handoff_ok = bbr_handoff_ok,
14884 	.tfb_tcp_mtu_chg = bbr_mtu_chg,
14885 	.tfb_pru_options = bbr_pru_options,
14886 };
14887 
14888 static const char *bbr_stack_names[] = {
14889 	__XSTRING(STACKNAME),
14890 #ifdef STACKALIAS
14891 	__XSTRING(STACKALIAS),
14892 #endif
14893 };
14894 
14895 static bool bbr_mod_inited = false;
14896 
14897 static int
14898 tcp_addbbr(module_t mod, int32_t type, void *data)
14899 {
14900 	int32_t err = 0;
14901 	int num_stacks;
14902 
14903 	switch (type) {
14904 	case MOD_LOAD:
14905 		printf("Attempting to load " __XSTRING(MODNAME) "\n");
14906 		bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
14907 		    sizeof(struct bbr_sendmap),
14908 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
14909 		bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
14910 		    sizeof(struct tcp_bbr),
14911 		    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
14912 		sysctl_ctx_init(&bbr_sysctl_ctx);
14913 		bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
14914 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
14915 		    OID_AUTO,
14916 #ifdef STACKALIAS
14917 		    __XSTRING(STACKALIAS),
14918 #else
14919 		    __XSTRING(STACKNAME),
14920 #endif
14921 		    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
14922 		    "");
14923 		if (bbr_sysctl_root == NULL) {
14924 			printf("Failed to add sysctl node\n");
14925 			err = EFAULT;
14926 			goto free_uma;
14927 		}
14928 		bbr_init_sysctls();
14929 		num_stacks = nitems(bbr_stack_names);
14930 		err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
14931 		    bbr_stack_names, &num_stacks);
14932 		if (err) {
14933 			printf("Failed to register %s stack name for "
14934 			    "%s module\n", bbr_stack_names[num_stacks],
14935 			    __XSTRING(MODNAME));
14936 			sysctl_ctx_free(&bbr_sysctl_ctx);
14937 	free_uma:
14938 			uma_zdestroy(bbr_zone);
14939 			uma_zdestroy(bbr_pcb_zone);
14940 			bbr_counter_destroy();
14941 			printf("Failed to register " __XSTRING(MODNAME)
14942 			    " module err:%d\n", err);
14943 			return (err);
14944 		}
14945 		tcp_lro_reg_mbufq();
14946 		bbr_mod_inited = true;
14947 		printf(__XSTRING(MODNAME) " is now available\n");
14948 		break;
14949 	case MOD_QUIESCE:
14950 		err = deregister_tcp_functions(&__tcp_bbr, true, false);
14951 		break;
14952 	case MOD_UNLOAD:
14953 		err = deregister_tcp_functions(&__tcp_bbr, false, true);
14954 		if (err == EBUSY)
14955 			break;
14956 		if (bbr_mod_inited) {
14957 			uma_zdestroy(bbr_zone);
14958 			uma_zdestroy(bbr_pcb_zone);
14959 			sysctl_ctx_free(&bbr_sysctl_ctx);
14960 			bbr_counter_destroy();
14961 			printf(__XSTRING(MODNAME)
14962 			    " is now no longer available\n");
14963 			bbr_mod_inited = false;
14964 		}
14965 		tcp_lro_dereg_mbufq();
14966 		err = 0;
14967 		break;
14968 	default:
14969 		return (EOPNOTSUPP);
14970 	}
14971 	return (err);
14972 }
14973 
14974 static moduledata_t tcp_bbr = {
14975 	.name = __XSTRING(MODNAME),
14976 	    .evhand = tcp_addbbr,
14977 	    .priv = 0
14978 };
14979 
14980 MODULE_VERSION(MODNAME, 1);
14981 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
14982 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
14983