xref: /freebsd-14-stable/sys/netinet/tcp_stacks/bbr.c (revision f28415489639df69d4bcda74c1199a6b062ab5cf)
1 /*-
2  * Copyright (c) 2016-2020 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  */
26 /**
27  * Author: Randall Stewart <rrs@netflix.com>
28  * This work is based on the ACM Queue paper
29  * BBR - Congestion Based Congestion Control
30  * and also numerous discussions with Neal, Yuchung and Van.
31  */
32 
33 #include <sys/cdefs.h>
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_ipsec.h"
37 #include "opt_ratelimit.h"
38 #include <sys/param.h>
39 #include <sys/arb.h>
40 #include <sys/module.h>
41 #include <sys/kernel.h>
42 #include <sys/libkern.h>
43 #ifdef TCP_HHOOK
44 #include <sys/hhook.h>
45 #endif
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/proc.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/systm.h>
53 #ifdef STATS
54 #include <sys/qmath.h>
55 #include <sys/tree.h>
56 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
57 #endif
58 #include <sys/refcount.h>
59 #include <sys/queue.h>
60 #include <sys/eventhandler.h>
61 #include <sys/smp.h>
62 #include <sys/kthread.h>
63 #include <sys/lock.h>
64 #include <sys/mutex.h>
65 #include <sys/tim_filter.h>
66 #include <sys/time.h>
67 #include <sys/protosw.h>
68 #include <vm/uma.h>
69 #include <sys/kern_prefetch.h>
70 
71 #include <net/route.h>
72 #include <net/route/nhop.h>
73 #include <net/vnet.h>
74 
75 #define TCPSTATES		/* for logging */
76 
77 #include <netinet/in.h>
78 #include <netinet/in_kdtrace.h>
79 #include <netinet/in_pcb.h>
80 #include <netinet/ip.h>
81 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
82 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
83 #include <netinet/ip_var.h>
84 #include <netinet/ip6.h>
85 #include <netinet6/in6_pcb.h>
86 #include <netinet6/ip6_var.h>
87 #define	TCPOUTFLAGS
88 #include <netinet/tcp.h>
89 #include <netinet/tcp_fsm.h>
90 #include <netinet/tcp_seq.h>
91 #include <netinet/tcp_timer.h>
92 #include <netinet/tcp_var.h>
93 #include <netinet/tcpip.h>
94 #include <netinet/tcp_hpts.h>
95 #include <netinet/cc/cc.h>
96 #include <netinet/tcp_log_buf.h>
97 #include <netinet/tcp_ratelimit.h>
98 #include <netinet/tcp_lro.h>
99 #ifdef TCP_OFFLOAD
100 #include <netinet/tcp_offload.h>
101 #endif
102 #ifdef INET6
103 #include <netinet6/tcp6_var.h>
104 #endif
105 #include <netinet/tcp_fastopen.h>
106 
107 #include <netipsec/ipsec_support.h>
108 #include <net/if.h>
109 #include <net/if_var.h>
110 #include <net/ethernet.h>
111 
112 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
113 #include <netipsec/ipsec.h>
114 #include <netipsec/ipsec6.h>
115 #endif				/* IPSEC */
116 
117 #include <netinet/udp.h>
118 #include <netinet/udp_var.h>
119 #include <machine/in_cksum.h>
120 
121 #ifdef MAC
122 #include <security/mac/mac_framework.h>
123 #endif
124 
125 #include "sack_filter.h"
126 #include "tcp_bbr.h"
127 #include "rack_bbr_common.h"
128 uma_zone_t bbr_zone;
129 uma_zone_t bbr_pcb_zone;
130 
131 struct sysctl_ctx_list bbr_sysctl_ctx;
132 struct sysctl_oid *bbr_sysctl_root;
133 
134 #define	TCPT_RANGESET_NOSLOP(tv, value, tvmin, tvmax) do { \
135 	(tv) = (value); \
136 	if ((u_long)(tv) < (u_long)(tvmin)) \
137 		(tv) = (tvmin); \
138 	if ((u_long)(tv) > (u_long)(tvmax)) \
139 		(tv) = (tvmax); \
140 } while(0)
141 
142 /*#define BBR_INVARIANT 1*/
143 
144 /*
145  * initial window
146  */
147 static uint32_t bbr_def_init_win = 10;
148 static int32_t bbr_persist_min = 250000;	/* 250ms */
149 static int32_t bbr_persist_max = 1000000;	/* 1 Second */
150 static int32_t bbr_cwnd_may_shrink = 0;
151 static int32_t bbr_cwndtarget_rtt_touse = BBR_RTT_PROP;
152 static int32_t bbr_num_pktepo_for_del_limit = BBR_NUM_RTTS_FOR_DEL_LIMIT;
153 static int32_t bbr_hardware_pacing_limit = 8000;
154 static int32_t bbr_quanta = 3;	/* How much extra quanta do we get? */
155 static int32_t bbr_no_retran = 0;
156 
157 static int32_t bbr_error_base_paceout = 10000; /* usec to pace */
158 static int32_t bbr_max_net_error_cnt = 10;
159 /* Should the following be dynamic too -- loss wise */
160 static int32_t bbr_rtt_gain_thresh = 0;
161 /* Measurement controls */
162 static int32_t bbr_use_google_algo = 1;
163 static int32_t bbr_ts_limiting = 1;
164 static int32_t bbr_ts_can_raise = 0;
165 static int32_t bbr_do_red = 600;
166 static int32_t bbr_red_scale = 20000;
167 static int32_t bbr_red_mul = 1;
168 static int32_t bbr_red_div = 2;
169 static int32_t bbr_red_growth_restrict = 1;
170 static int32_t  bbr_target_is_bbunit = 0;
171 static int32_t bbr_drop_limit = 0;
172 /*
173  * How much gain do we need to see to
174  * stay in startup?
175  */
176 static int32_t bbr_marks_rxt_sack_passed = 0;
177 static int32_t bbr_start_exit = 25;
178 static int32_t bbr_low_start_exit = 25;	/* When we are in reduced gain */
179 static int32_t bbr_startup_loss_thresh = 2000;	/* 20.00% loss */
180 static int32_t bbr_hptsi_max_mul = 1;	/* These two mul/div assure a min pacing */
181 static int32_t bbr_hptsi_max_div = 2;	/* time, 0 means turned off. We need this
182 					 * if we go back ever to where the pacer
183 					 * has priority over timers.
184 					 */
185 static int32_t bbr_policer_call_from_rack_to = 0;
186 static int32_t bbr_policer_detection_enabled = 1;
187 static int32_t bbr_min_measurements_req = 1;	/* We need at least 2
188 						 * measurements before we are
189 						 * "good" note that 2 == 1.
190 						 * This is because we use a >
191 						 * comparison. This means if
192 						 * min_measure was 0, it takes
193 						 * num-measures > min(0) and
194 						 * you get 1 measurement and
195 						 * you are good. Set to 1, you
196 						 * have to have two
197 						 * measurements (this is done
198 						 * to prevent it from being ok
199 						 * to have no measurements). */
200 static int32_t bbr_no_pacing_until = 4;
201 
202 static int32_t bbr_min_usec_delta = 20000;	/* 20,000 usecs */
203 static int32_t bbr_min_peer_delta = 20;		/* 20 units */
204 static int32_t bbr_delta_percent = 150;		/* 15.0 % */
205 
206 static int32_t bbr_target_cwnd_mult_limit = 8;
207 /*
208  * bbr_cwnd_min_val is the number of
209  * segments we hold to in the RTT probe
210  * state typically 4.
211  */
212 static int32_t bbr_cwnd_min_val = BBR_PROBERTT_NUM_MSS;
213 
214 static int32_t bbr_cwnd_min_val_hs = BBR_HIGHSPEED_NUM_MSS;
215 
216 static int32_t bbr_gain_to_target = 1;
217 static int32_t bbr_gain_gets_extra_too = 1;
218 /*
219  * bbr_high_gain is the 2/ln(2) value we need
220  * to double the sending rate in startup. This
221  * is used for both cwnd and hptsi gain's.
222  */
223 static int32_t bbr_high_gain = BBR_UNIT * 2885 / 1000 + 1;
224 static int32_t bbr_startup_lower = BBR_UNIT * 1500 / 1000 + 1;
225 static int32_t bbr_use_lower_gain_in_startup = 1;
226 
227 /* thresholds for reduction on drain in sub-states/drain */
228 static int32_t bbr_drain_rtt = BBR_SRTT;
229 static int32_t bbr_drain_floor = 88;
230 static int32_t google_allow_early_out = 1;
231 static int32_t google_consider_lost = 1;
232 static int32_t bbr_drain_drop_mul = 4;
233 static int32_t bbr_drain_drop_div = 5;
234 static int32_t bbr_rand_ot = 50;
235 static int32_t bbr_can_force_probertt = 0;
236 static int32_t bbr_can_adjust_probertt = 1;
237 static int32_t bbr_probertt_sets_rtt = 0;
238 static int32_t bbr_can_use_ts_for_rtt = 1;
239 static int32_t bbr_is_ratio = 0;
240 static int32_t bbr_sub_drain_app_limit = 1;
241 static int32_t bbr_prtt_slam_cwnd = 1;
242 static int32_t bbr_sub_drain_slam_cwnd = 1;
243 static int32_t bbr_slam_cwnd_in_main_drain = 1;
244 static int32_t bbr_filter_len_sec = 6;	/* How long does the rttProp filter
245 					 * hold */
246 static uint32_t bbr_rtt_probe_limit = (USECS_IN_SECOND * 4);
247 /*
248  * bbr_drain_gain is the reverse of the high_gain
249  * designed to drain back out the standing queue
250  * that is formed in startup by causing a larger
251  * hptsi gain and thus drainging the packets
252  * in flight.
253  */
254 static int32_t bbr_drain_gain = BBR_UNIT * 1000 / 2885;
255 static int32_t bbr_rttprobe_gain = 192;
256 
257 /*
258  * The cwnd_gain is the default cwnd gain applied when
259  * calculating a target cwnd. Note that the cwnd is
260  * a secondary factor in the way BBR works (see the
261  * paper and think about it, it will take some time).
262  * Basically the hptsi_gain spreads the packets out
263  * so you never get more than BDP to the peer even
264  * if the cwnd is high. In our implemenation that
265  * means in non-recovery/retransmission scenarios
266  * cwnd will never be reached by the flight-size.
267  */
268 static int32_t bbr_cwnd_gain = BBR_UNIT * 2;
269 static int32_t bbr_tlp_type_to_use = BBR_SRTT;
270 static int32_t bbr_delack_time = 100000;	/* 100ms in useconds */
271 static int32_t bbr_sack_not_required = 0;	/* set to one to allow non-sack to use bbr */
272 static int32_t bbr_initial_bw_bps = 62500;	/* 500kbps in bytes ps */
273 static int32_t bbr_ignore_data_after_close = 1;
274 static int16_t bbr_hptsi_gain[] = {
275 	(BBR_UNIT *5 / 4),
276 	(BBR_UNIT * 3 / 4),
277 	BBR_UNIT,
278 	BBR_UNIT,
279 	BBR_UNIT,
280 	BBR_UNIT,
281 	BBR_UNIT,
282 	BBR_UNIT
283 };
284 int32_t bbr_use_rack_resend_cheat = 1;
285 int32_t bbr_sends_full_iwnd = 1;
286 
287 #define BBR_HPTSI_GAIN_MAX 8
288 /*
289  * The BBR module incorporates a number of
290  * TCP ideas that have been put out into the IETF
291  * over the last few years:
292  * - Yuchung Cheng's RACK TCP (for which its named) that
293  *    will stop us using the number of dup acks and instead
294  *    use time as the gage of when we retransmit.
295  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
296  *    of Dukkipati et.al.
297  * - Van Jacobson's et.al BBR.
298  *
299  * RACK depends on SACK, so if an endpoint arrives that
300  * cannot do SACK the state machine below will shuttle the
301  * connection back to using the "default" TCP stack that is
302  * in FreeBSD.
303  *
304  * To implement BBR and RACK the original TCP stack was first decomposed
305  * into a functional state machine with individual states
306  * for each of the possible TCP connection states. The do_segment
307  * functions role in life is to mandate the connection supports SACK
308  * initially and then assure that the RACK state matches the conenction
309  * state before calling the states do_segment function. Data processing
310  * of inbound segments also now happens in the hpts_do_segment in general
311  * with only one exception. This is so we can keep the connection on
312  * a single CPU.
313  *
314  * Each state is simplified due to the fact that the original do_segment
315  * has been decomposed and we *know* what state we are in (no
316  * switches on the state) and all tests for SACK are gone. This
317  * greatly simplifies what each state does.
318  *
319  * TCP output is also over-written with a new version since it
320  * must maintain the new rack scoreboard and has had hptsi
321  * integrated as a requirment. Still todo is to eliminate the
322  * use of the callout_() system and use the hpts for all
323  * timers as well.
324  */
325 static uint32_t bbr_rtt_probe_time = 200000;	/* 200ms in micro seconds */
326 static uint32_t bbr_rtt_probe_cwndtarg = 4;	/* How many mss's outstanding */
327 static const int32_t bbr_min_req_free = 2;	/* The min we must have on the
328 						 * free list */
329 static int32_t bbr_tlp_thresh = 1;
330 static int32_t bbr_reorder_thresh = 2;
331 static int32_t bbr_reorder_fade = 60000000;	/* 0 - never fade, def
332 						 * 60,000,000 - 60 seconds */
333 static int32_t bbr_pkt_delay = 1000;
334 static int32_t bbr_min_to = 1000;	/* Number of usec's minimum timeout */
335 static int32_t bbr_incr_timers = 1;
336 
337 static int32_t bbr_tlp_min = 10000;	/* 10ms in usecs */
338 static int32_t bbr_delayed_ack_time = 200000;	/* 200ms in usecs */
339 static int32_t bbr_exit_startup_at_loss = 1;
340 
341 /*
342  * bbr_lt_bw_ratio is 1/8th
343  * bbr_lt_bw_diff is  < 4 Kbit/sec
344  */
345 static uint64_t bbr_lt_bw_diff = 4000 / 8;	/* In bytes per second */
346 static uint64_t bbr_lt_bw_ratio = 8;	/* For 1/8th */
347 static uint32_t bbr_lt_bw_max_rtts = 48;	/* How many rtt's do we use
348 						 * the lt_bw for */
349 static uint32_t bbr_lt_intvl_min_rtts = 4;	/* Min num of RTT's to measure
350 						 * lt_bw */
351 static int32_t bbr_lt_intvl_fp = 0;		/* False positive epoch diff */
352 static int32_t bbr_lt_loss_thresh = 196;	/* Lost vs delivered % */
353 static int32_t bbr_lt_fd_thresh = 100;		/* false detection % */
354 
355 static int32_t bbr_verbose_logging = 0;
356 /*
357  * Currently regular tcp has a rto_min of 30ms
358  * the backoff goes 12 times so that ends up
359  * being a total of 122.850 seconds before a
360  * connection is killed.
361  */
362 static int32_t bbr_rto_min_ms = 30;	/* 30ms same as main freebsd */
363 static int32_t bbr_rto_max_sec = 4;	/* 4 seconds */
364 
365 /****************************************************/
366 /* DEFAULT TSO SIZING  (cpu performance impacting)  */
367 /****************************************************/
368 /* What amount is our formula using to get TSO size */
369 static int32_t bbr_hptsi_per_second = 1000;
370 
371 /*
372  * For hptsi under bbr_cross_over connections what is delay
373  * target 7ms (in usec) combined with a seg_max of 2
374  * gets us close to identical google behavior in
375  * TSO size selection (possibly more 1MSS sends).
376  */
377 static int32_t bbr_hptsi_segments_delay_tar = 7000;
378 
379 /* Does pacing delay include overhead's in its time calculations? */
380 static int32_t bbr_include_enet_oh = 0;
381 static int32_t bbr_include_ip_oh = 1;
382 static int32_t bbr_include_tcp_oh = 1;
383 static int32_t bbr_google_discount = 10;
384 
385 /* Do we use (nf mode) pkt-epoch to drive us or rttProp? */
386 static int32_t bbr_state_is_pkt_epoch = 0;
387 static int32_t bbr_state_drain_2_tar = 1;
388 /* What is the max the 0 - bbr_cross_over MBPS TSO target
389  * can reach using our delay target. Note that this
390  * value becomes the floor for the cross over
391  * algorithm.
392  */
393 static int32_t bbr_hptsi_segments_max = 2;
394 static int32_t bbr_hptsi_segments_floor = 1;
395 static int32_t bbr_hptsi_utter_max = 0;
396 
397 /* What is the min the 0 - bbr_cross-over MBPS  TSO target can be */
398 static int32_t bbr_hptsi_bytes_min = 1460;
399 static int32_t bbr_all_get_min = 0;
400 
401 /* Cross over point from algo-a to algo-b */
402 static uint32_t bbr_cross_over = TWENTY_THREE_MBPS;
403 
404 /* Do we deal with our restart state? */
405 static int32_t bbr_uses_idle_restart = 0;
406 static int32_t bbr_idle_restart_threshold = 100000;	/* 100ms in useconds */
407 
408 /* Do we allow hardware pacing? */
409 static int32_t bbr_allow_hdwr_pacing = 0;
410 static int32_t bbr_hdwr_pace_adjust = 2;	/* multipler when we calc the tso size */
411 static int32_t bbr_hdwr_pace_floor = 1;
412 static int32_t bbr_hdwr_pacing_delay_cnt = 10;
413 
414 /****************************************************/
415 static int32_t bbr_resends_use_tso = 0;
416 static int32_t bbr_tlp_max_resend = 2;
417 static int32_t bbr_sack_block_limit = 128;
418 
419 #define  BBR_MAX_STAT 19
420 counter_u64_t bbr_state_time[BBR_MAX_STAT];
421 counter_u64_t bbr_state_lost[BBR_MAX_STAT];
422 counter_u64_t bbr_state_resend[BBR_MAX_STAT];
423 counter_u64_t bbr_stat_arry[BBR_STAT_SIZE];
424 counter_u64_t bbr_opts_arry[BBR_OPTS_SIZE];
425 counter_u64_t bbr_out_size[TCP_MSS_ACCT_SIZE];
426 counter_u64_t bbr_flows_whdwr_pacing;
427 counter_u64_t bbr_flows_nohdwr_pacing;
428 
429 counter_u64_t bbr_nohdwr_pacing_enobuf;
430 counter_u64_t bbr_hdwr_pacing_enobuf;
431 
432 static inline uint64_t bbr_get_bw(struct tcp_bbr *bbr);
433 
434 /*
435  * Static defintions we need for forward declarations.
436  */
437 static uint32_t
438 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain,
439 		      uint32_t useconds_time, uint64_t bw);
440 static uint32_t
441 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain);
442 static void
443 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win);
444 static void
445 bbr_set_probebw_gains(struct tcp_bbr *bbr,  uint32_t cts, uint32_t losses);
446 static void
447 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int line,
448 		    int dolog);
449 static uint32_t
450 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain);
451 static void
452 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch,
453 		 int32_t pkt_epoch, uint32_t losses);
454 static uint32_t
455 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts,
456 		     struct bbr_sendmap *rsm);
457 static uint32_t
458 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp);
459 static uint32_t
460 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
461 		    struct bbr_sendmap *rsm, uint32_t srtt, uint32_t cts);
462 static void
463 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
464 		 int32_t line);
465 static void
466 bbr_set_state_target(struct tcp_bbr *bbr, int line);
467 static void
468 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line);
469 static void
470 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick,
471 		       int event, int line);
472 static void
473 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts);
474 static void
475 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts);
476 static void
477 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
478 		    uint32_t rtt, uint32_t line, uint8_t is_start,
479 		    uint16_t set);
480 static struct bbr_sendmap *
481 bbr_find_lowest_rsm(struct tcp_bbr *bbr);
482 static __inline uint32_t
483 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type);
484 static void
485 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot,
486 		 uint8_t which);
487 static void
488 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts,
489 		  uint32_t time_since_sent, uint32_t srtt,
490 		  uint32_t thresh, uint32_t to);
491 static void
492 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag);
493 static void
494 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot,
495 		    uint32_t del_by, uint32_t cts, uint32_t sloton,
496 		    uint32_t prev_delay);
497 static void
498 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
499 		  int32_t line);
500 static void
501 bbr_stop_all_timers(struct tcpcb *tp, struct tcp_bbr *bbr);
502 static void
503 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts);
504 static void
505 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts);
506 static void
507 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts);
508 static void
509 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
510 			  uint32_t cts, uint32_t usecs, uint64_t bw,
511 			  uint32_t override, int mod);
512 static int bbr_ctloutput(struct tcpcb *tp, struct sockopt *sopt);
513 
514 static inline uint8_t
bbr_state_val(struct tcp_bbr * bbr)515 bbr_state_val(struct tcp_bbr *bbr)
516 {
517 	return(bbr->rc_bbr_substate);
518 }
519 
520 static inline uint32_t
get_min_cwnd(struct tcp_bbr * bbr)521 get_min_cwnd(struct tcp_bbr *bbr)
522 {
523 	int mss;
524 
525 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
526 		  bbr->r_ctl.rc_pace_max_segs);
527 	if (bbr_get_rtt(bbr, BBR_RTT_PROP) < BBR_HIGH_SPEED)
528 		return (bbr_cwnd_min_val_hs * mss);
529 	else
530 		return (bbr_cwnd_min_val * mss);
531 }
532 
533 static uint32_t
bbr_get_persists_timer_val(struct tcpcb * tp,struct tcp_bbr * bbr)534 bbr_get_persists_timer_val(struct tcpcb *tp, struct tcp_bbr *bbr)
535 {
536 	uint64_t srtt, var;
537 	uint64_t ret_val;
538 
539 	bbr->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
540 	if (tp->t_srtt == 0) {
541 		srtt = (uint64_t)BBR_INITIAL_RTO;
542 		var = 0;
543 	} else {
544 		srtt = ((uint64_t)TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
545 		var = ((uint64_t)TICKS_2_USEC(tp->t_rttvar) >> TCP_RTT_SHIFT);
546 	}
547 	TCPT_RANGESET_NOSLOP(ret_val, ((srtt + var) * tcp_backoff[tp->t_rxtshift]),
548 	    bbr_persist_min, bbr_persist_max);
549 	return ((uint32_t)ret_val);
550 }
551 
552 static uint32_t
bbr_timer_start(struct tcpcb * tp,struct tcp_bbr * bbr,uint32_t cts)553 bbr_timer_start(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
554 {
555 	/*
556 	 * Start the FR timer, we do this based on getting the first one in
557 	 * the rc_tmap. Note that if its NULL we must stop the timer. in all
558 	 * events we need to stop the running timer (if its running) before
559 	 * starting the new one.
560 	 */
561 	uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
562 	int32_t idx;
563 	int32_t is_tlp_timer = 0;
564 	struct bbr_sendmap *rsm;
565 
566 	if (bbr->rc_all_timers_stopped) {
567 		/* All timers have been stopped none are to run */
568 		return (0);
569 	}
570 	if (bbr->rc_in_persist) {
571 		/* We can't start any timer in persists */
572 		return (bbr_get_persists_timer_val(tp, bbr));
573 	}
574 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
575 	if ((rsm == NULL) ||
576 	    ((tp->t_flags & TF_SACK_PERMIT) == 0) ||
577 	    (tp->t_state < TCPS_ESTABLISHED)) {
578 		/* Nothing on the send map */
579 activate_rxt:
580 		if (SEQ_LT(tp->snd_una, tp->snd_max) ||
581 		    sbavail(&tptosocket(tp)->so_snd)) {
582 			uint64_t tov;
583 
584 			time_since_sent = 0;
585 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
586 			if (rsm) {
587 				idx = rsm->r_rtr_cnt - 1;
588 				if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
589 					tstmp_touse = rsm->r_tim_lastsent[idx];
590 				else
591 					tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
592 				if (TSTMP_GT(tstmp_touse, cts))
593 				    time_since_sent = cts - tstmp_touse;
594 			}
595 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
596 			if (tp->t_srtt == 0)
597 				tov = BBR_INITIAL_RTO;
598 			else
599 				tov = ((uint64_t)(TICKS_2_USEC(tp->t_srtt) +
600 				    ((uint64_t)TICKS_2_USEC(tp->t_rttvar) * (uint64_t)4)) >> TCP_RTT_SHIFT);
601 			if (tp->t_rxtshift)
602 				tov *= tcp_backoff[tp->t_rxtshift];
603 			if (tov > time_since_sent)
604 				tov -= time_since_sent;
605 			else
606 				tov = bbr->r_ctl.rc_min_to;
607 			TCPT_RANGESET_NOSLOP(to, tov,
608 			    (bbr->r_ctl.rc_min_rto_ms * MS_IN_USEC),
609 			    (bbr->rc_max_rto_sec * USECS_IN_SECOND));
610 			bbr_log_timer_var(bbr, 2, cts, 0, bbr_get_rtt(bbr, BBR_SRTT), 0, to);
611 			return (to);
612 		}
613 		return (0);
614 	}
615 	if (rsm->r_flags & BBR_ACKED) {
616 		rsm = bbr_find_lowest_rsm(bbr);
617 		if (rsm == NULL) {
618 			/* No lowest? */
619 			goto activate_rxt;
620 		}
621 	}
622 	/* Convert from ms to usecs */
623 	if (rsm->r_flags & BBR_SACK_PASSED) {
624 		if ((tp->t_flags & TF_SENTFIN) &&
625 		    ((tp->snd_max - tp->snd_una) == 1) &&
626 		    (rsm->r_flags & BBR_HAS_FIN)) {
627 			/*
628 			 * We don't start a bbr rack timer if all we have is
629 			 * a FIN outstanding.
630 			 */
631 			goto activate_rxt;
632 		}
633 		srtt = bbr_get_rtt(bbr, BBR_RTT_RACK);
634 		thresh = bbr_calc_thresh_rack(bbr, srtt, cts, rsm);
635 		idx = rsm->r_rtr_cnt - 1;
636 		exp = rsm->r_tim_lastsent[idx] + thresh;
637 		if (SEQ_GEQ(exp, cts)) {
638 			to = exp - cts;
639 			if (to < bbr->r_ctl.rc_min_to) {
640 				to = bbr->r_ctl.rc_min_to;
641 			}
642 		} else {
643 			to = bbr->r_ctl.rc_min_to;
644 		}
645 	} else {
646 		/* Ok we need to do a TLP not RACK */
647 		if (bbr->rc_tlp_in_progress != 0) {
648 			/*
649 			 * The previous send was a TLP.
650 			 */
651 			goto activate_rxt;
652 		}
653 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
654 		if (rsm == NULL) {
655 			/* We found no rsm to TLP with. */
656 			goto activate_rxt;
657 		}
658 		if (rsm->r_flags & BBR_HAS_FIN) {
659 			/* If its a FIN we don't do TLP */
660 			rsm = NULL;
661 			goto activate_rxt;
662 		}
663 		time_since_sent = 0;
664 		idx = rsm->r_rtr_cnt - 1;
665 		if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
666 			tstmp_touse = rsm->r_tim_lastsent[idx];
667 		else
668 			tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
669 		if (TSTMP_GT(tstmp_touse, cts))
670 		    time_since_sent = cts - tstmp_touse;
671 		is_tlp_timer = 1;
672 		srtt = bbr_get_rtt(bbr, bbr_tlp_type_to_use);
673 		thresh = bbr_calc_thresh_tlp(tp, bbr, rsm, srtt, cts);
674 		if (thresh > time_since_sent)
675 			to = thresh - time_since_sent;
676 		else
677 			to = bbr->r_ctl.rc_min_to;
678 		if (to > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
679 			/*
680 			 * If the TLP time works out to larger than the max
681 			 * RTO lets not do TLP.. just RTO.
682 			 */
683 			goto activate_rxt;
684 		}
685 		if ((bbr->rc_tlp_rtx_out == 1) &&
686 		    (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq)) {
687 			/*
688 			 * Second retransmit of the same TLP
689 			 * lets not.
690 			 */
691 			bbr->rc_tlp_rtx_out = 0;
692 			goto activate_rxt;
693 		}
694 		if (rsm->r_start != bbr->r_ctl.rc_last_tlp_seq) {
695 			/*
696 			 * The tail is no longer the last one I did a probe
697 			 * on
698 			 */
699 			bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
700 			bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
701 		}
702 	}
703 	if (is_tlp_timer == 0) {
704 		BBR_STAT_INC(bbr_to_arm_rack);
705 		bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
706 	} else {
707 		bbr_log_timer_var(bbr, 1, cts, time_since_sent, srtt, thresh, to);
708 		if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
709 			/*
710 			 * We have exceeded how many times we can retran the
711 			 * current TLP timer, switch to the RTO timer.
712 			 */
713 			goto activate_rxt;
714 		} else {
715 			BBR_STAT_INC(bbr_to_arm_tlp);
716 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
717 		}
718 	}
719 	return (to);
720 }
721 
722 static inline int32_t
bbr_minseg(struct tcp_bbr * bbr)723 bbr_minseg(struct tcp_bbr *bbr)
724 {
725 	return (bbr->r_ctl.rc_pace_min_segs - bbr->rc_last_options);
726 }
727 
728 static void
bbr_start_hpts_timer(struct tcp_bbr * bbr,struct tcpcb * tp,uint32_t cts,int32_t frm,int32_t slot,uint32_t tot_len)729 bbr_start_hpts_timer(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts, int32_t frm, int32_t slot, uint32_t tot_len)
730 {
731 	struct inpcb *inp = tptoinpcb(tp);
732 	struct hpts_diag diag;
733 	uint32_t delayed_ack = 0;
734 	uint32_t left = 0;
735 	uint32_t hpts_timeout;
736 	uint8_t stopped;
737 	int32_t delay_calc = 0;
738 	uint32_t prev_delay = 0;
739 
740 	if (tcp_in_hpts(tp)) {
741 		/* A previous call is already set up */
742 		return;
743 	}
744 	if ((tp->t_state == TCPS_CLOSED) ||
745 	    (tp->t_state == TCPS_LISTEN)) {
746 		return;
747 	}
748 	stopped = bbr->rc_tmr_stopped;
749 	if (stopped && TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
750 		left = bbr->r_ctl.rc_timer_exp - cts;
751 	}
752 	bbr->r_ctl.rc_hpts_flags = 0;
753 	bbr->r_ctl.rc_timer_exp = 0;
754 	prev_delay = bbr->r_ctl.rc_last_delay_val;
755 	if (bbr->r_ctl.rc_last_delay_val &&
756 	    (slot == 0)) {
757 		/*
758 		 * If a previous pacer delay was in place we
759 		 * are not coming from the output side (where
760 		 * we calculate a delay, more likely a timer).
761 		 */
762 		slot = bbr->r_ctl.rc_last_delay_val;
763 		if (TSTMP_GT(cts, bbr->rc_pacer_started)) {
764 			/* Compensate for time passed  */
765 			delay_calc = cts - bbr->rc_pacer_started;
766 			if (delay_calc <= slot)
767 				slot -= delay_calc;
768 		}
769 	}
770 	/* Do we have early to make up for by pushing out the pacing time? */
771 	if (bbr->r_agg_early_set) {
772 		bbr_log_pacing_delay_calc(bbr, 0, bbr->r_ctl.rc_agg_early, cts, slot, 0, bbr->r_agg_early_set, 2);
773 		slot += bbr->r_ctl.rc_agg_early;
774 		bbr->r_ctl.rc_agg_early = 0;
775 		bbr->r_agg_early_set = 0;
776 	}
777 	/* Are we running a total debt that needs to be compensated for? */
778 	if (bbr->r_ctl.rc_hptsi_agg_delay) {
779 		if (slot > bbr->r_ctl.rc_hptsi_agg_delay) {
780 			/* We nuke the delay */
781 			slot -= bbr->r_ctl.rc_hptsi_agg_delay;
782 			bbr->r_ctl.rc_hptsi_agg_delay = 0;
783 		} else {
784 			/* We nuke some of the delay, put in a minimal 100usecs  */
785 			bbr->r_ctl.rc_hptsi_agg_delay -= slot;
786 			bbr->r_ctl.rc_last_delay_val = slot = 100;
787 		}
788 	}
789 	bbr->r_ctl.rc_last_delay_val = slot;
790 	hpts_timeout = bbr_timer_start(tp, bbr, cts);
791 	if (tp->t_flags & TF_DELACK) {
792 		if (bbr->rc_in_persist == 0) {
793 			delayed_ack = bbr_delack_time;
794 		} else {
795 			/*
796 			 * We are in persists and have
797 			 * gotten a new data element.
798 			 */
799 			if (hpts_timeout > bbr_delack_time) {
800 				/*
801 				 * Lets make the persists timer (which acks)
802 				 * be the smaller of hpts_timeout and bbr_delack_time.
803 				 */
804 				hpts_timeout = bbr_delack_time;
805 			}
806 		}
807 	}
808 	if (delayed_ack &&
809 	    ((hpts_timeout == 0) ||
810 	     (delayed_ack < hpts_timeout))) {
811 		/* We need a Delayed ack timer */
812 		bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
813 		hpts_timeout = delayed_ack;
814 	}
815 	if (slot) {
816 		/* Mark that we have a pacing timer up */
817 		BBR_STAT_INC(bbr_paced_segments);
818 		bbr->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
819 	}
820 	/*
821 	 * If no timers are going to run and we will fall off thfe hptsi
822 	 * wheel, we resort to a keep-alive timer if its configured.
823 	 */
824 	if ((hpts_timeout == 0) &&
825 	    (slot == 0)) {
826 		if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
827 		    (tp->t_state <= TCPS_CLOSING)) {
828 			/*
829 			 * Ok we have no timer (persists, rack, tlp, rxt  or
830 			 * del-ack), we don't have segments being paced. So
831 			 * all that is left is the keepalive timer.
832 			 */
833 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
834 				hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
835 			} else {
836 				hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
837 			}
838 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
839 		}
840 	}
841 	if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
842 	    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
843 		/*
844 		 * RACK, TLP, persists and RXT timers all are restartable
845 		 * based on actions input .. i.e we received a packet (ack
846 		 * or sack) and that changes things (rw, or snd_una etc).
847 		 * Thus we can restart them with a new value. For
848 		 * keep-alive, delayed_ack we keep track of what was left
849 		 * and restart the timer with a smaller value.
850 		 */
851 		if (left < hpts_timeout)
852 			hpts_timeout = left;
853 	}
854 	if (bbr->r_ctl.rc_incr_tmrs && slot &&
855 	    (bbr->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
856 		/*
857 		 * If configured to do so, and the timer is either
858 		 * the TLP or RXT timer, we need to increase the timeout
859 		 * by the pacing time. Consider the bottleneck at my
860 		 * machine as an example, we are sending something
861 		 * to start a TLP on. The last packet won't be emitted
862 		 * fully until the pacing time (the bottleneck will hold
863 		 * the data in place). Once the packet is emitted that
864 		 * is when we want to start waiting for the TLP. This
865 		 * is most evident with hardware pacing (where the nic
866 		 * is holding the packet(s) before emitting). But it
867 		 * can also show up in the network so we do it for all
868 		 * cases. Technically we would take off one packet from
869 		 * this extra delay but this is easier and being more
870 		 * conservative is probably better.
871 		 */
872 		hpts_timeout += slot;
873 	}
874 	if (hpts_timeout) {
875 		/*
876 		 * Hack alert for now we can't time-out over 2147 seconds (a
877 		 * bit more than 35min)
878 		 */
879 		if (hpts_timeout > 0x7ffffffe)
880 			hpts_timeout = 0x7ffffffe;
881 		bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
882 	} else
883 		bbr->r_ctl.rc_timer_exp = 0;
884 	if ((slot) &&
885 	    (bbr->rc_use_google ||
886 	     bbr->output_error_seen ||
887 	     (slot <= hpts_timeout))  ) {
888 		/*
889 		 * Tell LRO that it can queue packets while
890 		 * we pace.
891 		 */
892 		bbr->rc_tp->t_flags2 |= TF2_MBUF_QUEUE_READY;
893 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
894 		    (bbr->rc_cwnd_limited == 0)) {
895 			/*
896 			 * If we are not cwnd limited and we
897 			 * are running a rack timer we put on
898 			 * the do not disturbe even for sack.
899 			 */
900 			tp->t_flags2 |= TF2_DONT_SACK_QUEUE;
901 		} else
902 			tp->t_flags2 &= ~TF2_DONT_SACK_QUEUE;
903 		bbr->rc_pacer_started = cts;
904 
905 		(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(slot),
906 					   __LINE__, &diag);
907 		bbr->rc_timer_first = 0;
908 		bbr->bbr_timer_src = frm;
909 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 1);
910 		bbr_log_hpts_diag(bbr, cts, &diag);
911 	} else if (hpts_timeout) {
912 		(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(hpts_timeout),
913 					   __LINE__, &diag);
914 		/*
915 		 * We add the flag here as well if the slot is set,
916 		 * since hpts will call in to clear the queue first before
917 		 * calling the output routine (which does our timers).
918 		 * We don't want to set the flag if its just a timer
919 		 * else the arrival of data might (that causes us
920 		 * to send more) might get delayed. Imagine being
921 		 * on a keep-alive timer and a request comes in for
922 		 * more data.
923 		 */
924 		if (slot)
925 			bbr->rc_pacer_started = cts;
926 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
927 		    (bbr->rc_cwnd_limited == 0)) {
928 			/*
929 			 * For a rack timer, don't wake us even
930 			 * if a sack arrives as long as we are
931 			 * not cwnd limited.
932 			 */
933 			tp->t_flags2 |= (TF2_MBUF_QUEUE_READY |
934 			    TF2_DONT_SACK_QUEUE);
935 		} else {
936 			/* All other timers wake us up */
937 			tp->t_flags2 &= ~(TF2_MBUF_QUEUE_READY |
938 			    TF2_DONT_SACK_QUEUE);
939 		}
940 		bbr->bbr_timer_src = frm;
941 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 0);
942 		bbr_log_hpts_diag(bbr, cts, &diag);
943 		bbr->rc_timer_first = 1;
944 	}
945 	bbr->rc_tmr_stopped = 0;
946 	bbr_log_type_bbrsnd(bbr, tot_len, slot, delay_calc, cts, frm, prev_delay);
947 }
948 
949 static void
bbr_timer_audit(struct tcpcb * tp,struct tcp_bbr * bbr,uint32_t cts,struct sockbuf * sb)950 bbr_timer_audit(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, struct sockbuf *sb)
951 {
952 	/*
953 	 * We received an ack, and then did not call send or were bounced
954 	 * out due to the hpts was running. Now a timer is up as well, is it
955 	 * the right timer?
956 	 */
957 	struct inpcb *inp;
958 	struct bbr_sendmap *rsm;
959 	uint32_t hpts_timeout;
960 	int tmr_up;
961 
962 	tmr_up = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
963 	if (bbr->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
964 		return;
965 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
966 	if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
967 	    (tmr_up == PACE_TMR_RXT)) {
968 		/* Should be an RXT */
969 		return;
970 	}
971 	inp = bbr->rc_inp;
972 	if (rsm == NULL) {
973 		/* Nothing outstanding? */
974 		if (tp->t_flags & TF_DELACK) {
975 			if (tmr_up == PACE_TMR_DELACK)
976 				/*
977 				 * We are supposed to have delayed ack up
978 				 * and we do
979 				 */
980 				return;
981 		} else if (((V_tcp_always_keepalive ||
982 			    inp->inp_socket->so_options & SO_KEEPALIVE) &&
983 			    (tp->t_state <= TCPS_CLOSING)) &&
984 			    (tmr_up == PACE_TMR_KEEP) &&
985 		    (tp->snd_max == tp->snd_una)) {
986 			/* We should have keep alive up and we do */
987 			return;
988 		}
989 	}
990 	if (rsm && (rsm->r_flags & BBR_SACK_PASSED)) {
991 		if ((tp->t_flags & TF_SENTFIN) &&
992 		    ((tp->snd_max - tp->snd_una) == 1) &&
993 		    (rsm->r_flags & BBR_HAS_FIN)) {
994 			/* needs to be a RXT */
995 			if (tmr_up == PACE_TMR_RXT)
996 				return;
997 			else
998 				goto wrong_timer;
999 		} else if (tmr_up == PACE_TMR_RACK)
1000 			return;
1001 		else
1002 			goto wrong_timer;
1003 	} else if (rsm && (tmr_up == PACE_TMR_RACK)) {
1004 		/* Rack timer has priority if we have data out */
1005 		return;
1006 	} else if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1007 		    ((tmr_up == PACE_TMR_TLP) ||
1008 	    (tmr_up == PACE_TMR_RXT))) {
1009 		/*
1010 		 * Either a TLP or RXT is fine if no sack-passed is in place
1011 		 * and data is outstanding.
1012 		 */
1013 		return;
1014 	} else if (tmr_up == PACE_TMR_DELACK) {
1015 		/*
1016 		 * If the delayed ack was going to go off before the
1017 		 * rtx/tlp/rack timer were going to expire, then that would
1018 		 * be the timer in control. Note we don't check the time
1019 		 * here trusting the code is correct.
1020 		 */
1021 		return;
1022 	}
1023 	if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1024 	    ((tmr_up == PACE_TMR_RXT) ||
1025 	     (tmr_up == PACE_TMR_TLP) ||
1026 	     (tmr_up == PACE_TMR_RACK))) {
1027 		/*
1028 		 * We have outstanding data and
1029 		 * we *do* have a RACK, TLP or RXT
1030 		 * timer running. We won't restart
1031 		 * anything here since thats probably ok we
1032 		 * will get called with some timer here shortly.
1033 		 */
1034 		return;
1035 	}
1036 	/*
1037 	 * Ok the timer originally started is not what we want now. We will
1038 	 * force the hpts to be stopped if any, and restart with the slot
1039 	 * set to what was in the saved slot.
1040 	 */
1041 wrong_timer:
1042 	if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) {
1043 		if (tcp_in_hpts(tp))
1044 			tcp_hpts_remove(tp);
1045 		bbr_timer_cancel(bbr, __LINE__, cts);
1046 		bbr_start_hpts_timer(bbr, tp, cts, 1, bbr->r_ctl.rc_last_delay_val,
1047 		    0);
1048 	} else {
1049 		/*
1050 		 * Output is hptsi so we just need to switch the type of
1051 		 * timer. We don't bother with keep-alive, since when we
1052 		 * jump through the output, it will start the keep-alive if
1053 		 * nothing is sent.
1054 		 *
1055 		 * We only need a delayed-ack added and or the hpts_timeout.
1056 		 */
1057 		hpts_timeout = bbr_timer_start(tp, bbr, cts);
1058 		if (tp->t_flags & TF_DELACK) {
1059 			if (hpts_timeout == 0) {
1060 				hpts_timeout = bbr_delack_time;
1061 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1062 			}
1063 			else if (hpts_timeout > bbr_delack_time) {
1064 				hpts_timeout = bbr_delack_time;
1065 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1066 			}
1067 		}
1068 		if (hpts_timeout) {
1069 			if (hpts_timeout > 0x7ffffffe)
1070 				hpts_timeout = 0x7ffffffe;
1071 			bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
1072 		}
1073 	}
1074 }
1075 
1076 int32_t bbr_clear_lost = 0;
1077 
1078 /*
1079  * Considers the two time values now (cts) and earlier.
1080  * If cts is smaller than earlier, we could have
1081  * had a sequence wrap (our counter wraps every
1082  * 70 min or so) or it could be just clock skew
1083  * getting us two different time values. Clock skew
1084  * will show up within 10ms or so. So in such
1085  * a case (where cts is behind earlier time by
1086  * less than 10ms) we return 0. Otherwise we
1087  * return the true difference between them.
1088  */
1089 static inline uint32_t
bbr_calc_time(uint32_t cts,uint32_t earlier_time)1090 bbr_calc_time(uint32_t cts, uint32_t earlier_time) {
1091 	/*
1092 	 * Given two timestamps, the current time stamp cts, and some other
1093 	 * time-stamp taken in theory earlier return the difference. The
1094 	 * trick is here sometimes locking will get the other timestamp
1095 	 * after the cts. If this occurs we need to return 0.
1096 	 */
1097 	if (TSTMP_GEQ(cts, earlier_time))
1098 		return (cts - earlier_time);
1099 	/*
1100 	 * cts is behind earlier_time if its less than 10ms consider it 0.
1101 	 * If its more than 10ms difference then we had a time wrap. Else
1102 	 * its just the normal locking foo. I wonder if we should not go to
1103 	 * 64bit TS and get rid of this issue.
1104 	 */
1105 	if (TSTMP_GEQ((cts + 10000), earlier_time))
1106 		return (0);
1107 	/*
1108 	 * Ok the time must have wrapped. So we need to answer a large
1109 	 * amount of time, which the normal subtraction should do.
1110 	 */
1111 	return (cts - earlier_time);
1112 }
1113 
1114 static int
sysctl_bbr_clear_lost(SYSCTL_HANDLER_ARGS)1115 sysctl_bbr_clear_lost(SYSCTL_HANDLER_ARGS)
1116 {
1117 	uint32_t stat;
1118 	int32_t error;
1119 
1120 	error = SYSCTL_OUT(req, &bbr_clear_lost, sizeof(uint32_t));
1121 	if (error || req->newptr == NULL)
1122 		return error;
1123 
1124 	error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
1125 	if (error)
1126 		return (error);
1127 	if (stat == 1) {
1128 #ifdef BBR_INVARIANTS
1129 		printf("Clearing BBR lost counters\n");
1130 #endif
1131 		COUNTER_ARRAY_ZERO(bbr_state_lost, BBR_MAX_STAT);
1132 		COUNTER_ARRAY_ZERO(bbr_state_time, BBR_MAX_STAT);
1133 		COUNTER_ARRAY_ZERO(bbr_state_resend, BBR_MAX_STAT);
1134 	} else if (stat == 2) {
1135 #ifdef BBR_INVARIANTS
1136 		printf("Clearing BBR option counters\n");
1137 #endif
1138 		COUNTER_ARRAY_ZERO(bbr_opts_arry, BBR_OPTS_SIZE);
1139 	} else if (stat == 3) {
1140 #ifdef BBR_INVARIANTS
1141 		printf("Clearing BBR stats counters\n");
1142 #endif
1143 		COUNTER_ARRAY_ZERO(bbr_stat_arry, BBR_STAT_SIZE);
1144 	} else if (stat == 4) {
1145 #ifdef BBR_INVARIANTS
1146 		printf("Clearing BBR out-size counters\n");
1147 #endif
1148 		COUNTER_ARRAY_ZERO(bbr_out_size, TCP_MSS_ACCT_SIZE);
1149 	}
1150 	bbr_clear_lost = 0;
1151 	return (0);
1152 }
1153 
1154 static void
bbr_init_sysctls(void)1155 bbr_init_sysctls(void)
1156 {
1157 	struct sysctl_oid *bbr_probertt;
1158 	struct sysctl_oid *bbr_hptsi;
1159 	struct sysctl_oid *bbr_measure;
1160 	struct sysctl_oid *bbr_cwnd;
1161 	struct sysctl_oid *bbr_timeout;
1162 	struct sysctl_oid *bbr_states;
1163 	struct sysctl_oid *bbr_startup;
1164 	struct sysctl_oid *bbr_policer;
1165 
1166 	/* Probe rtt controls */
1167 	bbr_probertt = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1168 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1169 	    OID_AUTO,
1170 	    "probertt",
1171 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1172 	    "");
1173 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1174 	    SYSCTL_CHILDREN(bbr_probertt),
1175 	    OID_AUTO, "gain", CTLFLAG_RW,
1176 	    &bbr_rttprobe_gain, 192,
1177 	    "What is the filter gain drop in probe_rtt (0=disable)?");
1178 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1179 	    SYSCTL_CHILDREN(bbr_probertt),
1180 	    OID_AUTO, "cwnd", CTLFLAG_RW,
1181 	    &bbr_rtt_probe_cwndtarg, 4,
1182 	    "How many mss's are outstanding during probe-rtt");
1183 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1184 	    SYSCTL_CHILDREN(bbr_probertt),
1185 	    OID_AUTO, "int", CTLFLAG_RW,
1186 	    &bbr_rtt_probe_limit, 4000000,
1187 	    "If RTT has not shrank in this many micro-seconds enter probe-rtt");
1188 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1189 	    SYSCTL_CHILDREN(bbr_probertt),
1190 	    OID_AUTO, "mintime", CTLFLAG_RW,
1191 	    &bbr_rtt_probe_time, 200000,
1192 	    "How many microseconds in probe-rtt");
1193 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1194 	    SYSCTL_CHILDREN(bbr_probertt),
1195 	    OID_AUTO, "filter_len_sec", CTLFLAG_RW,
1196 	    &bbr_filter_len_sec, 6,
1197 	    "How long in seconds does the rttProp filter run?");
1198 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1199 	    SYSCTL_CHILDREN(bbr_probertt),
1200 	    OID_AUTO, "drain_rtt", CTLFLAG_RW,
1201 	    &bbr_drain_rtt, BBR_SRTT,
1202 	    "What is the drain rtt to use in probeRTT (rtt_prop=0, rtt_rack=1, rtt_pkt=2, rtt_srtt=3?");
1203 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1204 	    SYSCTL_CHILDREN(bbr_probertt),
1205 	    OID_AUTO, "can_force", CTLFLAG_RW,
1206 	    &bbr_can_force_probertt, 0,
1207 	    "If we keep setting new low rtt's but delay going in probe-rtt can we force in??");
1208 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1209 	    SYSCTL_CHILDREN(bbr_probertt),
1210 	    OID_AUTO, "enter_sets_force", CTLFLAG_RW,
1211 	    &bbr_probertt_sets_rtt, 0,
1212 	    "In NF mode, do we imitate google_mode and set the rttProp on entry to probe-rtt?");
1213 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1214 	    SYSCTL_CHILDREN(bbr_probertt),
1215 	    OID_AUTO, "can_adjust", CTLFLAG_RW,
1216 	    &bbr_can_adjust_probertt, 1,
1217 	    "Can we dynamically adjust the probe-rtt limits and times?");
1218 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1219 	    SYSCTL_CHILDREN(bbr_probertt),
1220 	    OID_AUTO, "is_ratio", CTLFLAG_RW,
1221 	    &bbr_is_ratio, 0,
1222 	    "is the limit to filter a ratio?");
1223 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1224 	    SYSCTL_CHILDREN(bbr_probertt),
1225 	    OID_AUTO, "use_cwnd", CTLFLAG_RW,
1226 	    &bbr_prtt_slam_cwnd, 0,
1227 	    "Should we set/recover cwnd?");
1228 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1229 	    SYSCTL_CHILDREN(bbr_probertt),
1230 	    OID_AUTO, "can_use_ts", CTLFLAG_RW,
1231 	    &bbr_can_use_ts_for_rtt, 1,
1232 	    "Can we use the ms timestamp if available for retransmistted rtt calculations?");
1233 
1234 	/* Pacing controls */
1235 	bbr_hptsi = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1236 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1237 	    OID_AUTO,
1238 	    "pacing",
1239 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1240 	    "");
1241 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1242 	    SYSCTL_CHILDREN(bbr_hptsi),
1243 	    OID_AUTO, "hw_pacing", CTLFLAG_RW,
1244 	    &bbr_allow_hdwr_pacing, 1,
1245 	    "Do we allow hardware pacing?");
1246 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1247 	    SYSCTL_CHILDREN(bbr_hptsi),
1248 	    OID_AUTO, "hw_pacing_limit", CTLFLAG_RW,
1249 	    &bbr_hardware_pacing_limit, 4000,
1250 	    "Do we have a limited number of connections for pacing chelsio (0=no limit)?");
1251 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1252 	    SYSCTL_CHILDREN(bbr_hptsi),
1253 	    OID_AUTO, "hw_pacing_adj", CTLFLAG_RW,
1254 	    &bbr_hdwr_pace_adjust, 2,
1255 	    "Multiplier to calculated tso size?");
1256 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1257 	    SYSCTL_CHILDREN(bbr_hptsi),
1258 	    OID_AUTO, "hw_pacing_floor", CTLFLAG_RW,
1259 	    &bbr_hdwr_pace_floor, 1,
1260 	    "Do we invoke the hardware pacing floor?");
1261 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1262 	    SYSCTL_CHILDREN(bbr_hptsi),
1263 	    OID_AUTO, "hw_pacing_delay_cnt", CTLFLAG_RW,
1264 	    &bbr_hdwr_pacing_delay_cnt, 10,
1265 	    "How many packets must be sent after hdwr pacing is enabled");
1266 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1267 	    SYSCTL_CHILDREN(bbr_hptsi),
1268 	    OID_AUTO, "bw_cross", CTLFLAG_RW,
1269 	    &bbr_cross_over, 3000000,
1270 	    "What is the point where we cross over to linux like TSO size set");
1271 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1272 	    SYSCTL_CHILDREN(bbr_hptsi),
1273 	    OID_AUTO, "seg_deltarg", CTLFLAG_RW,
1274 	    &bbr_hptsi_segments_delay_tar, 7000,
1275 	    "What is the worse case delay target for hptsi < 48Mbp connections");
1276 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1277 	    SYSCTL_CHILDREN(bbr_hptsi),
1278 	    OID_AUTO, "enet_oh", CTLFLAG_RW,
1279 	    &bbr_include_enet_oh, 0,
1280 	    "Do we include the ethernet overhead in calculating pacing delay?");
1281 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1282 	    SYSCTL_CHILDREN(bbr_hptsi),
1283 	    OID_AUTO, "ip_oh", CTLFLAG_RW,
1284 	    &bbr_include_ip_oh, 1,
1285 	    "Do we include the IP overhead in calculating pacing delay?");
1286 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1287 	    SYSCTL_CHILDREN(bbr_hptsi),
1288 	    OID_AUTO, "tcp_oh", CTLFLAG_RW,
1289 	    &bbr_include_tcp_oh, 0,
1290 	    "Do we include the TCP overhead in calculating pacing delay?");
1291 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1292 	    SYSCTL_CHILDREN(bbr_hptsi),
1293 	    OID_AUTO, "google_discount", CTLFLAG_RW,
1294 	    &bbr_google_discount, 10,
1295 	    "What is the default google discount percentage wise for pacing (11 = 1.1%%)?");
1296 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1297 	    SYSCTL_CHILDREN(bbr_hptsi),
1298 	    OID_AUTO, "all_get_min", CTLFLAG_RW,
1299 	    &bbr_all_get_min, 0,
1300 	    "If you are less than a MSS do you just get the min?");
1301 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1302 	    SYSCTL_CHILDREN(bbr_hptsi),
1303 	    OID_AUTO, "tso_min", CTLFLAG_RW,
1304 	    &bbr_hptsi_bytes_min, 1460,
1305 	    "For 0 -> 24Mbps what is floor number of segments for TSO");
1306 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1307 	    SYSCTL_CHILDREN(bbr_hptsi),
1308 	    OID_AUTO, "seg_tso_max", CTLFLAG_RW,
1309 	    &bbr_hptsi_segments_max, 6,
1310 	    "For 0 -> 24Mbps what is top number of segments for TSO");
1311 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1312 	    SYSCTL_CHILDREN(bbr_hptsi),
1313 	    OID_AUTO, "seg_floor", CTLFLAG_RW,
1314 	    &bbr_hptsi_segments_floor, 1,
1315 	    "Minimum TSO size we will fall too in segments");
1316 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1317 	    SYSCTL_CHILDREN(bbr_hptsi),
1318 	    OID_AUTO, "utter_max", CTLFLAG_RW,
1319 	    &bbr_hptsi_utter_max, 0,
1320 	    "The absolute maximum that any pacing (outside of hardware) can be");
1321 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1322 	    SYSCTL_CHILDREN(bbr_hptsi),
1323 	    OID_AUTO, "seg_divisor", CTLFLAG_RW,
1324 	    &bbr_hptsi_per_second, 100,
1325 	    "What is the divisor in our hptsi TSO calculation 512Mbps < X > 24Mbps ");
1326 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1327 	    SYSCTL_CHILDREN(bbr_hptsi),
1328 	    OID_AUTO, "srtt_mul", CTLFLAG_RW,
1329 	    &bbr_hptsi_max_mul, 1,
1330 	    "The multiplier for pace len max");
1331 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1332 	    SYSCTL_CHILDREN(bbr_hptsi),
1333 	    OID_AUTO, "srtt_div", CTLFLAG_RW,
1334 	    &bbr_hptsi_max_div, 2,
1335 	    "The divisor for pace len max");
1336 	/* Measurement controls */
1337 	bbr_measure = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1338 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1339 	    OID_AUTO,
1340 	    "measure",
1341 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1342 	    "Measurement controls");
1343 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1344 	    SYSCTL_CHILDREN(bbr_measure),
1345 	    OID_AUTO, "min_i_bw", CTLFLAG_RW,
1346 	    &bbr_initial_bw_bps, 62500,
1347 	    "Minimum initial b/w in bytes per second");
1348 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1349 	    SYSCTL_CHILDREN(bbr_measure),
1350 	    OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1351 	    &bbr_sack_not_required, 0,
1352 	    "Do we allow bbr to run on connections not supporting SACK?");
1353 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1354 	    SYSCTL_CHILDREN(bbr_measure),
1355 	    OID_AUTO, "use_google", CTLFLAG_RW,
1356 	    &bbr_use_google_algo, 0,
1357 	    "Use has close to google V1.0 has possible?");
1358 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1359 	    SYSCTL_CHILDREN(bbr_measure),
1360 	    OID_AUTO, "ts_limiting", CTLFLAG_RW,
1361 	    &bbr_ts_limiting, 1,
1362 	    "Do we attempt to use the peers timestamp to limit b/w caculations?");
1363 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1364 	    SYSCTL_CHILDREN(bbr_measure),
1365 	    OID_AUTO, "ts_can_raise", CTLFLAG_RW,
1366 	    &bbr_ts_can_raise, 0,
1367 	    "Can we raise the b/w via timestamp b/w calculation?");
1368 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1369 	    SYSCTL_CHILDREN(bbr_measure),
1370 	    OID_AUTO, "ts_delta", CTLFLAG_RW,
1371 	    &bbr_min_usec_delta, 20000,
1372 	    "How long in usec between ts of our sends in ts validation code?");
1373 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1374 	    SYSCTL_CHILDREN(bbr_measure),
1375 	    OID_AUTO, "ts_peer_delta", CTLFLAG_RW,
1376 	    &bbr_min_peer_delta, 20,
1377 	    "What min numerical value should be between the peer deltas?");
1378 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1379 	    SYSCTL_CHILDREN(bbr_measure),
1380 	    OID_AUTO, "ts_delta_percent", CTLFLAG_RW,
1381 	    &bbr_delta_percent, 150,
1382 	    "What percentage (150 = 15.0) do we allow variance for?");
1383 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1384 	    SYSCTL_CHILDREN(bbr_measure),
1385 	    OID_AUTO, "min_measure_good_bw", CTLFLAG_RW,
1386 	    &bbr_min_measurements_req, 1,
1387 	    "What is the minimum measurement count we need before we switch to our b/w estimate");
1388 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1389 	    SYSCTL_CHILDREN(bbr_measure),
1390 	    OID_AUTO, "min_measure_before_pace", CTLFLAG_RW,
1391 	    &bbr_no_pacing_until, 4,
1392 	    "How many pkt-epoch's (0 is off) do we need before pacing is on?");
1393 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1394 	    SYSCTL_CHILDREN(bbr_measure),
1395 	    OID_AUTO, "quanta", CTLFLAG_RW,
1396 	    &bbr_quanta, 2,
1397 	    "Extra quanta to add when calculating the target (ID section 4.2.3.2).");
1398 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1399 	    SYSCTL_CHILDREN(bbr_measure),
1400 	    OID_AUTO, "noretran", CTLFLAG_RW,
1401 	    &bbr_no_retran, 0,
1402 	    "Should google mode not use retransmission measurements for the b/w estimation?");
1403 	/* State controls */
1404 	bbr_states = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1405 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1406 	    OID_AUTO,
1407 	    "states",
1408 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1409 	    "State controls");
1410 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1411 	    SYSCTL_CHILDREN(bbr_states),
1412 	    OID_AUTO, "idle_restart", CTLFLAG_RW,
1413 	    &bbr_uses_idle_restart, 0,
1414 	    "Do we use a new special idle_restart state to ramp back up quickly?");
1415 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1416 	    SYSCTL_CHILDREN(bbr_states),
1417 	    OID_AUTO, "idle_restart_threshold", CTLFLAG_RW,
1418 	    &bbr_idle_restart_threshold, 100000,
1419 	    "How long must we be idle before we restart??");
1420 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1421 	    SYSCTL_CHILDREN(bbr_states),
1422 	    OID_AUTO, "use_pkt_epoch", CTLFLAG_RW,
1423 	    &bbr_state_is_pkt_epoch, 0,
1424 	    "Do we use a pkt-epoch for substate if 0 rttProp?");
1425 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1426 	    SYSCTL_CHILDREN(bbr_states),
1427 	    OID_AUTO, "startup_rtt_gain", CTLFLAG_RW,
1428 	    &bbr_rtt_gain_thresh, 0,
1429 	    "What increase in RTT triggers us to stop ignoring no-loss and possibly exit startup?");
1430 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1431 	    SYSCTL_CHILDREN(bbr_states),
1432 	    OID_AUTO, "drain_floor", CTLFLAG_RW,
1433 	    &bbr_drain_floor, 88,
1434 	    "What is the lowest we can drain (pg) too?");
1435 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1436 	    SYSCTL_CHILDREN(bbr_states),
1437 	    OID_AUTO, "drain_2_target", CTLFLAG_RW,
1438 	    &bbr_state_drain_2_tar, 1,
1439 	    "Do we drain to target in drain substate?");
1440 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1441 	    SYSCTL_CHILDREN(bbr_states),
1442 	    OID_AUTO, "gain_2_target", CTLFLAG_RW,
1443 	    &bbr_gain_to_target, 1,
1444 	    "Does probe bw gain to target??");
1445 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1446 	    SYSCTL_CHILDREN(bbr_states),
1447 	    OID_AUTO, "gain_extra_time", CTLFLAG_RW,
1448 	    &bbr_gain_gets_extra_too, 1,
1449 	    "Does probe bw gain get the extra time too?");
1450 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1451 	    SYSCTL_CHILDREN(bbr_states),
1452 	    OID_AUTO, "ld_div", CTLFLAG_RW,
1453 	    &bbr_drain_drop_div, 5,
1454 	    "Long drain drop divider?");
1455 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1456 	    SYSCTL_CHILDREN(bbr_states),
1457 	    OID_AUTO, "ld_mul", CTLFLAG_RW,
1458 	    &bbr_drain_drop_mul, 4,
1459 	    "Long drain drop multiplier?");
1460 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1461 	    SYSCTL_CHILDREN(bbr_states),
1462 	    OID_AUTO, "rand_ot_disc", CTLFLAG_RW,
1463 	    &bbr_rand_ot, 50,
1464 	    "Random discount of the ot?");
1465 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1466 	    SYSCTL_CHILDREN(bbr_states),
1467 	    OID_AUTO, "dr_filter_life", CTLFLAG_RW,
1468 	    &bbr_num_pktepo_for_del_limit, BBR_NUM_RTTS_FOR_DEL_LIMIT,
1469 	    "How many packet-epochs does the b/w delivery rate last?");
1470 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1471 	    SYSCTL_CHILDREN(bbr_states),
1472 	    OID_AUTO, "subdrain_applimited", CTLFLAG_RW,
1473 	    &bbr_sub_drain_app_limit, 0,
1474 	    "Does our sub-state drain invoke app limited if its long?");
1475 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1476 	    SYSCTL_CHILDREN(bbr_states),
1477 	    OID_AUTO, "use_cwnd_subdrain", CTLFLAG_RW,
1478 	    &bbr_sub_drain_slam_cwnd, 0,
1479 	    "Should we set/recover cwnd for sub-state drain?");
1480 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1481 	    SYSCTL_CHILDREN(bbr_states),
1482 	    OID_AUTO, "use_cwnd_maindrain", CTLFLAG_RW,
1483 	    &bbr_slam_cwnd_in_main_drain, 0,
1484 	    "Should we set/recover cwnd for main-state drain?");
1485 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1486 	    SYSCTL_CHILDREN(bbr_states),
1487 	    OID_AUTO, "google_gets_earlyout", CTLFLAG_RW,
1488 	    &google_allow_early_out, 1,
1489 	    "Should we allow google probe-bw/drain to exit early at flight target?");
1490 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1491 	    SYSCTL_CHILDREN(bbr_states),
1492 	    OID_AUTO, "google_exit_loss", CTLFLAG_RW,
1493 	    &google_consider_lost, 1,
1494 	    "Should we have losses exit gain of probebw in google mode??");
1495 	/* Startup controls */
1496 	bbr_startup = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1497 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1498 	    OID_AUTO,
1499 	    "startup",
1500 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1501 	    "Startup controls");
1502 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1503 	    SYSCTL_CHILDREN(bbr_startup),
1504 	    OID_AUTO, "cheat_iwnd", CTLFLAG_RW,
1505 	    &bbr_sends_full_iwnd, 1,
1506 	    "Do we not pace but burst out initial windows has our TSO size?");
1507 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1508 	    SYSCTL_CHILDREN(bbr_startup),
1509 	    OID_AUTO, "loss_threshold", CTLFLAG_RW,
1510 	    &bbr_startup_loss_thresh, 2000,
1511 	    "In startup what is the loss threshold in a pe that will exit us from startup?");
1512 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1513 	    SYSCTL_CHILDREN(bbr_startup),
1514 	    OID_AUTO, "use_lowerpg", CTLFLAG_RW,
1515 	    &bbr_use_lower_gain_in_startup, 1,
1516 	    "Should we use a lower hptsi gain if we see loss in startup?");
1517 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1518 	    SYSCTL_CHILDREN(bbr_startup),
1519 	    OID_AUTO, "gain", CTLFLAG_RW,
1520 	    &bbr_start_exit, 25,
1521 	    "What gain percent do we need to see to stay in startup??");
1522 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1523 	    SYSCTL_CHILDREN(bbr_startup),
1524 	    OID_AUTO, "low_gain", CTLFLAG_RW,
1525 	    &bbr_low_start_exit, 15,
1526 	    "What gain percent do we need to see to stay in the lower gain startup??");
1527 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1528 	    SYSCTL_CHILDREN(bbr_startup),
1529 	    OID_AUTO, "loss_exit", CTLFLAG_RW,
1530 	    &bbr_exit_startup_at_loss, 1,
1531 	    "Should we exit startup at loss in an epoch if we are not gaining?");
1532 	/* CWND controls */
1533 	bbr_cwnd = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1534 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1535 	    OID_AUTO,
1536 	    "cwnd",
1537 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1538 	    "Cwnd controls");
1539 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1540 	    SYSCTL_CHILDREN(bbr_cwnd),
1541 	    OID_AUTO, "tar_rtt", CTLFLAG_RW,
1542 	    &bbr_cwndtarget_rtt_touse, 0,
1543 	    "Target cwnd rtt measurement to use (0=rtt_prop, 1=rtt_rack, 2=pkt_rtt, 3=srtt)?");
1544 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1545 	    SYSCTL_CHILDREN(bbr_cwnd),
1546 	    OID_AUTO, "may_shrink", CTLFLAG_RW,
1547 	    &bbr_cwnd_may_shrink, 0,
1548 	    "Can the cwnd shrink if it would grow to more than the target?");
1549 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1550 	    SYSCTL_CHILDREN(bbr_cwnd),
1551 	    OID_AUTO, "max_target_limit", CTLFLAG_RW,
1552 	    &bbr_target_cwnd_mult_limit, 8,
1553 	    "Do we limit the cwnd to some multiple of the cwnd target if cwnd can't shrink 0=no?");
1554 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1555 	    SYSCTL_CHILDREN(bbr_cwnd),
1556 	    OID_AUTO, "highspeed_min", CTLFLAG_RW,
1557 	    &bbr_cwnd_min_val_hs, BBR_HIGHSPEED_NUM_MSS,
1558 	    "What is the high-speed min cwnd (rttProp under 1ms)");
1559 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1560 	    SYSCTL_CHILDREN(bbr_cwnd),
1561 	    OID_AUTO, "lowspeed_min", CTLFLAG_RW,
1562 	    &bbr_cwnd_min_val, BBR_PROBERTT_NUM_MSS,
1563 	    "What is the min cwnd (rttProp > 1ms)");
1564 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1565 	    SYSCTL_CHILDREN(bbr_cwnd),
1566 	    OID_AUTO, "initwin", CTLFLAG_RW,
1567 	    &bbr_def_init_win, 10,
1568 	    "What is the BBR initial window, if 0 use tcp version");
1569 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1570 	    SYSCTL_CHILDREN(bbr_cwnd),
1571 	    OID_AUTO, "do_loss_red", CTLFLAG_RW,
1572 	    &bbr_do_red, 600,
1573 	    "Do we reduce the b/w at exit from recovery based on ratio of prop/srtt (800=80.0, 0=off)?");
1574 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1575 	    SYSCTL_CHILDREN(bbr_cwnd),
1576 	    OID_AUTO, "red_scale", CTLFLAG_RW,
1577 	    &bbr_red_scale, 20000,
1578 	    "What RTT do we scale with?");
1579 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1580 	    SYSCTL_CHILDREN(bbr_cwnd),
1581 	    OID_AUTO, "red_growslow", CTLFLAG_RW,
1582 	    &bbr_red_growth_restrict, 1,
1583 	    "Do we restrict cwnd growth for whats in flight?");
1584 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1585 	    SYSCTL_CHILDREN(bbr_cwnd),
1586 	    OID_AUTO, "red_div", CTLFLAG_RW,
1587 	    &bbr_red_div, 2,
1588 	    "If we reduce whats the divisor?");
1589 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1590 	    SYSCTL_CHILDREN(bbr_cwnd),
1591 	    OID_AUTO, "red_mul", CTLFLAG_RW,
1592 	    &bbr_red_mul, 1,
1593 	    "If we reduce whats the mulitiplier?");
1594 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1595 	    SYSCTL_CHILDREN(bbr_cwnd),
1596 	    OID_AUTO, "target_is_unit", CTLFLAG_RW,
1597 	    &bbr_target_is_bbunit, 0,
1598 	    "Is the state target the pacing_gain or BBR_UNIT?");
1599 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1600 	    SYSCTL_CHILDREN(bbr_cwnd),
1601 	    OID_AUTO, "drop_limit", CTLFLAG_RW,
1602 	    &bbr_drop_limit, 0,
1603 	    "Number of segments limit for drop (0=use min_cwnd w/flight)?");
1604 
1605 	/* Timeout controls */
1606 	bbr_timeout = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1607 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1608 	    OID_AUTO,
1609 	    "timeout",
1610 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1611 	    "Time out controls");
1612 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1613 	    SYSCTL_CHILDREN(bbr_timeout),
1614 	    OID_AUTO, "delack", CTLFLAG_RW,
1615 	    &bbr_delack_time, 100000,
1616 	    "BBR's delayed ack time");
1617 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1618 	    SYSCTL_CHILDREN(bbr_timeout),
1619 	    OID_AUTO, "tlp_uses", CTLFLAG_RW,
1620 	    &bbr_tlp_type_to_use, 3,
1621 	    "RTT that TLP uses in its calculations, 0=rttProp, 1=Rack_rtt, 2=pkt_rtt and 3=srtt");
1622 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1623 	    SYSCTL_CHILDREN(bbr_timeout),
1624 	    OID_AUTO, "persmin", CTLFLAG_RW,
1625 	    &bbr_persist_min, 250000,
1626 	    "What is the minimum time in microseconds between persists");
1627 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1628 	    SYSCTL_CHILDREN(bbr_timeout),
1629 	    OID_AUTO, "persmax", CTLFLAG_RW,
1630 	    &bbr_persist_max, 1000000,
1631 	    "What is the largest delay in microseconds between persists");
1632 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1633 	    SYSCTL_CHILDREN(bbr_timeout),
1634 	    OID_AUTO, "tlp_minto", CTLFLAG_RW,
1635 	    &bbr_tlp_min, 10000,
1636 	    "TLP Min timeout in usecs");
1637 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1638 	    SYSCTL_CHILDREN(bbr_timeout),
1639 	    OID_AUTO, "tlp_dack_time", CTLFLAG_RW,
1640 	    &bbr_delayed_ack_time, 200000,
1641 	    "TLP delayed ack compensation value");
1642 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1643 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1644 	    OID_AUTO, "minrto", CTLFLAG_RW,
1645 	    &bbr_rto_min_ms, 30,
1646 	    "Minimum RTO in ms");
1647 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1648 	    SYSCTL_CHILDREN(bbr_timeout),
1649 	    OID_AUTO, "maxrto", CTLFLAG_RW,
1650 	    &bbr_rto_max_sec, 4,
1651 	    "Maximum RTO in seconds -- should be at least as large as min_rto");
1652 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1653 	    SYSCTL_CHILDREN(bbr_timeout),
1654 	    OID_AUTO, "tlp_retry", CTLFLAG_RW,
1655 	    &bbr_tlp_max_resend, 2,
1656 	    "How many times does TLP retry a single segment or multiple with no ACK");
1657 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1658 	    SYSCTL_CHILDREN(bbr_timeout),
1659 	    OID_AUTO, "minto", CTLFLAG_RW,
1660 	    &bbr_min_to, 1000,
1661 	    "Minimum rack timeout in useconds");
1662 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1663 	    SYSCTL_CHILDREN(bbr_timeout),
1664 	    OID_AUTO, "pktdelay", CTLFLAG_RW,
1665 	    &bbr_pkt_delay, 1000,
1666 	    "Extra RACK time (in useconds) besides reordering thresh");
1667 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1668 	    SYSCTL_CHILDREN(bbr_timeout),
1669 	    OID_AUTO, "incr_tmrs", CTLFLAG_RW,
1670 	    &bbr_incr_timers, 1,
1671 	    "Increase the RXT/TLP timer by the pacing time used?");
1672 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1673 	    SYSCTL_CHILDREN(bbr_timeout),
1674 	    OID_AUTO, "rxtmark_sackpassed", CTLFLAG_RW,
1675 	    &bbr_marks_rxt_sack_passed, 0,
1676 	    "Mark sack passed on all those not ack'd when a RXT hits?");
1677 	/* Policer controls */
1678 	bbr_policer = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1679 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1680 	    OID_AUTO,
1681 	    "policer",
1682 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1683 	    "Policer controls");
1684 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1685 	    SYSCTL_CHILDREN(bbr_policer),
1686 	    OID_AUTO, "detect_enable", CTLFLAG_RW,
1687 	    &bbr_policer_detection_enabled, 1,
1688 	    "Is policer detection enabled??");
1689 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1690 	    SYSCTL_CHILDREN(bbr_policer),
1691 	    OID_AUTO, "min_pes", CTLFLAG_RW,
1692 	    &bbr_lt_intvl_min_rtts, 4,
1693 	    "Minimum number of PE's?");
1694 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1695 	    SYSCTL_CHILDREN(bbr_policer),
1696 	    OID_AUTO, "bwdiff", CTLFLAG_RW,
1697 	    &bbr_lt_bw_diff, (4000/8),
1698 	    "Minimal bw diff?");
1699 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1700 	    SYSCTL_CHILDREN(bbr_policer),
1701 	    OID_AUTO, "bwratio", CTLFLAG_RW,
1702 	    &bbr_lt_bw_ratio, 8,
1703 	    "Minimal bw diff?");
1704 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1705 	    SYSCTL_CHILDREN(bbr_policer),
1706 	    OID_AUTO, "from_rack_rxt", CTLFLAG_RW,
1707 	    &bbr_policer_call_from_rack_to, 0,
1708 	    "Do we call the policer detection code from a rack-timeout?");
1709 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1710 	    SYSCTL_CHILDREN(bbr_policer),
1711 	    OID_AUTO, "false_postive", CTLFLAG_RW,
1712 	    &bbr_lt_intvl_fp, 0,
1713 	    "What packet epoch do we do false-positive detection at (0=no)?");
1714 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1715 	    SYSCTL_CHILDREN(bbr_policer),
1716 	    OID_AUTO, "loss_thresh", CTLFLAG_RW,
1717 	    &bbr_lt_loss_thresh, 196,
1718 	    "Loss threshold 196 = 19.6%?");
1719 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1720 	    SYSCTL_CHILDREN(bbr_policer),
1721 	    OID_AUTO, "false_postive_thresh", CTLFLAG_RW,
1722 	    &bbr_lt_fd_thresh, 100,
1723 	    "What percentage is the false detection threshold (150=15.0)?");
1724 	/* All the rest */
1725 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1726 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1727 	    OID_AUTO, "cheat_rxt", CTLFLAG_RW,
1728 	    &bbr_use_rack_resend_cheat, 0,
1729 	    "Do we burst 1ms between sends on retransmissions (like rack)?");
1730 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1731 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1732 	    OID_AUTO, "error_paceout", CTLFLAG_RW,
1733 	    &bbr_error_base_paceout, 10000,
1734 	    "When we hit an error what is the min to pace out in usec's?");
1735 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1736 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1737 	    OID_AUTO, "kill_paceout", CTLFLAG_RW,
1738 	    &bbr_max_net_error_cnt, 10,
1739 	    "When we hit this many errors in a row, kill the session?");
1740 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1741 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1742 	    OID_AUTO, "data_after_close", CTLFLAG_RW,
1743 	    &bbr_ignore_data_after_close, 1,
1744 	    "Do we hold off sending a RST until all pending data is ack'd");
1745 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1746 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1747 	    OID_AUTO, "resend_use_tso", CTLFLAG_RW,
1748 	    &bbr_resends_use_tso, 0,
1749 	    "Can resends use TSO?");
1750 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1751 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1752 	    OID_AUTO, "sblklimit", CTLFLAG_RW,
1753 	    &bbr_sack_block_limit, 128,
1754 	    "When do we start ignoring small sack blocks");
1755 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1756 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1757 	    OID_AUTO, "bb_verbose", CTLFLAG_RW,
1758 	    &bbr_verbose_logging, 0,
1759 	    "Should BBR black box logging be verbose");
1760 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1761 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1762 	    OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1763 	    &bbr_reorder_thresh, 2,
1764 	    "What factor for rack will be added when seeing reordering (shift right)");
1765 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1766 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1767 	    OID_AUTO, "reorder_fade", CTLFLAG_RW,
1768 	    &bbr_reorder_fade, 0,
1769 	    "Does reorder detection fade, if so how many ms (0 means never)");
1770 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1771 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1772 	    OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1773 	    &bbr_tlp_thresh, 1,
1774 	    "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1775 	/* Stats and counters */
1776 	/* The pacing counters for hdwr/software can't be in the array */
1777 	bbr_nohdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1778 	bbr_hdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1779 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1780 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1781 	    OID_AUTO, "enob_hdwr_pacing", CTLFLAG_RD,
1782 	    &bbr_hdwr_pacing_enobuf,
1783 	    "Total number of enobufs for hardware paced flows");
1784 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1785 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1786 	    OID_AUTO, "enob_no_hdwr_pacing", CTLFLAG_RD,
1787 	    &bbr_nohdwr_pacing_enobuf,
1788 	    "Total number of enobufs for non-hardware paced flows");
1789 
1790 	bbr_flows_whdwr_pacing = counter_u64_alloc(M_WAITOK);
1791 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1792 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1793 	    OID_AUTO, "hdwr_pacing", CTLFLAG_RD,
1794 	    &bbr_flows_whdwr_pacing,
1795 	    "Total number of hardware paced flows");
1796 	bbr_flows_nohdwr_pacing = counter_u64_alloc(M_WAITOK);
1797 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1798 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1799 	    OID_AUTO, "software_pacing", CTLFLAG_RD,
1800 	    &bbr_flows_nohdwr_pacing,
1801 	    "Total number of software paced flows");
1802 	COUNTER_ARRAY_ALLOC(bbr_stat_arry, BBR_STAT_SIZE, M_WAITOK);
1803 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1804 	    OID_AUTO, "stats", CTLFLAG_RD,
1805 	    bbr_stat_arry, BBR_STAT_SIZE, "BBR Stats");
1806 	COUNTER_ARRAY_ALLOC(bbr_opts_arry, BBR_OPTS_SIZE, M_WAITOK);
1807 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1808 	    OID_AUTO, "opts", CTLFLAG_RD,
1809 	    bbr_opts_arry, BBR_OPTS_SIZE, "BBR Option Stats");
1810 	COUNTER_ARRAY_ALLOC(bbr_state_lost, BBR_MAX_STAT, M_WAITOK);
1811 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1812 	    OID_AUTO, "lost", CTLFLAG_RD,
1813 	    bbr_state_lost, BBR_MAX_STAT, "Stats of when losses occur");
1814 	COUNTER_ARRAY_ALLOC(bbr_state_resend, BBR_MAX_STAT, M_WAITOK);
1815 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1816 	    OID_AUTO, "stateresend", CTLFLAG_RD,
1817 	    bbr_state_resend, BBR_MAX_STAT, "Stats of what states resend");
1818 	COUNTER_ARRAY_ALLOC(bbr_state_time, BBR_MAX_STAT, M_WAITOK);
1819 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1820 	    OID_AUTO, "statetime", CTLFLAG_RD,
1821 	    bbr_state_time, BBR_MAX_STAT, "Stats of time spent in the states");
1822 	COUNTER_ARRAY_ALLOC(bbr_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1823 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1824 	    OID_AUTO, "outsize", CTLFLAG_RD,
1825 	    bbr_out_size, TCP_MSS_ACCT_SIZE, "Size of output calls");
1826 	SYSCTL_ADD_PROC(&bbr_sysctl_ctx,
1827 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1828 	    OID_AUTO, "clrlost", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1829 	    &bbr_clear_lost, 0, sysctl_bbr_clear_lost, "IU", "Clear lost counters");
1830 }
1831 
1832 static void
bbr_counter_destroy(void)1833 bbr_counter_destroy(void)
1834 {
1835 	COUNTER_ARRAY_FREE(bbr_stat_arry, BBR_STAT_SIZE);
1836 	COUNTER_ARRAY_FREE(bbr_opts_arry, BBR_OPTS_SIZE);
1837 	COUNTER_ARRAY_FREE(bbr_out_size, TCP_MSS_ACCT_SIZE);
1838 	COUNTER_ARRAY_FREE(bbr_state_lost, BBR_MAX_STAT);
1839 	COUNTER_ARRAY_FREE(bbr_state_time, BBR_MAX_STAT);
1840 	COUNTER_ARRAY_FREE(bbr_state_resend, BBR_MAX_STAT);
1841 	counter_u64_free(bbr_nohdwr_pacing_enobuf);
1842 	counter_u64_free(bbr_hdwr_pacing_enobuf);
1843 	counter_u64_free(bbr_flows_whdwr_pacing);
1844 	counter_u64_free(bbr_flows_nohdwr_pacing);
1845 
1846 }
1847 
1848 static __inline void
bbr_fill_in_logging_data(struct tcp_bbr * bbr,struct tcp_log_bbr * l,uint32_t cts)1849 bbr_fill_in_logging_data(struct tcp_bbr *bbr, struct tcp_log_bbr *l, uint32_t cts)
1850 {
1851 	memset(l, 0, sizeof(union tcp_log_stackspecific));
1852 	l->cur_del_rate = bbr->r_ctl.rc_bbr_cur_del_rate;
1853 	l->delRate = get_filter_value(&bbr->r_ctl.rc_delrate);
1854 	l->rttProp = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
1855 	l->bw_inuse = bbr_get_bw(bbr);
1856 	l->inflight = ctf_flight_size(bbr->rc_tp,
1857 			  (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
1858 	l->applimited = bbr->r_ctl.r_app_limited_until;
1859 	l->delivered = bbr->r_ctl.rc_delivered;
1860 	l->timeStamp = cts;
1861 	l->lost = bbr->r_ctl.rc_lost;
1862 	l->bbr_state = bbr->rc_bbr_state;
1863 	l->bbr_substate = bbr_state_val(bbr);
1864 	l->epoch = bbr->r_ctl.rc_rtt_epoch;
1865 	l->lt_epoch = bbr->r_ctl.rc_lt_epoch;
1866 	l->pacing_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
1867 	l->cwnd_gain = bbr->r_ctl.rc_bbr_cwnd_gain;
1868 	l->inhpts = tcp_in_hpts(bbr->rc_tp);
1869 	l->use_lt_bw = bbr->rc_lt_use_bw;
1870 	l->pkts_out = bbr->r_ctl.rc_flight_at_input;
1871 	l->pkt_epoch = bbr->r_ctl.rc_pkt_epoch;
1872 }
1873 
1874 static void
bbr_log_type_bw_reduce(struct tcp_bbr * bbr,int reason)1875 bbr_log_type_bw_reduce(struct tcp_bbr *bbr, int reason)
1876 {
1877 	if (tcp_bblogging_on(bbr->rc_tp)) {
1878 		union tcp_log_stackspecific log;
1879 
1880 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1881 		log.u_bbr.flex1 = 0;
1882 		log.u_bbr.flex2 = 0;
1883 		log.u_bbr.flex5 = 0;
1884 		log.u_bbr.flex3 = 0;
1885 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_loss_rate;
1886 		log.u_bbr.flex7 = reason;
1887 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_enters_probertt;
1888 		log.u_bbr.flex8 = 0;
1889 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1890 		    &bbr->rc_inp->inp_socket->so_rcv,
1891 		    &bbr->rc_inp->inp_socket->so_snd,
1892 		    BBR_LOG_BW_RED_EV, 0,
1893 		    0, &log, false, &bbr->rc_tv);
1894 	}
1895 }
1896 
1897 static void
bbr_log_type_rwnd_collapse(struct tcp_bbr * bbr,int seq,int mode,uint32_t count)1898 bbr_log_type_rwnd_collapse(struct tcp_bbr *bbr, int seq, int mode, uint32_t count)
1899 {
1900 	if (tcp_bblogging_on(bbr->rc_tp)) {
1901 		union tcp_log_stackspecific log;
1902 
1903 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1904 		log.u_bbr.flex1 = seq;
1905 		log.u_bbr.flex2 = count;
1906 		log.u_bbr.flex8 = mode;
1907 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1908 		    &bbr->rc_inp->inp_socket->so_rcv,
1909 		    &bbr->rc_inp->inp_socket->so_snd,
1910 		    BBR_LOG_LOWGAIN, 0,
1911 		    0, &log, false, &bbr->rc_tv);
1912 	}
1913 }
1914 
1915 static void
bbr_log_type_just_return(struct tcp_bbr * bbr,uint32_t cts,uint32_t tlen,uint8_t hpts_calling,uint8_t reason,uint32_t p_maxseg,int len)1916 bbr_log_type_just_return(struct tcp_bbr *bbr, uint32_t cts, uint32_t tlen, uint8_t hpts_calling,
1917     uint8_t reason, uint32_t p_maxseg, int len)
1918 {
1919 	if (tcp_bblogging_on(bbr->rc_tp)) {
1920 		union tcp_log_stackspecific log;
1921 
1922 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1923 		log.u_bbr.flex1 = p_maxseg;
1924 		log.u_bbr.flex2 = bbr->r_ctl.rc_hpts_flags;
1925 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
1926 		log.u_bbr.flex4 = reason;
1927 		log.u_bbr.flex5 = bbr->rc_in_persist;
1928 		log.u_bbr.flex6 = bbr->r_ctl.rc_last_delay_val;
1929 		log.u_bbr.flex7 = p_maxseg;
1930 		log.u_bbr.flex8 = bbr->rc_in_persist;
1931 		log.u_bbr.pkts_out = 0;
1932 		log.u_bbr.applimited = len;
1933 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1934 		    &bbr->rc_inp->inp_socket->so_rcv,
1935 		    &bbr->rc_inp->inp_socket->so_snd,
1936 		    BBR_LOG_JUSTRET, 0,
1937 		    tlen, &log, false, &bbr->rc_tv);
1938 	}
1939 }
1940 
1941 static void
bbr_log_type_enter_rec(struct tcp_bbr * bbr,uint32_t seq)1942 bbr_log_type_enter_rec(struct tcp_bbr *bbr, uint32_t seq)
1943 {
1944 	if (tcp_bblogging_on(bbr->rc_tp)) {
1945 		union tcp_log_stackspecific log;
1946 
1947 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1948 		log.u_bbr.flex1 = seq;
1949 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
1950 		log.u_bbr.flex3 = bbr->r_ctl.rc_recovery_start;
1951 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1952 		    &bbr->rc_inp->inp_socket->so_rcv,
1953 		    &bbr->rc_inp->inp_socket->so_snd,
1954 		    BBR_LOG_ENTREC, 0,
1955 		    0, &log, false, &bbr->rc_tv);
1956 	}
1957 }
1958 
1959 static void
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)1960 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)
1961 {
1962 	if (tcp_bblogging_on(tp)) {
1963 		union tcp_log_stackspecific log;
1964 
1965 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1966 		log.u_bbr.flex1 = tso;
1967 		log.u_bbr.flex2 = maxseg;
1968 		log.u_bbr.flex3 = mtu;
1969 		log.u_bbr.flex4 = csum_flags;
1970 		TCP_LOG_EVENTP(tp, NULL,
1971 		    &bbr->rc_inp->inp_socket->so_rcv,
1972 		    &bbr->rc_inp->inp_socket->so_snd,
1973 		    BBR_LOG_MSGSIZE, 0,
1974 		    0, &log, false, &bbr->rc_tv);
1975 	}
1976 }
1977 
1978 static void
bbr_log_flowend(struct tcp_bbr * bbr)1979 bbr_log_flowend(struct tcp_bbr *bbr)
1980 {
1981 	if (tcp_bblogging_on(bbr->rc_tp)) {
1982 		union tcp_log_stackspecific log;
1983 		struct sockbuf *r, *s;
1984 		struct timeval tv;
1985 
1986 		if (bbr->rc_inp->inp_socket) {
1987 			r = &bbr->rc_inp->inp_socket->so_rcv;
1988 			s = &bbr->rc_inp->inp_socket->so_snd;
1989 		} else {
1990 			r = s = NULL;
1991 		}
1992 		bbr_fill_in_logging_data(bbr, &log.u_bbr, tcp_get_usecs(&tv));
1993 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1994 		    r, s,
1995 		    TCP_LOG_FLOWEND, 0,
1996 		    0, &log, false, &tv);
1997 	}
1998 }
1999 
2000 static void
bbr_log_pkt_epoch(struct tcp_bbr * bbr,uint32_t cts,uint32_t line,uint32_t lost,uint32_t del)2001 bbr_log_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line,
2002     uint32_t lost, uint32_t del)
2003 {
2004 	if (tcp_bblogging_on(bbr->rc_tp)) {
2005 		union tcp_log_stackspecific log;
2006 
2007 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2008 		log.u_bbr.flex1 = lost;
2009 		log.u_bbr.flex2 = del;
2010 		log.u_bbr.flex3 = bbr->r_ctl.rc_bbr_lastbtlbw;
2011 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_rtt;
2012 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2013 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2014 		log.u_bbr.flex7 = line;
2015 		log.u_bbr.flex8 = 0;
2016 		log.u_bbr.inflight = bbr->r_ctl.r_measurement_count;
2017 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2018 		    &bbr->rc_inp->inp_socket->so_rcv,
2019 		    &bbr->rc_inp->inp_socket->so_snd,
2020 		    BBR_LOG_PKT_EPOCH, 0,
2021 		    0, &log, false, &bbr->rc_tv);
2022 	}
2023 }
2024 
2025 static void
bbr_log_time_epoch(struct tcp_bbr * bbr,uint32_t cts,uint32_t line,uint32_t epoch_time)2026 bbr_log_time_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line, uint32_t epoch_time)
2027 {
2028 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2029 		union tcp_log_stackspecific log;
2030 
2031 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2032 		log.u_bbr.flex1 = bbr->r_ctl.rc_lost;
2033 		log.u_bbr.flex2 = bbr->rc_inp->inp_socket->so_snd.sb_lowat;
2034 		log.u_bbr.flex3 = bbr->rc_inp->inp_socket->so_snd.sb_hiwat;
2035 		log.u_bbr.flex7 = line;
2036 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2037 		    &bbr->rc_inp->inp_socket->so_rcv,
2038 		    &bbr->rc_inp->inp_socket->so_snd,
2039 		    BBR_LOG_TIME_EPOCH, 0,
2040 		    0, &log, false, &bbr->rc_tv);
2041 	}
2042 }
2043 
2044 static void
bbr_log_set_of_state_target(struct tcp_bbr * bbr,uint32_t new_tar,int line,int meth)2045 bbr_log_set_of_state_target(struct tcp_bbr *bbr, uint32_t new_tar, int line, int meth)
2046 {
2047 	if (tcp_bblogging_on(bbr->rc_tp)) {
2048 		union tcp_log_stackspecific log;
2049 
2050 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2051 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2052 		log.u_bbr.flex2 = new_tar;
2053 		log.u_bbr.flex3 = line;
2054 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2055 		log.u_bbr.flex5 = bbr_quanta;
2056 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_min_segs;
2057 		log.u_bbr.flex7 = bbr->rc_last_options;
2058 		log.u_bbr.flex8 = meth;
2059 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2060 		    &bbr->rc_inp->inp_socket->so_rcv,
2061 		    &bbr->rc_inp->inp_socket->so_snd,
2062 		    BBR_LOG_STATE_TARGET, 0,
2063 		    0, &log, false, &bbr->rc_tv);
2064 	}
2065 
2066 }
2067 
2068 static void
bbr_log_type_statechange(struct tcp_bbr * bbr,uint32_t cts,int32_t line)2069 bbr_log_type_statechange(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2070 {
2071 	if (tcp_bblogging_on(bbr->rc_tp)) {
2072 		union tcp_log_stackspecific log;
2073 
2074 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2075 		log.u_bbr.flex1 = line;
2076 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2077 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2078 		if (bbr_state_is_pkt_epoch)
2079 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
2080 		else
2081 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PROP);
2082 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2083 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2084 		log.u_bbr.flex7 = (bbr->r_ctl.rc_target_at_state/1000);
2085 		log.u_bbr.lt_epoch = bbr->r_ctl.rc_level_state_extra;
2086 		log.u_bbr.pkts_out = bbr->r_ctl.rc_target_at_state;
2087 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2088 		    &bbr->rc_inp->inp_socket->so_rcv,
2089 		    &bbr->rc_inp->inp_socket->so_snd,
2090 		    BBR_LOG_STATE, 0,
2091 		    0, &log, false, &bbr->rc_tv);
2092 	}
2093 }
2094 
2095 static void
bbr_log_rtt_shrinks(struct tcp_bbr * bbr,uint32_t cts,uint32_t applied,uint32_t rtt,uint32_t line,uint8_t reas,uint16_t cond)2096 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
2097 		    uint32_t rtt, uint32_t line, uint8_t reas, uint16_t cond)
2098 {
2099 	if (tcp_bblogging_on(bbr->rc_tp)) {
2100 		union tcp_log_stackspecific log;
2101 
2102 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2103 		log.u_bbr.flex1 = line;
2104 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2105 		log.u_bbr.flex3 = bbr->r_ctl.last_in_probertt;
2106 		log.u_bbr.flex4 = applied;
2107 		log.u_bbr.flex5 = rtt;
2108 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2109 		log.u_bbr.flex7 = cond;
2110 		log.u_bbr.flex8 = reas;
2111 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2112 		    &bbr->rc_inp->inp_socket->so_rcv,
2113 		    &bbr->rc_inp->inp_socket->so_snd,
2114 		    BBR_LOG_RTT_SHRINKS, 0,
2115 		    0, &log, false, &bbr->rc_tv);
2116 	}
2117 }
2118 
2119 static void
bbr_log_type_exit_rec(struct tcp_bbr * bbr)2120 bbr_log_type_exit_rec(struct tcp_bbr *bbr)
2121 {
2122 	if (tcp_bblogging_on(bbr->rc_tp)) {
2123 		union tcp_log_stackspecific log;
2124 
2125 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2126 		log.u_bbr.flex1 = bbr->r_ctl.rc_recovery_start;
2127 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
2128 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2129 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2130 		    &bbr->rc_inp->inp_socket->so_rcv,
2131 		    &bbr->rc_inp->inp_socket->so_snd,
2132 		    BBR_LOG_EXITREC, 0,
2133 		    0, &log, false, &bbr->rc_tv);
2134 	}
2135 }
2136 
2137 static void
bbr_log_type_cwndupd(struct tcp_bbr * bbr,uint32_t bytes_this_ack,uint32_t chg,uint32_t prev_acked,int32_t meth,uint32_t target,uint32_t th_ack,int32_t line)2138 bbr_log_type_cwndupd(struct tcp_bbr *bbr, uint32_t bytes_this_ack, uint32_t chg,
2139     uint32_t prev_acked, int32_t meth, uint32_t target, uint32_t th_ack, int32_t line)
2140 {
2141 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2142 		union tcp_log_stackspecific log;
2143 
2144 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2145 		log.u_bbr.flex1 = line;
2146 		log.u_bbr.flex2 = prev_acked;
2147 		log.u_bbr.flex3 = bytes_this_ack;
2148 		log.u_bbr.flex4 = chg;
2149 		log.u_bbr.flex5 = th_ack;
2150 		log.u_bbr.flex6 = target;
2151 		log.u_bbr.flex8 = meth;
2152 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2153 		    &bbr->rc_inp->inp_socket->so_rcv,
2154 		    &bbr->rc_inp->inp_socket->so_snd,
2155 		    BBR_LOG_CWND, 0,
2156 		    0, &log, false, &bbr->rc_tv);
2157 	}
2158 }
2159 
2160 static void
bbr_log_rtt_sample(struct tcp_bbr * bbr,uint32_t rtt,uint32_t tsin)2161 bbr_log_rtt_sample(struct tcp_bbr *bbr, uint32_t rtt, uint32_t tsin)
2162 {
2163 	/*
2164 	 * Log the rtt sample we are applying to the srtt algorithm in
2165 	 * useconds.
2166 	 */
2167 	if (tcp_bblogging_on(bbr->rc_tp)) {
2168 		union tcp_log_stackspecific log;
2169 
2170 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2171 		log.u_bbr.flex1 = rtt;
2172 		log.u_bbr.flex2 = bbr->r_ctl.rc_bbr_state_time;
2173 		log.u_bbr.flex3 = bbr->r_ctl.rc_ack_hdwr_delay;
2174 		log.u_bbr.flex4 = bbr->rc_tp->ts_offset;
2175 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2176 		log.u_bbr.pkts_out = tcp_tv_to_mssectick(&bbr->rc_tv);
2177 		log.u_bbr.flex6 = tsin;
2178 		log.u_bbr.flex7 = 0;
2179 		log.u_bbr.flex8 = bbr->rc_ack_was_delayed;
2180 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2181 		    &bbr->rc_inp->inp_socket->so_rcv,
2182 		    &bbr->rc_inp->inp_socket->so_snd,
2183 		    TCP_LOG_RTT, 0,
2184 		    0, &log, false, &bbr->rc_tv);
2185 	}
2186 }
2187 
2188 static void
bbr_log_type_pesist(struct tcp_bbr * bbr,uint32_t cts,uint32_t time_in,int32_t line,uint8_t enter_exit)2189 bbr_log_type_pesist(struct tcp_bbr *bbr, uint32_t cts, uint32_t time_in, int32_t line, uint8_t enter_exit)
2190 {
2191 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2192 		union tcp_log_stackspecific log;
2193 
2194 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2195 		log.u_bbr.flex1 = time_in;
2196 		log.u_bbr.flex2 = line;
2197 		log.u_bbr.flex8 = enter_exit;
2198 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2199 		    &bbr->rc_inp->inp_socket->so_rcv,
2200 		    &bbr->rc_inp->inp_socket->so_snd,
2201 		    BBR_LOG_PERSIST, 0,
2202 		    0, &log, false, &bbr->rc_tv);
2203 	}
2204 }
2205 static void
bbr_log_ack_clear(struct tcp_bbr * bbr,uint32_t cts)2206 bbr_log_ack_clear(struct tcp_bbr *bbr, uint32_t cts)
2207 {
2208 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2209 		union tcp_log_stackspecific log;
2210 
2211 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2212 		log.u_bbr.flex1 = bbr->rc_tp->ts_recent_age;
2213 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2214 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2215 		log.u_bbr.flex4 = bbr->r_ctl.rc_went_idle_time;
2216 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2217 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2218 		    &bbr->rc_inp->inp_socket->so_rcv,
2219 		    &bbr->rc_inp->inp_socket->so_snd,
2220 		    BBR_LOG_ACKCLEAR, 0,
2221 		    0, &log, false, &bbr->rc_tv);
2222 	}
2223 }
2224 
2225 static void
bbr_log_ack_event(struct tcp_bbr * bbr,struct tcphdr * th,struct tcpopt * to,uint32_t tlen,uint16_t nsegs,uint32_t cts,int32_t nxt_pkt,struct mbuf * m)2226 bbr_log_ack_event(struct tcp_bbr *bbr, struct tcphdr *th, struct tcpopt *to, uint32_t tlen,
2227 		  uint16_t nsegs, uint32_t cts, int32_t nxt_pkt, struct mbuf *m)
2228 {
2229 	if (tcp_bblogging_on(bbr->rc_tp)) {
2230 		union tcp_log_stackspecific log;
2231 		struct timeval tv;
2232 
2233 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2234 		log.u_bbr.flex1 = nsegs;
2235 		log.u_bbr.flex2 = bbr->r_ctl.rc_lost_bytes;
2236 		if (m) {
2237 			struct timespec ts;
2238 
2239 			log.u_bbr.flex3 = m->m_flags;
2240 			if (m->m_flags & M_TSTMP) {
2241 				mbuf_tstmp2timespec(m, &ts);
2242 				tv.tv_sec = ts.tv_sec;
2243 				tv.tv_usec = ts.tv_nsec / 1000;
2244 				log.u_bbr.lt_epoch = tcp_tv_to_usectick(&tv);
2245 			} else {
2246 				log.u_bbr.lt_epoch = 0;
2247 			}
2248 			if (m->m_flags & M_TSTMP_LRO) {
2249 				mbuf_tstmp2timeval(m, &tv);
2250 				log.u_bbr.flex5 = tcp_tv_to_usectick(&tv);
2251 			} else {
2252 				/* No arrival timestamp */
2253 				log.u_bbr.flex5 = 0;
2254 			}
2255 
2256 			log.u_bbr.pkts_out = tcp_get_usecs(&tv);
2257 		} else {
2258 			log.u_bbr.flex3 = 0;
2259 			log.u_bbr.flex5 = 0;
2260 			log.u_bbr.flex6 = 0;
2261 			log.u_bbr.pkts_out = 0;
2262 		}
2263 		log.u_bbr.flex4 = bbr->r_ctl.rc_target_at_state;
2264 		log.u_bbr.flex7 = bbr->r_wanted_output;
2265 		log.u_bbr.flex8 = bbr->rc_in_persist;
2266 		TCP_LOG_EVENTP(bbr->rc_tp, th,
2267 		    &bbr->rc_inp->inp_socket->so_rcv,
2268 		    &bbr->rc_inp->inp_socket->so_snd,
2269 		    TCP_LOG_IN, 0,
2270 		    tlen, &log, true, &bbr->rc_tv);
2271 	}
2272 }
2273 
2274 static void
bbr_log_doseg_done(struct tcp_bbr * bbr,uint32_t cts,int32_t nxt_pkt,int32_t did_out)2275 bbr_log_doseg_done(struct tcp_bbr *bbr, uint32_t cts, int32_t nxt_pkt, int32_t did_out)
2276 {
2277 	if (tcp_bblogging_on(bbr->rc_tp)) {
2278 		union tcp_log_stackspecific log;
2279 
2280 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2281 		log.u_bbr.flex1 = did_out;
2282 		log.u_bbr.flex2 = nxt_pkt;
2283 		log.u_bbr.flex3 = bbr->r_ctl.rc_last_delay_val;
2284 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2285 		log.u_bbr.flex5 = bbr->r_ctl.rc_timer_exp;
2286 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_bytes;
2287 		log.u_bbr.flex7 = bbr->r_wanted_output;
2288 		log.u_bbr.flex8 = bbr->rc_in_persist;
2289 		log.u_bbr.pkts_out = bbr->r_ctl.highest_hdwr_delay;
2290 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2291 		    &bbr->rc_inp->inp_socket->so_rcv,
2292 		    &bbr->rc_inp->inp_socket->so_snd,
2293 		    BBR_LOG_DOSEG_DONE, 0,
2294 		    0, &log, true, &bbr->rc_tv);
2295 	}
2296 }
2297 
2298 static void
bbr_log_enobuf_jmp(struct tcp_bbr * bbr,uint32_t len,uint32_t cts,int32_t line,uint32_t o_len,uint32_t segcnt,uint32_t segsiz)2299 bbr_log_enobuf_jmp(struct tcp_bbr *bbr, uint32_t len, uint32_t cts,
2300     int32_t line, uint32_t o_len, uint32_t segcnt, uint32_t segsiz)
2301 {
2302 	if (tcp_bblogging_on(bbr->rc_tp)) {
2303 		union tcp_log_stackspecific log;
2304 
2305 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2306 		log.u_bbr.flex1 = line;
2307 		log.u_bbr.flex2 = o_len;
2308 		log.u_bbr.flex3 = segcnt;
2309 		log.u_bbr.flex4 = segsiz;
2310 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2311 		    &bbr->rc_inp->inp_socket->so_rcv,
2312 		    &bbr->rc_inp->inp_socket->so_snd,
2313 		    BBR_LOG_ENOBUF_JMP, ENOBUFS,
2314 		    len, &log, true, &bbr->rc_tv);
2315 	}
2316 }
2317 
2318 static void
bbr_log_to_processing(struct tcp_bbr * bbr,uint32_t cts,int32_t ret,int32_t timers,uint8_t hpts_calling)2319 bbr_log_to_processing(struct tcp_bbr *bbr, uint32_t cts, int32_t ret, int32_t timers, uint8_t hpts_calling)
2320 {
2321 	if (tcp_bblogging_on(bbr->rc_tp)) {
2322 		union tcp_log_stackspecific log;
2323 
2324 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2325 		log.u_bbr.flex1 = timers;
2326 		log.u_bbr.flex2 = ret;
2327 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
2328 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2329 		log.u_bbr.flex5 = cts;
2330 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2331 		log.u_bbr.flex8 = hpts_calling;
2332 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2333 		    &bbr->rc_inp->inp_socket->so_rcv,
2334 		    &bbr->rc_inp->inp_socket->so_snd,
2335 		    BBR_LOG_TO_PROCESS, 0,
2336 		    0, &log, false, &bbr->rc_tv);
2337 	}
2338 }
2339 
2340 static void
bbr_log_to_event(struct tcp_bbr * bbr,uint32_t cts,int32_t to_num)2341 bbr_log_to_event(struct tcp_bbr *bbr, uint32_t cts, int32_t to_num)
2342 {
2343 	if (tcp_bblogging_on(bbr->rc_tp)) {
2344 		union tcp_log_stackspecific log;
2345 		uint64_t ar;
2346 
2347 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2348 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2349 		log.u_bbr.flex2 = 0;
2350 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2351 		ar = (uint64_t)(bbr->r_ctl.rc_resend);
2352 		ar >>= 32;
2353 		ar &= 0x00000000ffffffff;
2354 		log.u_bbr.flex4 = (uint32_t)ar;
2355 		ar = (uint64_t)bbr->r_ctl.rc_resend;
2356 		ar &= 0x00000000ffffffff;
2357 		log.u_bbr.flex5 = (uint32_t)ar;
2358 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2359 		log.u_bbr.flex8 = to_num;
2360 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2361 		    &bbr->rc_inp->inp_socket->so_rcv,
2362 		    &bbr->rc_inp->inp_socket->so_snd,
2363 		    BBR_LOG_RTO, 0,
2364 		    0, &log, false, &bbr->rc_tv);
2365 	}
2366 }
2367 
2368 static void
bbr_log_startup_event(struct tcp_bbr * bbr,uint32_t cts,uint32_t flex1,uint32_t flex2,uint32_t flex3,uint8_t reason)2369 bbr_log_startup_event(struct tcp_bbr *bbr, uint32_t cts, uint32_t flex1, uint32_t flex2, uint32_t flex3, uint8_t reason)
2370 {
2371 	if (tcp_bblogging_on(bbr->rc_tp)) {
2372 		union tcp_log_stackspecific log;
2373 
2374 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2375 		log.u_bbr.flex1 = flex1;
2376 		log.u_bbr.flex2 = flex2;
2377 		log.u_bbr.flex3 = flex3;
2378 		log.u_bbr.flex4 = 0;
2379 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2380 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2381 		log.u_bbr.flex8 = reason;
2382 		log.u_bbr.cur_del_rate = bbr->r_ctl.rc_bbr_lastbtlbw;
2383 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2384 		    &bbr->rc_inp->inp_socket->so_rcv,
2385 		    &bbr->rc_inp->inp_socket->so_snd,
2386 		    BBR_LOG_REDUCE, 0,
2387 		    0, &log, false, &bbr->rc_tv);
2388 	}
2389 }
2390 
2391 static void
bbr_log_hpts_diag(struct tcp_bbr * bbr,uint32_t cts,struct hpts_diag * diag)2392 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag)
2393 {
2394 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2395 		union tcp_log_stackspecific log;
2396 
2397 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2398 		log.u_bbr.flex1 = diag->p_nxt_slot;
2399 		log.u_bbr.flex2 = diag->p_cur_slot;
2400 		log.u_bbr.flex3 = diag->slot_req;
2401 		log.u_bbr.flex4 = diag->inp_hptsslot;
2402 		log.u_bbr.flex5 = diag->slot_remaining;
2403 		log.u_bbr.flex6 = diag->need_new_to;
2404 		log.u_bbr.flex7 = diag->p_hpts_active;
2405 		log.u_bbr.flex8 = diag->p_on_min_sleep;
2406 		/* Hijack other fields as needed  */
2407 		log.u_bbr.epoch = diag->have_slept;
2408 		log.u_bbr.lt_epoch = diag->yet_to_sleep;
2409 		log.u_bbr.pkts_out = diag->co_ret;
2410 		log.u_bbr.applimited = diag->hpts_sleep_time;
2411 		log.u_bbr.delivered = diag->p_prev_slot;
2412 		log.u_bbr.inflight = diag->p_runningslot;
2413 		log.u_bbr.bw_inuse = diag->wheel_slot;
2414 		log.u_bbr.rttProp = diag->wheel_cts;
2415 		log.u_bbr.delRate = diag->maxslots;
2416 		log.u_bbr.cur_del_rate = diag->p_curtick;
2417 		log.u_bbr.cur_del_rate <<= 32;
2418 		log.u_bbr.cur_del_rate |= diag->p_lasttick;
2419 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2420 		    &bbr->rc_inp->inp_socket->so_rcv,
2421 		    &bbr->rc_inp->inp_socket->so_snd,
2422 		    BBR_LOG_HPTSDIAG, 0,
2423 		    0, &log, false, &bbr->rc_tv);
2424 	}
2425 }
2426 
2427 static void
bbr_log_timer_var(struct tcp_bbr * bbr,int mode,uint32_t cts,uint32_t time_since_sent,uint32_t srtt,uint32_t thresh,uint32_t to)2428 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
2429     uint32_t thresh, uint32_t to)
2430 {
2431 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2432 		union tcp_log_stackspecific log;
2433 
2434 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2435 		log.u_bbr.flex1 = bbr->rc_tp->t_rttvar;
2436 		log.u_bbr.flex2 = time_since_sent;
2437 		log.u_bbr.flex3 = srtt;
2438 		log.u_bbr.flex4 = thresh;
2439 		log.u_bbr.flex5 = to;
2440 		log.u_bbr.flex6 = bbr->rc_tp->t_srtt;
2441 		log.u_bbr.flex8 = mode;
2442 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2443 		    &bbr->rc_inp->inp_socket->so_rcv,
2444 		    &bbr->rc_inp->inp_socket->so_snd,
2445 		    BBR_LOG_TIMERPREP, 0,
2446 		    0, &log, false, &bbr->rc_tv);
2447 	}
2448 }
2449 
2450 static void
bbr_log_pacing_delay_calc(struct tcp_bbr * bbr,uint16_t gain,uint32_t len,uint32_t cts,uint32_t usecs,uint64_t bw,uint32_t override,int mod)2451 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
2452     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod)
2453 {
2454 	if (tcp_bblogging_on(bbr->rc_tp)) {
2455 		union tcp_log_stackspecific log;
2456 
2457 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2458 		log.u_bbr.flex1 = usecs;
2459 		log.u_bbr.flex2 = len;
2460 		log.u_bbr.flex3 = (uint32_t)((bw >> 32) & 0x00000000ffffffff);
2461 		log.u_bbr.flex4 = (uint32_t)(bw & 0x00000000ffffffff);
2462 		if (override)
2463 			log.u_bbr.flex5 = (1 << 2);
2464 		else
2465 			log.u_bbr.flex5 = 0;
2466 		log.u_bbr.flex6 = override;
2467 		log.u_bbr.flex7 = gain;
2468 		log.u_bbr.flex8 = mod;
2469 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2470 		    &bbr->rc_inp->inp_socket->so_rcv,
2471 		    &bbr->rc_inp->inp_socket->so_snd,
2472 		    BBR_LOG_HPTSI_CALC, 0,
2473 		    len, &log, false, &bbr->rc_tv);
2474 	}
2475 }
2476 
2477 static void
bbr_log_to_start(struct tcp_bbr * bbr,uint32_t cts,uint32_t to,int32_t slot,uint8_t which)2478 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2479 {
2480 	if (tcp_bblogging_on(bbr->rc_tp)) {
2481 		union tcp_log_stackspecific log;
2482 
2483 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2484 
2485 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2486 		log.u_bbr.flex2 = to;
2487 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2488 		log.u_bbr.flex4 = slot;
2489 		log.u_bbr.flex5 = bbr->rc_tp->t_hpts_slot;
2490 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2491 		log.u_bbr.pkts_out = bbr->rc_tp->t_flags2;
2492 		log.u_bbr.flex8 = which;
2493 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2494 		    &bbr->rc_inp->inp_socket->so_rcv,
2495 		    &bbr->rc_inp->inp_socket->so_snd,
2496 		    BBR_LOG_TIMERSTAR, 0,
2497 		    0, &log, false, &bbr->rc_tv);
2498 	}
2499 }
2500 
2501 static void
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)2502 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)
2503 {
2504 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2505 		union tcp_log_stackspecific log;
2506 
2507 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2508 		log.u_bbr.flex1 = thresh;
2509 		log.u_bbr.flex2 = lro;
2510 		log.u_bbr.flex3 = bbr->r_ctl.rc_reorder_ts;
2511 		log.u_bbr.flex4 = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
2512 		log.u_bbr.flex5 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2513 		log.u_bbr.flex6 = srtt;
2514 		log.u_bbr.flex7 = bbr->r_ctl.rc_reorder_shift;
2515 		log.u_bbr.flex8 = frm;
2516 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2517 		    &bbr->rc_inp->inp_socket->so_rcv,
2518 		    &bbr->rc_inp->inp_socket->so_snd,
2519 		    BBR_LOG_THRESH_CALC, 0,
2520 		    0, &log, false, &bbr->rc_tv);
2521 	}
2522 }
2523 
2524 static void
bbr_log_to_cancel(struct tcp_bbr * bbr,int32_t line,uint32_t cts,uint8_t hpts_removed)2525 bbr_log_to_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts, uint8_t hpts_removed)
2526 {
2527 	if (tcp_bblogging_on(bbr->rc_tp)) {
2528 		union tcp_log_stackspecific log;
2529 
2530 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2531 		log.u_bbr.flex1 = line;
2532 		log.u_bbr.flex2 = bbr->bbr_timer_src;
2533 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2534 		log.u_bbr.flex4 = bbr->rc_in_persist;
2535 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2536 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2537 		log.u_bbr.flex8 = hpts_removed;
2538 		log.u_bbr.pkts_out = bbr->rc_pacer_started;
2539 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2540 		    &bbr->rc_inp->inp_socket->so_rcv,
2541 		    &bbr->rc_inp->inp_socket->so_snd,
2542 		    BBR_LOG_TIMERCANC, 0,
2543 		    0, &log, false, &bbr->rc_tv);
2544 	}
2545 }
2546 
2547 static void
bbr_log_tstmp_validation(struct tcp_bbr * bbr,uint64_t peer_delta,uint64_t delta)2548 bbr_log_tstmp_validation(struct tcp_bbr *bbr, uint64_t peer_delta, uint64_t delta)
2549 {
2550 	if (tcp_bblogging_on(bbr->rc_tp)) {
2551 		union tcp_log_stackspecific log;
2552 
2553 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2554 		log.u_bbr.flex1 = bbr->r_ctl.bbr_peer_tsratio;
2555 		log.u_bbr.flex2 = (peer_delta >> 32);
2556 		log.u_bbr.flex3 = (peer_delta & 0x00000000ffffffff);
2557 		log.u_bbr.flex4 = (delta >> 32);
2558 		log.u_bbr.flex5 = (delta & 0x00000000ffffffff);
2559 		log.u_bbr.flex7 = bbr->rc_ts_clock_set;
2560 		log.u_bbr.flex8 = bbr->rc_ts_cant_be_used;
2561 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2562 		    &bbr->rc_inp->inp_socket->so_rcv,
2563 		    &bbr->rc_inp->inp_socket->so_snd,
2564 		    BBR_LOG_TSTMP_VAL, 0,
2565 		    0, &log, false, &bbr->rc_tv);
2566 	}
2567 }
2568 
2569 static void
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)2570 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)
2571 {
2572 	if (tcp_bblogging_on(bbr->rc_tp)) {
2573 		union tcp_log_stackspecific log;
2574 
2575 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2576 		log.u_bbr.flex1 = tsosz;
2577 		log.u_bbr.flex2 = tls;
2578 		log.u_bbr.flex3 = tcp_min_hptsi_time;
2579 		log.u_bbr.flex4 = bbr->r_ctl.bbr_hptsi_bytes_min;
2580 		log.u_bbr.flex5 = old_val;
2581 		log.u_bbr.flex6 = maxseg;
2582 		log.u_bbr.flex7 = bbr->rc_no_pacing;
2583 		log.u_bbr.flex7 <<= 1;
2584 		log.u_bbr.flex7 |= bbr->rc_past_init_win;
2585 		if (hdwr)
2586 			log.u_bbr.flex8 = 0x80 | bbr->rc_use_google;
2587 		else
2588 			log.u_bbr.flex8 = bbr->rc_use_google;
2589 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2590 		    &bbr->rc_inp->inp_socket->so_rcv,
2591 		    &bbr->rc_inp->inp_socket->so_snd,
2592 		    BBR_LOG_BBRTSO, 0,
2593 		    0, &log, false, &bbr->rc_tv);
2594 	}
2595 }
2596 
2597 static void
bbr_log_type_rsmclear(struct tcp_bbr * bbr,uint32_t cts,struct bbr_sendmap * rsm,uint32_t flags,uint32_t line)2598 bbr_log_type_rsmclear(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm,
2599 		      uint32_t flags, uint32_t line)
2600 {
2601 	if (tcp_bblogging_on(bbr->rc_tp)) {
2602 		union tcp_log_stackspecific log;
2603 
2604 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2605 		log.u_bbr.flex1 = line;
2606 		log.u_bbr.flex2 = rsm->r_start;
2607 		log.u_bbr.flex3 = rsm->r_end;
2608 		log.u_bbr.flex4 = rsm->r_delivered;
2609 		log.u_bbr.flex5 = rsm->r_rtr_cnt;
2610 		log.u_bbr.flex6 = rsm->r_dupack;
2611 		log.u_bbr.flex7 = rsm->r_tim_lastsent[0];
2612 		log.u_bbr.flex8 = rsm->r_flags;
2613 		/* Hijack the pkts_out fids */
2614 		log.u_bbr.applimited = flags;
2615 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2616 		    &bbr->rc_inp->inp_socket->so_rcv,
2617 		    &bbr->rc_inp->inp_socket->so_snd,
2618 		    BBR_RSM_CLEARED, 0,
2619 		    0, &log, false, &bbr->rc_tv);
2620 	}
2621 }
2622 
2623 static void
bbr_log_type_bbrupd(struct tcp_bbr * bbr,uint8_t flex8,uint32_t cts,uint32_t flex3,uint32_t flex2,uint32_t flex5,uint32_t flex6,uint32_t pkts_out,int flex7,uint32_t flex4,uint32_t flex1)2624 bbr_log_type_bbrupd(struct tcp_bbr *bbr, uint8_t flex8, uint32_t cts,
2625     uint32_t flex3, uint32_t flex2, uint32_t flex5,
2626     uint32_t flex6, uint32_t pkts_out, int flex7,
2627     uint32_t flex4, uint32_t flex1)
2628 {
2629 
2630 	if (tcp_bblogging_on(bbr->rc_tp)) {
2631 		union tcp_log_stackspecific log;
2632 
2633 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2634 		log.u_bbr.flex1 = flex1;
2635 		log.u_bbr.flex2 = flex2;
2636 		log.u_bbr.flex3 = flex3;
2637 		log.u_bbr.flex4 = flex4;
2638 		log.u_bbr.flex5 = flex5;
2639 		log.u_bbr.flex6 = flex6;
2640 		log.u_bbr.flex7 = flex7;
2641 		/* Hijack the pkts_out fids */
2642 		log.u_bbr.pkts_out = pkts_out;
2643 		log.u_bbr.flex8 = flex8;
2644 		if (bbr->rc_ack_was_delayed)
2645 			log.u_bbr.epoch = bbr->r_ctl.rc_ack_hdwr_delay;
2646 		else
2647 			log.u_bbr.epoch = 0;
2648 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2649 		    &bbr->rc_inp->inp_socket->so_rcv,
2650 		    &bbr->rc_inp->inp_socket->so_snd,
2651 		    BBR_LOG_BBRUPD, 0,
2652 		    flex2, &log, false, &bbr->rc_tv);
2653 	}
2654 }
2655 
2656 static void
bbr_log_type_ltbw(struct tcp_bbr * bbr,uint32_t cts,int32_t reason,uint32_t newbw,uint32_t obw,uint32_t diff,uint32_t tim)2657 bbr_log_type_ltbw(struct tcp_bbr *bbr, uint32_t cts, int32_t reason,
2658 	uint32_t newbw, uint32_t obw, uint32_t diff,
2659 	uint32_t tim)
2660 {
2661 	if (/*bbr_verbose_logging && */tcp_bblogging_on(bbr->rc_tp)) {
2662 		union tcp_log_stackspecific log;
2663 
2664 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2665 		log.u_bbr.flex1 = reason;
2666 		log.u_bbr.flex2 = newbw;
2667 		log.u_bbr.flex3 = obw;
2668 		log.u_bbr.flex4 = diff;
2669 		log.u_bbr.flex5 = bbr->r_ctl.rc_lt_lost;
2670 		log.u_bbr.flex6 = bbr->r_ctl.rc_lt_del;
2671 		log.u_bbr.flex7 = bbr->rc_lt_is_sampling;
2672 		log.u_bbr.pkts_out = tim;
2673 		log.u_bbr.bw_inuse = bbr->r_ctl.rc_lt_bw;
2674 		if (bbr->rc_lt_use_bw == 0)
2675 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
2676 		else
2677 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
2678 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2679 		    &bbr->rc_inp->inp_socket->so_rcv,
2680 		    &bbr->rc_inp->inp_socket->so_snd,
2681 		    BBR_LOG_BWSAMP, 0,
2682 		    0, &log, false, &bbr->rc_tv);
2683 	}
2684 }
2685 
2686 static inline void
bbr_log_progress_event(struct tcp_bbr * bbr,struct tcpcb * tp,uint32_t tick,int event,int line)2687 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line)
2688 {
2689 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2690 		union tcp_log_stackspecific log;
2691 
2692 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2693 		log.u_bbr.flex1 = line;
2694 		log.u_bbr.flex2 = tick;
2695 		log.u_bbr.flex3 = tp->t_maxunacktime;
2696 		log.u_bbr.flex4 = tp->t_acktime;
2697 		log.u_bbr.flex8 = event;
2698 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2699 		    &bbr->rc_inp->inp_socket->so_rcv,
2700 		    &bbr->rc_inp->inp_socket->so_snd,
2701 		    BBR_LOG_PROGRESS, 0,
2702 		    0, &log, false, &bbr->rc_tv);
2703 	}
2704 }
2705 
2706 static void
bbr_type_log_hdwr_pacing(struct tcp_bbr * bbr,const struct ifnet * ifp,uint64_t rate,uint64_t hw_rate,int line,uint32_t cts,int error)2707 bbr_type_log_hdwr_pacing(struct tcp_bbr *bbr, const struct ifnet *ifp,
2708 			 uint64_t rate, uint64_t hw_rate, int line, uint32_t cts,
2709 			 int error)
2710 {
2711 	if (tcp_bblogging_on(bbr->rc_tp)) {
2712 		union tcp_log_stackspecific log;
2713 
2714 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2715 		log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2716 		log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2717 		log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2718 		log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2719 		log.u_bbr.bw_inuse = rate;
2720 		log.u_bbr.flex5 = line;
2721 		log.u_bbr.flex6 = error;
2722 		log.u_bbr.flex8 = bbr->skip_gain;
2723 		log.u_bbr.flex8 <<= 1;
2724 		log.u_bbr.flex8 |= bbr->gain_is_limited;
2725 		log.u_bbr.flex8 <<= 1;
2726 		log.u_bbr.flex8 |= bbr->bbr_hdrw_pacing;
2727 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
2728 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2729 		    &bbr->rc_inp->inp_socket->so_rcv,
2730 		    &bbr->rc_inp->inp_socket->so_snd,
2731 		    BBR_LOG_HDWR_PACE, 0,
2732 		    0, &log, false, &bbr->rc_tv);
2733 	}
2734 }
2735 
2736 static void
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)2737 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)
2738 {
2739 	if (tcp_bblogging_on(bbr->rc_tp)) {
2740 		union tcp_log_stackspecific log;
2741 
2742 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2743 		log.u_bbr.flex1 = slot;
2744 		log.u_bbr.flex2 = del_by;
2745 		log.u_bbr.flex3 = prev_delay;
2746 		log.u_bbr.flex4 = line;
2747 		log.u_bbr.flex5 = bbr->r_ctl.rc_last_delay_val;
2748 		log.u_bbr.flex6 = bbr->r_ctl.rc_hptsi_agg_delay;
2749 		log.u_bbr.flex7 = (0x0000ffff & bbr->r_ctl.rc_hpts_flags);
2750 		log.u_bbr.flex8 = bbr->rc_in_persist;
2751 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2752 		    &bbr->rc_inp->inp_socket->so_rcv,
2753 		    &bbr->rc_inp->inp_socket->so_snd,
2754 		    BBR_LOG_BBRSND, 0,
2755 		    len, &log, false, &bbr->rc_tv);
2756 	}
2757 }
2758 
2759 static void
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)2760 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)
2761 {
2762 	if (tcp_bblogging_on(bbr->rc_tp)) {
2763 		union tcp_log_stackspecific log;
2764 
2765 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2766 		log.u_bbr.flex1 = bbr->r_ctl.rc_delivered;
2767 		log.u_bbr.flex2 = 0;
2768 		log.u_bbr.flex3 = bbr->r_ctl.rc_lowest_rtt;
2769 		log.u_bbr.flex4 = end;
2770 		log.u_bbr.flex5 = seq;
2771 		log.u_bbr.flex6 = t;
2772 		log.u_bbr.flex7 = match;
2773 		log.u_bbr.flex8 = flags;
2774 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2775 		    &bbr->rc_inp->inp_socket->so_rcv,
2776 		    &bbr->rc_inp->inp_socket->so_snd,
2777 		    BBR_LOG_BBRRTT, 0,
2778 		    0, &log, false, &bbr->rc_tv);
2779 	}
2780 }
2781 
2782 static void
bbr_log_exit_gain(struct tcp_bbr * bbr,uint32_t cts,int32_t entry_method)2783 bbr_log_exit_gain(struct tcp_bbr *bbr, uint32_t cts, int32_t entry_method)
2784 {
2785 	if (tcp_bblogging_on(bbr->rc_tp)) {
2786 		union tcp_log_stackspecific log;
2787 
2788 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2789 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2790 		log.u_bbr.flex2 = (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
2791 		log.u_bbr.flex3 = bbr->r_ctl.gain_epoch;
2792 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2793 		log.u_bbr.flex5 = bbr->r_ctl.rc_pace_min_segs;
2794 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_state_atflight;
2795 		log.u_bbr.flex7 = 0;
2796 		log.u_bbr.flex8 = entry_method;
2797 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2798 		    &bbr->rc_inp->inp_socket->so_rcv,
2799 		    &bbr->rc_inp->inp_socket->so_snd,
2800 		    BBR_LOG_EXIT_GAIN, 0,
2801 		    0, &log, false, &bbr->rc_tv);
2802 	}
2803 }
2804 
2805 static void
bbr_log_settings_change(struct tcp_bbr * bbr,int settings_desired)2806 bbr_log_settings_change(struct tcp_bbr *bbr, int settings_desired)
2807 {
2808 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2809 		union tcp_log_stackspecific log;
2810 
2811 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2812 		/* R-HU */
2813 		log.u_bbr.flex1 = 0;
2814 		log.u_bbr.flex2 = 0;
2815 		log.u_bbr.flex3 = 0;
2816 		log.u_bbr.flex4 = 0;
2817 		log.u_bbr.flex7 = 0;
2818 		log.u_bbr.flex8 = settings_desired;
2819 
2820 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2821 		    &bbr->rc_inp->inp_socket->so_rcv,
2822 		    &bbr->rc_inp->inp_socket->so_snd,
2823 		    BBR_LOG_SETTINGS_CHG, 0,
2824 		    0, &log, false, &bbr->rc_tv);
2825 	}
2826 }
2827 
2828 /*
2829  * Returns the bw from the our filter.
2830  */
2831 static inline uint64_t
bbr_get_full_bw(struct tcp_bbr * bbr)2832 bbr_get_full_bw(struct tcp_bbr *bbr)
2833 {
2834 	uint64_t bw;
2835 
2836 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2837 
2838 	return (bw);
2839 }
2840 
2841 static inline void
bbr_set_pktepoch(struct tcp_bbr * bbr,uint32_t cts,int32_t line)2842 bbr_set_pktepoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2843 {
2844 	uint64_t calclr;
2845 	uint32_t lost, del;
2846 
2847 	if (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_pktepoch)
2848 		lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lost_at_pktepoch;
2849 	else
2850 		lost = 0;
2851 	del = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_pkt_epoch_del;
2852 	if (lost == 0)  {
2853 		calclr = 0;
2854 	} else if (del) {
2855 		calclr = lost;
2856 		calclr *= (uint64_t)1000;
2857 		calclr /= (uint64_t)del;
2858 	} else {
2859 		/* Nothing delivered? 100.0% loss */
2860 		calclr = 1000;
2861 	}
2862 	bbr->r_ctl.rc_pkt_epoch_loss_rate =  (uint32_t)calclr;
2863 	if (IN_RECOVERY(bbr->rc_tp->t_flags))
2864 		bbr->r_ctl.recovery_lr += (uint32_t)calclr;
2865 	bbr->r_ctl.rc_pkt_epoch++;
2866 	if (bbr->rc_no_pacing &&
2867 	    (bbr->r_ctl.rc_pkt_epoch >= bbr->no_pacing_until)) {
2868 		bbr->rc_no_pacing = 0;
2869 		tcp_bbr_tso_size_check(bbr, cts);
2870 	}
2871 	bbr->r_ctl.rc_pkt_epoch_rtt = bbr_calc_time(cts, bbr->r_ctl.rc_pkt_epoch_time);
2872 	bbr->r_ctl.rc_pkt_epoch_time = cts;
2873 	/* What was our loss rate */
2874 	bbr_log_pkt_epoch(bbr, cts, line, lost, del);
2875 	bbr->r_ctl.rc_pkt_epoch_del = bbr->r_ctl.rc_delivered;
2876 	bbr->r_ctl.rc_lost_at_pktepoch = bbr->r_ctl.rc_lost;
2877 }
2878 
2879 static inline void
bbr_set_epoch(struct tcp_bbr * bbr,uint32_t cts,int32_t line)2880 bbr_set_epoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2881 {
2882 	uint32_t epoch_time;
2883 
2884 	/* Tick the RTT clock */
2885 	bbr->r_ctl.rc_rtt_epoch++;
2886 	epoch_time = cts - bbr->r_ctl.rc_rcv_epoch_start;
2887 	bbr_log_time_epoch(bbr, cts, line, epoch_time);
2888 	bbr->r_ctl.rc_rcv_epoch_start = cts;
2889 }
2890 
2891 static inline void
bbr_isit_a_pkt_epoch(struct tcp_bbr * bbr,uint32_t cts,struct bbr_sendmap * rsm,int32_t line,int32_t cum_acked)2892 bbr_isit_a_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm, int32_t line, int32_t cum_acked)
2893 {
2894 	if (SEQ_GEQ(rsm->r_delivered, bbr->r_ctl.rc_pkt_epoch_del)) {
2895 		bbr->rc_is_pkt_epoch_now = 1;
2896 	}
2897 }
2898 
2899 /*
2900  * Returns the bw from either the b/w filter
2901  * or from the lt_bw (if the connection is being
2902  * policed).
2903  */
2904 static inline uint64_t
__bbr_get_bw(struct tcp_bbr * bbr)2905 __bbr_get_bw(struct tcp_bbr *bbr)
2906 {
2907 	uint64_t bw, min_bw;
2908 	uint64_t rtt;
2909 	int gm_measure_cnt = 1;
2910 
2911 	/*
2912 	 * For startup we make, like google, a
2913 	 * minimum b/w. This is generated from the
2914 	 * IW and the rttProp. We do fall back to srtt
2915 	 * if for some reason (initial handshake) we don't
2916 	 * have a rttProp. We, in the worst case, fall back
2917 	 * to the configured min_bw (rc_initial_hptsi_bw).
2918 	 */
2919 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
2920 		/* Attempt first to use rttProp */
2921 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2922 		if (rtt && (rtt < 0xffffffff)) {
2923 measure:
2924 			min_bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2925 				((uint64_t)1000000);
2926 			min_bw /= rtt;
2927 			if (min_bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2928 				min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2929 			}
2930 
2931 		} else if (bbr->rc_tp->t_srtt != 0) {
2932 			/* No rttProp, use srtt? */
2933 			rtt = bbr_get_rtt(bbr, BBR_SRTT);
2934 			goto measure;
2935 		} else {
2936 			min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2937 		}
2938 	} else
2939 		min_bw = 0;
2940 
2941 	if ((bbr->rc_past_init_win == 0) &&
2942 	    (bbr->r_ctl.rc_delivered > bbr_initial_cwnd(bbr, bbr->rc_tp)))
2943 		bbr->rc_past_init_win = 1;
2944 	if ((bbr->rc_use_google)  && (bbr->r_ctl.r_measurement_count >= 1))
2945 		gm_measure_cnt = 0;
2946 	if (gm_measure_cnt &&
2947 	    ((bbr->r_ctl.r_measurement_count < bbr_min_measurements_req) ||
2948 	     (bbr->rc_past_init_win == 0))) {
2949 		/* For google we use our guess rate until we get 1 measurement */
2950 
2951 use_initial_window:
2952 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2953 		if (rtt && (rtt < 0xffffffff)) {
2954 			/*
2955 			 * We have an RTT measurement. Use that in
2956 			 * combination with our initial window to calculate
2957 			 * a b/w.
2958 			 */
2959 			bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2960 				((uint64_t)1000000);
2961 			bw /= rtt;
2962 			if (bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2963 				bw = bbr->r_ctl.rc_initial_hptsi_bw;
2964 			}
2965 		} else {
2966 			/* Drop back to the 40 and punt to a default */
2967 			bw = bbr->r_ctl.rc_initial_hptsi_bw;
2968 		}
2969 		if (bw < 1)
2970 			/* Probably should panic */
2971 			bw = 1;
2972 		if (bw > min_bw)
2973 			return (bw);
2974 		else
2975 			return (min_bw);
2976 	}
2977 	if (bbr->rc_lt_use_bw)
2978 		bw = bbr->r_ctl.rc_lt_bw;
2979 	else if (bbr->r_recovery_bw && (bbr->rc_use_google == 0))
2980 		bw = bbr->r_ctl.red_bw;
2981 	else
2982 		bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2983 	if (bw == 0) {
2984 		/* We should not be at 0, go to the initial window then  */
2985 		goto use_initial_window;
2986 	}
2987 	if (bw < min_bw)
2988 		bw = min_bw;
2989 	return (bw);
2990 }
2991 
2992 static inline uint64_t
bbr_get_bw(struct tcp_bbr * bbr)2993 bbr_get_bw(struct tcp_bbr *bbr)
2994 {
2995 	uint64_t bw;
2996 
2997 	bw = __bbr_get_bw(bbr);
2998 	return (bw);
2999 }
3000 
3001 static inline void
bbr_reset_lt_bw_interval(struct tcp_bbr * bbr,uint32_t cts)3002 bbr_reset_lt_bw_interval(struct tcp_bbr *bbr, uint32_t cts)
3003 {
3004 	bbr->r_ctl.rc_lt_epoch = bbr->r_ctl.rc_pkt_epoch;
3005 	bbr->r_ctl.rc_lt_time = bbr->r_ctl.rc_del_time;
3006 	bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3007 	bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3008 }
3009 
3010 static inline void
bbr_reset_lt_bw_sampling(struct tcp_bbr * bbr,uint32_t cts)3011 bbr_reset_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts)
3012 {
3013 	bbr->rc_lt_is_sampling = 0;
3014 	bbr->rc_lt_use_bw = 0;
3015 	bbr->r_ctl.rc_lt_bw = 0;
3016 	bbr_reset_lt_bw_interval(bbr, cts);
3017 }
3018 
3019 static inline void
bbr_lt_bw_samp_done(struct tcp_bbr * bbr,uint64_t bw,uint32_t cts,uint32_t timin)3020 bbr_lt_bw_samp_done(struct tcp_bbr *bbr, uint64_t bw, uint32_t cts, uint32_t timin)
3021 {
3022 	uint64_t diff;
3023 
3024 	/* Do we have a previous sample? */
3025 	if (bbr->r_ctl.rc_lt_bw) {
3026 		/* Get the diff in bytes per second */
3027 		if (bbr->r_ctl.rc_lt_bw > bw)
3028 			diff = bbr->r_ctl.rc_lt_bw - bw;
3029 		else
3030 			diff = bw - bbr->r_ctl.rc_lt_bw;
3031 		if ((diff <= bbr_lt_bw_diff) ||
3032 		    (diff <= (bbr->r_ctl.rc_lt_bw / bbr_lt_bw_ratio))) {
3033 			/* Consider us policed */
3034 			uint32_t saved_bw;
3035 
3036 			saved_bw = (uint32_t)bbr->r_ctl.rc_lt_bw;
3037 			bbr->r_ctl.rc_lt_bw = (bw + bbr->r_ctl.rc_lt_bw) / 2;	/* average of two */
3038 			bbr->rc_lt_use_bw = 1;
3039 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
3040 			/*
3041 			 * Use pkt based epoch for measuring length of
3042 			 * policer up
3043 			 */
3044 			bbr->r_ctl.rc_lt_epoch_use = bbr->r_ctl.rc_pkt_epoch;
3045 			/*
3046 			 * reason 4 is we need to start consider being
3047 			 * policed
3048 			 */
3049 			bbr_log_type_ltbw(bbr, cts, 4, (uint32_t)bw, saved_bw, (uint32_t)diff, timin);
3050 			return;
3051 		}
3052 	}
3053 	bbr->r_ctl.rc_lt_bw = bw;
3054 	bbr_reset_lt_bw_interval(bbr, cts);
3055 	bbr_log_type_ltbw(bbr, cts, 5, 0, (uint32_t)bw, 0, timin);
3056 }
3057 
3058 static void
bbr_randomize_extra_state_time(struct tcp_bbr * bbr)3059 bbr_randomize_extra_state_time(struct tcp_bbr *bbr)
3060 {
3061 	uint32_t ran, deduct;
3062 
3063 	ran = arc4random_uniform(bbr_rand_ot);
3064 	if (ran) {
3065 		deduct = bbr->r_ctl.rc_level_state_extra / ran;
3066 		bbr->r_ctl.rc_level_state_extra -= deduct;
3067 	}
3068 }
3069 /*
3070  * Return randomly the starting state
3071  * to use in probebw.
3072  */
3073 static uint8_t
bbr_pick_probebw_substate(struct tcp_bbr * bbr,uint32_t cts)3074 bbr_pick_probebw_substate(struct tcp_bbr *bbr, uint32_t cts)
3075 {
3076 	uint32_t ran;
3077 	uint8_t ret_val;
3078 
3079 	/* Initialize the offset to 0 */
3080 	bbr->r_ctl.rc_exta_time_gd = 0;
3081 	bbr->rc_hit_state_1 = 0;
3082 	bbr->r_ctl.rc_level_state_extra = 0;
3083 	ran = arc4random_uniform((BBR_SUBSTATE_COUNT-1));
3084 	/*
3085 	 * The math works funny here :) the return value is used to set the
3086 	 * substate and then the state change is called which increments by
3087 	 * one. So if we return 1 (DRAIN) we will increment to 2 (LEVEL1) when
3088 	 * we fully enter the state. Note that the (8 - 1 - ran) assures that
3089 	 * we return 1 - 7, so we dont return 0 and end up starting in
3090 	 * state 1 (DRAIN).
3091 	 */
3092 	ret_val = BBR_SUBSTATE_COUNT - 1 - ran;
3093 	/* Set an epoch */
3094 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP))
3095 		bbr_set_epoch(bbr, cts, __LINE__);
3096 
3097 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
3098 	return (ret_val);
3099 }
3100 
3101 static void
bbr_lt_bw_sampling(struct tcp_bbr * bbr,uint32_t cts,int32_t loss_detected)3102 bbr_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts, int32_t loss_detected)
3103 {
3104 	uint32_t diff, d_time;
3105 	uint64_t del_time, bw, lost, delivered;
3106 
3107 	if (bbr->r_use_policer == 0)
3108 		return;
3109 	if (bbr->rc_lt_use_bw) {
3110 		/* We are using lt bw do we stop yet? */
3111 		diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
3112 		if (diff > bbr_lt_bw_max_rtts) {
3113 			/* Reset it all */
3114 reset_all:
3115 			bbr_reset_lt_bw_sampling(bbr, cts);
3116 			if (bbr->rc_filled_pipe) {
3117 				bbr_set_epoch(bbr, cts, __LINE__);
3118 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
3119 				bbr_substate_change(bbr, cts, __LINE__, 0);
3120 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
3121 				bbr_log_type_statechange(bbr, cts, __LINE__);
3122 			} else {
3123 				/*
3124 				 * This should not happen really
3125 				 * unless we remove the startup/drain
3126 				 * restrictions above.
3127 				 */
3128 				bbr->rc_bbr_state = BBR_STATE_STARTUP;
3129 				bbr_set_epoch(bbr, cts, __LINE__);
3130 				bbr->r_ctl.rc_bbr_state_time = cts;
3131 				bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
3132 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
3133 				bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
3134 				bbr_set_state_target(bbr, __LINE__);
3135 				bbr_log_type_statechange(bbr, cts, __LINE__);
3136 			}
3137 			/* reason 0 is to stop using lt-bw */
3138 			bbr_log_type_ltbw(bbr, cts, 0, 0, 0, 0, 0);
3139 			return;
3140 		}
3141 		if (bbr_lt_intvl_fp == 0) {
3142 			/* Not doing false-positive detection */
3143 			return;
3144 		}
3145 		/* False positive detection */
3146 		if (diff == bbr_lt_intvl_fp) {
3147 			/* At bbr_lt_intvl_fp we record the lost */
3148 			bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3149 			bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3150 		} else if (diff > (bbr_lt_intvl_min_rtts + bbr_lt_intvl_fp)) {
3151 			/* Now is our loss rate still high? */
3152 			lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3153 			delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3154 			if ((delivered == 0) ||
3155 			    (((lost * 1000)/delivered) < bbr_lt_fd_thresh)) {
3156 				/* No still below our threshold */
3157 				bbr_log_type_ltbw(bbr, cts, 7, lost, delivered, 0, 0);
3158 			} else {
3159 				/* Yikes its still high, it must be a false positive */
3160 				bbr_log_type_ltbw(bbr, cts, 8, lost, delivered, 0, 0);
3161 				goto reset_all;
3162 			}
3163 		}
3164 		return;
3165 	}
3166 	/*
3167 	 * Wait for the first loss before sampling, to let the policer
3168 	 * exhaust its tokens and estimate the steady-state rate allowed by
3169 	 * the policer. Starting samples earlier includes bursts that
3170 	 * over-estimate the bw.
3171 	 */
3172 	if (bbr->rc_lt_is_sampling == 0) {
3173 		/* reason 1 is to begin doing the sampling  */
3174 		if (loss_detected == 0)
3175 			return;
3176 		bbr_reset_lt_bw_interval(bbr, cts);
3177 		bbr->rc_lt_is_sampling = 1;
3178 		bbr_log_type_ltbw(bbr, cts, 1, 0, 0, 0, 0);
3179 		return;
3180 	}
3181 	/* Now how long were we delivering long term last> */
3182 	if (TSTMP_GEQ(bbr->r_ctl.rc_del_time, bbr->r_ctl.rc_lt_time))
3183 		d_time = bbr->r_ctl.rc_del_time - bbr->r_ctl.rc_lt_time;
3184 	else
3185 		d_time = 0;
3186 
3187 	/* To avoid underestimates, reset sampling if we run out of data. */
3188 	if (bbr->r_ctl.r_app_limited_until) {
3189 		/* Can not measure in app-limited state */
3190 		bbr_reset_lt_bw_sampling(bbr, cts);
3191 		/* reason 2 is to reset sampling due to app limits  */
3192 		bbr_log_type_ltbw(bbr, cts, 2, 0, 0, 0, d_time);
3193 		return;
3194 	}
3195 	diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
3196 	if (diff < bbr_lt_intvl_min_rtts) {
3197 		/*
3198 		 * need more samples (we don't
3199 		 * start on a round like linux so
3200 		 * we need 1 more).
3201 		 */
3202 		/* 6 is not_enough time or no-loss */
3203 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3204 		return;
3205 	}
3206 	if (diff > (4 * bbr_lt_intvl_min_rtts)) {
3207 		/*
3208 		 * For now if we wait too long, reset all sampling. We need
3209 		 * to do some research here, its possible that we should
3210 		 * base this on how much loss as occurred.. something like
3211 		 * if its under 10% (or some thresh) reset all otherwise
3212 		 * don't.  Thats for phase II I guess.
3213 		 */
3214 		bbr_reset_lt_bw_sampling(bbr, cts);
3215  		/* reason 3 is to reset sampling due too long of sampling */
3216 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3217 		return;
3218 	}
3219 	/*
3220 	 * End sampling interval when a packet is lost, so we estimate the
3221 	 * policer tokens were exhausted. Stopping the sampling before the
3222 	 * tokens are exhausted under-estimates the policed rate.
3223 	 */
3224 	if (loss_detected == 0) {
3225 		/* 6 is not_enough time or no-loss */
3226 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3227 		return;
3228 	}
3229 	/* Calculate packets lost and delivered in sampling interval. */
3230 	lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3231 	delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3232 	if ((delivered == 0) ||
3233 	    (((lost * 1000)/delivered) < bbr_lt_loss_thresh)) {
3234 		bbr_log_type_ltbw(bbr, cts, 6, lost, delivered, 0, d_time);
3235 		return;
3236 	}
3237 	if (d_time < 1000) {
3238 		/* Not enough time. wait */
3239 		/* 6 is not_enough time or no-loss */
3240 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3241 		return;
3242 	}
3243 	if (d_time >= (0xffffffff / USECS_IN_MSEC)) {
3244 		/* Too long */
3245 		bbr_reset_lt_bw_sampling(bbr, cts);
3246  		/* reason 3 is to reset sampling due too long of sampling */
3247 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3248 		return;
3249 	}
3250 	del_time = d_time;
3251 	bw = delivered;
3252 	bw *= (uint64_t)USECS_IN_SECOND;
3253 	bw /= del_time;
3254 	bbr_lt_bw_samp_done(bbr, bw, cts, d_time);
3255 }
3256 
3257 /*
3258  * Allocate a sendmap from our zone.
3259  */
3260 static struct bbr_sendmap *
bbr_alloc(struct tcp_bbr * bbr)3261 bbr_alloc(struct tcp_bbr *bbr)
3262 {
3263 	struct bbr_sendmap *rsm;
3264 
3265 	BBR_STAT_INC(bbr_to_alloc);
3266 	rsm = uma_zalloc(bbr_zone, (M_NOWAIT | M_ZERO));
3267 	if (rsm) {
3268 		bbr->r_ctl.rc_num_maps_alloced++;
3269 		return (rsm);
3270 	}
3271 	if (bbr->r_ctl.rc_free_cnt) {
3272 		BBR_STAT_INC(bbr_to_alloc_emerg);
3273 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
3274 		TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
3275 		bbr->r_ctl.rc_free_cnt--;
3276 		return (rsm);
3277 	}
3278 	BBR_STAT_INC(bbr_to_alloc_failed);
3279 	return (NULL);
3280 }
3281 
3282 static struct bbr_sendmap *
bbr_alloc_full_limit(struct tcp_bbr * bbr)3283 bbr_alloc_full_limit(struct tcp_bbr *bbr)
3284 {
3285 	if ((V_tcp_map_entries_limit > 0) &&
3286 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
3287 		BBR_STAT_INC(bbr_alloc_limited);
3288 		if (!bbr->alloc_limit_reported) {
3289 			bbr->alloc_limit_reported = 1;
3290 			BBR_STAT_INC(bbr_alloc_limited_conns);
3291 		}
3292 		return (NULL);
3293 	}
3294 	return (bbr_alloc(bbr));
3295 }
3296 
3297 /* wrapper to allocate a sendmap entry, subject to a specific limit */
3298 static struct bbr_sendmap *
bbr_alloc_limit(struct tcp_bbr * bbr,uint8_t limit_type)3299 bbr_alloc_limit(struct tcp_bbr *bbr, uint8_t limit_type)
3300 {
3301 	struct bbr_sendmap *rsm;
3302 
3303 	if (limit_type) {
3304 		/* currently there is only one limit type */
3305 		if (V_tcp_map_split_limit > 0 &&
3306 		    bbr->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
3307 			BBR_STAT_INC(bbr_split_limited);
3308 			if (!bbr->alloc_limit_reported) {
3309 				bbr->alloc_limit_reported = 1;
3310 				BBR_STAT_INC(bbr_alloc_limited_conns);
3311 			}
3312 			return (NULL);
3313 		}
3314 	}
3315 
3316 	/* allocate and mark in the limit type, if set */
3317 	rsm = bbr_alloc(bbr);
3318 	if (rsm != NULL && limit_type) {
3319 		rsm->r_limit_type = limit_type;
3320 		bbr->r_ctl.rc_num_split_allocs++;
3321 	}
3322 	return (rsm);
3323 }
3324 
3325 static void
bbr_free(struct tcp_bbr * bbr,struct bbr_sendmap * rsm)3326 bbr_free(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
3327 {
3328 	if (rsm->r_limit_type) {
3329 		/* currently there is only one limit type */
3330 		bbr->r_ctl.rc_num_split_allocs--;
3331 	}
3332 	if (rsm->r_is_smallmap)
3333 		bbr->r_ctl.rc_num_small_maps_alloced--;
3334 	if (bbr->r_ctl.rc_tlp_send == rsm)
3335 		bbr->r_ctl.rc_tlp_send = NULL;
3336 	if (bbr->r_ctl.rc_resend == rsm) {
3337 		bbr->r_ctl.rc_resend = NULL;
3338 	}
3339 	if (bbr->r_ctl.rc_next == rsm)
3340 		bbr->r_ctl.rc_next = NULL;
3341 	if (bbr->r_ctl.rc_sacklast == rsm)
3342 		bbr->r_ctl.rc_sacklast = NULL;
3343 	if (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
3344 		memset(rsm, 0, sizeof(struct bbr_sendmap));
3345 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
3346 		rsm->r_limit_type = 0;
3347 		bbr->r_ctl.rc_free_cnt++;
3348 		return;
3349 	}
3350 	bbr->r_ctl.rc_num_maps_alloced--;
3351 	uma_zfree(bbr_zone, rsm);
3352 }
3353 
3354 /*
3355  * Returns the BDP.
3356  */
3357 static uint64_t
bbr_get_bw_delay_prod(uint64_t rtt,uint64_t bw)3358 bbr_get_bw_delay_prod(uint64_t rtt, uint64_t bw) {
3359 	/*
3360 	 * Calculate the bytes in flight needed given the bw (in bytes per
3361 	 * second) and the specifyed rtt in useconds. We need to put out the
3362 	 * returned value per RTT to match that rate. Gain will normally
3363 	 * raise it up from there.
3364 	 *
3365 	 * This should not overflow as long as the bandwidth is below 1
3366 	 * TByte per second (bw < 10**12 = 2**40) and the rtt is smaller
3367 	 * than 1000 seconds (rtt < 10**3 * 10**6 = 10**9 = 2**30).
3368 	 */
3369 	uint64_t usec_per_sec;
3370 
3371 	usec_per_sec = USECS_IN_SECOND;
3372 	return ((rtt * bw) / usec_per_sec);
3373 }
3374 
3375 /*
3376  * Return the initial cwnd.
3377  */
3378 static uint32_t
bbr_initial_cwnd(struct tcp_bbr * bbr,struct tcpcb * tp)3379 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp)
3380 {
3381 	uint32_t i_cwnd;
3382 
3383 	if (bbr->rc_init_win) {
3384 		i_cwnd = bbr->rc_init_win * tp->t_maxseg;
3385 	} else if (V_tcp_initcwnd_segments)
3386 		i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
3387 		    max(2 * tp->t_maxseg, 14600));
3388 	else if (V_tcp_do_rfc3390)
3389 		i_cwnd = min(4 * tp->t_maxseg,
3390 		    max(2 * tp->t_maxseg, 4380));
3391 	else {
3392 		/* Per RFC5681 Section 3.1 */
3393 		if (tp->t_maxseg > 2190)
3394 			i_cwnd = 2 * tp->t_maxseg;
3395 		else if (tp->t_maxseg > 1095)
3396 			i_cwnd = 3 * tp->t_maxseg;
3397 		else
3398 			i_cwnd = 4 * tp->t_maxseg;
3399 	}
3400 	return (i_cwnd);
3401 }
3402 
3403 /*
3404  * Given a specified gain, return the target
3405  * cwnd based on that gain.
3406  */
3407 static uint32_t
bbr_get_raw_target_cwnd(struct tcp_bbr * bbr,uint32_t gain,uint64_t bw)3408 bbr_get_raw_target_cwnd(struct tcp_bbr *bbr, uint32_t gain, uint64_t bw)
3409 {
3410 	uint64_t bdp, rtt;
3411 	uint32_t cwnd;
3412 
3413 	if ((get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) ||
3414 	    (bbr_get_full_bw(bbr) == 0)) {
3415 		/* No measurements yet */
3416 		return (bbr_initial_cwnd(bbr, bbr->rc_tp));
3417 	}
3418 	/*
3419 	 * Get bytes per RTT needed (rttProp is normally in
3420 	 * bbr_cwndtarget_rtt_touse)
3421 	 */
3422 	rtt = bbr_get_rtt(bbr, bbr_cwndtarget_rtt_touse);
3423 	/* Get the bdp from the two values */
3424 	bdp = bbr_get_bw_delay_prod(rtt, bw);
3425 	/* Now apply the gain */
3426 	cwnd = (uint32_t)(((bdp * ((uint64_t)gain)) + (uint64_t)(BBR_UNIT - 1)) / ((uint64_t)BBR_UNIT));
3427 
3428 	return (cwnd);
3429 }
3430 
3431 static uint32_t
bbr_get_target_cwnd(struct tcp_bbr * bbr,uint64_t bw,uint32_t gain)3432 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain)
3433 {
3434 	uint32_t cwnd, mss;
3435 
3436 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
3437 	/* Get the base cwnd with gain rounded to a mss */
3438 	cwnd = roundup(bbr_get_raw_target_cwnd(bbr, bw, gain), mss);
3439 	/*
3440 	 * Add in N (2 default since we do not have a
3441 	 * fq layer to trap packets in) quanta's per the I-D
3442 	 * section 4.2.3.2 quanta adjust.
3443 	 */
3444 	cwnd += (bbr_quanta * bbr->r_ctl.rc_pace_max_segs);
3445 	if (bbr->rc_use_google) {
3446 		if((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3447 		   (bbr_state_val(bbr) == BBR_SUB_GAIN)) {
3448 			/*
3449 			 * The linux implementation adds
3450 			 * an extra 2 x mss in gain cycle which
3451 			 * is documented no-where except in the code.
3452 			 * so we add more for Neal undocumented feature
3453 			 */
3454 			cwnd += 2 * mss;
3455 		}
3456  		if ((cwnd / mss) & 0x1) {
3457 			/* Round up for odd num mss */
3458 			cwnd += mss;
3459 		}
3460 	}
3461 	/* Are we below the min cwnd? */
3462 	if (cwnd < get_min_cwnd(bbr))
3463 		return (get_min_cwnd(bbr));
3464 	return (cwnd);
3465 }
3466 
3467 static uint16_t
bbr_gain_adjust(struct tcp_bbr * bbr,uint16_t gain)3468 bbr_gain_adjust(struct tcp_bbr *bbr, uint16_t gain)
3469 {
3470 	if (gain < 1)
3471 		gain = 1;
3472 	return (gain);
3473 }
3474 
3475 static uint32_t
bbr_get_header_oh(struct tcp_bbr * bbr)3476 bbr_get_header_oh(struct tcp_bbr *bbr)
3477 {
3478 	int seg_oh;
3479 
3480 	seg_oh = 0;
3481 	if (bbr->r_ctl.rc_inc_tcp_oh) {
3482 		/* Do we include TCP overhead? */
3483 		seg_oh = (bbr->rc_last_options + sizeof(struct tcphdr));
3484 	}
3485 	if (bbr->r_ctl.rc_inc_ip_oh) {
3486 		/* Do we include IP overhead? */
3487 #ifdef INET6
3488 		if (bbr->r_is_v6) {
3489 			seg_oh += sizeof(struct ip6_hdr);
3490 		} else
3491 #endif
3492 		{
3493 
3494 #ifdef INET
3495 			seg_oh += sizeof(struct ip);
3496 #endif
3497 		}
3498 	}
3499 	if (bbr->r_ctl.rc_inc_enet_oh) {
3500 		/* Do we include the ethernet overhead?  */
3501 		seg_oh += sizeof(struct ether_header);
3502 	}
3503 	return(seg_oh);
3504 }
3505 
3506 static uint32_t
bbr_get_pacing_length(struct tcp_bbr * bbr,uint16_t gain,uint32_t useconds_time,uint64_t bw)3507 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain, uint32_t useconds_time, uint64_t bw)
3508 {
3509 	uint64_t divor, res, tim;
3510 
3511 	if (useconds_time == 0)
3512 		return (0);
3513 	gain = bbr_gain_adjust(bbr, gain);
3514 	divor = (uint64_t)USECS_IN_SECOND * (uint64_t)BBR_UNIT;
3515 	tim = useconds_time;
3516 	res = (tim * bw * gain) / divor;
3517 	if (res == 0)
3518 		res = 1;
3519 	return ((uint32_t)res);
3520 }
3521 
3522 /*
3523  * Given a gain and a length return the delay in useconds that
3524  * should be used to evenly space out packets
3525  * on the connection (based on the gain factor).
3526  */
3527 static uint32_t
bbr_get_pacing_delay(struct tcp_bbr * bbr,uint16_t gain,int32_t len,uint32_t cts,int nolog)3528 bbr_get_pacing_delay(struct tcp_bbr *bbr, uint16_t gain, int32_t len, uint32_t cts, int nolog)
3529 {
3530 	uint64_t bw, lentim, res;
3531 	uint32_t usecs, srtt, over = 0;
3532 	uint32_t seg_oh, num_segs, maxseg;
3533 
3534 	if (len == 0)
3535 		return (0);
3536 
3537 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
3538 	num_segs = (len + maxseg - 1) / maxseg;
3539 	if (bbr->rc_use_google == 0) {
3540 		seg_oh = bbr_get_header_oh(bbr);
3541 		len += (num_segs * seg_oh);
3542 	}
3543 	gain = bbr_gain_adjust(bbr, gain);
3544 	bw = bbr_get_bw(bbr);
3545 	if (bbr->rc_use_google) {
3546 		uint64_t cbw;
3547 
3548 		/*
3549 		 * Reduce the b/w by the google discount
3550 		 * factor 10 = 1%.
3551 		 */
3552 		cbw = bw *  (uint64_t)(1000 - bbr->r_ctl.bbr_google_discount);
3553 		cbw /= (uint64_t)1000;
3554 		/* We don't apply a discount if it results in 0 */
3555 		if (cbw > 0)
3556 			bw = cbw;
3557 	}
3558 	lentim = ((uint64_t)len *
3559 		  (uint64_t)USECS_IN_SECOND *
3560 		  (uint64_t)BBR_UNIT);
3561 	res = lentim / ((uint64_t)gain * bw);
3562 	if (res == 0)
3563 		res = 1;
3564 	usecs = (uint32_t)res;
3565 	srtt = bbr_get_rtt(bbr, BBR_SRTT);
3566 	if (bbr_hptsi_max_mul && bbr_hptsi_max_div &&
3567 	    (bbr->rc_use_google == 0) &&
3568 	    (usecs > ((srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div))) {
3569 		/*
3570 		 * We cannot let the delay be more than 1/2 the srtt time.
3571 		 * Otherwise we cannot pace out or send properly.
3572 		 */
3573 		over = usecs = (srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div;
3574 		BBR_STAT_INC(bbr_hpts_min_time);
3575 	}
3576 	if (!nolog)
3577 		bbr_log_pacing_delay_calc(bbr, gain, len, cts, usecs, bw, over, 1);
3578 	return (usecs);
3579 }
3580 
3581 static void
bbr_ack_received(struct tcpcb * tp,struct tcp_bbr * bbr,struct tcphdr * th,uint32_t bytes_this_ack,uint32_t sack_changed,uint32_t prev_acked,int32_t line,uint32_t losses)3582 bbr_ack_received(struct tcpcb *tp, struct tcp_bbr *bbr, struct tcphdr *th, uint32_t bytes_this_ack,
3583 		 uint32_t sack_changed, uint32_t prev_acked, int32_t line, uint32_t losses)
3584 {
3585 	uint64_t bw;
3586 	uint32_t cwnd, target_cwnd, saved_bytes, maxseg;
3587 	int32_t meth;
3588 
3589 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3590 
3591 #ifdef STATS
3592 	if ((tp->t_flags & TF_GPUTINPROG) &&
3593 	    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
3594 		/*
3595 		 * Strech acks and compressed acks will cause this to
3596 		 * oscillate but we are doing it the same way as the main
3597 		 * stack so it will be compariable (though possibly not
3598 		 * ideal).
3599 		 */
3600 		int32_t cgput;
3601 		int64_t gput, time_stamp;
3602 
3603 		gput = (int64_t) (th->th_ack - tp->gput_seq) * 8;
3604 		time_stamp = max(1, ((bbr->r_ctl.rc_rcvtime - tp->gput_ts) / 1000));
3605 		cgput = gput / time_stamp;
3606 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
3607 					 cgput);
3608 		if (tp->t_stats_gput_prev > 0)
3609 			stats_voi_update_abs_s32(tp->t_stats,
3610 						 VOI_TCP_GPUT_ND,
3611 						 ((gput - tp->t_stats_gput_prev) * 100) /
3612 						 tp->t_stats_gput_prev);
3613 		tp->t_flags &= ~TF_GPUTINPROG;
3614 		tp->t_stats_gput_prev = cgput;
3615 	}
3616 #endif
3617 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3618 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
3619 		/* We don't change anything in probe-rtt */
3620 		return;
3621 	}
3622 	maxseg = tp->t_maxseg - bbr->rc_last_options;
3623 	saved_bytes = bytes_this_ack;
3624 	bytes_this_ack += sack_changed;
3625 	if (bytes_this_ack > prev_acked) {
3626 		bytes_this_ack -= prev_acked;
3627 		/*
3628 		 * A byte ack'd gives us a full mss
3629 		 * to be like linux i.e. they count packets.
3630 		 */
3631 		if ((bytes_this_ack < maxseg) && bbr->rc_use_google)
3632 			bytes_this_ack = maxseg;
3633 	} else {
3634 		/* Unlikely */
3635 		bytes_this_ack = 0;
3636 	}
3637 	cwnd = tp->snd_cwnd;
3638 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3639 	if (bw)
3640 		target_cwnd = bbr_get_target_cwnd(bbr,
3641 						  bw,
3642 						  (uint32_t)bbr->r_ctl.rc_bbr_cwnd_gain);
3643 	else
3644 		target_cwnd = bbr_initial_cwnd(bbr, bbr->rc_tp);
3645 	if (IN_RECOVERY(tp->t_flags) &&
3646 	    (bbr->bbr_prev_in_rec == 0)) {
3647 		/*
3648 		 * We are entering recovery and
3649 		 * thus packet conservation.
3650 		 */
3651 		bbr->pkt_conservation = 1;
3652 		bbr->r_ctl.rc_recovery_start = bbr->r_ctl.rc_rcvtime;
3653 		cwnd = ctf_flight_size(tp,
3654 				       (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3655 			bytes_this_ack;
3656 	}
3657 	if (IN_RECOVERY(tp->t_flags)) {
3658 		uint32_t flight;
3659 
3660 		bbr->bbr_prev_in_rec = 1;
3661 		if (cwnd > losses) {
3662 			cwnd -= losses;
3663 			if (cwnd < maxseg)
3664 				cwnd = maxseg;
3665 		} else
3666 			cwnd = maxseg;
3667 		flight = ctf_flight_size(tp,
3668 					 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3669 		bbr_log_type_cwndupd(bbr, flight, 0,
3670 				     losses, 10, 0, 0, line);
3671 		if (bbr->pkt_conservation) {
3672 			uint32_t time_in;
3673 
3674 			if (TSTMP_GEQ(bbr->r_ctl.rc_rcvtime, bbr->r_ctl.rc_recovery_start))
3675 				time_in = bbr->r_ctl.rc_rcvtime - bbr->r_ctl.rc_recovery_start;
3676 			else
3677 				time_in = 0;
3678 
3679 			if (time_in >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
3680 				/* Clear packet conservation after an rttProp */
3681 				bbr->pkt_conservation = 0;
3682 			} else {
3683 				if ((flight + bytes_this_ack) > cwnd)
3684 					cwnd = flight + bytes_this_ack;
3685 				if (cwnd < get_min_cwnd(bbr))
3686 					cwnd = get_min_cwnd(bbr);
3687 				tp->snd_cwnd = cwnd;
3688 				bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed,
3689 						     prev_acked, 1, target_cwnd, th->th_ack, line);
3690 				return;
3691 			}
3692 		}
3693 	} else
3694 		bbr->bbr_prev_in_rec = 0;
3695 	if ((bbr->rc_use_google == 0) && bbr->r_ctl.restrict_growth) {
3696 		bbr->r_ctl.restrict_growth--;
3697 		if (bytes_this_ack > maxseg)
3698 			bytes_this_ack = maxseg;
3699 	}
3700 	if (bbr->rc_filled_pipe) {
3701 		/*
3702 		 * Here we have exited startup and filled the pipe. We will
3703 		 * thus allow the cwnd to shrink to the target. We hit here
3704 		 * mostly.
3705 		 */
3706 		uint32_t s_cwnd;
3707 
3708 		meth = 2;
3709 		s_cwnd = min((cwnd + bytes_this_ack), target_cwnd);
3710 		if (s_cwnd > cwnd)
3711 			cwnd = s_cwnd;
3712 		else if (bbr_cwnd_may_shrink || bbr->rc_use_google || bbr->rc_no_pacing)
3713 			cwnd = s_cwnd;
3714 	} else {
3715 		/*
3716 		 * Here we are still in startup, we increase cwnd by what
3717 		 * has been acked.
3718 		 */
3719 		if ((cwnd < target_cwnd) ||
3720 		    (bbr->rc_past_init_win == 0)) {
3721 			meth = 3;
3722 			cwnd += bytes_this_ack;
3723 		} else {
3724 			/*
3725 			 * Method 4 means we are at target so no gain in
3726 			 * startup and past the initial window.
3727 			 */
3728 			meth = 4;
3729 		}
3730 	}
3731 	tp->snd_cwnd = max(cwnd, get_min_cwnd(bbr));
3732 	bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed, prev_acked, meth, target_cwnd, th->th_ack, line);
3733 }
3734 
3735 static void
tcp_bbr_partialack(struct tcpcb * tp)3736 tcp_bbr_partialack(struct tcpcb *tp)
3737 {
3738 	struct tcp_bbr *bbr;
3739 
3740 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3741 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3742 	if (ctf_flight_size(tp,
3743 		(bbr->r_ctl.rc_sacked  + bbr->r_ctl.rc_lost_bytes)) <=
3744 	    tp->snd_cwnd) {
3745 		bbr->r_wanted_output = 1;
3746 	}
3747 }
3748 
3749 static void
bbr_post_recovery(struct tcpcb * tp)3750 bbr_post_recovery(struct tcpcb *tp)
3751 {
3752 	struct tcp_bbr *bbr;
3753 	uint32_t  flight;
3754 
3755 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3756 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3757 	/*
3758 	 * Here we just exit recovery.
3759 	 */
3760 	EXIT_RECOVERY(tp->t_flags);
3761 	/* Lock in our b/w reduction for the specified number of pkt-epochs */
3762 	bbr->r_recovery_bw = 0;
3763 	tp->snd_recover = tp->snd_una;
3764 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3765 	bbr->pkt_conservation = 0;
3766 	if (bbr->rc_use_google == 0) {
3767 		/*
3768 		 * For non-google mode lets
3769 		 * go ahead and make sure we clear
3770 		 * the recovery state so if we
3771 		 * bounce back in to recovery we
3772 		 * will do PC.
3773 		 */
3774 		bbr->bbr_prev_in_rec = 0;
3775 	}
3776 	bbr_log_type_exit_rec(bbr);
3777 	if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3778 		tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3779 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 15, 0, 0, __LINE__);
3780 	} else {
3781 		/* For probe-rtt case lets fix up its saved_cwnd */
3782 		if (bbr->r_ctl.rc_saved_cwnd < bbr->r_ctl.rc_cwnd_on_ent) {
3783 			bbr->r_ctl.rc_saved_cwnd = bbr->r_ctl.rc_cwnd_on_ent;
3784 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 16, 0, 0, __LINE__);
3785 		}
3786 	}
3787 	flight = ctf_flight_size(tp,
3788 		     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3789 	if ((bbr->rc_use_google == 0) &&
3790 	    bbr_do_red) {
3791 		uint64_t val, lr2use;
3792 		uint32_t maxseg, newcwnd, acks_inflight, ratio, cwnd;
3793 		uint32_t *cwnd_p;
3794 
3795 		if (bbr_get_rtt(bbr, BBR_SRTT)) {
3796 			val = ((uint64_t)bbr_get_rtt(bbr, BBR_RTT_PROP) * (uint64_t)1000);
3797 			val /= bbr_get_rtt(bbr, BBR_SRTT);
3798 			ratio = (uint32_t)val;
3799 		} else
3800 			ratio = 1000;
3801 
3802 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div,
3803 				     bbr->r_ctl.recovery_lr, 21,
3804 				     ratio,
3805 				     bbr->r_ctl.rc_red_cwnd_pe,
3806 				     __LINE__);
3807 		if ((ratio < bbr_do_red) || (bbr_do_red == 0))
3808 			goto done;
3809 		if (((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3810 		     bbr_prtt_slam_cwnd) ||
3811 		    (bbr_sub_drain_slam_cwnd &&
3812 		     (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3813 		     bbr->rc_hit_state_1 &&
3814 		     (bbr_state_val(bbr) == BBR_SUB_DRAIN)) ||
3815 		    ((bbr->rc_bbr_state == BBR_STATE_DRAIN) &&
3816 		     bbr_slam_cwnd_in_main_drain)) {
3817 			/*
3818 			 * Here we must poke at the saved cwnd
3819 			 * as well as the cwnd.
3820 			 */
3821 			cwnd = bbr->r_ctl.rc_saved_cwnd;
3822 			cwnd_p = &bbr->r_ctl.rc_saved_cwnd;
3823 		} else {
3824  			cwnd = tp->snd_cwnd;
3825 			cwnd_p = &tp->snd_cwnd;
3826 		}
3827 		maxseg = tp->t_maxseg - bbr->rc_last_options;
3828 		/* Add the overall lr with the recovery lr */
3829 		if (bbr->r_ctl.rc_lost == 0)
3830 			lr2use = 0;
3831 		else if (bbr->r_ctl.rc_delivered == 0)
3832 			lr2use = 1000;
3833 		else {
3834 			lr2use = (uint64_t)bbr->r_ctl.rc_lost * (uint64_t)1000;
3835 			lr2use /= bbr->r_ctl.rc_delivered;
3836 		}
3837 		lr2use += bbr->r_ctl.recovery_lr;
3838 		acks_inflight = (flight / (maxseg * 2));
3839 		if (bbr_red_scale) {
3840 			lr2use *= bbr_get_rtt(bbr, BBR_SRTT);
3841 			lr2use /= bbr_red_scale;
3842 			if ((bbr_red_growth_restrict) &&
3843 			    ((bbr_get_rtt(bbr, BBR_SRTT)/bbr_red_scale) > 1))
3844 			    bbr->r_ctl.restrict_growth += acks_inflight;
3845 		}
3846 		if (lr2use) {
3847 			val = (uint64_t)cwnd * lr2use;
3848 			val /= 1000;
3849 			if (cwnd > val)
3850 				newcwnd = roundup((cwnd - val), maxseg);
3851 			else
3852 				newcwnd = maxseg;
3853 		} else {
3854 			val = (uint64_t)cwnd * (uint64_t)bbr_red_mul;
3855 			val /= (uint64_t)bbr_red_div;
3856 			newcwnd = roundup((uint32_t)val, maxseg);
3857 		}
3858 		/* with standard delayed acks how many acks can I expect? */
3859 		if (bbr_drop_limit == 0) {
3860 			/*
3861 			 * Anticpate how much we will
3862 			 * raise the cwnd based on the acks.
3863 			 */
3864 			if ((newcwnd + (acks_inflight * maxseg)) < get_min_cwnd(bbr)) {
3865 				/* We do enforce the min (with the acks) */
3866 				newcwnd = (get_min_cwnd(bbr) - acks_inflight);
3867 			}
3868 		} else {
3869 			/*
3870 			 * A strict drop limit of N is inplace
3871 			 */
3872 			if (newcwnd < (bbr_drop_limit * maxseg)) {
3873 				newcwnd = bbr_drop_limit * maxseg;
3874 			}
3875 		}
3876 		/* For the next N acks do we restrict the growth */
3877 		*cwnd_p = newcwnd;
3878 		if (tp->snd_cwnd > newcwnd)
3879 			tp->snd_cwnd = newcwnd;
3880 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div, val, 22,
3881 				     (uint32_t)lr2use,
3882 				     bbr_get_rtt(bbr, BBR_SRTT), __LINE__);
3883 		bbr->r_ctl.rc_red_cwnd_pe = bbr->r_ctl.rc_pkt_epoch;
3884 	}
3885 done:
3886 	bbr->r_ctl.recovery_lr = 0;
3887 	if (flight <= tp->snd_cwnd) {
3888 		bbr->r_wanted_output = 1;
3889 	}
3890 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3891 }
3892 
3893 static void
bbr_setup_red_bw(struct tcp_bbr * bbr,uint32_t cts)3894 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts)
3895 {
3896 	bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3897 	/* Limit the drop in b/w to 1/2 our current filter. */
3898 	if (bbr->r_ctl.red_bw > bbr->r_ctl.rc_bbr_cur_del_rate)
3899 		bbr->r_ctl.red_bw = bbr->r_ctl.rc_bbr_cur_del_rate;
3900 	if (bbr->r_ctl.red_bw < (get_filter_value(&bbr->r_ctl.rc_delrate) / 2))
3901 		bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate) / 2;
3902 	tcp_bbr_tso_size_check(bbr, cts);
3903 }
3904 
3905 static void
bbr_cong_signal(struct tcpcb * tp,struct tcphdr * th,uint32_t type,struct bbr_sendmap * rsm)3906 bbr_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type, struct bbr_sendmap *rsm)
3907 {
3908 	struct tcp_bbr *bbr;
3909 
3910 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3911 #ifdef STATS
3912 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
3913 #endif
3914 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3915 	switch (type) {
3916 	case CC_NDUPACK:
3917 		if (!IN_RECOVERY(tp->t_flags)) {
3918 			tp->snd_recover = tp->snd_max;
3919 			/* Start a new epoch */
3920 			bbr_set_pktepoch(bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
3921 			if (bbr->rc_lt_is_sampling || bbr->rc_lt_use_bw) {
3922 				/*
3923 				 * Move forward the lt epoch
3924 				 * so it won't count the truncated
3925 				 * epoch.
3926 				 */
3927 				bbr->r_ctl.rc_lt_epoch++;
3928 			}
3929 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
3930 				/*
3931 				 * Just like the policer detection code
3932 				 * if we are in startup we must push
3933 				 * forward the last startup epoch
3934 				 * to hide the truncated PE.
3935 				 */
3936 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
3937 			}
3938 			bbr->r_ctl.rc_cwnd_on_ent = tp->snd_cwnd;
3939 			ENTER_RECOVERY(tp->t_flags);
3940 			bbr->rc_tlp_rtx_out = 0;
3941 			bbr->r_ctl.recovery_lr = bbr->r_ctl.rc_pkt_epoch_loss_rate;
3942 			tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3943 			if (tcp_in_hpts(bbr->rc_tp) &&
3944 			    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) == 0)) {
3945 				/*
3946 				 * When we enter recovery, we need to restart
3947 				 * any timers. This may mean we gain an agg
3948 				 * early, which will be made up for at the last
3949 				 * rxt out.
3950 				 */
3951 				bbr->rc_timer_first = 1;
3952 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
3953 			}
3954 			/*
3955 			 * Calculate a new cwnd based on to the current
3956 			 * delivery rate with no gain. We get the bdp
3957 			 * without gaining it up like we normally would and
3958 			 * we use the last cur_del_rate.
3959 			 */
3960 			if ((bbr->rc_use_google == 0) &&
3961 			    (bbr->r_ctl.bbr_rttprobe_gain_val ||
3962 			     (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT))) {
3963 				tp->snd_cwnd = ctf_flight_size(tp,
3964 					           (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3965 					(tp->t_maxseg - bbr->rc_last_options);
3966 				if (tp->snd_cwnd < get_min_cwnd(bbr)) {
3967 					/* We always gate to min cwnd */
3968 					tp->snd_cwnd = get_min_cwnd(bbr);
3969 				}
3970 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 14, 0, 0, __LINE__);
3971 			}
3972 			bbr_log_type_enter_rec(bbr, rsm->r_start);
3973 		}
3974 		break;
3975 	case CC_RTO_ERR:
3976 		KMOD_TCPSTAT_INC(tcps_sndrexmitbad);
3977 		/* RTO was unnecessary, so reset everything. */
3978 		bbr_reset_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime);
3979 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3980 			tp->snd_cwnd = tp->snd_cwnd_prev;
3981 			tp->snd_ssthresh = tp->snd_ssthresh_prev;
3982 			tp->snd_recover = tp->snd_recover_prev;
3983 			tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3984 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 13, 0, 0, __LINE__);
3985 		}
3986 		tp->t_badrxtwin = 0;
3987 		break;
3988 	}
3989 }
3990 
3991 /*
3992  * Indicate whether this ack should be delayed.  We can delay the ack if
3993  * following conditions are met:
3994  *	- There is no delayed ack timer in progress.
3995  *	- Our last ack wasn't a 0-sized window. We never want to delay
3996  *	  the ack that opens up a 0-sized window.
3997  *	- LRO wasn't used for this segment. We make sure by checking that the
3998  *	  segment size is not larger than the MSS.
3999  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
4000  *	  connection.
4001  *	- The data being acked is less than a full segment (a stretch ack
4002  *        of more than a segment we should ack.
4003  *      - nsegs is 1 (if its more than that we received more than 1 ack).
4004  */
4005 #define DELAY_ACK(tp, bbr, nsegs)				\
4006 	(((tp->t_flags & TF_RXWIN0SENT) == 0) &&		\
4007 	 ((tp->t_flags & TF_DELACK) == 0) && 		 	\
4008 	 ((bbr->bbr_segs_rcvd + nsegs) < tp->t_delayed_ack) &&	\
4009 	 (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4010 
4011 /*
4012  * Return the lowest RSM in the map of
4013  * packets still in flight that is not acked.
4014  * This should normally find on the first one
4015  * since we remove packets from the send
4016  * map after they are marked ACKED.
4017  */
4018 static struct bbr_sendmap *
bbr_find_lowest_rsm(struct tcp_bbr * bbr)4019 bbr_find_lowest_rsm(struct tcp_bbr *bbr)
4020 {
4021 	struct bbr_sendmap *rsm;
4022 
4023 	/*
4024 	 * Walk the time-order transmitted list looking for an rsm that is
4025 	 * not acked. This will be the one that was sent the longest time
4026 	 * ago that is still outstanding.
4027 	 */
4028 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_tmap, r_tnext) {
4029 		if (rsm->r_flags & BBR_ACKED) {
4030 			continue;
4031 		}
4032 		goto finish;
4033 	}
4034 finish:
4035 	return (rsm);
4036 }
4037 
4038 static struct bbr_sendmap *
bbr_find_high_nonack(struct tcp_bbr * bbr,struct bbr_sendmap * rsm)4039 bbr_find_high_nonack(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
4040 {
4041 	struct bbr_sendmap *prsm;
4042 
4043 	/*
4044 	 * Walk the sequence order list backward until we hit and arrive at
4045 	 * the highest seq not acked. In theory when this is called it
4046 	 * should be the last segment (which it was not).
4047 	 */
4048 	prsm = rsm;
4049 	TAILQ_FOREACH_REVERSE_FROM(prsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4050 		if (prsm->r_flags & (BBR_ACKED | BBR_HAS_FIN)) {
4051 			continue;
4052 		}
4053 		return (prsm);
4054 	}
4055 	return (NULL);
4056 }
4057 
4058 /*
4059  * Returns to the caller the number of microseconds that
4060  * the packet can be outstanding before we think we
4061  * should have had an ack returned.
4062  */
4063 static uint32_t
bbr_calc_thresh_rack(struct tcp_bbr * bbr,uint32_t srtt,uint32_t cts,struct bbr_sendmap * rsm)4064 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm)
4065 {
4066 	/*
4067 	 * lro is the flag we use to determine if we have seen reordering.
4068 	 * If it gets set we have seen reordering. The reorder logic either
4069 	 * works in one of two ways:
4070 	 *
4071 	 * If reorder-fade is configured, then we track the last time we saw
4072 	 * re-ordering occur. If we reach the point where enough time as
4073 	 * passed we no longer consider reordering has occuring.
4074 	 *
4075 	 * Or if reorder-face is 0, then once we see reordering we consider
4076 	 * the connection to alway be subject to reordering and just set lro
4077 	 * to 1.
4078 	 *
4079 	 * In the end if lro is non-zero we add the extra time for
4080 	 * reordering in.
4081 	 */
4082 	int32_t lro;
4083 	uint32_t thresh, t_rxtcur;
4084 
4085 	if (srtt == 0)
4086 		srtt = 1;
4087 	if (bbr->r_ctl.rc_reorder_ts) {
4088 		if (bbr->r_ctl.rc_reorder_fade) {
4089 			if (SEQ_GEQ(cts, bbr->r_ctl.rc_reorder_ts)) {
4090 				lro = cts - bbr->r_ctl.rc_reorder_ts;
4091 				if (lro == 0) {
4092 					/*
4093 					 * No time as passed since the last
4094 					 * reorder, mark it as reordering.
4095 					 */
4096 					lro = 1;
4097 				}
4098 			} else {
4099 				/* Negative time? */
4100 				lro = 0;
4101 			}
4102 			if (lro > bbr->r_ctl.rc_reorder_fade) {
4103 				/* Turn off reordering seen too */
4104 				bbr->r_ctl.rc_reorder_ts = 0;
4105 				lro = 0;
4106 			}
4107 		} else {
4108 			/* Reodering does not fade */
4109 			lro = 1;
4110 		}
4111 	} else {
4112 		lro = 0;
4113 	}
4114 	thresh = srtt + bbr->r_ctl.rc_pkt_delay;
4115 	if (lro) {
4116 		/* It must be set, if not you get 1/4 rtt */
4117 		if (bbr->r_ctl.rc_reorder_shift)
4118 			thresh += (srtt >> bbr->r_ctl.rc_reorder_shift);
4119 		else
4120 			thresh += (srtt >> 2);
4121 	} else {
4122 		thresh += 1000;
4123 	}
4124 	/* We don't let the rack timeout be above a RTO */
4125 	if ((bbr->rc_tp)->t_srtt == 0)
4126 		t_rxtcur = BBR_INITIAL_RTO;
4127 	else
4128 		t_rxtcur = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
4129 	if (thresh > t_rxtcur) {
4130 		thresh = t_rxtcur;
4131 	}
4132 	/* And we don't want it above the RTO max either */
4133 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4134 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4135 	}
4136 	bbr_log_thresh_choice(bbr, cts, thresh, lro, srtt, rsm, BBR_TO_FRM_RACK);
4137 	return (thresh);
4138 }
4139 
4140 /*
4141  * Return to the caller the amount of time in mico-seconds
4142  * that should be used for the TLP timer from the last
4143  * send time of this packet.
4144  */
4145 static uint32_t
bbr_calc_thresh_tlp(struct tcpcb * tp,struct tcp_bbr * bbr,struct bbr_sendmap * rsm,uint32_t srtt,uint32_t cts)4146 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
4147     struct bbr_sendmap *rsm, uint32_t srtt,
4148     uint32_t cts)
4149 {
4150 	uint32_t thresh, len, maxseg, t_rxtcur;
4151 	struct bbr_sendmap *prsm;
4152 
4153 	if (srtt == 0)
4154 		srtt = 1;
4155 	if (bbr->rc_tlp_threshold)
4156 		thresh = srtt + (srtt / bbr->rc_tlp_threshold);
4157 	else
4158 		thresh = (srtt * 2);
4159 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4160 	/* Get the previous sent packet, if any  */
4161 	len = rsm->r_end - rsm->r_start;
4162 
4163 	/* 2.1 behavior */
4164 	prsm = TAILQ_PREV(rsm, bbr_head, r_tnext);
4165 	if (prsm && (len <= maxseg)) {
4166 		/*
4167 		 * Two packets outstanding, thresh should be (2*srtt) +
4168 		 * possible inter-packet delay (if any).
4169 		 */
4170 		uint32_t inter_gap = 0;
4171 		int idx, nidx;
4172 
4173 		idx = rsm->r_rtr_cnt - 1;
4174 		nidx = prsm->r_rtr_cnt - 1;
4175 		if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
4176 			/* Yes it was sent later (or at the same time) */
4177 			inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
4178 		}
4179 		thresh += inter_gap;
4180 	} else if (len <= maxseg) {
4181 		/*
4182 		 * Possibly compensate for delayed-ack.
4183 		 */
4184 		uint32_t alt_thresh;
4185 
4186 		alt_thresh = srtt + (srtt / 2) + bbr_delayed_ack_time;
4187 		if (alt_thresh > thresh)
4188 			thresh = alt_thresh;
4189 	}
4190 	/* Not above the current  RTO */
4191 	if (tp->t_srtt == 0)
4192 		t_rxtcur = BBR_INITIAL_RTO;
4193 	else
4194 		t_rxtcur = TICKS_2_USEC(tp->t_rxtcur);
4195 
4196 	bbr_log_thresh_choice(bbr, cts, thresh, t_rxtcur, srtt, rsm, BBR_TO_FRM_TLP);
4197 	/* Not above an RTO */
4198 	if (thresh > t_rxtcur) {
4199 		thresh = t_rxtcur;
4200 	}
4201 	/* Not above a RTO max */
4202 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4203 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4204 	}
4205 	/* And now apply the user TLP min */
4206 	if (thresh < bbr_tlp_min) {
4207 		thresh = bbr_tlp_min;
4208 	}
4209 	return (thresh);
4210 }
4211 
4212 /*
4213  * Return one of three RTTs to use (in microseconds).
4214  */
4215 static __inline uint32_t
bbr_get_rtt(struct tcp_bbr * bbr,int32_t rtt_type)4216 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type)
4217 {
4218 	uint32_t f_rtt;
4219 	uint32_t srtt;
4220 
4221 	f_rtt = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
4222 	if (get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) {
4223 		/* We have no rtt at all */
4224 		if (bbr->rc_tp->t_srtt == 0)
4225 			f_rtt = BBR_INITIAL_RTO;
4226 		else
4227 			f_rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4228 		/*
4229 		 * Since we don't know how good the rtt is apply a
4230 		 * delayed-ack min
4231 		 */
4232 		if (f_rtt < bbr_delayed_ack_time) {
4233 			f_rtt = bbr_delayed_ack_time;
4234 		}
4235 	}
4236 	/* Take the filter version or last measured pkt-rtt */
4237 	if (rtt_type == BBR_RTT_PROP) {
4238 		srtt = f_rtt;
4239 	} else if (rtt_type == BBR_RTT_PKTRTT) {
4240 		if (bbr->r_ctl.rc_pkt_epoch_rtt) {
4241 			srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
4242 		} else {
4243 			/* No pkt rtt yet */
4244 			srtt = f_rtt;
4245 		}
4246 	} else if (rtt_type == BBR_RTT_RACK) {
4247 		srtt = bbr->r_ctl.rc_last_rtt;
4248 		/* We need to add in any internal delay for our timer */
4249 		if (bbr->rc_ack_was_delayed)
4250 			srtt += bbr->r_ctl.rc_ack_hdwr_delay;
4251 	} else if (rtt_type == BBR_SRTT) {
4252 		srtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4253 	} else {
4254 		/* TSNH */
4255 		srtt = f_rtt;
4256 #ifdef BBR_INVARIANTS
4257 		panic("Unknown rtt request type %d", rtt_type);
4258 #endif
4259 	}
4260 	return (srtt);
4261 }
4262 
4263 static int
bbr_is_lost(struct tcp_bbr * bbr,struct bbr_sendmap * rsm,uint32_t cts)4264 bbr_is_lost(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t cts)
4265 {
4266 	uint32_t thresh;
4267 
4268 	thresh = bbr_calc_thresh_rack(bbr, bbr_get_rtt(bbr, BBR_RTT_RACK),
4269 				      cts, rsm);
4270 	if ((cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)]) >= thresh) {
4271 		/* It is lost (past time) */
4272 		return (1);
4273 	}
4274 	return (0);
4275 }
4276 
4277 /*
4278  * Return a sendmap if we need to retransmit something.
4279  */
4280 static struct bbr_sendmap *
bbr_check_recovery_mode(struct tcpcb * tp,struct tcp_bbr * bbr,uint32_t cts)4281 bbr_check_recovery_mode(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4282 {
4283 	/*
4284 	 * Check to see that we don't need to fall into recovery. We will
4285 	 * need to do so if our oldest transmit is past the time we should
4286 	 * have had an ack.
4287 	 */
4288 
4289 	struct bbr_sendmap *rsm;
4290 	int32_t idx;
4291 
4292 	if (TAILQ_EMPTY(&bbr->r_ctl.rc_map)) {
4293 		/* Nothing outstanding that we know of */
4294 		return (NULL);
4295 	}
4296 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
4297 	if (rsm == NULL) {
4298 		/* Nothing in the transmit map */
4299 		return (NULL);
4300 	}
4301 	if (tp->t_flags & TF_SENTFIN) {
4302 		/* Fin restricted, don't find anything once a fin is sent */
4303 		return (NULL);
4304 	}
4305 	if (rsm->r_flags & BBR_ACKED) {
4306 		/*
4307 		 * Ok the first one is acked (this really should not happen
4308 		 * since we remove the from the tmap once they are acked)
4309 		 */
4310 		rsm = bbr_find_lowest_rsm(bbr);
4311 		if (rsm == NULL)
4312 			return (NULL);
4313 	}
4314 	idx = rsm->r_rtr_cnt - 1;
4315 	if (SEQ_LEQ(cts, rsm->r_tim_lastsent[idx])) {
4316 		/* Send timestamp is the same or less? can't be ready */
4317 		return (NULL);
4318 	}
4319 	/* Get our RTT time */
4320 	if (bbr_is_lost(bbr, rsm, cts) &&
4321 	    ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
4322 	     (rsm->r_flags & BBR_SACK_PASSED))) {
4323 		if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4324 			rsm->r_flags |= BBR_MARKED_LOST;
4325 			bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4326 			bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4327 		}
4328 		bbr_cong_signal(tp, NULL, CC_NDUPACK, rsm);
4329 #ifdef BBR_INVARIANTS
4330 		if ((rsm->r_end - rsm->r_start) == 0)
4331 			panic("tp:%p bbr:%p rsm:%p length is 0?", tp, bbr, rsm);
4332 #endif
4333 		return (rsm);
4334 	}
4335 	return (NULL);
4336 }
4337 
4338 /*
4339  * RACK Timer, here we simply do logging and house keeping.
4340  * the normal bbr_output_wtime() function will call the
4341  * appropriate thing to check if we need to do a RACK retransmit.
4342  * We return 1, saying don't proceed with bbr_output_wtime only
4343  * when all timers have been stopped (destroyed PCB?).
4344  */
4345 static int
bbr_timeout_rack(struct tcpcb * tp,struct tcp_bbr * bbr,uint32_t cts)4346 bbr_timeout_rack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4347 {
4348 	/*
4349 	 * This timer simply provides an internal trigger to send out data.
4350 	 * The check_recovery_mode call will see if there are needed
4351 	 * retransmissions, if so we will enter fast-recovery. The output
4352 	 * call may or may not do the same thing depending on sysctl
4353 	 * settings.
4354 	 */
4355 	uint32_t lost;
4356 
4357 	if (bbr->rc_all_timers_stopped) {
4358 		return (1);
4359 	}
4360 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4361 		/* Its not time yet */
4362 		return (0);
4363 	}
4364 	BBR_STAT_INC(bbr_to_tot);
4365 	lost = bbr->r_ctl.rc_lost;
4366 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4367 		bbr_set_state(tp, bbr, 0);
4368 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_RACK);
4369 	if (bbr->r_ctl.rc_resend == NULL) {
4370 		/* Lets do the check here */
4371 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
4372 	}
4373 	if (bbr_policer_call_from_rack_to)
4374 		bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4375 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
4376 	return (0);
4377 }
4378 
4379 static __inline void
bbr_clone_rsm(struct tcp_bbr * bbr,struct bbr_sendmap * nrsm,struct bbr_sendmap * rsm,uint32_t start)4380 bbr_clone_rsm(struct tcp_bbr *bbr, struct bbr_sendmap *nrsm, struct bbr_sendmap *rsm, uint32_t start)
4381 {
4382 	int idx;
4383 
4384 	nrsm->r_start = start;
4385 	nrsm->r_end = rsm->r_end;
4386 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4387 	nrsm-> r_rtt_not_allowed = rsm->r_rtt_not_allowed;
4388 	nrsm->r_flags = rsm->r_flags;
4389 	/* We don't transfer forward the SYN flag */
4390 	nrsm->r_flags &= ~BBR_HAS_SYN;
4391 	/* We move forward the FIN flag, not that this should happen */
4392 	rsm->r_flags &= ~BBR_HAS_FIN;
4393 	nrsm->r_dupack = rsm->r_dupack;
4394 	nrsm->r_rtr_bytes = 0;
4395 	nrsm->r_is_gain = rsm->r_is_gain;
4396 	nrsm->r_is_drain = rsm->r_is_drain;
4397 	nrsm->r_delivered = rsm->r_delivered;
4398 	nrsm->r_ts_valid = rsm->r_ts_valid;
4399 	nrsm->r_del_ack_ts = rsm->r_del_ack_ts;
4400 	nrsm->r_del_time = rsm->r_del_time;
4401 	nrsm->r_app_limited = rsm->r_app_limited;
4402 	nrsm->r_first_sent_time = rsm->r_first_sent_time;
4403 	nrsm->r_flight_at_send = rsm->r_flight_at_send;
4404 	/* We split a piece the lower section looses any just_ret flag. */
4405 	nrsm->r_bbr_state = rsm->r_bbr_state;
4406 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4407 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4408 	}
4409 	rsm->r_end = nrsm->r_start;
4410 	idx = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
4411 	idx /= 8;
4412 	/* Check if we got too small */
4413 	if ((rsm->r_is_smallmap == 0) &&
4414 	    ((rsm->r_end - rsm->r_start) <= idx)) {
4415 		bbr->r_ctl.rc_num_small_maps_alloced++;
4416 		rsm->r_is_smallmap = 1;
4417 	}
4418 	/* Check the new one as well */
4419 	if ((nrsm->r_end - nrsm->r_start) <= idx) {
4420 		bbr->r_ctl.rc_num_small_maps_alloced++;
4421 		nrsm->r_is_smallmap = 1;
4422 	}
4423 }
4424 
4425 static int
bbr_sack_mergable(struct bbr_sendmap * at,uint32_t start,uint32_t end)4426 bbr_sack_mergable(struct bbr_sendmap *at,
4427 		  uint32_t start, uint32_t end)
4428 {
4429 	/*
4430 	 * Given a sack block defined by
4431 	 * start and end, and a current position
4432 	 * at. Return 1 if either side of at
4433 	 * would show that the block is mergable
4434 	 * to that side. A block to be mergable
4435 	 * must have overlap with the start/end
4436 	 * and be in the SACK'd state.
4437 	 */
4438 	struct bbr_sendmap *l_rsm;
4439 	struct bbr_sendmap *r_rsm;
4440 
4441 	/* first get the either side blocks */
4442 	l_rsm = TAILQ_PREV(at, bbr_head, r_next);
4443 	r_rsm = TAILQ_NEXT(at, r_next);
4444 	if (l_rsm && (l_rsm->r_flags & BBR_ACKED)) {
4445 		/* Potentially mergeable */
4446 		if ((l_rsm->r_end == start) ||
4447 		    (SEQ_LT(start, l_rsm->r_end) &&
4448 		     SEQ_GT(end, l_rsm->r_end))) {
4449 			    /*
4450 			     * map blk   |------|
4451 			     * sack blk         |------|
4452 			     * <or>
4453 			     * map blk   |------|
4454 			     * sack blk      |------|
4455 			     */
4456 			    return (1);
4457 		    }
4458 	}
4459 	if (r_rsm && (r_rsm->r_flags & BBR_ACKED)) {
4460 		/* Potentially mergeable */
4461 		if ((r_rsm->r_start == end) ||
4462 		    (SEQ_LT(start, r_rsm->r_start) &&
4463 		     SEQ_GT(end, r_rsm->r_start))) {
4464 			/*
4465 			 * map blk          |---------|
4466 			 * sack blk    |----|
4467 			 * <or>
4468 			 * map blk          |---------|
4469 			 * sack blk    |-------|
4470 			 */
4471 			return (1);
4472 		}
4473 	}
4474 	return (0);
4475 }
4476 
4477 static struct bbr_sendmap *
bbr_merge_rsm(struct tcp_bbr * bbr,struct bbr_sendmap * l_rsm,struct bbr_sendmap * r_rsm)4478 bbr_merge_rsm(struct tcp_bbr *bbr,
4479 	      struct bbr_sendmap *l_rsm,
4480 	      struct bbr_sendmap *r_rsm)
4481 {
4482 	/*
4483 	 * We are merging two ack'd RSM's,
4484 	 * the l_rsm is on the left (lower seq
4485 	 * values) and the r_rsm is on the right
4486 	 * (higher seq value). The simplest way
4487 	 * to merge these is to move the right
4488 	 * one into the left. I don't think there
4489 	 * is any reason we need to try to find
4490 	 * the oldest (or last oldest retransmitted).
4491 	 */
4492 	l_rsm->r_end = r_rsm->r_end;
4493 	if (l_rsm->r_dupack < r_rsm->r_dupack)
4494 		l_rsm->r_dupack = r_rsm->r_dupack;
4495 	if (r_rsm->r_rtr_bytes)
4496 		l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
4497 	if (r_rsm->r_in_tmap) {
4498 		/* This really should not happen */
4499 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, r_rsm, r_tnext);
4500 	}
4501 	if (r_rsm->r_app_limited)
4502 		l_rsm->r_app_limited = r_rsm->r_app_limited;
4503 	/* Now the flags */
4504 	if (r_rsm->r_flags & BBR_HAS_FIN)
4505 		l_rsm->r_flags |= BBR_HAS_FIN;
4506 	if (r_rsm->r_flags & BBR_TLP)
4507 		l_rsm->r_flags |= BBR_TLP;
4508 	if (r_rsm->r_flags & BBR_RWND_COLLAPSED)
4509 		l_rsm->r_flags |= BBR_RWND_COLLAPSED;
4510 	if (r_rsm->r_flags & BBR_MARKED_LOST) {
4511 		/* This really should not happen */
4512 		bbr->r_ctl.rc_lost_bytes -= r_rsm->r_end - r_rsm->r_start;
4513 	}
4514 	TAILQ_REMOVE(&bbr->r_ctl.rc_map, r_rsm, r_next);
4515 	if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
4516 		/* Transfer the split limit to the map we free */
4517 		r_rsm->r_limit_type = l_rsm->r_limit_type;
4518 		l_rsm->r_limit_type = 0;
4519 	}
4520 	bbr_free(bbr, r_rsm);
4521 	return(l_rsm);
4522 }
4523 
4524 /*
4525  * TLP Timer, here we simply setup what segment we want to
4526  * have the TLP expire on, the normal bbr_output_wtime() will then
4527  * send it out.
4528  *
4529  * We return 1, saying don't proceed with bbr_output_wtime only
4530  * when all timers have been stopped (destroyed PCB?).
4531  */
4532 static int
bbr_timeout_tlp(struct tcpcb * tp,struct tcp_bbr * bbr,uint32_t cts)4533 bbr_timeout_tlp(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4534 {
4535 	/*
4536 	 * Tail Loss Probe.
4537 	 */
4538 	struct bbr_sendmap *rsm = NULL;
4539 	struct socket *so;
4540 	uint32_t amm;
4541 	uint32_t out, avail;
4542 	uint32_t maxseg;
4543 	int collapsed_win = 0;
4544 
4545 	if (bbr->rc_all_timers_stopped) {
4546 		return (1);
4547 	}
4548 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4549 		/* Its not time yet */
4550 		return (0);
4551 	}
4552 	if (ctf_progress_timeout_check(tp, true)) {
4553 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4554 		return (-ETIMEDOUT);	/* tcp_drop() */
4555 	}
4556 	/* Did we somehow get into persists? */
4557 	if (bbr->rc_in_persist) {
4558 		return (0);
4559 	}
4560 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4561 		bbr_set_state(tp, bbr, 0);
4562 	BBR_STAT_INC(bbr_tlp_tot);
4563 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4564 	/*
4565 	 * A TLP timer has expired. We have been idle for 2 rtts. So we now
4566 	 * need to figure out how to force a full MSS segment out.
4567 	 */
4568 	so = tptosocket(tp);
4569 	avail = sbavail(&so->so_snd);
4570 	out = ctf_outstanding(tp);
4571 	if (out > tp->snd_wnd) {
4572 		/* special case, we need a retransmission */
4573 		collapsed_win = 1;
4574 		goto need_retran;
4575 	}
4576 	if (avail > out) {
4577 		/* New data is available */
4578 		amm = avail - out;
4579 		if (amm > maxseg) {
4580 			amm = maxseg;
4581 		} else if ((amm < maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
4582 			/* not enough to fill a MTU and no-delay is off */
4583 			goto need_retran;
4584 		}
4585 		/* Set the send-new override */
4586 		if ((out + amm) <= tp->snd_wnd) {
4587 			bbr->rc_tlp_new_data = 1;
4588 		} else {
4589 			goto need_retran;
4590 		}
4591 		bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4592 		bbr->r_ctl.rc_last_tlp_seq = tp->snd_max;
4593 		bbr->r_ctl.rc_tlp_send = NULL;
4594 		/* cap any slots */
4595 		BBR_STAT_INC(bbr_tlp_newdata);
4596 		goto send;
4597 	}
4598 need_retran:
4599 	/*
4600 	 * Ok we need to arrange the last un-acked segment to be re-sent, or
4601 	 * optionally the first un-acked segment.
4602 	 */
4603 	if (collapsed_win == 0) {
4604 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
4605 		if (rsm && (rsm->r_flags & (BBR_ACKED | BBR_HAS_FIN))) {
4606 			rsm = bbr_find_high_nonack(bbr, rsm);
4607 		}
4608 		if (rsm == NULL) {
4609 			goto restore;
4610 		}
4611 	} else {
4612 		/*
4613 		 * We must find the last segment
4614 		 * that was acceptable by the client.
4615 		 */
4616 		TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4617 			if ((rsm->r_flags & BBR_RWND_COLLAPSED) == 0) {
4618 				/* Found one */
4619 				break;
4620 			}
4621 		}
4622 		if (rsm == NULL) {
4623 			/* None? if so send the first */
4624 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4625 			if (rsm == NULL)
4626 				goto restore;
4627 		}
4628 	}
4629 	if ((rsm->r_end - rsm->r_start) > maxseg) {
4630 		/*
4631 		 * We need to split this the last segment in two.
4632 		 */
4633 		struct bbr_sendmap *nrsm;
4634 
4635 		nrsm = bbr_alloc_full_limit(bbr);
4636 		if (nrsm == NULL) {
4637 			/*
4638 			 * We can't get memory to split, we can either just
4639 			 * not split it. Or retransmit the whole piece, lets
4640 			 * do the large send (BTLP :-) ).
4641 			 */
4642 			goto go_for_it;
4643 		}
4644 		bbr_clone_rsm(bbr, nrsm, rsm, (rsm->r_end - maxseg));
4645 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
4646 		if (rsm->r_in_tmap) {
4647 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4648 			nrsm->r_in_tmap = 1;
4649 		}
4650 		rsm->r_flags &= (~BBR_HAS_FIN);
4651 		rsm = nrsm;
4652 	}
4653 go_for_it:
4654 	bbr->r_ctl.rc_tlp_send = rsm;
4655 	bbr->rc_tlp_rtx_out = 1;
4656 	if (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) {
4657 		bbr->r_ctl.rc_tlp_seg_send_cnt++;
4658 		tp->t_rxtshift++;
4659 	} else {
4660 		bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
4661 		bbr->r_ctl.rc_tlp_seg_send_cnt = 1;
4662 	}
4663 send:
4664 	if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
4665 		/*
4666 		 * Can't [re]/transmit a segment we have retransmitted the
4667 		 * max times. We need the retransmit timer to take over.
4668 		 */
4669 restore:
4670 		bbr->rc_tlp_new_data = 0;
4671 		bbr->r_ctl.rc_tlp_send = NULL;
4672 		if (rsm)
4673 			rsm->r_flags &= ~BBR_TLP;
4674 		BBR_STAT_INC(bbr_tlp_retran_fail);
4675 		return (0);
4676 	} else if (rsm) {
4677 		rsm->r_flags |= BBR_TLP;
4678 	}
4679 	if (rsm && (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) &&
4680 	    (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend)) {
4681 		/*
4682 		 * We have retransmitted to many times for TLP. Switch to
4683 		 * the regular RTO timer
4684 		 */
4685 		goto restore;
4686 	}
4687 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TLP);
4688 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
4689 	return (0);
4690 }
4691 
4692 /*
4693  * Delayed ack Timer, here we simply need to setup the
4694  * ACK_NOW flag and remove the DELACK flag. From there
4695  * the output routine will send the ack out.
4696  *
4697  * We only return 1, saying don't proceed, if all timers
4698  * are stopped (destroyed PCB?).
4699  */
4700 static int
bbr_timeout_delack(struct tcpcb * tp,struct tcp_bbr * bbr,uint32_t cts)4701 bbr_timeout_delack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4702 {
4703 	if (bbr->rc_all_timers_stopped) {
4704 		return (1);
4705 	}
4706 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_DELACK);
4707 	tp->t_flags &= ~TF_DELACK;
4708 	tp->t_flags |= TF_ACKNOW;
4709 	KMOD_TCPSTAT_INC(tcps_delack);
4710 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
4711 	return (0);
4712 }
4713 
4714 /*
4715  * Here we send a KEEP-ALIVE like probe to the
4716  * peer, we do not send data.
4717  *
4718  * We only return 1, saying don't proceed, if all timers
4719  * are stopped (destroyed PCB?).
4720  */
4721 static int
bbr_timeout_persist(struct tcpcb * tp,struct tcp_bbr * bbr,uint32_t cts)4722 bbr_timeout_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4723 {
4724 	struct tcptemp *t_template;
4725 	int32_t retval = 1;
4726 
4727 	if (bbr->rc_all_timers_stopped) {
4728 		return (1);
4729 	}
4730 	if (bbr->rc_in_persist == 0)
4731 		return (0);
4732 
4733 	/*
4734 	 * Persistence timer into zero window. Force a byte to be output, if
4735 	 * possible.
4736 	 */
4737 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_PERSIST);
4738 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
4739 	KMOD_TCPSTAT_INC(tcps_persisttimeo);
4740 	/*
4741 	 * Have we exceeded the user specified progress time?
4742 	 */
4743 	if (ctf_progress_timeout_check(tp, true)) {
4744 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4745 		return (-ETIMEDOUT);	/* tcp_drop() */
4746 	}
4747 	/*
4748 	 * Hack: if the peer is dead/unreachable, we do not time out if the
4749 	 * window is closed.  After a full backoff, drop the connection if
4750 	 * the idle time (no responses to probes) reaches the maximum
4751 	 * backoff that we would use if retransmitting.
4752 	 */
4753 	if (tp->t_rxtshift >= V_tcp_retries &&
4754 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
4755 	    ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
4756 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4757 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4758 		return (-ETIMEDOUT);	/* tcp_drop() */
4759 	}
4760 	if ((sbavail(&bbr->rc_inp->inp_socket->so_snd) == 0) &&
4761 	    tp->snd_una == tp->snd_max) {
4762 		bbr_exit_persist(tp, bbr, cts, __LINE__);
4763 		retval = 0;
4764 		goto out;
4765 	}
4766 	/*
4767 	 * If the user has closed the socket then drop a persisting
4768 	 * connection after a much reduced timeout.
4769 	 */
4770 	if (tp->t_state > TCPS_CLOSE_WAIT &&
4771 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
4772 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4773 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4774 		return (-ETIMEDOUT);	/* tcp_drop() */
4775 	}
4776 	t_template = tcpip_maketemplate(bbr->rc_inp);
4777 	if (t_template) {
4778 		tcp_respond(tp, t_template->tt_ipgen,
4779 			    &t_template->tt_t, (struct mbuf *)NULL,
4780 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4781 		/* This sends an ack */
4782 		if (tp->t_flags & TF_DELACK)
4783 			tp->t_flags &= ~TF_DELACK;
4784 		free(t_template, M_TEMP);
4785 	}
4786 	if (tp->t_rxtshift < V_tcp_retries)
4787 		tp->t_rxtshift++;
4788 	bbr_start_hpts_timer(bbr, tp, cts, 3, 0, 0);
4789 out:
4790 	return (retval);
4791 }
4792 
4793 /*
4794  * If a keepalive goes off, we had no other timers
4795  * happening. We always return 1 here since this
4796  * routine either drops the connection or sends
4797  * out a segment with respond.
4798  */
4799 static int
bbr_timeout_keepalive(struct tcpcb * tp,struct tcp_bbr * bbr,uint32_t cts)4800 bbr_timeout_keepalive(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4801 {
4802 	struct tcptemp *t_template;
4803 	struct inpcb *inp = tptoinpcb(tp);
4804 
4805 	if (bbr->rc_all_timers_stopped) {
4806 		return (1);
4807 	}
4808 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
4809 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_KEEP);
4810 	/*
4811 	 * Keep-alive timer went off; send something or drop connection if
4812 	 * idle for too long.
4813 	 */
4814 	KMOD_TCPSTAT_INC(tcps_keeptimeo);
4815 	if (tp->t_state < TCPS_ESTABLISHED)
4816 		goto dropit;
4817 	if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
4818 	    tp->t_state <= TCPS_CLOSING) {
4819 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
4820 			goto dropit;
4821 		/*
4822 		 * Send a packet designed to force a response if the peer is
4823 		 * up and reachable: either an ACK if the connection is
4824 		 * still alive, or an RST if the peer has closed the
4825 		 * connection due to timeout or reboot. Using sequence
4826 		 * number tp->snd_una-1 causes the transmitted zero-length
4827 		 * segment to lie outside the receive window; by the
4828 		 * protocol spec, this requires the correspondent TCP to
4829 		 * respond.
4830 		 */
4831 		KMOD_TCPSTAT_INC(tcps_keepprobe);
4832 		t_template = tcpip_maketemplate(inp);
4833 		if (t_template) {
4834 			tcp_respond(tp, t_template->tt_ipgen,
4835 			    &t_template->tt_t, (struct mbuf *)NULL,
4836 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4837 			free(t_template, M_TEMP);
4838 		}
4839 	}
4840 	bbr_start_hpts_timer(bbr, tp, cts, 4, 0, 0);
4841 	return (1);
4842 dropit:
4843 	KMOD_TCPSTAT_INC(tcps_keepdrops);
4844 	tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
4845 	return (-ETIMEDOUT);	/* tcp_drop() */
4846 }
4847 
4848 /*
4849  * Retransmit helper function, clear up all the ack
4850  * flags and take care of important book keeping.
4851  */
4852 static void
bbr_remxt_tmr(struct tcpcb * tp)4853 bbr_remxt_tmr(struct tcpcb *tp)
4854 {
4855 	/*
4856 	 * The retransmit timer went off, all sack'd blocks must be
4857 	 * un-acked.
4858 	 */
4859 	struct bbr_sendmap *rsm, *trsm = NULL;
4860 	struct tcp_bbr *bbr;
4861 	uint32_t cts, lost;
4862 
4863 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4864 	cts = tcp_get_usecs(&bbr->rc_tv);
4865 	lost = bbr->r_ctl.rc_lost;
4866 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4867 		bbr_set_state(tp, bbr, 0);
4868 
4869 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
4870 		if (rsm->r_flags & BBR_ACKED) {
4871 			uint32_t old_flags;
4872 
4873 			rsm->r_dupack = 0;
4874 			if (rsm->r_in_tmap == 0) {
4875 				/* We must re-add it back to the tlist */
4876 				if (trsm == NULL) {
4877 					TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
4878 				} else {
4879 					TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, trsm, rsm, r_tnext);
4880 				}
4881 				rsm->r_in_tmap = 1;
4882 			}
4883 			old_flags = rsm->r_flags;
4884 			rsm->r_flags |= BBR_RXT_CLEARED;
4885 			rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS);
4886 			bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
4887 		} else {
4888 			if ((tp->t_state < TCPS_ESTABLISHED) &&
4889 			    (rsm->r_start == tp->snd_una)) {
4890 				/*
4891 				 * Special case for TCP FO. Where
4892 				 * we sent more data beyond the snd_max.
4893 				 * We don't mark that as lost and stop here.
4894 				 */
4895 				break;
4896 			}
4897 			if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4898 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4899 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4900 			}
4901 			if (bbr_marks_rxt_sack_passed) {
4902 				/*
4903 				 * With this option, we will rack out
4904 				 * in 1ms increments the rest of the packets.
4905 				 */
4906 				rsm->r_flags |= BBR_SACK_PASSED | BBR_MARKED_LOST;
4907 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4908 			} else {
4909 				/*
4910 				 * With this option we only mark them lost
4911 				 * and remove all sack'd markings. We will run
4912 				 * another RXT or a TLP. This will cause
4913 				 * us to eventually send more based on what
4914 				 * ack's come in.
4915 				 */
4916 				rsm->r_flags |= BBR_MARKED_LOST;
4917 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4918 				rsm->r_flags &= ~BBR_SACK_PASSED;
4919 			}
4920 		}
4921 		trsm = rsm;
4922 	}
4923 	bbr->r_ctl.rc_resend = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4924 	/* Clear the count (we just un-acked them) */
4925 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TMR);
4926 	bbr->rc_tlp_new_data = 0;
4927 	bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4928 	/* zap the behindness on a rxt */
4929 	bbr->r_ctl.rc_hptsi_agg_delay = 0;
4930 	bbr->r_agg_early_set = 0;
4931 	bbr->r_ctl.rc_agg_early = 0;
4932 	bbr->rc_tlp_rtx_out = 0;
4933 	bbr->r_ctl.rc_sacked = 0;
4934 	bbr->r_ctl.rc_sacklast = NULL;
4935 	bbr->r_timer_override = 1;
4936 	bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4937 }
4938 
4939 /*
4940  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
4941  * we will setup to retransmit the lowest seq number outstanding.
4942  */
4943 static int
bbr_timeout_rxt(struct tcpcb * tp,struct tcp_bbr * bbr,uint32_t cts)4944 bbr_timeout_rxt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4945 {
4946 	struct inpcb *inp = tptoinpcb(tp);
4947 	int32_t rexmt;
4948 	int32_t retval = 0;
4949 	bool isipv6;
4950 
4951 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
4952 	if (bbr->rc_all_timers_stopped) {
4953 		return (1);
4954 	}
4955 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
4956 	    (tp->snd_una == tp->snd_max)) {
4957 		/* Nothing outstanding .. nothing to do */
4958 		return (0);
4959 	}
4960 	/*
4961 	 * Retransmission timer went off.  Message has not been acked within
4962 	 * retransmit interval.  Back off to a longer retransmit interval
4963 	 * and retransmit one segment.
4964 	 */
4965 	if (ctf_progress_timeout_check(tp, true)) {
4966 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4967 		return (-ETIMEDOUT);	/* tcp_drop() */
4968 	}
4969 	bbr_remxt_tmr(tp);
4970 	if ((bbr->r_ctl.rc_resend == NULL) ||
4971 	    ((bbr->r_ctl.rc_resend->r_flags & BBR_RWND_COLLAPSED) == 0)) {
4972 		/*
4973 		 * If the rwnd collapsed on
4974 		 * the one we are retransmitting
4975 		 * it does not count against the
4976 		 * rxt count.
4977 		 */
4978 		tp->t_rxtshift++;
4979 	}
4980 	if (tp->t_rxtshift > V_tcp_retries) {
4981 		tp->t_rxtshift = V_tcp_retries;
4982 		KMOD_TCPSTAT_INC(tcps_timeoutdrop);
4983 		tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
4984 		/* XXXGL: previously t_softerror was casted to uint16_t */
4985 		MPASS(tp->t_softerror >= 0);
4986 		retval = tp->t_softerror ? -tp->t_softerror : -ETIMEDOUT;
4987 		return (retval);	/* tcp_drop() */
4988 	}
4989 	if (tp->t_state == TCPS_SYN_SENT) {
4990 		/*
4991 		 * If the SYN was retransmitted, indicate CWND to be limited
4992 		 * to 1 segment in cc_conn_init().
4993 		 */
4994 		tp->snd_cwnd = 1;
4995 	} else if (tp->t_rxtshift == 1) {
4996 		/*
4997 		 * first retransmit; record ssthresh and cwnd so they can be
4998 		 * recovered if this turns out to be a "bad" retransmit. A
4999 		 * retransmit is considered "bad" if an ACK for this segment
5000 		 * is received within RTT/2 interval; the assumption here is
5001 		 * that the ACK was already in flight.  See "On Estimating
5002 		 * End-to-End Network Path Properties" by Allman and Paxson
5003 		 * for more details.
5004 		 */
5005 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5006 		if (!IN_RECOVERY(tp->t_flags)) {
5007 			tp->snd_cwnd_prev = tp->snd_cwnd;
5008 			tp->snd_ssthresh_prev = tp->snd_ssthresh;
5009 			tp->snd_recover_prev = tp->snd_recover;
5010 			tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
5011 			tp->t_flags |= TF_PREVVALID;
5012 		} else {
5013 			tp->t_flags &= ~TF_PREVVALID;
5014 		}
5015 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5016 	} else {
5017 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5018 		tp->t_flags &= ~TF_PREVVALID;
5019 	}
5020 	KMOD_TCPSTAT_INC(tcps_rexmttimeo);
5021 	if ((tp->t_state == TCPS_SYN_SENT) ||
5022 	    (tp->t_state == TCPS_SYN_RECEIVED))
5023 		rexmt = USEC_2_TICKS(BBR_INITIAL_RTO) * tcp_backoff[tp->t_rxtshift];
5024 	else
5025 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
5026 	TCPT_RANGESET(tp->t_rxtcur, rexmt,
5027 	    MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms),
5028 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
5029 	/*
5030 	 * We enter the path for PLMTUD if connection is established or, if
5031 	 * connection is FIN_WAIT_1 status, reason for the last is that if
5032 	 * amount of data we send is very small, we could send it in couple
5033 	 * of packets and process straight to FIN. In that case we won't
5034 	 * catch ESTABLISHED state.
5035 	 */
5036 #ifdef INET6
5037 	isipv6 = (inp->inp_vflag & INP_IPV6) ? true : false;
5038 #else
5039 	isipv6 = false;
5040 #endif
5041 	if (((V_tcp_pmtud_blackhole_detect == 1) ||
5042 	    (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
5043 	    (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
5044 	    ((tp->t_state == TCPS_ESTABLISHED) ||
5045 	    (tp->t_state == TCPS_FIN_WAIT_1))) {
5046 		/*
5047 		 * Idea here is that at each stage of mtu probe (usually,
5048 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
5049 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
5050 		 * should take care of that.
5051 		 */
5052 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
5053 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
5054 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
5055 		    tp->t_rxtshift % 2 == 0)) {
5056 			/*
5057 			 * Enter Path MTU Black-hole Detection mechanism: -
5058 			 * Disable Path MTU Discovery (IP "DF" bit). -
5059 			 * Reduce MTU to lower value than what we negotiated
5060 			 * with peer.
5061 			 */
5062 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
5063 				/*
5064 				 * Record that we may have found a black
5065 				 * hole.
5066 				 */
5067 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
5068 				/* Keep track of previous MSS. */
5069 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
5070 			}
5071 			/*
5072 			 * Reduce the MSS to blackhole value or to the
5073 			 * default in an attempt to retransmit.
5074 			 */
5075 #ifdef INET6
5076 			isipv6 = bbr->r_is_v6;
5077 			if (isipv6 &&
5078 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
5079 				/* Use the sysctl tuneable blackhole MSS. */
5080 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
5081 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5082 			} else if (isipv6) {
5083 				/* Use the default MSS. */
5084 				tp->t_maxseg = V_tcp_v6mssdflt;
5085 				/*
5086 				 * Disable Path MTU Discovery when we switch
5087 				 * to minmss.
5088 				 */
5089 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5090 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5091 			}
5092 #endif
5093 #if defined(INET6) && defined(INET)
5094 			else
5095 #endif
5096 #ifdef INET
5097 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
5098 				/* Use the sysctl tuneable blackhole MSS. */
5099 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
5100 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5101 			} else {
5102 				/* Use the default MSS. */
5103 				tp->t_maxseg = V_tcp_mssdflt;
5104 				/*
5105 				 * Disable Path MTU Discovery when we switch
5106 				 * to minmss.
5107 				 */
5108 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5109 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5110 			}
5111 #endif
5112 		} else {
5113 			/*
5114 			 * If further retransmissions are still unsuccessful
5115 			 * with a lowered MTU, maybe this isn't a blackhole
5116 			 * and we restore the previous MSS and blackhole
5117 			 * detection flags. The limit '6' is determined by
5118 			 * giving each probe stage (1448, 1188, 524) 2
5119 			 * chances to recover.
5120 			 */
5121 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
5122 			    (tp->t_rxtshift >= 6)) {
5123 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
5124 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
5125 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
5126 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
5127 			}
5128 		}
5129 	}
5130 	/*
5131 	 * Disable RFC1323 and SACK if we haven't got any response to our
5132 	 * third SYN to work-around some broken terminal servers (most of
5133 	 * which have hopefully been retired) that have bad VJ header
5134 	 * compression code which trashes TCP segments containing
5135 	 * unknown-to-them TCP options.
5136 	 */
5137 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
5138 	    (tp->t_rxtshift == 3))
5139 		tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
5140 	/*
5141 	 * If we backed off this far, our srtt estimate is probably bogus.
5142 	 * Clobber it so we'll take the next rtt measurement as our srtt;
5143 	 * move the current srtt into rttvar to keep the current retransmit
5144 	 * times until then.
5145 	 */
5146 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
5147 #ifdef INET6
5148 		if (bbr->r_is_v6)
5149 			in6_losing(inp);
5150 		else
5151 #endif
5152 			in_losing(inp);
5153 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
5154 		tp->t_srtt = 0;
5155 	}
5156 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
5157 	tp->snd_recover = tp->snd_max;
5158 	tp->t_flags |= TF_ACKNOW;
5159 	tp->t_rtttime = 0;
5160 
5161 	return (retval);
5162 }
5163 
5164 static int
bbr_process_timers(struct tcpcb * tp,struct tcp_bbr * bbr,uint32_t cts,uint8_t hpts_calling)5165 bbr_process_timers(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, uint8_t hpts_calling)
5166 {
5167 	int32_t ret = 0;
5168 	int32_t timers = (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
5169 
5170 	if (timers == 0) {
5171 		return (0);
5172 	}
5173 	if (tp->t_state == TCPS_LISTEN) {
5174 		/* no timers on listen sockets */
5175 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
5176 			return (0);
5177 		return (1);
5178 	}
5179 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
5180 		uint32_t left;
5181 
5182 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
5183 			ret = -1;
5184 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5185 			return (0);
5186 		}
5187 		if (hpts_calling == 0) {
5188 			ret = -2;
5189 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5190 			return (0);
5191 		}
5192 		/*
5193 		 * Ok our timer went off early and we are not paced false
5194 		 * alarm, go back to sleep.
5195 		 */
5196 		left = bbr->r_ctl.rc_timer_exp - cts;
5197 		ret = -3;
5198 		bbr_log_to_processing(bbr, cts, ret, left, hpts_calling);
5199 		tcp_hpts_insert(tp, HPTS_USEC_TO_SLOTS(left));
5200 		return (1);
5201 	}
5202 	bbr->rc_tmr_stopped = 0;
5203 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
5204 	if (timers & PACE_TMR_DELACK) {
5205 		ret = bbr_timeout_delack(tp, bbr, cts);
5206 	} else if (timers & PACE_TMR_PERSIT) {
5207 		ret = bbr_timeout_persist(tp, bbr, cts);
5208 	} else if (timers & PACE_TMR_RACK) {
5209 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5210 		ret = bbr_timeout_rack(tp, bbr, cts);
5211 	} else if (timers & PACE_TMR_TLP) {
5212 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5213 		ret = bbr_timeout_tlp(tp, bbr, cts);
5214 	} else if (timers & PACE_TMR_RXT) {
5215 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5216 		ret = bbr_timeout_rxt(tp, bbr, cts);
5217 	} else if (timers & PACE_TMR_KEEP) {
5218 		ret = bbr_timeout_keepalive(tp, bbr, cts);
5219 	}
5220 	bbr_log_to_processing(bbr, cts, ret, timers, hpts_calling);
5221 	return (ret);
5222 }
5223 
5224 static void
bbr_timer_cancel(struct tcp_bbr * bbr,int32_t line,uint32_t cts)5225 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts)
5226 {
5227 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
5228 		uint8_t hpts_removed = 0;
5229 
5230 		if (tcp_in_hpts(bbr->rc_tp) &&
5231 		    (bbr->rc_timer_first == 1)) {
5232 			/*
5233 			 * If we are canceling timer's when we have the
5234 			 * timer ahead of the output being paced. We also
5235 			 * must remove ourselves from the hpts.
5236 			 */
5237 			hpts_removed = 1;
5238 			tcp_hpts_remove(bbr->rc_tp);
5239 			if (bbr->r_ctl.rc_last_delay_val) {
5240 				/* Update the last hptsi delay too */
5241 				uint32_t time_since_send;
5242 
5243 				if (TSTMP_GT(cts, bbr->rc_pacer_started))
5244 					time_since_send = cts - bbr->rc_pacer_started;
5245 				else
5246 					time_since_send = 0;
5247 				if (bbr->r_ctl.rc_last_delay_val > time_since_send) {
5248 					/* Cut down our slot time */
5249 					bbr->r_ctl.rc_last_delay_val -= time_since_send;
5250 				} else {
5251 					bbr->r_ctl.rc_last_delay_val = 0;
5252 				}
5253 				bbr->rc_pacer_started = cts;
5254 			}
5255 		}
5256 		bbr->rc_timer_first = 0;
5257 		bbr_log_to_cancel(bbr, line, cts, hpts_removed);
5258 		bbr->rc_tmr_stopped = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
5259 		bbr->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
5260 	}
5261 }
5262 
5263 static int
bbr_stopall(struct tcpcb * tp)5264 bbr_stopall(struct tcpcb *tp)
5265 {
5266 	struct tcp_bbr *bbr;
5267 
5268 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
5269 	bbr->rc_all_timers_stopped = 1;
5270 
5271 	tcp_hpts_remove(tp);
5272 
5273 	return (0);
5274 }
5275 
5276 static uint32_t
bbr_get_earliest_send_outstanding(struct tcp_bbr * bbr,struct bbr_sendmap * u_rsm,uint32_t cts)5277 bbr_get_earliest_send_outstanding(struct tcp_bbr *bbr, struct bbr_sendmap *u_rsm, uint32_t cts)
5278 {
5279 	struct bbr_sendmap *rsm;
5280 
5281 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
5282 	if ((rsm == NULL) || (u_rsm == rsm))
5283 		return (cts);
5284 	return(rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
5285 }
5286 
5287 static void
bbr_update_rsm(struct tcpcb * tp,struct tcp_bbr * bbr,struct bbr_sendmap * rsm,uint32_t cts,uint32_t pacing_time)5288 bbr_update_rsm(struct tcpcb *tp, struct tcp_bbr *bbr,
5289      struct bbr_sendmap *rsm, uint32_t cts, uint32_t pacing_time)
5290 {
5291 	int32_t idx;
5292 
5293 	rsm->r_rtr_cnt++;
5294 	rsm->r_dupack = 0;
5295 	if (rsm->r_rtr_cnt > BBR_NUM_OF_RETRANS) {
5296 		rsm->r_rtr_cnt = BBR_NUM_OF_RETRANS;
5297 		rsm->r_flags |= BBR_OVERMAX;
5298 	}
5299 	if (rsm->r_flags & BBR_RWND_COLLAPSED) {
5300 		/* Take off the collapsed flag at rxt */
5301 		rsm->r_flags &= ~BBR_RWND_COLLAPSED;
5302 	}
5303 	if (rsm->r_flags & BBR_MARKED_LOST) {
5304 		/* We have retransmitted, its no longer lost */
5305 		rsm->r_flags &= ~BBR_MARKED_LOST;
5306 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
5307 	}
5308 	if (rsm->r_flags & BBR_RXT_CLEARED) {
5309 		/*
5310 		 * We hit a RXT timer on it and
5311 		 * we cleared the "acked" flag.
5312 		 * We now have it going back into
5313 		 * flight, we can remove the cleared
5314 		 * flag and possibly do accounting on
5315 		 * this piece.
5316 		 */
5317 		rsm->r_flags &= ~BBR_RXT_CLEARED;
5318 	}
5319 	if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & BBR_TLP) == 0)) {
5320 		bbr->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
5321 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
5322 	}
5323 	idx = rsm->r_rtr_cnt - 1;
5324 	rsm->r_tim_lastsent[idx] = cts;
5325 	rsm->r_pacing_delay = pacing_time;
5326 	rsm->r_delivered = bbr->r_ctl.rc_delivered;
5327 	rsm->r_ts_valid = bbr->rc_ts_valid;
5328 	if (bbr->rc_ts_valid)
5329 		rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5330 	if (bbr->r_ctl.r_app_limited_until)
5331 		rsm->r_app_limited = 1;
5332 	else
5333 		rsm->r_app_limited = 0;
5334 	if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5335 		rsm->r_bbr_state = bbr_state_val(bbr);
5336 	else
5337 		rsm->r_bbr_state = 8;
5338 	if (rsm->r_flags & BBR_ACKED) {
5339 		/* Problably MTU discovery messing with us */
5340 		uint32_t old_flags;
5341 
5342 		old_flags = rsm->r_flags;
5343 		rsm->r_flags &= ~BBR_ACKED;
5344 		bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
5345 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
5346 		if (bbr->r_ctl.rc_sacked == 0)
5347 			bbr->r_ctl.rc_sacklast = NULL;
5348 	}
5349 	if (rsm->r_in_tmap) {
5350 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5351 	}
5352 	TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5353 	rsm->r_in_tmap = 1;
5354 	if (rsm->r_flags & BBR_SACK_PASSED) {
5355 		/* We have retransmitted due to the SACK pass */
5356 		rsm->r_flags &= ~BBR_SACK_PASSED;
5357 		rsm->r_flags |= BBR_WAS_SACKPASS;
5358 	}
5359 	rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5360 	rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5361 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5362 	bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
5363 	if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5364 		rsm->r_is_gain = 1;
5365 		rsm->r_is_drain = 0;
5366 	} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5367 		rsm->r_is_drain = 1;
5368 		rsm->r_is_gain = 0;
5369 	} else {
5370 		rsm->r_is_drain = 0;
5371 		rsm->r_is_gain = 0;
5372 	}
5373 	rsm->r_del_time = bbr->r_ctl.rc_del_time; /* TEMP GOOGLE CODE */
5374 }
5375 
5376 /*
5377  * Returns 0, or the sequence where we stopped
5378  * updating. We also update the lenp to be the amount
5379  * of data left.
5380  */
5381 
5382 static uint32_t
bbr_update_entry(struct tcpcb * tp,struct tcp_bbr * bbr,struct bbr_sendmap * rsm,uint32_t cts,int32_t * lenp,uint32_t pacing_time)5383 bbr_update_entry(struct tcpcb *tp, struct tcp_bbr *bbr,
5384     struct bbr_sendmap *rsm, uint32_t cts, int32_t *lenp, uint32_t pacing_time)
5385 {
5386 	/*
5387 	 * We (re-)transmitted starting at rsm->r_start for some length
5388 	 * (possibly less than r_end.
5389 	 */
5390 	struct bbr_sendmap *nrsm;
5391 	uint32_t c_end;
5392 	int32_t len;
5393 
5394 	len = *lenp;
5395 	c_end = rsm->r_start + len;
5396 	if (SEQ_GEQ(c_end, rsm->r_end)) {
5397 		/*
5398 		 * We retransmitted the whole piece or more than the whole
5399 		 * slopping into the next rsm.
5400 		 */
5401 		bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5402 		if (c_end == rsm->r_end) {
5403 			*lenp = 0;
5404 			return (0);
5405 		} else {
5406 			int32_t act_len;
5407 
5408 			/* Hangs over the end return whats left */
5409 			act_len = rsm->r_end - rsm->r_start;
5410 			*lenp = (len - act_len);
5411 			return (rsm->r_end);
5412 		}
5413 		/* We don't get out of this block. */
5414 	}
5415 	/*
5416 	 * Here we retransmitted less than the whole thing which means we
5417 	 * have to split this into what was transmitted and what was not.
5418 	 */
5419 	nrsm = bbr_alloc_full_limit(bbr);
5420 	if (nrsm == NULL) {
5421 		*lenp = 0;
5422 		return (0);
5423 	}
5424 	/*
5425 	 * So here we are going to take the original rsm and make it what we
5426 	 * retransmitted. nrsm will be the tail portion we did not
5427 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
5428 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
5429 	 * 1, 6 and the new piece will be 6, 11.
5430 	 */
5431 	bbr_clone_rsm(bbr, nrsm, rsm, c_end);
5432 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
5433 	nrsm->r_dupack = 0;
5434 	if (rsm->r_in_tmap) {
5435 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
5436 		nrsm->r_in_tmap = 1;
5437 	}
5438 	rsm->r_flags &= (~BBR_HAS_FIN);
5439 	bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5440 	*lenp = 0;
5441 	return (0);
5442 }
5443 
5444 static uint64_t
bbr_get_hardware_rate(struct tcp_bbr * bbr)5445 bbr_get_hardware_rate(struct tcp_bbr *bbr)
5446 {
5447 	uint64_t bw;
5448 
5449 	bw = bbr_get_bw(bbr);
5450 	bw *= (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN];
5451 	bw /= (uint64_t)BBR_UNIT;
5452 	return(bw);
5453 }
5454 
5455 static void
bbr_setup_less_of_rate(struct tcp_bbr * bbr,uint32_t cts,uint64_t act_rate,uint64_t rate_wanted)5456 bbr_setup_less_of_rate(struct tcp_bbr *bbr, uint32_t cts,
5457 		       uint64_t act_rate, uint64_t rate_wanted)
5458 {
5459 	/*
5460 	 * We could not get a full gains worth
5461 	 * of rate.
5462 	 */
5463 	if (get_filter_value(&bbr->r_ctl.rc_delrate) >= act_rate) {
5464 		/* we can't even get the real rate */
5465 		uint64_t red;
5466 
5467 		bbr->skip_gain = 1;
5468 		bbr->gain_is_limited = 0;
5469 		red = get_filter_value(&bbr->r_ctl.rc_delrate) - act_rate;
5470 		if (red)
5471 			filter_reduce_by(&bbr->r_ctl.rc_delrate, red, cts);
5472 	} else {
5473 		/* We can use a lower gain */
5474 		bbr->skip_gain = 0;
5475 		bbr->gain_is_limited = 1;
5476 	}
5477 }
5478 
5479 static void
bbr_update_hardware_pacing_rate(struct tcp_bbr * bbr,uint32_t cts)5480 bbr_update_hardware_pacing_rate(struct tcp_bbr *bbr, uint32_t cts)
5481 {
5482 	const struct tcp_hwrate_limit_table *nrte;
5483 	int error, rate = -1;
5484 
5485 	if (bbr->r_ctl.crte == NULL)
5486 		return;
5487 	if ((bbr->rc_inp->inp_route.ro_nh == NULL) ||
5488 	    (bbr->rc_inp->inp_route.ro_nh->nh_ifp == NULL)) {
5489 		/* Lost our routes? */
5490 		/* Clear the way for a re-attempt */
5491 		bbr->bbr_attempt_hdwr_pace = 0;
5492 lost_rate:
5493 		bbr->gain_is_limited = 0;
5494 		bbr->skip_gain = 0;
5495 		bbr->bbr_hdrw_pacing = 0;
5496 		counter_u64_add(bbr_flows_whdwr_pacing, -1);
5497 		counter_u64_add(bbr_flows_nohdwr_pacing, 1);
5498 		tcp_bbr_tso_size_check(bbr, cts);
5499 		return;
5500 	}
5501 	rate = bbr_get_hardware_rate(bbr);
5502 	nrte = tcp_chg_pacing_rate(bbr->r_ctl.crte,
5503 				   bbr->rc_tp,
5504 				   bbr->rc_inp->inp_route.ro_nh->nh_ifp,
5505 				   rate,
5506 				   (RS_PACING_GEQ|RS_PACING_SUB_OK),
5507 				   &error, NULL);
5508 	if (nrte == NULL) {
5509 		goto lost_rate;
5510 	}
5511 	if (nrte != bbr->r_ctl.crte) {
5512 		bbr->r_ctl.crte = nrte;
5513 		if (error == 0)  {
5514 			BBR_STAT_INC(bbr_hdwr_rl_mod_ok);
5515 			if (bbr->r_ctl.crte->rate < rate) {
5516 				/* We have a problem */
5517 				bbr_setup_less_of_rate(bbr, cts,
5518 						       bbr->r_ctl.crte->rate, rate);
5519 			} else {
5520 				/* We are good */
5521 				bbr->gain_is_limited = 0;
5522 				bbr->skip_gain = 0;
5523 			}
5524 		} else {
5525 			/* A failure should release the tag */
5526 			BBR_STAT_INC(bbr_hdwr_rl_mod_fail);
5527 			bbr->gain_is_limited = 0;
5528 			bbr->skip_gain = 0;
5529 			bbr->bbr_hdrw_pacing = 0;
5530 		}
5531 		bbr_type_log_hdwr_pacing(bbr,
5532 					 bbr->r_ctl.crte->ptbl->rs_ifp,
5533 					 rate,
5534 					 bbr->r_ctl.crte->rate,
5535 					 __LINE__,
5536 					 cts,
5537 					 error);
5538 	}
5539 }
5540 
5541 static void
bbr_adjust_for_hw_pacing(struct tcp_bbr * bbr,uint32_t cts)5542 bbr_adjust_for_hw_pacing(struct tcp_bbr *bbr, uint32_t cts)
5543 {
5544 	/*
5545 	 * If we have hardware pacing support
5546 	 * we need to factor that in for our
5547 	 * TSO size.
5548 	 */
5549 	const struct tcp_hwrate_limit_table *rlp;
5550 	uint32_t cur_delay, seg_sz, maxseg, new_tso, delta, hdwr_delay;
5551 
5552 	if ((bbr->bbr_hdrw_pacing == 0) ||
5553 	    (IN_RECOVERY(bbr->rc_tp->t_flags)) ||
5554 	    (bbr->r_ctl.crte == NULL))
5555 		return;
5556 	if (bbr->hw_pacing_set == 0) {
5557 		/* Not yet by the hdwr pacing count delay */
5558 		return;
5559 	}
5560 	if (bbr_hdwr_pace_adjust == 0) {
5561 		/* No adjustment */
5562 		return;
5563 	}
5564 	rlp = bbr->r_ctl.crte;
5565 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options)
5566 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5567 	else
5568 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5569 	/*
5570 	 * So lets first get the
5571 	 * time we will take between
5572 	 * TSO sized sends currently without
5573 	 * hardware help.
5574 	 */
5575 	cur_delay = bbr_get_pacing_delay(bbr, BBR_UNIT,
5576 		        bbr->r_ctl.rc_pace_max_segs, cts, 1);
5577 	hdwr_delay = bbr->r_ctl.rc_pace_max_segs / maxseg;
5578 	hdwr_delay *= rlp->time_between;
5579 	if (cur_delay > hdwr_delay)
5580 		delta = cur_delay - hdwr_delay;
5581 	else
5582 		delta = 0;
5583 	bbr_log_type_tsosize(bbr, cts, delta, cur_delay, hdwr_delay,
5584 			     (bbr->r_ctl.rc_pace_max_segs / maxseg),
5585 			     1);
5586 	if (delta &&
5587 	    (delta < (max(rlp->time_between,
5588 			  bbr->r_ctl.bbr_hptsi_segments_delay_tar)))) {
5589 		/*
5590 		 * Now lets divide by the pacing
5591 		 * time between each segment the
5592 		 * hardware sends rounding up and
5593 		 * derive a bytes from that. We multiply
5594 		 * that by bbr_hdwr_pace_adjust to get
5595 		 * more bang for our buck.
5596 		 *
5597 		 * The goal is to have the software pacer
5598 		 * waiting no more than an additional
5599 		 * pacing delay if we can (without the
5600 		 * compensation i.e. x bbr_hdwr_pace_adjust).
5601 		 */
5602 		seg_sz = max(((cur_delay + rlp->time_between)/rlp->time_between),
5603 			     (bbr->r_ctl.rc_pace_max_segs/maxseg));
5604 		seg_sz *= bbr_hdwr_pace_adjust;
5605 		if (bbr_hdwr_pace_floor &&
5606 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5607 			/* Currently hardware paces
5608 			 * out rs_min_seg segments at a time.
5609 			 * We need to make sure we always send at least
5610 			 * a full burst of bbr_hdwr_pace_floor down.
5611 			 */
5612 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5613 		}
5614 		seg_sz *= maxseg;
5615 	} else if (delta == 0) {
5616 		/*
5617 		 * The highest pacing rate is
5618 		 * above our b/w gained. This means
5619 		 * we probably are going quite fast at
5620 		 * the hardware highest rate. Lets just multiply
5621 		 * the calculated TSO size by the
5622 		 * multiplier factor (its probably
5623 		 * 4 segments in the default config for
5624 		 * mlx).
5625 		 */
5626 		seg_sz = bbr->r_ctl.rc_pace_max_segs * bbr_hdwr_pace_adjust;
5627 		if (bbr_hdwr_pace_floor &&
5628 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5629 			/* Currently hardware paces
5630 			 * out rs_min_seg segments at a time.
5631 			 * We need to make sure we always send at least
5632 			 * a full burst of bbr_hdwr_pace_floor down.
5633 			 */
5634 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5635 		}
5636 	} else {
5637 		/*
5638 		 * The pacing time difference is so
5639 		 * big that the hardware will
5640 		 * pace out more rapidly then we
5641 		 * really want and then we
5642 		 * will have a long delay. Lets just keep
5643 		 * the same TSO size so its as if
5644 		 * we were not using hdwr pacing (we
5645 		 * just gain a bit of spacing from the
5646 		 * hardware if seg_sz > 1).
5647 		 */
5648 		seg_sz = bbr->r_ctl.rc_pace_max_segs;
5649 	}
5650 	if (seg_sz > bbr->r_ctl.rc_pace_max_segs)
5651 		new_tso = seg_sz;
5652 	else
5653 		new_tso = bbr->r_ctl.rc_pace_max_segs;
5654 	if (new_tso >= (PACE_MAX_IP_BYTES-maxseg))
5655 		new_tso = PACE_MAX_IP_BYTES - maxseg;
5656 
5657 	if (new_tso != bbr->r_ctl.rc_pace_max_segs) {
5658 		bbr_log_type_tsosize(bbr, cts, new_tso, 0, bbr->r_ctl.rc_pace_max_segs, maxseg, 0);
5659 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5660 	}
5661 }
5662 
5663 static void
tcp_bbr_tso_size_check(struct tcp_bbr * bbr,uint32_t cts)5664 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts)
5665 {
5666 	uint64_t bw;
5667 	uint32_t old_tso = 0, new_tso;
5668 	uint32_t maxseg, bytes;
5669 	uint32_t tls_seg=0;
5670 	/*
5671 	 * Google/linux uses the following algorithm to determine
5672 	 * the TSO size based on the b/w of the link (from Neal Cardwell email 9/27/18):
5673 	 *
5674 	 *  bytes = bw_in_bytes_per_second / 1000
5675 	 *  bytes = min(bytes, 64k)
5676 	 *  tso_segs = bytes / MSS
5677 	 *  if (bw < 1.2Mbs)
5678 	 *      min_tso_segs = 1
5679 	 *  else
5680 	 *	min_tso_segs = 2
5681 	 * tso_segs = max(tso_segs, min_tso_segs)
5682 	 *
5683 	 * * Note apply a device specific limit (we apply this in the
5684 	 *   tcp_m_copym).
5685 	 * Note that before the initial measurement is made google bursts out
5686 	 * a full iwnd just like new-reno/cubic.
5687 	 *
5688 	 * We do not use this algorithm. Instead we
5689 	 * use a two phased approach:
5690 	 *
5691 	 *  if ( bw <= per-tcb-cross-over)
5692 	 *     goal_tso =  calculate how much with this bw we
5693 	 *                 can send in goal-time seconds.
5694 	 *     if (goal_tso > mss)
5695 	 *         seg = goal_tso / mss
5696 	 *         tso = seg * mss
5697 	 *     else
5698 	 *         tso = mss
5699 	 *     if (tso > per-tcb-max)
5700 	 *         tso = per-tcb-max
5701 	 *  else if ( bw > 512Mbps)
5702 	 *     tso = max-tso (64k/mss)
5703 	 *  else
5704 	 *     goal_tso = bw / per-tcb-divsor
5705 	 *     seg = (goal_tso + mss-1)/mss
5706 	 *     tso = seg * mss
5707 	 *
5708 	 * if (tso < per-tcb-floor)
5709 	 *    tso = per-tcb-floor
5710 	 * if (tso > per-tcb-utter_max)
5711 	 *    tso = per-tcb-utter_max
5712 	 *
5713 	 * Note the default per-tcb-divisor is 1000 (same as google).
5714 	 * the goal cross over is 30Mbps however. To recreate googles
5715 	 * algorithm you need to set:
5716 	 *
5717 	 * cross-over = 23,168,000 bps
5718 	 * goal-time = 18000
5719 	 * per-tcb-max = 2
5720 	 * per-tcb-divisor = 1000
5721 	 * per-tcb-floor = 1
5722 	 *
5723 	 * This will get you "google bbr" behavior with respect to tso size.
5724 	 *
5725 	 * Note we do set anything TSO size until we are past the initial
5726 	 * window. Before that we gnerally use either a single MSS
5727 	 * or we use the full IW size (so we burst a IW at a time)
5728 	 */
5729 
5730 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options) {
5731 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5732 	} else {
5733 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5734 	}
5735 	old_tso = bbr->r_ctl.rc_pace_max_segs;
5736 	if (bbr->rc_past_init_win == 0) {
5737 		/*
5738 		 * Not enough data has been acknowledged to make a
5739 		 * judgement. Set up the initial TSO based on if we
5740 		 * are sending a full IW at once or not.
5741 		 */
5742 		if (bbr->rc_use_google)
5743 			bbr->r_ctl.rc_pace_max_segs = ((bbr->rc_tp->t_maxseg - bbr->rc_last_options) * 2);
5744 		else if (bbr->bbr_init_win_cheat)
5745 			bbr->r_ctl.rc_pace_max_segs = bbr_initial_cwnd(bbr, bbr->rc_tp);
5746 		else
5747 			bbr->r_ctl.rc_pace_max_segs = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5748 		if (bbr->r_ctl.rc_pace_min_segs != bbr->rc_tp->t_maxseg)
5749 			bbr->r_ctl.rc_pace_min_segs = bbr->rc_tp->t_maxseg;
5750 		if (bbr->r_ctl.rc_pace_max_segs == 0) {
5751 			bbr->r_ctl.rc_pace_max_segs = maxseg;
5752 		}
5753 		bbr_log_type_tsosize(bbr, cts, bbr->r_ctl.rc_pace_max_segs, tls_seg, old_tso, maxseg, 0);
5754 			bbr_adjust_for_hw_pacing(bbr, cts);
5755 		return;
5756 	}
5757 	/**
5758 	 * Now lets set the TSO goal based on our delivery rate in
5759 	 * bytes per second. Note we only do this if
5760 	 * we have acked at least the initial cwnd worth of data.
5761 	 */
5762 	bw = bbr_get_bw(bbr);
5763 	if (IN_RECOVERY(bbr->rc_tp->t_flags) &&
5764 	     (bbr->rc_use_google == 0)) {
5765 		/* We clamp to one MSS in recovery */
5766 		new_tso = maxseg;
5767 	} else if (bbr->rc_use_google) {
5768 		int min_tso_segs;
5769 
5770 		/* Google considers the gain too */
5771 		if (bbr->r_ctl.rc_bbr_hptsi_gain != BBR_UNIT) {
5772 			bw *= bbr->r_ctl.rc_bbr_hptsi_gain;
5773 			bw /= BBR_UNIT;
5774 		}
5775 		bytes = bw / 1024;
5776 		if (bytes > (64 * 1024))
5777 			bytes = 64 * 1024;
5778 		new_tso = bytes / maxseg;
5779 		if (bw < ONE_POINT_TWO_MEG)
5780 			min_tso_segs = 1;
5781 		else
5782 			min_tso_segs = 2;
5783 		if (new_tso < min_tso_segs)
5784 			new_tso = min_tso_segs;
5785 		new_tso *= maxseg;
5786 	} else if (bbr->rc_no_pacing) {
5787 		new_tso = (PACE_MAX_IP_BYTES / maxseg) * maxseg;
5788 	} else if (bw <= bbr->r_ctl.bbr_cross_over) {
5789 		/*
5790 		 * Calculate the worse case b/w TSO if we are inserting no
5791 		 * more than a delay_target number of TSO's.
5792 		 */
5793 		uint32_t tso_len, min_tso;
5794 
5795 		tso_len = bbr_get_pacing_length(bbr, BBR_UNIT, bbr->r_ctl.bbr_hptsi_segments_delay_tar, bw);
5796 		if (tso_len > maxseg) {
5797 			new_tso = tso_len / maxseg;
5798 			if (new_tso > bbr->r_ctl.bbr_hptsi_segments_max)
5799 				new_tso = bbr->r_ctl.bbr_hptsi_segments_max;
5800 			new_tso *= maxseg;
5801 		} else {
5802 			/*
5803 			 * less than a full sized frame yikes.. long rtt or
5804 			 * low bw?
5805 			 */
5806 			min_tso = bbr_minseg(bbr);
5807 			if ((tso_len > min_tso) && (bbr_all_get_min == 0))
5808 				new_tso = rounddown(tso_len, min_tso);
5809 			else
5810 				new_tso = min_tso;
5811 		}
5812 	} else if (bw > FIVETWELVE_MBPS) {
5813 		/*
5814 		 * This guy is so fast b/w wise that we can TSO as large as
5815 		 * possible of segments that the NIC will allow.
5816 		 */
5817 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5818 	} else {
5819 		/*
5820 		 * This formula is based on attempting to send a segment or
5821 		 * more every bbr_hptsi_per_second. The default is 1000
5822 		 * which means you are targeting what you can send every 1ms
5823 		 * based on the peers bw.
5824 		 *
5825 		 * If the number drops to say 500, then you are looking more
5826 		 * at 2ms and you will raise how much we send in a single
5827 		 * TSO thus saving CPU (less bbr_output_wtime() calls). The
5828 		 * trade off of course is you will send more at once and
5829 		 * thus tend to clump up the sends into larger "bursts"
5830 		 * building a queue.
5831 		 */
5832 		bw /= bbr->r_ctl.bbr_hptsi_per_second;
5833 		new_tso = roundup(bw, (uint64_t)maxseg);
5834 		/*
5835 		 * Gate the floor to match what our lower than 48Mbps
5836 		 * algorithm does. The ceiling (bbr_hptsi_segments_max) thus
5837 		 * becomes the floor for this calculation.
5838 		 */
5839 		if (new_tso < (bbr->r_ctl.bbr_hptsi_segments_max * maxseg))
5840 			new_tso = (bbr->r_ctl.bbr_hptsi_segments_max * maxseg);
5841 	}
5842 	if (bbr->r_ctl.bbr_hptsi_segments_floor && (new_tso < (maxseg * bbr->r_ctl.bbr_hptsi_segments_floor)))
5843 		new_tso = maxseg * bbr->r_ctl.bbr_hptsi_segments_floor;
5844 	if (new_tso > PACE_MAX_IP_BYTES)
5845 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5846 	/* Enforce an utter maximum. */
5847 	if (bbr->r_ctl.bbr_utter_max && (new_tso > (bbr->r_ctl.bbr_utter_max * maxseg))) {
5848 		new_tso = bbr->r_ctl.bbr_utter_max * maxseg;
5849 	}
5850 	if (old_tso != new_tso) {
5851 		/* Only log changes */
5852 		bbr_log_type_tsosize(bbr, cts, new_tso, tls_seg, old_tso, maxseg, 0);
5853 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5854 	}
5855 	/* We have hardware pacing! */
5856 	bbr_adjust_for_hw_pacing(bbr, cts);
5857 }
5858 
5859 static void
bbr_log_output(struct tcp_bbr * bbr,struct tcpcb * tp,struct tcpopt * to,int32_t len,uint32_t seq_out,uint16_t th_flags,int32_t err,uint32_t cts,struct mbuf * mb,int32_t * abandon,struct bbr_sendmap * hintrsm,uint32_t delay_calc,struct sockbuf * sb)5860 bbr_log_output(struct tcp_bbr *bbr, struct tcpcb *tp, struct tcpopt *to, int32_t len,
5861     uint32_t seq_out, uint16_t th_flags, int32_t err, uint32_t cts,
5862     struct mbuf *mb, int32_t * abandon, struct bbr_sendmap *hintrsm, uint32_t delay_calc,
5863     struct sockbuf *sb)
5864 {
5865 
5866 	struct bbr_sendmap *rsm, *nrsm;
5867 	register uint32_t snd_max, snd_una;
5868 	uint32_t pacing_time;
5869 	/*
5870 	 * Add to the RACK log of packets in flight or retransmitted. If
5871 	 * there is a TS option we will use the TS echoed, if not we will
5872 	 * grab a TS.
5873 	 *
5874 	 * Retransmissions will increment the count and move the ts to its
5875 	 * proper place. Note that if options do not include TS's then we
5876 	 * won't be able to effectively use the ACK for an RTT on a retran.
5877 	 *
5878 	 * Notes about r_start and r_end. Lets consider a send starting at
5879 	 * sequence 1 for 10 bytes. In such an example the r_start would be
5880 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
5881 	 * This means that r_end is actually the first sequence for the next
5882 	 * slot (11).
5883 	 *
5884 	 */
5885 	INP_WLOCK_ASSERT(tptoinpcb(tp));
5886 	if (err) {
5887 		/*
5888 		 * We don't log errors -- we could but snd_max does not
5889 		 * advance in this case either.
5890 		 */
5891 		return;
5892 	}
5893 	if (th_flags & TH_RST) {
5894 		/*
5895 		 * We don't log resets and we return immediately from
5896 		 * sending
5897 		 */
5898 		*abandon = 1;
5899 		return;
5900 	}
5901 	snd_una = tp->snd_una;
5902 	if (th_flags & (TH_SYN | TH_FIN) && (hintrsm == NULL)) {
5903 		/*
5904 		 * The call to bbr_log_output is made before bumping
5905 		 * snd_max. This means we can record one extra byte on a SYN
5906 		 * or FIN if seq_out is adding more on and a FIN is present
5907 		 * (and we are not resending).
5908 		 */
5909 		if ((th_flags & TH_SYN) && (tp->iss == seq_out))
5910 			len++;
5911 		if (th_flags & TH_FIN)
5912 			len++;
5913 	}
5914 	if (SEQ_LEQ((seq_out + len), snd_una)) {
5915 		/* Are sending an old segment to induce an ack (keep-alive)? */
5916 		return;
5917 	}
5918 	if (SEQ_LT(seq_out, snd_una)) {
5919 		/* huh? should we panic? */
5920 		uint32_t end;
5921 
5922 		end = seq_out + len;
5923 		seq_out = snd_una;
5924 		len = end - seq_out;
5925 	}
5926 	snd_max = tp->snd_max;
5927 	if (len == 0) {
5928 		/* We don't log zero window probes */
5929 		return;
5930 	}
5931 	pacing_time = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, len, cts, 1);
5932 	/* First question is it a retransmission? */
5933 	if (seq_out == snd_max) {
5934 again:
5935 		rsm = bbr_alloc(bbr);
5936 		if (rsm == NULL) {
5937 			return;
5938 		}
5939 		rsm->r_flags = 0;
5940 		if (th_flags & TH_SYN)
5941 			rsm->r_flags |= BBR_HAS_SYN;
5942 		if (th_flags & TH_FIN)
5943 			rsm->r_flags |= BBR_HAS_FIN;
5944 		rsm->r_tim_lastsent[0] = cts;
5945 		rsm->r_rtr_cnt = 1;
5946 		rsm->r_rtr_bytes = 0;
5947 		rsm->r_start = seq_out;
5948 		rsm->r_end = rsm->r_start + len;
5949 		rsm->r_dupack = 0;
5950 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
5951 		rsm->r_pacing_delay = pacing_time;
5952 		rsm->r_ts_valid = bbr->rc_ts_valid;
5953 		if (bbr->rc_ts_valid)
5954 			rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5955 		rsm->r_del_time = bbr->r_ctl.rc_del_time;
5956 		if (bbr->r_ctl.r_app_limited_until)
5957 			rsm->r_app_limited = 1;
5958 		else
5959 			rsm->r_app_limited = 0;
5960 		rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5961 		rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5962 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5963 		/*
5964 		 * Here we must also add in this rsm since snd_max
5965 		 * is updated after we return from a new send.
5966 		 */
5967 		rsm->r_flight_at_send += len;
5968 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
5969 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5970 		rsm->r_in_tmap = 1;
5971 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5972 			rsm->r_bbr_state = bbr_state_val(bbr);
5973 		else
5974 			rsm->r_bbr_state = 8;
5975 		if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5976 			rsm->r_is_gain = 1;
5977 			rsm->r_is_drain = 0;
5978 		} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5979 			rsm->r_is_drain = 1;
5980 			rsm->r_is_gain = 0;
5981 		} else {
5982 			rsm->r_is_drain = 0;
5983 			rsm->r_is_gain = 0;
5984 		}
5985 		return;
5986 	}
5987 	/*
5988 	 * If we reach here its a retransmission and we need to find it.
5989 	 */
5990 more:
5991 	if (hintrsm && (hintrsm->r_start == seq_out)) {
5992 		rsm = hintrsm;
5993 		hintrsm = NULL;
5994 	} else if (bbr->r_ctl.rc_next) {
5995 		/* We have a hint from a previous run */
5996 		rsm = bbr->r_ctl.rc_next;
5997 	} else {
5998 		/* No hints sorry */
5999 		rsm = NULL;
6000 	}
6001 	if ((rsm) && (rsm->r_start == seq_out)) {
6002 		/*
6003 		 * We used rc_next or hintrsm  to retransmit, hopefully the
6004 		 * likely case.
6005 		 */
6006 		seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6007 		if (len == 0) {
6008 			return;
6009 		} else {
6010 			goto more;
6011 		}
6012 	}
6013 	/* Ok it was not the last pointer go through it the hard way. */
6014 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6015 		if (rsm->r_start == seq_out) {
6016 			seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6017 			bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
6018 			if (len == 0) {
6019 				return;
6020 			} else {
6021 				continue;
6022 			}
6023 		}
6024 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
6025 			/* Transmitted within this piece */
6026 			/*
6027 			 * Ok we must split off the front and then let the
6028 			 * update do the rest
6029 			 */
6030 			nrsm = bbr_alloc_full_limit(bbr);
6031 			if (nrsm == NULL) {
6032 				bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
6033 				return;
6034 			}
6035 			/*
6036 			 * copy rsm to nrsm and then trim the front of rsm
6037 			 * to not include this part.
6038 			 */
6039 			bbr_clone_rsm(bbr, nrsm, rsm, seq_out);
6040 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
6041 			if (rsm->r_in_tmap) {
6042 				TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6043 				nrsm->r_in_tmap = 1;
6044 			}
6045 			rsm->r_flags &= (~BBR_HAS_FIN);
6046 			seq_out = bbr_update_entry(tp, bbr, nrsm, cts, &len, pacing_time);
6047 			if (len == 0) {
6048 				return;
6049 			}
6050 		}
6051 	}
6052 	/*
6053 	 * Hmm not found in map did they retransmit both old and on into the
6054 	 * new?
6055 	 */
6056 	if (seq_out == tp->snd_max) {
6057 		goto again;
6058 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
6059 #ifdef BBR_INVARIANTS
6060 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
6061 		    seq_out, len, tp->snd_una, tp->snd_max);
6062 		printf("Starting Dump of all rack entries\n");
6063 		TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6064 			printf("rsm:%p start:%u end:%u\n",
6065 			    rsm, rsm->r_start, rsm->r_end);
6066 		}
6067 		printf("Dump complete\n");
6068 		panic("seq_out not found rack:%p tp:%p",
6069 		    bbr, tp);
6070 #endif
6071 	} else {
6072 #ifdef BBR_INVARIANTS
6073 		/*
6074 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
6075 		 * flag)
6076 		 */
6077 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
6078 		    seq_out, len, tp->snd_max, tp);
6079 #endif
6080 	}
6081 }
6082 
6083 static void
bbr_collapse_rtt(struct tcpcb * tp,struct tcp_bbr * bbr,int32_t rtt)6084 bbr_collapse_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, int32_t rtt)
6085 {
6086 	/*
6087 	 * Collapse timeout back the cum-ack moved.
6088 	 */
6089 	tp->t_rxtshift = 0;
6090 	tp->t_softerror = 0;
6091 }
6092 
6093 static void
tcp_bbr_xmit_timer(struct tcp_bbr * bbr,uint32_t rtt_usecs,uint32_t rsm_send_time,uint32_t r_start,uint32_t tsin)6094 tcp_bbr_xmit_timer(struct tcp_bbr *bbr, uint32_t rtt_usecs, uint32_t rsm_send_time, uint32_t r_start, uint32_t tsin)
6095 {
6096 	bbr->rtt_valid = 1;
6097 	bbr->r_ctl.cur_rtt = rtt_usecs;
6098 	bbr->r_ctl.ts_in = tsin;
6099 	if (rsm_send_time)
6100 		bbr->r_ctl.cur_rtt_send_time = rsm_send_time;
6101 }
6102 
6103 static void
bbr_make_timestamp_determination(struct tcp_bbr * bbr)6104 bbr_make_timestamp_determination(struct tcp_bbr *bbr)
6105 {
6106 	/**
6107 	 * We have in our bbr control:
6108 	 * 1) The timestamp we started observing cum-acks (bbr->r_ctl.bbr_ts_check_tstmp).
6109 	 * 2) Our timestamp indicating when we sent that packet (bbr->r_ctl.rsm->bbr_ts_check_our_cts).
6110 	 * 3) The current timestamp that just came in (bbr->r_ctl.last_inbound_ts)
6111 	 * 4) The time that the packet that generated that ack was sent (bbr->r_ctl.cur_rtt_send_time)
6112 	 *
6113 	 * Now we can calculate the time between the sends by doing:
6114 	 *
6115 	 * delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts
6116 	 *
6117 	 * And the peer's time between receiving them by doing:
6118 	 *
6119 	 * peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp
6120 	 *
6121 	 * We want to figure out if the timestamp values are in msec, 10msec or usec.
6122 	 * We also may find that we can't use the timestamps if say we see
6123 	 * that the peer_delta indicates that though we may have taken 10ms to
6124 	 * pace out the data, it only saw 1ms between the two packets. This would
6125 	 * indicate that somewhere on the path is a batching entity that is giving
6126 	 * out time-slices of the actual b/w. This would mean we could not use
6127 	 * reliably the peers timestamps.
6128 	 *
6129 	 * We expect delta > peer_delta initially. Until we figure out the
6130 	 * timestamp difference which we will store in bbr->r_ctl.bbr_peer_tsratio.
6131 	 * If we place 1000 there then its a ms vs our usec. If we place 10000 there
6132 	 * then its 10ms vs our usec. If the peer is running a usec clock we would
6133 	 * put a 1 there. If the value is faster then ours, we will disable the
6134 	 * use of timestamps (though we could revist this later if we find it to be not
6135 	 * just an isolated one or two flows)).
6136 	 *
6137 	 * To detect the batching middle boxes we will come up with our compensation and
6138 	 * if with it in place, we find the peer is drastically off (by some margin) in
6139 	 * the smaller direction, then we will assume the worst case and disable use of timestamps.
6140 	 *
6141 	 */
6142 	uint64_t delta, peer_delta, delta_up;
6143 
6144 	delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts;
6145 	if (delta < bbr_min_usec_delta) {
6146 		/*
6147 		 * Have not seen a min amount of time
6148 		 * between our send times so we can
6149 		 * make a determination of the timestamp
6150 		 * yet.
6151 		 */
6152 		return;
6153 	}
6154 	peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp;
6155 	if (peer_delta < bbr_min_peer_delta) {
6156 		/*
6157 		 * We may have enough in the form of
6158 		 * our delta but the peers number
6159 		 * has not changed that much. It could
6160 		 * be its clock ratio is such that
6161 		 * we need more data (10ms tick) or
6162 		 * there may be other compression scenarios
6163 		 * going on. In any event we need the
6164 		 * spread to be larger.
6165 		 */
6166 		return;
6167 	}
6168 	/* Ok lets first see which way our delta is going */
6169 	if (peer_delta > delta) {
6170 		/* Very unlikely, the peer without
6171 		 * compensation shows that it saw
6172 		 * the two sends arrive further apart
6173 		 * then we saw then in micro-seconds.
6174 		 */
6175 		if (peer_delta < (delta + ((delta * (uint64_t)1000)/ (uint64_t)bbr_delta_percent))) {
6176 			/* well it looks like the peer is a micro-second clock. */
6177 			bbr->rc_ts_clock_set = 1;
6178 			bbr->r_ctl.bbr_peer_tsratio = 1;
6179 		} else {
6180 			bbr->rc_ts_cant_be_used = 1;
6181 			bbr->rc_ts_clock_set = 1;
6182 		}
6183 		return;
6184 	}
6185 	/* Ok we know that the peer_delta is smaller than our send distance */
6186 	bbr->rc_ts_clock_set = 1;
6187 	/* First question is it within the percentage that they are using usec time? */
6188 	delta_up = (peer_delta * 1000) / (uint64_t)bbr_delta_percent;
6189 	if ((peer_delta + delta_up) >= delta) {
6190 		/* Its a usec clock */
6191 		bbr->r_ctl.bbr_peer_tsratio = 1;
6192 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6193 		return;
6194 	}
6195 	/* Ok if not usec, what about 10usec (though unlikely)? */
6196 	delta_up = (peer_delta * 1000 * 10) / (uint64_t)bbr_delta_percent;
6197 	if (((peer_delta * 10) + delta_up) >= delta) {
6198 		bbr->r_ctl.bbr_peer_tsratio = 10;
6199 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6200 		return;
6201 	}
6202 	/* And what about 100usec (though again unlikely)? */
6203 	delta_up = (peer_delta * 1000 * 100) / (uint64_t)bbr_delta_percent;
6204 	if (((peer_delta * 100) + delta_up) >= delta) {
6205 		bbr->r_ctl.bbr_peer_tsratio = 100;
6206 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6207 		return;
6208 	}
6209 	/* And how about 1 msec (the most likely one)? */
6210 	delta_up = (peer_delta * 1000 * 1000) / (uint64_t)bbr_delta_percent;
6211 	if (((peer_delta * 1000) + delta_up) >= delta) {
6212 		bbr->r_ctl.bbr_peer_tsratio = 1000;
6213 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6214 		return;
6215 	}
6216 	/* Ok if not msec could it be 10 msec? */
6217 	delta_up = (peer_delta * 1000 * 10000) / (uint64_t)bbr_delta_percent;
6218 	if (((peer_delta * 10000) + delta_up) >= delta) {
6219 		bbr->r_ctl.bbr_peer_tsratio = 10000;
6220 		return;
6221 	}
6222 	/* If we fall down here the clock tick so slowly we can't use it */
6223 	bbr->rc_ts_cant_be_used = 1;
6224 	bbr->r_ctl.bbr_peer_tsratio = 0;
6225 	bbr_log_tstmp_validation(bbr, peer_delta, delta);
6226 }
6227 
6228 /*
6229  * Collect new round-trip time estimate
6230  * and update averages and current timeout.
6231  */
6232 static void
tcp_bbr_xmit_timer_commit(struct tcp_bbr * bbr,struct tcpcb * tp,uint32_t cts)6233 tcp_bbr_xmit_timer_commit(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts)
6234 {
6235 	int32_t delta;
6236 	uint32_t rtt, tsin;
6237 	int32_t rtt_ticks;
6238 
6239 	if (bbr->rtt_valid == 0)
6240 		/* No valid sample */
6241 		return;
6242 
6243 	rtt = bbr->r_ctl.cur_rtt;
6244 	tsin = bbr->r_ctl.ts_in;
6245 	if (bbr->rc_prtt_set_ts) {
6246 		/*
6247 		 * We are to force feed the rttProp filter due
6248 		 * to an entry into PROBE_RTT. This assures
6249 		 * that the times are sync'd between when we
6250 		 * go into PROBE_RTT and the filter expiration.
6251 		 *
6252 		 * Google does not use a true filter, so they do
6253 		 * this implicitly since they only keep one value
6254 		 * and when they enter probe-rtt they update the
6255 		 * value to the newest rtt.
6256 		 */
6257 		uint32_t rtt_prop;
6258 
6259 		bbr->rc_prtt_set_ts = 0;
6260 		rtt_prop = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
6261 		if (rtt > rtt_prop)
6262 			filter_increase_by_small(&bbr->r_ctl.rc_rttprop, (rtt - rtt_prop), cts);
6263 		else
6264 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6265 	}
6266 #ifdef STATS
6267 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_PATHRTT, imax(0, rtt));
6268 #endif
6269 	if (bbr->rc_ack_was_delayed)
6270 		rtt += bbr->r_ctl.rc_ack_hdwr_delay;
6271 
6272 	if (rtt < bbr->r_ctl.rc_lowest_rtt)
6273 		bbr->r_ctl.rc_lowest_rtt = rtt;
6274 	bbr_log_rtt_sample(bbr, rtt, tsin);
6275 	if (bbr->r_init_rtt) {
6276 		/*
6277 		 * The initial rtt is not-trusted, nuke it and lets get
6278 		 * our first valid measurement in.
6279 		 */
6280 		bbr->r_init_rtt = 0;
6281 		tp->t_srtt = 0;
6282 	}
6283 	if ((bbr->rc_ts_clock_set == 0) && bbr->rc_ts_valid) {
6284 		/*
6285 		 * So we have not yet figured out
6286 		 * what the peers TSTMP value is
6287 		 * in (most likely ms). We need a
6288 		 * series of cum-ack's to determine
6289 		 * this reliably.
6290 		 */
6291 		if (bbr->rc_ack_is_cumack) {
6292 			if (bbr->rc_ts_data_set) {
6293 				/* Lets attempt to determine the timestamp granularity. */
6294 				bbr_make_timestamp_determination(bbr);
6295 			} else {
6296 				bbr->rc_ts_data_set = 1;
6297 				bbr->r_ctl.bbr_ts_check_tstmp = bbr->r_ctl.last_inbound_ts;
6298 				bbr->r_ctl.bbr_ts_check_our_cts = bbr->r_ctl.cur_rtt_send_time;
6299 			}
6300 		} else {
6301 			/*
6302 			 * We have to have consecutive acks
6303 			 * reset any "filled" state to none.
6304 			 */
6305 			bbr->rc_ts_data_set = 0;
6306 		}
6307 	}
6308 	/* Round it up */
6309 	rtt_ticks = USEC_2_TICKS((rtt + (USECS_IN_MSEC - 1)));
6310 	if (tp->t_srtt != 0) {
6311 		/*
6312 		 * srtt is stored as fixed point with 5 bits after the
6313 		 * binary point (i.e., scaled by 8).  The following magic is
6314 		 * equivalent to the smoothing algorithm in rfc793 with an
6315 		 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6316 		 * Adjust rtt to origin 0.
6317 		 */
6318 
6319 		delta = ((rtt_ticks - 1) << TCP_DELTA_SHIFT)
6320 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6321 
6322 		tp->t_srtt += delta;
6323 		if (tp->t_srtt <= 0)
6324 			tp->t_srtt = 1;
6325 
6326 		/*
6327 		 * We accumulate a smoothed rtt variance (actually, a
6328 		 * smoothed mean difference), then set the retransmit timer
6329 		 * to smoothed rtt + 4 times the smoothed variance. rttvar
6330 		 * is stored as fixed point with 4 bits after the binary
6331 		 * point (scaled by 16).  The following is equivalent to
6332 		 * rfc793 smoothing with an alpha of .75 (rttvar =
6333 		 * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
6334 		 * wired-in beta.
6335 		 */
6336 		if (delta < 0)
6337 			delta = -delta;
6338 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6339 		tp->t_rttvar += delta;
6340 		if (tp->t_rttvar <= 0)
6341 			tp->t_rttvar = 1;
6342 	} else {
6343 		/*
6344 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
6345 		 * variance to half the rtt (so our first retransmit happens
6346 		 * at 3*rtt).
6347 		 */
6348 		tp->t_srtt = rtt_ticks << TCP_RTT_SHIFT;
6349 		tp->t_rttvar = rtt_ticks << (TCP_RTTVAR_SHIFT - 1);
6350 	}
6351 	KMOD_TCPSTAT_INC(tcps_rttupdated);
6352 	if (tp->t_rttupdated < UCHAR_MAX)
6353 		tp->t_rttupdated++;
6354 #ifdef STATS
6355 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt_ticks));
6356 #endif
6357 	/*
6358 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
6359 	 * way we do the smoothing, srtt and rttvar will each average +1/2
6360 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
6361 	 * tick of rounding and 1 extra tick because of +-1/2 tick
6362 	 * uncertainty in the firing of the timer.  The bias will give us
6363 	 * exactly the 1.5 tick we need.  But, because the bias is
6364 	 * statistical, we have to test that we don't drop below the minimum
6365 	 * feasible timer (which is 2 ticks).
6366 	 */
6367 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6368 	    max(MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms), rtt_ticks + 2),
6369 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
6370 
6371 	/*
6372 	 * We received an ack for a packet that wasn't retransmitted; it is
6373 	 * probably safe to discard any error indications we've received
6374 	 * recently.  This isn't quite right, but close enough for now (a
6375 	 * route might have failed after we sent a segment, and the return
6376 	 * path might not be symmetrical).
6377 	 */
6378 	tp->t_softerror = 0;
6379 	rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
6380 	if (bbr->r_ctl.bbr_smallest_srtt_this_state > rtt)
6381 		bbr->r_ctl.bbr_smallest_srtt_this_state = rtt;
6382 }
6383 
6384 static void
bbr_set_reduced_rtt(struct tcp_bbr * bbr,uint32_t cts,uint32_t line)6385 bbr_set_reduced_rtt(struct tcp_bbr *bbr, uint32_t cts, uint32_t line)
6386 {
6387 	bbr->r_ctl.rc_rtt_shrinks = cts;
6388 	if (bbr_can_force_probertt &&
6389 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
6390 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
6391 		/*
6392 		 * We should enter probe-rtt its been too long
6393 		 * since we have been there.
6394 		 */
6395 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
6396 	} else
6397 		bbr_check_probe_rtt_limits(bbr, cts);
6398 }
6399 
6400 static void
tcp_bbr_commit_bw(struct tcp_bbr * bbr,uint32_t cts)6401 tcp_bbr_commit_bw(struct tcp_bbr *bbr, uint32_t cts)
6402 {
6403 	uint64_t orig_bw;
6404 
6405 	if (bbr->r_ctl.rc_bbr_cur_del_rate == 0) {
6406 		/* We never apply a zero measurement */
6407 		bbr_log_type_bbrupd(bbr, 20, cts, 0, 0,
6408 				    0, 0, 0, 0, 0, 0);
6409 		return;
6410 	}
6411 	if (bbr->r_ctl.r_measurement_count < 0xffffffff)
6412 		bbr->r_ctl.r_measurement_count++;
6413 	orig_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
6414 	apply_filter_max(&bbr->r_ctl.rc_delrate, bbr->r_ctl.rc_bbr_cur_del_rate, bbr->r_ctl.rc_pkt_epoch);
6415 	bbr_log_type_bbrupd(bbr, 21, cts, (uint32_t)orig_bw,
6416 			    (uint32_t)get_filter_value(&bbr->r_ctl.rc_delrate),
6417 			    0, 0, 0, 0, 0, 0);
6418 	if (orig_bw &&
6419 	    (orig_bw != get_filter_value(&bbr->r_ctl.rc_delrate))) {
6420 		if (bbr->bbr_hdrw_pacing) {
6421 			/*
6422 			 * Apply a new rate to the hardware
6423 			 * possibly.
6424 			 */
6425 			bbr_update_hardware_pacing_rate(bbr, cts);
6426 		}
6427 		bbr_set_state_target(bbr, __LINE__);
6428 		tcp_bbr_tso_size_check(bbr, cts);
6429 		if (bbr->r_recovery_bw)  {
6430 			bbr_setup_red_bw(bbr, cts);
6431 			bbr_log_type_bw_reduce(bbr, BBR_RED_BW_USELRBW);
6432 		}
6433 	} else if ((orig_bw == 0) && get_filter_value(&bbr->r_ctl.rc_delrate))
6434 		tcp_bbr_tso_size_check(bbr, cts);
6435 }
6436 
6437 static void
bbr_nf_measurement(struct tcp_bbr * bbr,struct bbr_sendmap * rsm,uint32_t rtt,uint32_t cts)6438 bbr_nf_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6439 {
6440 	if (bbr->rc_in_persist == 0) {
6441 		/* We log only when not in persist */
6442 		/* Translate to a Bytes Per Second */
6443 		uint64_t tim, bw, ts_diff, ts_bw;
6444 		uint32_t delivered;
6445 
6446 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6447 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6448 		else
6449 			tim = 1;
6450 		/*
6451 		 * Now that we have processed the tim (skipping the sample
6452 		 * or possibly updating the time, go ahead and
6453 		 * calculate the cdr.
6454 		 */
6455 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6456 		bw = (uint64_t)delivered;
6457 		bw *= (uint64_t)USECS_IN_SECOND;
6458 		bw /= tim;
6459 		if (bw == 0) {
6460 			/* We must have a calculatable amount */
6461 			return;
6462 		}
6463 		/*
6464 		 * If we are using this b/w shove it in now so we
6465 		 * can see in the trace viewer if it gets over-ridden.
6466 		 */
6467 		if (rsm->r_ts_valid &&
6468 		    bbr->rc_ts_valid &&
6469 		    bbr->rc_ts_clock_set &&
6470 		    (bbr->rc_ts_cant_be_used == 0) &&
6471 		    bbr->rc_use_ts_limit) {
6472 			ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6473 			ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6474 			if ((delivered == 0) ||
6475 			    (rtt < 1000)) {
6476 				/* Can't use the ts */
6477 				bbr_log_type_bbrupd(bbr, 61, cts,
6478 						    ts_diff,
6479 						    bbr->r_ctl.last_inbound_ts,
6480 						    rsm->r_del_ack_ts, 0,
6481 						    0, 0, 0, delivered);
6482 			} else {
6483 				ts_bw = (uint64_t)delivered;
6484 				ts_bw *= (uint64_t)USECS_IN_SECOND;
6485 				ts_bw /= ts_diff;
6486 				bbr_log_type_bbrupd(bbr, 62, cts,
6487 						    (ts_bw >> 32),
6488 						    (ts_bw & 0xffffffff), 0, 0,
6489 						    0, 0, ts_diff, delivered);
6490 				if ((bbr->ts_can_raise) &&
6491 				    (ts_bw > bw)) {
6492 					bbr_log_type_bbrupd(bbr, 8, cts,
6493 							    delivered,
6494 							    ts_diff,
6495 							    (bw >> 32),
6496 							    (bw & 0x00000000ffffffff),
6497 							    0, 0, 0, 0);
6498 					bw = ts_bw;
6499 				} else if (ts_bw && (ts_bw < bw)) {
6500 					bbr_log_type_bbrupd(bbr, 7, cts,
6501 							    delivered,
6502 							    ts_diff,
6503 							    (bw >> 32),
6504 							    (bw & 0x00000000ffffffff),
6505 							    0, 0, 0, 0);
6506 					bw = ts_bw;
6507 				}
6508 			}
6509 		}
6510 		if (rsm->r_first_sent_time &&
6511 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6512 			uint64_t sbw, sti;
6513 			/*
6514 			 * We use what was in flight at the time of our
6515 			 * send  and the size of this send to figure
6516 			 * out what we have been sending at (amount).
6517 			 * For the time we take from the time of
6518 			 * the send of the first send outstanding
6519 			 * until this send plus this sends pacing
6520 			 * time. This gives us a good calculation
6521 			 * as to the rate we have been sending at.
6522 			 */
6523 
6524 			sbw = (uint64_t)(rsm->r_flight_at_send);
6525 			sbw *= (uint64_t)USECS_IN_SECOND;
6526 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6527 			sti += rsm->r_pacing_delay;
6528 			sbw /= sti;
6529 			if (sbw < bw) {
6530 				bbr_log_type_bbrupd(bbr, 6, cts,
6531 						    delivered,
6532 						    (uint32_t)sti,
6533 						    (bw >> 32),
6534 						    (uint32_t)bw,
6535 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6536 						    (uint32_t)sbw);
6537 				bw = sbw;
6538 			}
6539 		}
6540 		/* Use the google algorithm for b/w measurements */
6541 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6542 		if ((rsm->r_app_limited == 0) ||
6543 		    (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6544 			tcp_bbr_commit_bw(bbr, cts);
6545 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6546 					    0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6547 		}
6548 	}
6549 }
6550 
6551 static void
bbr_google_measurement(struct tcp_bbr * bbr,struct bbr_sendmap * rsm,uint32_t rtt,uint32_t cts)6552 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6553 {
6554 	if (bbr->rc_in_persist == 0) {
6555 		/* We log only when not in persist */
6556 		/* Translate to a Bytes Per Second */
6557 		uint64_t tim, bw;
6558 		uint32_t delivered;
6559 		int no_apply = 0;
6560 
6561 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6562 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6563 		else
6564 			tim = 1;
6565 		/*
6566 		 * Now that we have processed the tim (skipping the sample
6567 		 * or possibly updating the time, go ahead and
6568 		 * calculate the cdr.
6569 		 */
6570 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6571 		bw = (uint64_t)delivered;
6572 		bw *= (uint64_t)USECS_IN_SECOND;
6573 		bw /= tim;
6574 		if (tim < bbr->r_ctl.rc_lowest_rtt) {
6575 			bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6576 					    tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6577 
6578 			no_apply = 1;
6579 		}
6580 		/*
6581 		 * If we are using this b/w shove it in now so we
6582 		 * can see in the trace viewer if it gets over-ridden.
6583 		 */
6584 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6585 		/* Gate by the sending rate */
6586 		if (rsm->r_first_sent_time &&
6587 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6588 			uint64_t sbw, sti;
6589 			/*
6590 			 * We use what was in flight at the time of our
6591 			 * send  and the size of this send to figure
6592 			 * out what we have been sending at (amount).
6593 			 * For the time we take from the time of
6594 			 * the send of the first send outstanding
6595 			 * until this send plus this sends pacing
6596 			 * time. This gives us a good calculation
6597 			 * as to the rate we have been sending at.
6598 			 */
6599 
6600 			sbw = (uint64_t)(rsm->r_flight_at_send);
6601 			sbw *= (uint64_t)USECS_IN_SECOND;
6602 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6603 			sti += rsm->r_pacing_delay;
6604 			sbw /= sti;
6605 			if (sbw < bw) {
6606 				bbr_log_type_bbrupd(bbr, 6, cts,
6607 						    delivered,
6608 						    (uint32_t)sti,
6609 						    (bw >> 32),
6610 						    (uint32_t)bw,
6611 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6612 						    (uint32_t)sbw);
6613 				bw = sbw;
6614 			}
6615 			if ((sti > tim) &&
6616 			    (sti < bbr->r_ctl.rc_lowest_rtt)) {
6617 				bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6618 						    (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6619 				no_apply = 1;
6620 			} else
6621 				no_apply = 0;
6622 		}
6623 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6624 		if ((no_apply == 0) &&
6625 		    ((rsm->r_app_limited == 0) ||
6626 		     (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6627 			tcp_bbr_commit_bw(bbr, cts);
6628 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6629 					    0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6630 		}
6631 	}
6632 }
6633 
6634 static void
bbr_update_bbr_info(struct tcp_bbr * bbr,struct bbr_sendmap * rsm,uint32_t rtt,uint32_t cts,uint32_t tsin,uint32_t uts,int32_t match,uint32_t rsm_send_time,int32_t ack_type,struct tcpopt * to)6635 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6636     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6637 {
6638 	uint64_t old_rttprop;
6639 
6640 	/* Update our delivery time and amount */
6641 	bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6642 	bbr->r_ctl.rc_del_time = cts;
6643 	if (rtt == 0) {
6644 		/*
6645 		 * 0 means its a retransmit, for now we don't use these for
6646 		 * the rest of BBR.
6647 		 */
6648 		return;
6649 	}
6650 	if ((bbr->rc_use_google == 0) &&
6651 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6652 	    (match != BBR_RTT_BY_TIMESTAMP)){
6653 		/*
6654 		 * We get a lot of rtt updates, lets not pay attention to
6655 		 * any that are not an exact match. That way we don't have
6656 		 * to worry about timestamps and the whole nonsense of
6657 		 * unsure if its a retransmission etc (if we ever had the
6658 		 * timestamp fixed to always have the last thing sent this
6659 		 * would not be a issue).
6660 		 */
6661 		return;
6662 	}
6663 	if ((bbr_no_retran && bbr->rc_use_google) &&
6664 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6665 	    (match != BBR_RTT_BY_TIMESTAMP)){
6666 		/*
6667 		 * We only do measurements in google mode
6668 		 * with bbr_no_retran on for sure things.
6669 		 */
6670 		return;
6671 	}
6672 	/* Only update srtt if we know by exact match */
6673 	tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6674 	if (ack_type == BBR_CUM_ACKED)
6675 		bbr->rc_ack_is_cumack = 1;
6676 	else
6677 		bbr->rc_ack_is_cumack = 0;
6678 	old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6679 	/*
6680 	 * Note the following code differs to the original
6681 	 * BBR spec. It calls for <= not <. However after a
6682 	 * long discussion in email with Neal, he acknowledged
6683 	 * that it should be < than so that we will have flows
6684 	 * going into probe-rtt (we were seeing cases where that
6685 	 * did not happen and caused ugly things to occur). We
6686 	 * have added this agreed upon fix to our code base.
6687 	 */
6688 	if (rtt < old_rttprop) {
6689 		/* Update when we last saw a rtt drop */
6690 		bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6691 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
6692 	}
6693 	bbr_log_type_bbrrttprop(bbr, rtt, rsm->r_end, uts, cts,
6694 	    match, rsm->r_start, rsm->r_flags);
6695 	apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6696 	if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6697 		/*
6698 		 * The RTT-prop moved, reset the target (may be a
6699 		 * nop for some states).
6700 		 */
6701 		bbr_set_state_target(bbr, __LINE__);
6702 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6703 			bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6704 					    __LINE__, BBR_RTTS_NEW_TARGET, 0);
6705 		else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6706 			/* It went up */
6707 			bbr_check_probe_rtt_limits(bbr, cts);
6708 	}
6709 	if ((bbr->rc_use_google == 0) &&
6710 	    (match == BBR_RTT_BY_TIMESTAMP)) {
6711 		/*
6712 		 * We don't do b/w update with
6713 		 * these since they are not really
6714 		 * reliable.
6715 		 */
6716 		return;
6717 	}
6718 	if (bbr->r_ctl.r_app_limited_until &&
6719 	    (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6720 		/* We are no longer app-limited */
6721 		bbr->r_ctl.r_app_limited_until = 0;
6722 	}
6723 	if (bbr->rc_use_google) {
6724 		bbr_google_measurement(bbr, rsm, rtt, cts);
6725 	} else {
6726 		bbr_nf_measurement(bbr, rsm, rtt, cts);
6727 	}
6728 }
6729 
6730 /*
6731  * Convert a timestamp that the main stack
6732  * uses (milliseconds) into one that bbr uses
6733  * (microseconds). Return that converted timestamp.
6734  */
6735 static uint32_t
bbr_ts_convert(uint32_t cts)6736 bbr_ts_convert(uint32_t cts) {
6737 	uint32_t sec, msec;
6738 
6739 	sec = cts / MS_IN_USEC;
6740 	msec = cts - (MS_IN_USEC * sec);
6741 	return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6742 }
6743 
6744 /*
6745  * Return 0 if we did not update the RTT time, return
6746  * 1 if we did.
6747  */
6748 static int
bbr_update_rtt(struct tcpcb * tp,struct tcp_bbr * bbr,struct bbr_sendmap * rsm,struct tcpopt * to,uint32_t cts,int32_t ack_type,uint32_t th_ack)6749 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6750     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6751 {
6752 	int32_t i;
6753 	uint32_t t, uts = 0;
6754 
6755 	if ((rsm->r_flags & BBR_ACKED) ||
6756 	    (rsm->r_flags & BBR_WAS_RENEGED) ||
6757 	    (rsm->r_flags & BBR_RXT_CLEARED)) {
6758 		/* Already done */
6759 		return (0);
6760 	}
6761 	if (rsm->r_rtt_not_allowed) {
6762 		/* Not allowed */
6763 		return (0);
6764 	}
6765 	if (rsm->r_rtr_cnt == 1) {
6766 		/*
6767 		 * Only one transmit. Hopefully the normal case.
6768 		 */
6769 		if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6770 			t = cts - rsm->r_tim_lastsent[0];
6771 		else
6772 			t = 1;
6773 		bbr->r_ctl.rc_last_rtt = t;
6774 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6775 				    BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6776 		return (1);
6777 	}
6778 	/* Convert to usecs */
6779 	if ((bbr_can_use_ts_for_rtt == 1) &&
6780 	    (bbr->rc_use_google == 1) &&
6781 	    (ack_type == BBR_CUM_ACKED) &&
6782 	    (to->to_flags & TOF_TS) &&
6783 	    (to->to_tsecr != 0)) {
6784 		t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
6785 		if (t < 1)
6786 			t = 1;
6787 		t *= MS_IN_USEC;
6788 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6789 				    BBR_RTT_BY_TIMESTAMP,
6790 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
6791 				    ack_type, to);
6792 		return (1);
6793 	}
6794 	uts = bbr_ts_convert(to->to_tsecr);
6795 	if ((to->to_flags & TOF_TS) &&
6796 	    (to->to_tsecr != 0) &&
6797 	    (ack_type == BBR_CUM_ACKED) &&
6798 	    ((rsm->r_flags & BBR_OVERMAX) == 0)) {
6799 		/*
6800 		 * Now which timestamp does it match? In this block the ACK
6801 		 * may be coming from a previous transmission.
6802 		 */
6803 		uint32_t fudge;
6804 
6805 		fudge = BBR_TIMER_FUDGE;
6806 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
6807 			if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
6808 			    (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
6809 				if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6810 					t = cts - rsm->r_tim_lastsent[i];
6811 				else
6812 					t = 1;
6813 				bbr->r_ctl.rc_last_rtt = t;
6814 				bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
6815 						    rsm->r_tim_lastsent[i], ack_type, to);
6816 				if ((i + 1) < rsm->r_rtr_cnt) {
6817 					/* Likely */
6818 					return (0);
6819 				} else if (rsm->r_flags & BBR_TLP) {
6820 					bbr->rc_tlp_rtx_out = 0;
6821 				}
6822 				return (1);
6823 			}
6824 		}
6825 		/* Fall through if we can't find a matching timestamp */
6826 	}
6827 	/*
6828 	 * Ok its a SACK block that we retransmitted. or a windows
6829 	 * machine without timestamps. We can tell nothing from the
6830 	 * time-stamp since its not there or the time the peer last
6831 	 * received a segment that moved forward its cum-ack point.
6832 	 *
6833 	 * Lets look at the last retransmit and see what we can tell
6834 	 * (with BBR for space we only keep 2 note we have to keep
6835 	 * at least 2 so the map can not be condensed more).
6836 	 */
6837 	i = rsm->r_rtr_cnt - 1;
6838 	if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6839 		t = cts - rsm->r_tim_lastsent[i];
6840 	else
6841 		goto not_sure;
6842 	if (t < bbr->r_ctl.rc_lowest_rtt) {
6843 		/*
6844 		 * We retransmitted and the ack came back in less
6845 		 * than the smallest rtt we have observed in the
6846 		 * windowed rtt. We most likey did an improper
6847 		 * retransmit as outlined in 4.2 Step 3 point 2 in
6848 		 * the rack-draft.
6849 		 *
6850 		 * Use the prior transmission to update all the
6851 		 * information as long as there is only one prior
6852 		 * transmission.
6853 		 */
6854 		if ((rsm->r_flags & BBR_OVERMAX) == 0) {
6855 #ifdef BBR_INVARIANTS
6856 			if (rsm->r_rtr_cnt == 1)
6857 				panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
6858 #endif
6859 			i = rsm->r_rtr_cnt - 2;
6860 			if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6861 				t = cts - rsm->r_tim_lastsent[i];
6862 			else
6863 				t = 1;
6864 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
6865 					    rsm->r_tim_lastsent[i], ack_type, to);
6866 			return (0);
6867 		} else {
6868 			/*
6869 			 * Too many prior transmissions, just
6870 			 * updated BBR delivered
6871 			 */
6872 not_sure:
6873 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6874 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6875 		}
6876 	} else {
6877 		/*
6878 		 * We retransmitted it and the retransmit did the
6879 		 * job.
6880 		 */
6881 		if (rsm->r_flags & BBR_TLP)
6882 			bbr->rc_tlp_rtx_out = 0;
6883 		if ((rsm->r_flags & BBR_OVERMAX) == 0)
6884 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
6885 					    BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
6886 		else
6887 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6888 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6889 		return (1);
6890 	}
6891 	return (0);
6892 }
6893 
6894 /*
6895  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
6896  */
6897 static void
bbr_log_sack_passed(struct tcpcb * tp,struct tcp_bbr * bbr,struct bbr_sendmap * rsm)6898 bbr_log_sack_passed(struct tcpcb *tp,
6899     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
6900 {
6901 	struct bbr_sendmap *nrsm;
6902 
6903 	nrsm = rsm;
6904 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
6905 	    bbr_head, r_tnext) {
6906 		if (nrsm == rsm) {
6907 			/* Skip original segment he is acked */
6908 			continue;
6909 		}
6910 		if (nrsm->r_flags & BBR_ACKED) {
6911 			/* Skip ack'd segments */
6912 			continue;
6913 		}
6914 		if (nrsm->r_flags & BBR_SACK_PASSED) {
6915 			/*
6916 			 * We found one that is already marked
6917 			 * passed, we have been here before and
6918 			 * so all others below this are marked.
6919 			 */
6920 			break;
6921 		}
6922 		BBR_STAT_INC(bbr_sack_passed);
6923 		nrsm->r_flags |= BBR_SACK_PASSED;
6924 		if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
6925 		    bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
6926 			bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
6927 			bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
6928 			nrsm->r_flags |= BBR_MARKED_LOST;
6929 		}
6930 		nrsm->r_flags &= ~BBR_WAS_SACKPASS;
6931 	}
6932 }
6933 
6934 /*
6935  * Returns the number of bytes that were
6936  * newly ack'd by sack blocks.
6937  */
6938 static uint32_t
bbr_proc_sack_blk(struct tcpcb * tp,struct tcp_bbr * bbr,struct sackblk * sack,struct tcpopt * to,struct bbr_sendmap ** prsm,uint32_t cts)6939 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
6940     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
6941 {
6942 	int32_t times = 0;
6943 	uint32_t start, end, changed = 0;
6944 	struct bbr_sendmap *rsm, *nrsm;
6945 	int32_t used_ref = 1;
6946 	uint8_t went_back = 0, went_fwd = 0;
6947 
6948 	start = sack->start;
6949 	end = sack->end;
6950 	rsm = *prsm;
6951 	if (rsm == NULL)
6952 		used_ref = 0;
6953 
6954 	/* Do we locate the block behind where we last were? */
6955 	if (rsm && SEQ_LT(start, rsm->r_start)) {
6956 		went_back = 1;
6957 		TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
6958 			if (SEQ_GEQ(start, rsm->r_start) &&
6959 			    SEQ_LT(start, rsm->r_end)) {
6960 				goto do_rest_ofb;
6961 			}
6962 		}
6963 	}
6964 start_at_beginning:
6965 	went_fwd = 1;
6966 	/*
6967 	 * Ok lets locate the block where this guy is fwd from rsm (if its
6968 	 * set)
6969 	 */
6970 	TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
6971 		if (SEQ_GEQ(start, rsm->r_start) &&
6972 		    SEQ_LT(start, rsm->r_end)) {
6973 			break;
6974 		}
6975 	}
6976 do_rest_ofb:
6977 	if (rsm == NULL) {
6978 		/*
6979 		 * This happens when we get duplicate sack blocks with the
6980 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
6981 		 * will not change there location so we would just start at
6982 		 * the end of the first one and get lost.
6983 		 */
6984 		if (tp->t_flags & TF_SENTFIN) {
6985 			/*
6986 			 * Check to see if we have not logged the FIN that
6987 			 * went out.
6988 			 */
6989 			nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
6990 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
6991 				/*
6992 				 * Ok we did not get the FIN logged.
6993 				 */
6994 				nrsm->r_end++;
6995 				rsm = nrsm;
6996 				goto do_rest_ofb;
6997 			}
6998 		}
6999 		if (times == 1) {
7000 #ifdef BBR_INVARIANTS
7001 			panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7002 			    tp, bbr, sack, to, prsm);
7003 #else
7004 			goto out;
7005 #endif
7006 		}
7007 		times++;
7008 		BBR_STAT_INC(bbr_sack_proc_restart);
7009 		rsm = NULL;
7010 		goto start_at_beginning;
7011 	}
7012 	/* Ok we have an ACK for some piece of rsm */
7013 	if (rsm->r_start != start) {
7014 		/*
7015 		 * Need to split this in two pieces the before and after.
7016 		 */
7017 		if (bbr_sack_mergable(rsm, start, end))
7018 			nrsm = bbr_alloc_full_limit(bbr);
7019 		else
7020 			nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7021 		if (nrsm == NULL) {
7022 			/* We could not allocate ignore the sack */
7023 			struct sackblk blk;
7024 
7025 			blk.start = start;
7026 			blk.end = end;
7027 			sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7028 			goto out;
7029 		}
7030 		bbr_clone_rsm(bbr, nrsm, rsm, start);
7031 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7032 		if (rsm->r_in_tmap) {
7033 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7034 			nrsm->r_in_tmap = 1;
7035 		}
7036 		rsm->r_flags &= (~BBR_HAS_FIN);
7037 		rsm = nrsm;
7038 	}
7039 	if (SEQ_GEQ(end, rsm->r_end)) {
7040 		/*
7041 		 * The end of this block is either beyond this guy or right
7042 		 * at this guy.
7043 		 */
7044 		if ((rsm->r_flags & BBR_ACKED) == 0) {
7045 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7046 			changed += (rsm->r_end - rsm->r_start);
7047 			bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7048 			bbr_log_sack_passed(tp, bbr, rsm);
7049 			if (rsm->r_flags & BBR_MARKED_LOST) {
7050 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7051 			}
7052 			/* Is Reordering occuring? */
7053 			if (rsm->r_flags & BBR_SACK_PASSED) {
7054 				BBR_STAT_INC(bbr_reorder_seen);
7055 				bbr->r_ctl.rc_reorder_ts = cts;
7056 				if (rsm->r_flags & BBR_MARKED_LOST) {
7057 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7058 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7059 						/* LT sampling also needs adjustment */
7060 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7061 				}
7062 			}
7063 			rsm->r_flags |= BBR_ACKED;
7064 			rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7065 			if (rsm->r_in_tmap) {
7066 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7067 				rsm->r_in_tmap = 0;
7068 			}
7069 		}
7070 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7071 		if (end == rsm->r_end) {
7072 			/* This block only - done */
7073 			goto out;
7074 		}
7075 		/* There is more not coverend by this rsm move on */
7076 		start = rsm->r_end;
7077 		nrsm = TAILQ_NEXT(rsm, r_next);
7078 		rsm = nrsm;
7079 		times = 0;
7080 		goto do_rest_ofb;
7081 	}
7082 	if (rsm->r_flags & BBR_ACKED) {
7083 		/* Been here done that */
7084 		goto out;
7085 	}
7086 	/* Ok we need to split off this one at the tail */
7087 	if (bbr_sack_mergable(rsm, start, end))
7088 		nrsm = bbr_alloc_full_limit(bbr);
7089 	else
7090 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7091 	if (nrsm == NULL) {
7092 		/* failed XXXrrs what can we do but loose the sack info? */
7093 		struct sackblk blk;
7094 
7095 		blk.start = start;
7096 		blk.end = end;
7097 		sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7098 		goto out;
7099 	}
7100 	/* Clone it */
7101 	bbr_clone_rsm(bbr, nrsm, rsm, end);
7102 	/* The sack block does not cover this guy fully */
7103 	rsm->r_flags &= (~BBR_HAS_FIN);
7104 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7105 	if (rsm->r_in_tmap) {
7106 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7107 		nrsm->r_in_tmap = 1;
7108 	}
7109 	nrsm->r_dupack = 0;
7110 	bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7111 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7112 	changed += (rsm->r_end - rsm->r_start);
7113 	bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7114 	bbr_log_sack_passed(tp, bbr, rsm);
7115 	/* Is Reordering occuring? */
7116 	if (rsm->r_flags & BBR_MARKED_LOST) {
7117 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7118 	}
7119 	if (rsm->r_flags & BBR_SACK_PASSED) {
7120 		BBR_STAT_INC(bbr_reorder_seen);
7121 		bbr->r_ctl.rc_reorder_ts = cts;
7122 		if (rsm->r_flags & BBR_MARKED_LOST) {
7123 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7124 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7125 				/* LT sampling also needs adjustment */
7126 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7127 		}
7128 	}
7129 	rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7130 	rsm->r_flags |= BBR_ACKED;
7131 	if (rsm->r_in_tmap) {
7132 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7133 		rsm->r_in_tmap = 0;
7134 	}
7135 out:
7136 	if (rsm && (rsm->r_flags & BBR_ACKED)) {
7137 		/*
7138 		 * Now can we merge this newly acked
7139 		 * block with either the previous or
7140 		 * next block?
7141 		 */
7142 		nrsm = TAILQ_NEXT(rsm, r_next);
7143 		if (nrsm &&
7144 		    (nrsm->r_flags & BBR_ACKED)) {
7145 			/* yep this and next can be merged */
7146 			rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7147 		}
7148 		/* Now what about the previous? */
7149 		nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7150 		if (nrsm &&
7151 		    (nrsm->r_flags & BBR_ACKED)) {
7152 			/* yep the previous and this can be merged */
7153 			rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7154 		}
7155 	}
7156 	if (used_ref == 0) {
7157 		BBR_STAT_INC(bbr_sack_proc_all);
7158 	} else {
7159 		BBR_STAT_INC(bbr_sack_proc_short);
7160 	}
7161 	if (went_fwd && went_back) {
7162 		BBR_STAT_INC(bbr_sack_search_both);
7163 	} else if (went_fwd) {
7164 		BBR_STAT_INC(bbr_sack_search_fwd);
7165 	} else if (went_back) {
7166 		BBR_STAT_INC(bbr_sack_search_back);
7167 	}
7168 	/* Save off where the next seq is */
7169 	if (rsm)
7170 		bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7171 	else
7172 		bbr->r_ctl.rc_sacklast = NULL;
7173 	*prsm = rsm;
7174 	return (changed);
7175 }
7176 
7177 static void inline
bbr_peer_reneges(struct tcp_bbr * bbr,struct bbr_sendmap * rsm,tcp_seq th_ack)7178 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7179 {
7180 	struct bbr_sendmap *tmap;
7181 
7182 	BBR_STAT_INC(bbr_reneges_seen);
7183 	tmap = NULL;
7184 	while (rsm && (rsm->r_flags & BBR_ACKED)) {
7185 		/* Its no longer sacked, mark it so */
7186 		uint32_t oflags;
7187 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7188 #ifdef BBR_INVARIANTS
7189 		if (rsm->r_in_tmap) {
7190 			panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7191 			    bbr, rsm, rsm->r_flags);
7192 		}
7193 #endif
7194 		oflags = rsm->r_flags;
7195 		if (rsm->r_flags & BBR_MARKED_LOST) {
7196 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7197 			bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7198 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7199 				/* LT sampling also needs adjustment */
7200 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7201 		}
7202 		rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7203 		rsm->r_flags |= BBR_WAS_RENEGED;
7204 		rsm->r_flags |= BBR_RXT_CLEARED;
7205 		bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7206 		/* Rebuild it into our tmap */
7207 		if (tmap == NULL) {
7208 			TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7209 			tmap = rsm;
7210 		} else {
7211 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7212 			tmap = rsm;
7213 		}
7214 		tmap->r_in_tmap = 1;
7215 		/*
7216 		 * XXXrrs Delivered? Should we do anything here?
7217 		 *
7218 		 * Of course we don't on a rxt timeout so maybe its ok that
7219 		 * we don't?
7220 		 *
7221 		 * For now lets not.
7222 		 */
7223 		rsm = TAILQ_NEXT(rsm, r_next);
7224 	}
7225 	/*
7226 	 * Now lets possibly clear the sack filter so we start recognizing
7227 	 * sacks that cover this area.
7228 	 */
7229 	sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7230 }
7231 
7232 static void
bbr_log_syn(struct tcpcb * tp,struct tcpopt * to)7233 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7234 {
7235 	struct tcp_bbr *bbr;
7236 	struct bbr_sendmap *rsm;
7237 	uint32_t cts;
7238 
7239 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7240 	cts = bbr->r_ctl.rc_rcvtime;
7241 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7242 	if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7243 		if ((rsm->r_end - rsm->r_start) <= 1) {
7244 			/* Log out the SYN completely */
7245 			bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7246 			rsm->r_rtr_bytes = 0;
7247 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7248 			if (rsm->r_in_tmap) {
7249 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7250 				rsm->r_in_tmap = 0;
7251 			}
7252 			if (bbr->r_ctl.rc_next == rsm) {
7253 				/* scoot along the marker */
7254 				bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7255 			}
7256 			if (to != NULL)
7257 				bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7258 			bbr_free(bbr, rsm);
7259 		} else {
7260 			/* There is more (Fast open)? strip out SYN. */
7261 			rsm->r_flags &= ~BBR_HAS_SYN;
7262 			rsm->r_start++;
7263 		}
7264 	}
7265 }
7266 
7267 /*
7268  * Returns the number of bytes that were
7269  * acknowledged by SACK blocks.
7270  */
7271 
7272 static uint32_t
bbr_log_ack(struct tcpcb * tp,struct tcpopt * to,struct tcphdr * th,uint32_t * prev_acked)7273 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7274     uint32_t *prev_acked)
7275 {
7276 	uint32_t changed, last_seq, entered_recovery = 0;
7277 	struct tcp_bbr *bbr;
7278 	struct bbr_sendmap *rsm;
7279 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7280 	register uint32_t th_ack;
7281 	int32_t i, j, k, new_sb, num_sack_blks = 0;
7282 	uint32_t cts, acked, ack_point, sack_changed = 0;
7283 	uint32_t p_maxseg, maxseg, p_acked = 0;
7284 
7285 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7286 	if (tcp_get_flags(th) & TH_RST) {
7287 		/* We don't log resets */
7288 		return (0);
7289 	}
7290 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7291 	cts = bbr->r_ctl.rc_rcvtime;
7292 
7293 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7294 	changed = 0;
7295 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7296 	p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7297 	th_ack = th->th_ack;
7298 	if (SEQ_GT(th_ack, tp->snd_una)) {
7299 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7300 		bbr->rc_tp->t_acktime = ticks;
7301 	}
7302 	if (SEQ_LEQ(th_ack, tp->snd_una)) {
7303 		/* Only sent here for sack processing */
7304 		goto proc_sack;
7305 	}
7306 	if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7307 		changed = th_ack - rsm->r_start;
7308 	} else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7309 		/*
7310 		 * For the SYN incoming case we will not have called
7311 		 * tcp_output for the sending of the SYN, so there will be
7312 		 * no map. All other cases should probably be a panic.
7313 		 */
7314 		if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7315 			/*
7316 			 * We have a timestamp that can be used to generate
7317 			 * an initial RTT.
7318 			 */
7319 			uint32_t ts, now, rtt;
7320 
7321 			ts = bbr_ts_convert(to->to_tsecr);
7322 			now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7323 			rtt = now - ts;
7324 			if (rtt < 1)
7325 				rtt = 1;
7326 			bbr_log_type_bbrrttprop(bbr, rtt,
7327 						tp->iss, 0, cts,
7328 						BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7329 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7330 			changed = 1;
7331 			bbr->r_wanted_output = 1;
7332 			goto out;
7333 		}
7334 		goto proc_sack;
7335 	} else if (rsm == NULL) {
7336 		goto out;
7337 	}
7338 	if (changed) {
7339 		/*
7340 		 * The ACK point is advancing to th_ack, we must drop off
7341 		 * the packets in the rack log and calculate any eligble
7342 		 * RTT's.
7343 		 */
7344 		bbr->r_wanted_output = 1;
7345 more:
7346 		if (rsm == NULL) {
7347 			if (tp->t_flags & TF_SENTFIN) {
7348 				/* if we send a FIN we will not hav a map */
7349 				goto proc_sack;
7350 			}
7351 #ifdef BBR_INVARIANTS
7352 			panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7353 			    tp,
7354 			    th, tp->t_state, bbr,
7355 			    tp->snd_una, tp->snd_max, changed);
7356 #endif
7357 			goto proc_sack;
7358 		}
7359 	}
7360 	if (SEQ_LT(th_ack, rsm->r_start)) {
7361 		/* Huh map is missing this */
7362 #ifdef BBR_INVARIANTS
7363 		printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7364 		    rsm->r_start,
7365 		    th_ack, tp->t_state,
7366 		    bbr->r_state, bbr);
7367 		panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7368 #endif
7369 		goto proc_sack;
7370 	} else if (th_ack == rsm->r_start) {
7371 		/* None here to ack */
7372 		goto proc_sack;
7373 	}
7374 	/*
7375 	 * Clear the dup ack counter, it will
7376 	 * either be freed or if there is some
7377 	 * remaining we need to start it at zero.
7378 	 */
7379 	rsm->r_dupack = 0;
7380 	/* Now do we consume the whole thing? */
7381 	if (SEQ_GEQ(th_ack, rsm->r_end)) {
7382 		/* Its all consumed. */
7383 		uint32_t left;
7384 
7385 		if (rsm->r_flags & BBR_ACKED) {
7386 			/*
7387 			 * It was acked on the scoreboard -- remove it from
7388 			 * total
7389 			 */
7390 			p_acked += (rsm->r_end - rsm->r_start);
7391 			bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7392 			if (bbr->r_ctl.rc_sacked == 0)
7393 				bbr->r_ctl.rc_sacklast = NULL;
7394 		} else {
7395 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7396 			if (rsm->r_flags & BBR_MARKED_LOST) {
7397 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7398 			}
7399 			if (rsm->r_flags & BBR_SACK_PASSED) {
7400 				/*
7401 				 * There are acked segments ACKED on the
7402 				 * scoreboard further up. We are seeing
7403 				 * reordering.
7404 				 */
7405 				BBR_STAT_INC(bbr_reorder_seen);
7406 				bbr->r_ctl.rc_reorder_ts = cts;
7407 				if (rsm->r_flags & BBR_MARKED_LOST) {
7408 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7409 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7410 						/* LT sampling also needs adjustment */
7411 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7412 				}
7413 			}
7414 			rsm->r_flags &= ~BBR_MARKED_LOST;
7415 		}
7416 		bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7417 		rsm->r_rtr_bytes = 0;
7418 		TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7419 		if (rsm->r_in_tmap) {
7420 			TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7421 			rsm->r_in_tmap = 0;
7422 		}
7423 		if (bbr->r_ctl.rc_next == rsm) {
7424 			/* scoot along the marker */
7425 			bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7426 		}
7427 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7428 		/* Adjust the packet counts */
7429 		left = th_ack - rsm->r_end;
7430 		/* Free back to zone */
7431 		bbr_free(bbr, rsm);
7432 		if (left) {
7433 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7434 			goto more;
7435 		}
7436 		goto proc_sack;
7437 	}
7438 	if (rsm->r_flags & BBR_ACKED) {
7439 		/*
7440 		 * It was acked on the scoreboard -- remove it from total
7441 		 * for the part being cum-acked.
7442 		 */
7443 		p_acked += (rsm->r_end - rsm->r_start);
7444 		bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7445 		if (bbr->r_ctl.rc_sacked == 0)
7446 			bbr->r_ctl.rc_sacklast = NULL;
7447 	} else {
7448 		/*
7449 		 * It was acked up to th_ack point for the first time
7450 		 */
7451 		struct bbr_sendmap lrsm;
7452 
7453 		memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7454 		lrsm.r_end = th_ack;
7455 		bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7456 	}
7457 	if ((rsm->r_flags & BBR_MARKED_LOST) &&
7458 	    ((rsm->r_flags & BBR_ACKED) == 0)) {
7459 		/*
7460 		 * It was marked lost and partly ack'd now
7461 		 * for the first time. We lower the rc_lost_bytes
7462 		 * and still leave it MARKED.
7463 		 */
7464 		bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7465 	}
7466 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7467 	bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7468 	rsm->r_rtr_bytes = 0;
7469 	/* adjust packet count */
7470 	rsm->r_start = th_ack;
7471 proc_sack:
7472 	/* Check for reneging */
7473 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7474 	if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7475 		/*
7476 		 * The peer has moved snd_una up to the edge of this send,
7477 		 * i.e. one that it had previously acked. The only way that
7478 		 * can be true if the peer threw away data (space issues)
7479 		 * that it had previously sacked (else it would have given
7480 		 * us snd_una up to (rsm->r_end). We need to undo the acked
7481 		 * markings here.
7482 		 *
7483 		 * Note we have to look to make sure th_ack is our
7484 		 * rsm->r_start in case we get an old ack where th_ack is
7485 		 * behind snd_una.
7486 		 */
7487 		bbr_peer_reneges(bbr, rsm, th->th_ack);
7488 	}
7489 	if ((to->to_flags & TOF_SACK) == 0) {
7490 		/* We are done nothing left to log */
7491 		goto out;
7492 	}
7493 	rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7494 	if (rsm) {
7495 		last_seq = rsm->r_end;
7496 	} else {
7497 		last_seq = tp->snd_max;
7498 	}
7499 	/* Sack block processing */
7500 	if (SEQ_GT(th_ack, tp->snd_una))
7501 		ack_point = th_ack;
7502 	else
7503 		ack_point = tp->snd_una;
7504 	for (i = 0; i < to->to_nsacks; i++) {
7505 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
7506 		    &sack, sizeof(sack));
7507 		sack.start = ntohl(sack.start);
7508 		sack.end = ntohl(sack.end);
7509 		if (SEQ_GT(sack.end, sack.start) &&
7510 		    SEQ_GT(sack.start, ack_point) &&
7511 		    SEQ_LT(sack.start, tp->snd_max) &&
7512 		    SEQ_GT(sack.end, ack_point) &&
7513 		    SEQ_LEQ(sack.end, tp->snd_max)) {
7514 			if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7515 			    (SEQ_LT(sack.end, last_seq)) &&
7516 			    ((sack.end - sack.start) < (p_maxseg / 8))) {
7517 				/*
7518 				 * Not the last piece and its smaller than
7519 				 * 1/8th of a p_maxseg. We ignore this.
7520 				 */
7521 				BBR_STAT_INC(bbr_runt_sacks);
7522 				continue;
7523 			}
7524 			sack_blocks[num_sack_blks] = sack;
7525 			num_sack_blks++;
7526 		} else if (SEQ_LEQ(sack.start, th_ack) &&
7527 		    SEQ_LEQ(sack.end, th_ack)) {
7528 			/*
7529 			 * Its a D-SACK block.
7530 			 */
7531 			tcp_record_dsack(tp, sack.start, sack.end, 0);
7532 		}
7533 	}
7534 	if (num_sack_blks == 0)
7535 		goto out;
7536 	/*
7537 	 * Sort the SACK blocks so we can update the rack scoreboard with
7538 	 * just one pass.
7539 	 */
7540 	new_sb = sack_filter_blks(&bbr->r_ctl.bbr_sf, sack_blocks,
7541 				  num_sack_blks, th->th_ack);
7542 	ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7543 	BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7544 	BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7545 	num_sack_blks = new_sb;
7546 	if (num_sack_blks < 2) {
7547 		goto do_sack_work;
7548 	}
7549 	/* Sort the sacks */
7550 	for (i = 0; i < num_sack_blks; i++) {
7551 		for (j = i + 1; j < num_sack_blks; j++) {
7552 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7553 				sack = sack_blocks[i];
7554 				sack_blocks[i] = sack_blocks[j];
7555 				sack_blocks[j] = sack;
7556 			}
7557 		}
7558 	}
7559 	/*
7560 	 * Now are any of the sack block ends the same (yes some
7561 	 * implememtations send these)?
7562 	 */
7563 again:
7564 	if (num_sack_blks > 1) {
7565 		for (i = 0; i < num_sack_blks; i++) {
7566 			for (j = i + 1; j < num_sack_blks; j++) {
7567 				if (sack_blocks[i].end == sack_blocks[j].end) {
7568 					/*
7569 					 * Ok these two have the same end we
7570 					 * want the smallest end and then
7571 					 * throw away the larger and start
7572 					 * again.
7573 					 */
7574 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7575 						/*
7576 						 * The second block covers
7577 						 * more area use that
7578 						 */
7579 						sack_blocks[i].start = sack_blocks[j].start;
7580 					}
7581 					/*
7582 					 * Now collapse out the dup-sack and
7583 					 * lower the count
7584 					 */
7585 					for (k = (j + 1); k < num_sack_blks; k++) {
7586 						sack_blocks[j].start = sack_blocks[k].start;
7587 						sack_blocks[j].end = sack_blocks[k].end;
7588 						j++;
7589 					}
7590 					num_sack_blks--;
7591 					goto again;
7592 				}
7593 			}
7594 		}
7595 	}
7596 do_sack_work:
7597 	rsm = bbr->r_ctl.rc_sacklast;
7598 	for (i = 0; i < num_sack_blks; i++) {
7599 		acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7600 		if (acked) {
7601 			bbr->r_wanted_output = 1;
7602 			changed += acked;
7603 			sack_changed += acked;
7604 		}
7605 	}
7606 out:
7607 	*prev_acked = p_acked;
7608 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7609 		/*
7610 		 * Ok we have a high probability that we need to go in to
7611 		 * recovery since we have data sack'd
7612 		 */
7613 		struct bbr_sendmap *rsm;
7614 
7615 		rsm = bbr_check_recovery_mode(tp, bbr, cts);
7616 		if (rsm) {
7617 			/* Enter recovery */
7618 			entered_recovery = 1;
7619 			bbr->r_wanted_output = 1;
7620 			/*
7621 			 * When we enter recovery we need to assure we send
7622 			 * one packet.
7623 			 */
7624 			if (bbr->r_ctl.rc_resend == NULL) {
7625 				bbr->r_ctl.rc_resend = rsm;
7626 			}
7627 		}
7628 	}
7629 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7630 		/*
7631 		 * See if we need to rack-retransmit anything if so set it
7632 		 * up as the thing to resend assuming something else is not
7633 		 * already in that position.
7634 		 */
7635 		if (bbr->r_ctl.rc_resend == NULL) {
7636 			bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7637 		}
7638 	}
7639 	/*
7640 	 * We return the amount that changed via sack, this is used by the
7641 	 * ack-received code to augment what was changed between th_ack <->
7642 	 * snd_una.
7643 	 */
7644 	return (sack_changed);
7645 }
7646 
7647 static void
bbr_strike_dupack(struct tcp_bbr * bbr)7648 bbr_strike_dupack(struct tcp_bbr *bbr)
7649 {
7650 	struct bbr_sendmap *rsm;
7651 
7652 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7653 	if (rsm && (rsm->r_dupack < 0xff)) {
7654 		rsm->r_dupack++;
7655 		if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7656 			bbr->r_wanted_output = 1;
7657 	}
7658 }
7659 
7660 /*
7661  * Return value of 1, we do not need to call bbr_process_data().
7662  * return value of 0, bbr_process_data can be called.
7663  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7664  * its unlocked and probably unsafe to touch the TCB.
7665  */
7666 static int
bbr_process_ack(struct mbuf * m,struct tcphdr * th,struct socket * so,struct tcpcb * tp,struct tcpopt * to,uint32_t tiwin,int32_t tlen,int32_t * ofia,int32_t thflags,int32_t * ret_val)7667 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7668     struct tcpcb *tp, struct tcpopt *to,
7669     uint32_t tiwin, int32_t tlen,
7670     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7671 {
7672 	int32_t ourfinisacked = 0;
7673 	int32_t acked_amount;
7674 	uint16_t nsegs;
7675 	int32_t acked;
7676 	uint32_t lost, sack_changed = 0;
7677 	struct mbuf *mfree;
7678 	struct tcp_bbr *bbr;
7679 	uint32_t prev_acked = 0;
7680 
7681 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7682 	lost = bbr->r_ctl.rc_lost;
7683 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
7684 	if (SEQ_GEQ(tp->snd_una, tp->iss + (65535 << tp->snd_scale))) {
7685 		/* Checking SEG.ACK against ISS is definitely redundant. */
7686 		tp->t_flags2 |= TF2_NO_ISS_CHECK;
7687 	}
7688 	if (!V_tcp_insecure_ack) {
7689 		tcp_seq seq_min;
7690 		bool ghost_ack_check;
7691 
7692 		if (tp->t_flags2 & TF2_NO_ISS_CHECK) {
7693 			/* Check for too old ACKs (RFC 5961, Section 5.2). */
7694 			seq_min = tp->snd_una - tp->max_sndwnd;
7695 			ghost_ack_check = false;
7696 		} else {
7697 			if (SEQ_GT(tp->iss + 1, tp->snd_una - tp->max_sndwnd)) {
7698 				/* Checking for ghost ACKs is stricter. */
7699 				seq_min = tp->iss + 1;
7700 				ghost_ack_check = true;
7701 			} else {
7702 				/*
7703 				 * Checking for too old ACKs (RFC 5961,
7704 				 * Section 5.2) is stricter.
7705 				 */
7706 				seq_min = tp->snd_una - tp->max_sndwnd;
7707 				ghost_ack_check = false;
7708 			}
7709 		}
7710 		if (SEQ_LT(th->th_ack, seq_min)) {
7711 			if (ghost_ack_check)
7712 				TCPSTAT_INC(tcps_rcvghostack);
7713 			else
7714 				TCPSTAT_INC(tcps_rcvacktooold);
7715 			/* Send challenge ACK. */
7716 			ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7717 			bbr->r_wanted_output = 1;
7718 			return (1);
7719 		}
7720 	}
7721 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
7722 		ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7723 		bbr->r_wanted_output = 1;
7724 		return (1);
7725 	}
7726 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7727 		/* Process the ack */
7728 		if (bbr->rc_in_persist)
7729 			tp->t_rxtshift = 0;
7730 		if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7731 			bbr_strike_dupack(bbr);
7732 		sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7733 	}
7734 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7735 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7736 		/*
7737 		 * Old ack, behind the last one rcv'd or a duplicate ack
7738 		 * with SACK info.
7739 		 */
7740 		if (th->th_ack == tp->snd_una) {
7741 			bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7742 			if (bbr->r_state == TCPS_SYN_SENT) {
7743 				/*
7744 				 * Special case on where we sent SYN. When
7745 				 * the SYN-ACK is processed in syn_sent
7746 				 * state it bumps the snd_una. This causes
7747 				 * us to hit here even though we did ack 1
7748 				 * byte.
7749 				 *
7750 				 * Go through the nothing left case so we
7751 				 * send data.
7752 				 */
7753 				goto nothing_left;
7754 			}
7755 		}
7756 		return (0);
7757 	}
7758 	/*
7759 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7760 	 * something we sent.
7761 	 */
7762 	if (tp->t_flags & TF_NEEDSYN) {
7763 		/*
7764 		 * T/TCP: Connection was half-synchronized, and our SYN has
7765 		 * been ACK'd (so connection is now fully synchronized).  Go
7766 		 * to non-starred state, increment snd_una for ACK of SYN,
7767 		 * and check if we can do window scaling.
7768 		 */
7769 		tp->t_flags &= ~TF_NEEDSYN;
7770 		tp->snd_una++;
7771 		/* Do window scaling? */
7772 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7773 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7774 			tp->rcv_scale = tp->request_r_scale;
7775 			/* Send window already scaled. */
7776 		}
7777 	}
7778 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7779 
7780 	acked = BYTES_THIS_ACK(tp, th);
7781 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7782 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
7783 
7784 	/*
7785 	 * If we just performed our first retransmit, and the ACK arrives
7786 	 * within our recovery window, then it was a mistake to do the
7787 	 * retransmit in the first place.  Recover our original cwnd and
7788 	 * ssthresh, and proceed to transmit where we left off.
7789 	 */
7790 	if (tp->t_flags & TF_PREVVALID) {
7791 		tp->t_flags &= ~TF_PREVVALID;
7792 		if (tp->t_rxtshift == 1 &&
7793 		    (int)(ticks - tp->t_badrxtwin) < 0)
7794 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7795 	}
7796 	SOCKBUF_LOCK(&so->so_snd);
7797 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
7798 	tp->snd_wnd -= acked_amount;
7799 	mfree = sbcut_locked(&so->so_snd, acked_amount);
7800 	/* NB: sowwakeup_locked() does an implicit unlock. */
7801 	sowwakeup_locked(so);
7802 	m_freem(mfree);
7803 	if (SEQ_GT(th->th_ack, tp->snd_una)) {
7804 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
7805 	}
7806 	tp->snd_una = th->th_ack;
7807 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
7808 	if (IN_RECOVERY(tp->t_flags)) {
7809 		if (SEQ_LT(th->th_ack, tp->snd_recover) &&
7810 		    (SEQ_LT(th->th_ack, tp->snd_max))) {
7811 			tcp_bbr_partialack(tp);
7812 		} else {
7813 			bbr_post_recovery(tp);
7814 		}
7815 	}
7816 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
7817 		tp->snd_recover = tp->snd_una;
7818 	}
7819 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
7820 		tp->snd_nxt = tp->snd_max;
7821 	}
7822 	if (tp->snd_una == tp->snd_max) {
7823 		/* Nothing left outstanding */
7824 nothing_left:
7825 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
7826 		if (sbavail(&so->so_snd) == 0)
7827 			bbr->rc_tp->t_acktime = 0;
7828 		if ((sbused(&so->so_snd) == 0) &&
7829 		    (tp->t_flags & TF_SENTFIN)) {
7830 			ourfinisacked = 1;
7831 		}
7832 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
7833 		if (bbr->rc_in_persist == 0) {
7834 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
7835 		}
7836 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
7837 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
7838 		/*
7839 		 * We invalidate the last ack here since we
7840 		 * don't want to transfer forward the time
7841 		 * for our sum's calculations.
7842 		 */
7843 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
7844 		    (sbavail(&so->so_snd) == 0) &&
7845 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
7846 			/*
7847 			 * The socket was gone and the peer sent data, time
7848 			 * to reset him.
7849 			 */
7850 			*ret_val = 1;
7851 			tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
7852 			/* tcp_close will kill the inp pre-log the Reset */
7853 			tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
7854 			tp = tcp_close(tp);
7855 			ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
7856 			BBR_STAT_INC(bbr_dropped_af_data);
7857 			return (1);
7858 		}
7859 		/* Set need output so persist might get set */
7860 		bbr->r_wanted_output = 1;
7861 	}
7862 	if (ofia)
7863 		*ofia = ourfinisacked;
7864 	return (0);
7865 }
7866 
7867 static void
bbr_enter_persist(struct tcpcb * tp,struct tcp_bbr * bbr,uint32_t cts,int32_t line)7868 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7869 {
7870 	if (bbr->rc_in_persist == 0) {
7871 		bbr_timer_cancel(bbr, __LINE__, cts);
7872 		bbr->r_ctl.rc_last_delay_val = 0;
7873 		tp->t_rxtshift = 0;
7874 		bbr->rc_in_persist = 1;
7875 		bbr->r_ctl.rc_went_idle_time = cts;
7876 		/* We should be capped when rw went to 0 but just in case */
7877 		bbr_log_type_pesist(bbr, cts, 0, line, 1);
7878 		/* Time freezes for the state, so do the accounting now */
7879 		if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
7880 			uint32_t time_in;
7881 
7882 			time_in = cts - bbr->r_ctl.rc_bbr_state_time;
7883 			if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7884 				int32_t idx;
7885 
7886 				idx = bbr_state_val(bbr);
7887 				counter_u64_add(bbr_state_time[(idx + 5)], time_in);
7888 			} else {
7889 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
7890 			}
7891 		}
7892 		bbr->r_ctl.rc_bbr_state_time = cts;
7893 	}
7894 }
7895 
7896 static void
bbr_restart_after_idle(struct tcp_bbr * bbr,uint32_t cts,uint32_t idle_time)7897 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
7898 {
7899 	/*
7900 	 * Note that if idle time does not exceed our
7901 	 * threshold, we do nothing continuing the state
7902 	 * transitions we were last walking through.
7903 	 */
7904 	if (idle_time >= bbr_idle_restart_threshold) {
7905 		if (bbr->rc_use_idle_restart) {
7906 			bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
7907 			/*
7908 			 * Set our target using BBR_UNIT, so
7909 			 * we increase at a dramatic rate but
7910 			 * we stop when we get the pipe
7911 			 * full again for our current b/w estimate.
7912 			 */
7913 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
7914 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
7915 			bbr_set_state_target(bbr, __LINE__);
7916 			/* Now setup our gains to ramp up */
7917 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
7918 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
7919 			bbr_log_type_statechange(bbr, cts, __LINE__);
7920 		} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7921 			bbr_substate_change(bbr, cts, __LINE__, 1);
7922 		}
7923 	}
7924 }
7925 
7926 static void
bbr_exit_persist(struct tcpcb * tp,struct tcp_bbr * bbr,uint32_t cts,int32_t line)7927 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7928 {
7929 	uint32_t idle_time;
7930 
7931 	if (bbr->rc_in_persist == 0)
7932 		return;
7933 	idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
7934 	bbr->rc_in_persist = 0;
7935 	bbr->rc_hit_state_1 = 0;
7936 	bbr->r_ctl.rc_del_time = cts;
7937 	/*
7938 	 * We invalidate the last ack here since we
7939 	 * don't want to transfer forward the time
7940 	 * for our sum's calculations.
7941 	 */
7942 	if (tcp_in_hpts(bbr->rc_tp)) {
7943 		tcp_hpts_remove(bbr->rc_tp);
7944 		bbr->rc_timer_first = 0;
7945 		bbr->r_ctl.rc_hpts_flags = 0;
7946 		bbr->r_ctl.rc_last_delay_val = 0;
7947 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
7948 		bbr->r_agg_early_set = 0;
7949 		bbr->r_ctl.rc_agg_early = 0;
7950 	}
7951 	bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
7952 	if (idle_time >= bbr_rtt_probe_time) {
7953 		/*
7954 		 * This qualifies as a RTT_PROBE session since we drop the
7955 		 * data outstanding to nothing and waited more than
7956 		 * bbr_rtt_probe_time.
7957 		 */
7958 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
7959 		bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
7960 	}
7961 	tp->t_rxtshift = 0;
7962 	/*
7963 	 * If in probeBW and we have persisted more than an RTT lets do
7964 	 * special handling.
7965 	 */
7966 	/* Force a time based epoch */
7967 	bbr_set_epoch(bbr, cts, __LINE__);
7968 	/*
7969 	 * Setup the lost so we don't count anything against the guy
7970 	 * we have been stuck with during persists.
7971 	 */
7972 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
7973 	/* Time un-freezes for the state */
7974 	bbr->r_ctl.rc_bbr_state_time = cts;
7975 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
7976 	    (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
7977 		/*
7978 		 * If we are going back to probe-bw
7979 		 * or probe_rtt, we may need to possibly
7980 		 * do a fast restart.
7981 		 */
7982 		bbr_restart_after_idle(bbr, cts, idle_time);
7983 	}
7984 }
7985 
7986 static void
bbr_collapsed_window(struct tcp_bbr * bbr)7987 bbr_collapsed_window(struct tcp_bbr *bbr)
7988 {
7989 	/*
7990 	 * Now we must walk the
7991 	 * send map and divide the
7992 	 * ones left stranded. These
7993 	 * guys can't cause us to abort
7994 	 * the connection and are really
7995 	 * "unsent". However if a buggy
7996 	 * client actually did keep some
7997 	 * of the data i.e. collapsed the win
7998 	 * and refused to ack and then opened
7999 	 * the win and acked that data. We would
8000 	 * get into an ack war, the simplier
8001 	 * method then of just pretending we
8002 	 * did not send those segments something
8003 	 * won't work.
8004 	 */
8005 	struct bbr_sendmap *rsm, *nrsm;
8006 	tcp_seq max_seq;
8007 	uint32_t maxseg;
8008 	int can_split = 0;
8009 	int fnd = 0;
8010 
8011 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
8012 	max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
8013 	bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
8014 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
8015 		/* Find the first seq past or at maxseq */
8016 		if (rsm->r_flags & BBR_RWND_COLLAPSED)
8017 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8018 		if (SEQ_GEQ(max_seq, rsm->r_start) &&
8019 		    SEQ_GEQ(rsm->r_end, max_seq)) {
8020 			fnd = 1;
8021 			break;
8022 		}
8023 	}
8024 	bbr->rc_has_collapsed = 0;
8025 	if (!fnd) {
8026 		/* Nothing to do strange */
8027 		return;
8028 	}
8029 	/*
8030 	 * Now can we split?
8031 	 *
8032 	 * We don't want to split if splitting
8033 	 * would generate too many small segments
8034 	 * less we let an attacker fragment our
8035 	 * send_map and leave us out of memory.
8036 	 */
8037 	if ((max_seq != rsm->r_start) &&
8038 	    (max_seq != rsm->r_end)){
8039 		/* can we split? */
8040 		int res1, res2;
8041 
8042 		res1 = max_seq - rsm->r_start;
8043 		res2 = rsm->r_end - max_seq;
8044 		if ((res1 >= (maxseg/8)) &&
8045 		    (res2 >= (maxseg/8))) {
8046 			/* No small pieces here */
8047 			can_split = 1;
8048 		} else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8049 			/* We are under the limit */
8050 			can_split = 1;
8051 		}
8052 	}
8053 	/* Ok do we need to split this rsm? */
8054 	if (max_seq == rsm->r_start) {
8055 		/* It's this guy no split required */
8056 		nrsm = rsm;
8057 	} else if (max_seq == rsm->r_end) {
8058 		/* It's the next one no split required. */
8059 		nrsm = TAILQ_NEXT(rsm, r_next);
8060 		if (nrsm == NULL) {
8061 			/* Huh? */
8062 			return;
8063 		}
8064 	} else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8065 		/* yep we need to split it */
8066 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8067 		if (nrsm == NULL) {
8068 			/* failed XXXrrs what can we do mark the whole? */
8069 			nrsm = rsm;
8070 			goto no_split;
8071 		}
8072 		/* Clone it */
8073 		bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8074 		bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8075 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8076 		if (rsm->r_in_tmap) {
8077 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8078 			nrsm->r_in_tmap = 1;
8079 		}
8080 	} else {
8081 		/*
8082 		 * Split not allowed just start here just
8083 		 * use this guy.
8084 		 */
8085 		nrsm = rsm;
8086 	}
8087 no_split:
8088 	BBR_STAT_INC(bbr_collapsed_win);
8089 	/* reuse fnd as a count */
8090 	fnd = 0;
8091 	TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8092 		nrsm->r_flags |= BBR_RWND_COLLAPSED;
8093 		fnd++;
8094 		bbr->rc_has_collapsed = 1;
8095 	}
8096 	bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8097 }
8098 
8099 static void
bbr_un_collapse_window(struct tcp_bbr * bbr)8100 bbr_un_collapse_window(struct tcp_bbr *bbr)
8101 {
8102 	struct bbr_sendmap *rsm;
8103 	int cleared = 0;
8104 
8105 	TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8106 		if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8107 			/* Clear the flag */
8108 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8109 			cleared++;
8110 		} else
8111 			break;
8112 	}
8113 	bbr_log_type_rwnd_collapse(bbr,
8114 				   (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8115 	bbr->rc_has_collapsed = 0;
8116 }
8117 
8118 /*
8119  * Return value of 1, the TCB is unlocked and most
8120  * likely gone, return value of 0, the TCB is still
8121  * locked.
8122  */
8123 static int
bbr_process_data(struct mbuf * m,struct tcphdr * th,struct socket * so,struct tcpcb * tp,int32_t drop_hdrlen,int32_t tlen,uint32_t tiwin,int32_t thflags,int32_t nxt_pkt)8124 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8125     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8126     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8127 {
8128 	/*
8129 	 * Update window information. Don't look at window if no ACK: TAC's
8130 	 * send garbage on first SYN.
8131 	 */
8132 	uint16_t nsegs;
8133 	int32_t tfo_syn;
8134 	struct tcp_bbr *bbr;
8135 
8136 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8137 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8138 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8139 	if ((thflags & TH_ACK) &&
8140 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8141 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8142 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8143 		/* keep track of pure window updates */
8144 		if (tlen == 0 &&
8145 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8146 			KMOD_TCPSTAT_INC(tcps_rcvwinupd);
8147 		tp->snd_wnd = tiwin;
8148 		tp->snd_wl1 = th->th_seq;
8149 		tp->snd_wl2 = th->th_ack;
8150 		if (tp->snd_wnd > tp->max_sndwnd)
8151 			tp->max_sndwnd = tp->snd_wnd;
8152 		bbr->r_wanted_output = 1;
8153 	} else if (thflags & TH_ACK) {
8154 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8155 			tp->snd_wnd = tiwin;
8156 			tp->snd_wl1 = th->th_seq;
8157 			tp->snd_wl2 = th->th_ack;
8158 		}
8159 	}
8160 	if (tp->snd_wnd < ctf_outstanding(tp))
8161 		/* The peer collapsed its window on us */
8162 		bbr_collapsed_window(bbr);
8163  	else if (bbr->rc_has_collapsed)
8164 		bbr_un_collapse_window(bbr);
8165 	/* Was persist timer active and now we have window space? */
8166 	if ((bbr->rc_in_persist != 0) &&
8167 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8168 				bbr_minseg(bbr)))) {
8169 		/*
8170 		 * Make the rate persist at end of persist mode if idle long
8171 		 * enough
8172 		 */
8173 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8174 
8175 		/* Make sure we output to start the timer */
8176 		bbr->r_wanted_output = 1;
8177 	}
8178 	/* Do we need to enter persist? */
8179 	if ((bbr->rc_in_persist == 0) &&
8180 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8181 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8182 	    (tp->snd_max == tp->snd_una) &&
8183 	    sbavail(&so->so_snd) &&
8184 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8185 		/* No send window.. we must enter persist */
8186 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8187 	}
8188 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8189 		m_freem(m);
8190 		return (0);
8191 	}
8192 	/*
8193 	 * We don't support urgent data but
8194 	 * drag along the up just to make sure
8195 	 * if there is a stack switch no one
8196 	 * is surprised.
8197 	 */
8198 	tp->rcv_up = tp->rcv_nxt;
8199 
8200 	/*
8201 	 * Process the segment text, merging it into the TCP sequencing
8202 	 * queue, and arranging for acknowledgment of receipt if necessary.
8203 	 * This process logically involves adjusting tp->rcv_wnd as data is
8204 	 * presented to the user (this happens in tcp_usrreq.c, case
8205 	 * PRU_RCVD).  If a FIN has already been received on this connection
8206 	 * then we just ignore the text.
8207 	 */
8208 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8209 		   IS_FASTOPEN(tp->t_flags));
8210 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
8211 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8212 		tcp_seq save_start = th->th_seq;
8213 		tcp_seq save_rnxt  = tp->rcv_nxt;
8214 		int     save_tlen  = tlen;
8215 
8216 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8217 		/*
8218 		 * Insert segment which includes th into TCP reassembly
8219 		 * queue with control block tp.  Set thflags to whether
8220 		 * reassembly now includes a segment with FIN.  This handles
8221 		 * the common case inline (segment is the next to be
8222 		 * received on an established connection, and the queue is
8223 		 * empty), avoiding linkage into and removal from the queue
8224 		 * and repetition of various conversions. Set DELACK for
8225 		 * segments received in order, but ack immediately when
8226 		 * segments are out of order (so fast retransmit can work).
8227 		 */
8228 		if (th->th_seq == tp->rcv_nxt &&
8229 		    SEGQ_EMPTY(tp) &&
8230 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
8231 		    tfo_syn)) {
8232 #ifdef NETFLIX_SB_LIMITS
8233 			u_int mcnt, appended;
8234 
8235 			if (so->so_rcv.sb_shlim) {
8236 				mcnt = m_memcnt(m);
8237 				appended = 0;
8238 				if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8239 				    CFO_NOSLEEP, NULL) == false) {
8240 					counter_u64_add(tcp_sb_shlim_fails, 1);
8241 					m_freem(m);
8242 					return (0);
8243 				}
8244 			}
8245 
8246 #endif
8247 			if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8248 				bbr->bbr_segs_rcvd += max(1, nsegs);
8249 				tp->t_flags |= TF_DELACK;
8250 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8251 			} else {
8252 				bbr->r_wanted_output = 1;
8253 				tp->t_flags |= TF_ACKNOW;
8254 			}
8255 			tp->rcv_nxt += tlen;
8256 			if (tlen &&
8257 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8258 			    (tp->t_fbyte_in == 0)) {
8259 				tp->t_fbyte_in = ticks;
8260 				if (tp->t_fbyte_in == 0)
8261 					tp->t_fbyte_in = 1;
8262 				if (tp->t_fbyte_out && tp->t_fbyte_in)
8263 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8264 			}
8265 			thflags = tcp_get_flags(th) & TH_FIN;
8266 			KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8267 			KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8268 			SOCKBUF_LOCK(&so->so_rcv);
8269 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8270 				m_freem(m);
8271 			else
8272 #ifdef NETFLIX_SB_LIMITS
8273 				appended =
8274 #endif
8275 					sbappendstream_locked(&so->so_rcv, m, 0);
8276 			/* NB: sorwakeup_locked() does an implicit unlock. */
8277 			sorwakeup_locked(so);
8278 #ifdef NETFLIX_SB_LIMITS
8279 			if (so->so_rcv.sb_shlim && appended != mcnt)
8280 				counter_fo_release(so->so_rcv.sb_shlim,
8281 				    mcnt - appended);
8282 #endif
8283 
8284 		} else {
8285 			/*
8286 			 * XXX: Due to the header drop above "th" is
8287 			 * theoretically invalid by now.  Fortunately
8288 			 * m_adj() doesn't actually frees any mbufs when
8289 			 * trimming from the head.
8290 			 */
8291 			tcp_seq temp = save_start;
8292 
8293 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
8294 			tp->t_flags |= TF_ACKNOW;
8295 			if (tp->t_flags & TF_WAKESOR) {
8296 				tp->t_flags &= ~TF_WAKESOR;
8297 				/* NB: sorwakeup_locked() does an implicit unlock. */
8298 				sorwakeup_locked(so);
8299 			}
8300 		}
8301 		if ((tp->t_flags & TF_SACK_PERMIT) &&
8302 		    (save_tlen > 0) &&
8303 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
8304 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8305 				/*
8306 				 * DSACK actually handled in the fastpath
8307 				 * above.
8308 				 */
8309 				tcp_update_sack_list(tp, save_start,
8310 				    save_start + save_tlen);
8311 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8312 				if ((tp->rcv_numsacks >= 1) &&
8313 				    (tp->sackblks[0].end == save_start)) {
8314 					/*
8315 					 * Partial overlap, recorded at todrop
8316 					 * above.
8317 					 */
8318 					tcp_update_sack_list(tp,
8319 					    tp->sackblks[0].start,
8320 					    tp->sackblks[0].end);
8321 				} else {
8322 					tcp_update_dsack_list(tp, save_start,
8323 					    save_start + save_tlen);
8324 				}
8325 			} else if (tlen >= save_tlen) {
8326 				/* Update of sackblks. */
8327 				tcp_update_dsack_list(tp, save_start,
8328 				    save_start + save_tlen);
8329 			} else if (tlen > 0) {
8330 				tcp_update_dsack_list(tp, save_start,
8331 				    save_start + tlen);
8332 			}
8333 		}
8334 	} else {
8335 		m_freem(m);
8336 		thflags &= ~TH_FIN;
8337 	}
8338 
8339 	/*
8340 	 * If FIN is received ACK the FIN and let the user know that the
8341 	 * connection is closing.
8342 	 */
8343 	if (thflags & TH_FIN) {
8344 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8345 			/* The socket upcall is handled by socantrcvmore. */
8346 			socantrcvmore(so);
8347 			/*
8348 			 * If connection is half-synchronized (ie NEEDSYN
8349 			 * flag on) then delay ACK, so it may be piggybacked
8350 			 * when SYN is sent. Otherwise, since we received a
8351 			 * FIN then no more input can be expected, send ACK
8352 			 * now.
8353 			 */
8354 			if (tp->t_flags & TF_NEEDSYN) {
8355 				tp->t_flags |= TF_DELACK;
8356 				bbr_timer_cancel(bbr,
8357 				    __LINE__, bbr->r_ctl.rc_rcvtime);
8358 			} else {
8359 				tp->t_flags |= TF_ACKNOW;
8360 			}
8361 			tp->rcv_nxt++;
8362 		}
8363 		switch (tp->t_state) {
8364 			/*
8365 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
8366 			 * CLOSE_WAIT state.
8367 			 */
8368 		case TCPS_SYN_RECEIVED:
8369 			tp->t_starttime = ticks;
8370 			/* FALLTHROUGH */
8371 		case TCPS_ESTABLISHED:
8372 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
8373 			break;
8374 
8375 			/*
8376 			 * If still in FIN_WAIT_1 STATE FIN has not been
8377 			 * acked so enter the CLOSING state.
8378 			 */
8379 		case TCPS_FIN_WAIT_1:
8380 			tcp_state_change(tp, TCPS_CLOSING);
8381 			break;
8382 
8383 			/*
8384 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
8385 			 * starting the time-wait timer, turning off the
8386 			 * other standard timers.
8387 			 */
8388 		case TCPS_FIN_WAIT_2:
8389 			bbr->rc_timer_first = 1;
8390 			bbr_timer_cancel(bbr,
8391 			    __LINE__, bbr->r_ctl.rc_rcvtime);
8392 			tcp_twstart(tp);
8393 			return (1);
8394 		}
8395 	}
8396 	/*
8397 	 * Return any desired output.
8398 	 */
8399 	if ((tp->t_flags & TF_ACKNOW) ||
8400 	    (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8401 		bbr->r_wanted_output = 1;
8402 	}
8403 	return (0);
8404 }
8405 
8406 /*
8407  * Here nothing is really faster, its just that we
8408  * have broken out the fast-data path also just like
8409  * the fast-ack. Return 1 if we processed the packet
8410  * return 0 if you need to take the "slow-path".
8411  */
8412 static int
bbr_do_fastnewdata(struct mbuf * m,struct tcphdr * th,struct socket * so,struct tcpcb * tp,struct tcpopt * to,int32_t drop_hdrlen,int32_t tlen,uint32_t tiwin,int32_t nxt_pkt)8413 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8414     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8415     uint32_t tiwin, int32_t nxt_pkt)
8416 {
8417 	uint16_t nsegs;
8418 	int32_t newsize = 0;	/* automatic sockbuf scaling */
8419 	struct tcp_bbr *bbr;
8420 #ifdef NETFLIX_SB_LIMITS
8421 	u_int mcnt, appended;
8422 #endif
8423 
8424 	/* On the hpts and we would have called output */
8425 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8426 
8427 	/*
8428 	 * If last ACK falls within this segment's sequence numbers, record
8429 	 * the timestamp. NOTE that the test is modified according to the
8430 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8431 	 */
8432 	if (bbr->r_ctl.rc_resend != NULL) {
8433 		return (0);
8434 	}
8435 	if (tiwin && tiwin != tp->snd_wnd) {
8436 		return (0);
8437 	}
8438 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8439 		return (0);
8440 	}
8441 	if (__predict_false((to->to_flags & TOF_TS) &&
8442 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8443 		return (0);
8444 	}
8445 	if (__predict_false((th->th_ack != tp->snd_una))) {
8446 		return (0);
8447 	}
8448 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8449 		return (0);
8450 	}
8451 	if ((to->to_flags & TOF_TS) != 0 &&
8452 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8453 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8454 		tp->ts_recent = to->to_tsval;
8455 	}
8456 	/*
8457 	 * This is a pure, in-sequence data packet with nothing on the
8458 	 * reassembly queue and we have enough buffer space to take it.
8459 	 */
8460 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8461 
8462 #ifdef NETFLIX_SB_LIMITS
8463 	if (so->so_rcv.sb_shlim) {
8464 		mcnt = m_memcnt(m);
8465 		appended = 0;
8466 		if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8467 		    CFO_NOSLEEP, NULL) == false) {
8468 			counter_u64_add(tcp_sb_shlim_fails, 1);
8469 			m_freem(m);
8470 			return (1);
8471 		}
8472 	}
8473 #endif
8474 	/* Clean receiver SACK report if present */
8475 	if (tp->rcv_numsacks)
8476 		tcp_clean_sackreport(tp);
8477 	KMOD_TCPSTAT_INC(tcps_preddat);
8478 	tp->rcv_nxt += tlen;
8479 	if (tlen &&
8480 	    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8481 	    (tp->t_fbyte_in == 0)) {
8482 		tp->t_fbyte_in = ticks;
8483 		if (tp->t_fbyte_in == 0)
8484 			tp->t_fbyte_in = 1;
8485 		if (tp->t_fbyte_out && tp->t_fbyte_in)
8486 			tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8487 	}
8488 	/*
8489 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8490 	 */
8491 	tp->snd_wl1 = th->th_seq;
8492 	/*
8493 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8494 	 */
8495 	tp->rcv_up = tp->rcv_nxt;
8496 	KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8497 	KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8498 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8499 
8500 	/* Add data to socket buffer. */
8501 	SOCKBUF_LOCK(&so->so_rcv);
8502 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8503 		m_freem(m);
8504 	} else {
8505 		/*
8506 		 * Set new socket buffer size. Give up when limit is
8507 		 * reached.
8508 		 */
8509 		if (newsize)
8510 			if (!sbreserve_locked(so, SO_RCV, newsize, NULL))
8511 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8512 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8513 
8514 #ifdef NETFLIX_SB_LIMITS
8515 		appended =
8516 #endif
8517 			sbappendstream_locked(&so->so_rcv, m, 0);
8518 		ctf_calc_rwin(so, tp);
8519 	}
8520 	/* NB: sorwakeup_locked() does an implicit unlock. */
8521 	sorwakeup_locked(so);
8522 #ifdef NETFLIX_SB_LIMITS
8523 	if (so->so_rcv.sb_shlim && mcnt != appended)
8524 		counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8525 #endif
8526 	if (DELAY_ACK(tp, bbr, nsegs)) {
8527 		bbr->bbr_segs_rcvd += max(1, nsegs);
8528 		tp->t_flags |= TF_DELACK;
8529 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8530 	} else {
8531 		bbr->r_wanted_output = 1;
8532 		tp->t_flags |= TF_ACKNOW;
8533 	}
8534 	return (1);
8535 }
8536 
8537 /*
8538  * This subfunction is used to try to highly optimize the
8539  * fast path. We again allow window updates that are
8540  * in sequence to remain in the fast-path. We also add
8541  * in the __predict's to attempt to help the compiler.
8542  * Note that if we return a 0, then we can *not* process
8543  * it and the caller should push the packet into the
8544  * slow-path. If we return 1, then all is well and
8545  * the packet is fully processed.
8546  */
8547 static int
bbr_fastack(struct mbuf * m,struct tcphdr * th,struct socket * so,struct tcpcb * tp,struct tcpopt * to,int32_t drop_hdrlen,int32_t tlen,uint32_t tiwin,int32_t nxt_pkt,uint8_t iptos)8548 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8549     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8550     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
8551 {
8552 	int32_t acked;
8553 	uint16_t nsegs;
8554 	uint32_t sack_changed;
8555 	uint32_t prev_acked = 0;
8556 	struct tcp_bbr *bbr;
8557 
8558 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8559 		/* Old ack, behind (or duplicate to) the last one rcv'd */
8560 		return (0);
8561 	}
8562 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8563 		/* Above what we have sent? */
8564 		return (0);
8565 	}
8566 	if (__predict_false(tiwin == 0)) {
8567 		/* zero window */
8568 		return (0);
8569 	}
8570 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8571 		/* We need a SYN or a FIN, unlikely.. */
8572 		return (0);
8573 	}
8574 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8575 		/* Timestamp is behind .. old ack with seq wrap? */
8576 		return (0);
8577 	}
8578 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8579 		/* Still recovering */
8580 		return (0);
8581 	}
8582 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8583 	if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8584 		/* We are retransmitting */
8585 		return (0);
8586 	}
8587 	if (__predict_false(bbr->rc_in_persist != 0)) {
8588 		/* In persist mode */
8589 		return (0);
8590 	}
8591 	if (bbr->r_ctl.rc_sacked) {
8592 		/* We have sack holes on our scoreboard */
8593 		return (0);
8594 	}
8595 	/* Ok if we reach here, we can process a fast-ack */
8596 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8597 	sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8598 	/*
8599 	 * We never detect loss in fast ack [we can't
8600 	 * have a sack and can't be in recovery so
8601 	 * we always pass 0 (nothing detected)].
8602 	 */
8603 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8604 	/* Did the window get updated? */
8605 	if (tiwin != tp->snd_wnd) {
8606 		tp->snd_wnd = tiwin;
8607 		tp->snd_wl1 = th->th_seq;
8608 		if (tp->snd_wnd > tp->max_sndwnd)
8609 			tp->max_sndwnd = tp->snd_wnd;
8610 	}
8611 	/* Do we need to exit persists? */
8612 	if ((bbr->rc_in_persist != 0) &&
8613 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8614 			       bbr_minseg(bbr)))) {
8615 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8616 		bbr->r_wanted_output = 1;
8617 	}
8618 	/* Do we need to enter persists? */
8619 	if ((bbr->rc_in_persist == 0) &&
8620 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8621 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8622 	    (tp->snd_max == tp->snd_una) &&
8623 	    sbavail(&so->so_snd) &&
8624 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8625 		/* No send window.. we must enter persist */
8626 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8627 	}
8628 	/*
8629 	 * If last ACK falls within this segment's sequence numbers, record
8630 	 * the timestamp. NOTE that the test is modified according to the
8631 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8632 	 */
8633 	if ((to->to_flags & TOF_TS) != 0 &&
8634 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8635 		tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8636 		tp->ts_recent = to->to_tsval;
8637 	}
8638 	/*
8639 	 * This is a pure ack for outstanding data.
8640 	 */
8641 	KMOD_TCPSTAT_INC(tcps_predack);
8642 
8643 	/*
8644 	 * "bad retransmit" recovery.
8645 	 */
8646 	if (tp->t_flags & TF_PREVVALID) {
8647 		tp->t_flags &= ~TF_PREVVALID;
8648 		if (tp->t_rxtshift == 1 &&
8649 		    (int)(ticks - tp->t_badrxtwin) < 0)
8650 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8651 	}
8652 	/*
8653 	 * Recalculate the transmit timer / rtt.
8654 	 *
8655 	 * Some boxes send broken timestamp replies during the SYN+ACK
8656 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
8657 	 * and blow up the retransmit timer.
8658 	 */
8659 	acked = BYTES_THIS_ACK(tp, th);
8660 
8661 #ifdef TCP_HHOOK
8662 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8663 	hhook_run_tcp_est_in(tp, th, to);
8664 #endif
8665 
8666 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8667 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
8668 	sbdrop(&so->so_snd, acked);
8669 
8670 	if (SEQ_GT(th->th_ack, tp->snd_una))
8671 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8672 	tp->snd_una = th->th_ack;
8673 	if (tp->snd_wnd < ctf_outstanding(tp))
8674 		/* The peer collapsed its window on us */
8675 		bbr_collapsed_window(bbr);
8676 	else if (bbr->rc_has_collapsed)
8677 		bbr_un_collapse_window(bbr);
8678 
8679 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8680 		tp->snd_recover = tp->snd_una;
8681 	}
8682 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8683 	/*
8684 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8685 	 */
8686 	tp->snd_wl2 = th->th_ack;
8687 	m_freem(m);
8688 	/*
8689 	 * If all outstanding data are acked, stop retransmit timer,
8690 	 * otherwise restart timer using current (possibly backed-off)
8691 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
8692 	 * If data are ready to send, let tcp_output decide between more
8693 	 * output or persist.
8694 	 * Wake up the socket if we have room to write more.
8695 	 */
8696 	sowwakeup(so);
8697 	if (tp->snd_una == tp->snd_max) {
8698 		/* Nothing left outstanding */
8699 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8700 		if (sbavail(&so->so_snd) == 0)
8701 			bbr->rc_tp->t_acktime = 0;
8702 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8703 		if (bbr->rc_in_persist == 0) {
8704 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8705 		}
8706 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8707 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8708 		/*
8709 		 * We invalidate the last ack here since we
8710 		 * don't want to transfer forward the time
8711 		 * for our sum's calculations.
8712 		 */
8713 		bbr->r_wanted_output = 1;
8714 	}
8715 	if (sbavail(&so->so_snd)) {
8716 		bbr->r_wanted_output = 1;
8717 	}
8718 	return (1);
8719 }
8720 
8721 /*
8722  * Return value of 1, the TCB is unlocked and most
8723  * likely gone, return value of 0, the TCB is still
8724  * locked.
8725  */
8726 static int
bbr_do_syn_sent(struct mbuf * m,struct tcphdr * th,struct socket * so,struct tcpcb * tp,struct tcpopt * to,int32_t drop_hdrlen,int32_t tlen,uint32_t tiwin,int32_t thflags,int32_t nxt_pkt,uint8_t iptos)8727 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8728     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8729     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8730 {
8731 	int32_t todrop;
8732 	int32_t ourfinisacked = 0;
8733 	struct tcp_bbr *bbr;
8734 	int32_t ret_val = 0;
8735 
8736 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8737 
8738 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8739 	ctf_calc_rwin(so, tp);
8740 	/*
8741 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
8742 	 * SYN, drop the input. if seg contains a RST, then drop the
8743 	 * connection. if seg does not contain SYN, then drop it. Otherwise
8744 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
8745 	 * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8746 	 * not support ECN so we will not say we are capable. if SYN has
8747 	 * been acked change to ESTABLISHED else SYN_RCVD state arrange for
8748 	 * segment to be acked (eventually) continue processing rest of
8749 	 * data/controls, beginning with URG
8750 	 */
8751 	if ((thflags & TH_ACK) &&
8752 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
8753 	    SEQ_GT(th->th_ack, tp->snd_max))) {
8754 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8755 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8756 		return (1);
8757 	}
8758 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
8759 		TCP_PROBE5(connect__refused, NULL, tp,
8760 		    mtod(m, const char *), tp, th);
8761 		tp = tcp_drop(tp, ECONNREFUSED);
8762 		ctf_do_drop(m, tp);
8763 		return (1);
8764 	}
8765 	if (thflags & TH_RST) {
8766 		ctf_do_drop(m, tp);
8767 		return (1);
8768 	}
8769 	if (!(thflags & TH_SYN)) {
8770 		ctf_do_drop(m, tp);
8771 		return (1);
8772 	}
8773 	tp->irs = th->th_seq;
8774 	tcp_rcvseqinit(tp);
8775 	if (thflags & TH_ACK) {
8776 		int tfo_partial = 0;
8777 
8778 		KMOD_TCPSTAT_INC(tcps_connects);
8779 		soisconnected(so);
8780 #ifdef MAC
8781 		mac_socketpeer_set_from_mbuf(m, so);
8782 #endif
8783 		/* Do window scaling on this connection? */
8784 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
8785 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
8786 			tp->rcv_scale = tp->request_r_scale;
8787 		}
8788 		tp->rcv_adv += min(tp->rcv_wnd,
8789 		    TCP_MAXWIN << tp->rcv_scale);
8790 		/*
8791 		 * If not all the data that was sent in the TFO SYN
8792 		 * has been acked, resend the remainder right away.
8793 		 */
8794 		if (IS_FASTOPEN(tp->t_flags) &&
8795 		    (tp->snd_una != tp->snd_max)) {
8796 			tp->snd_nxt = th->th_ack;
8797 			tfo_partial = 1;
8798 		}
8799 		/*
8800 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
8801 		 * will be turned on later.
8802 		 */
8803 		if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && !tfo_partial) {
8804 			bbr->bbr_segs_rcvd += 1;
8805 			tp->t_flags |= TF_DELACK;
8806 			bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8807 		} else {
8808 			bbr->r_wanted_output = 1;
8809 			tp->t_flags |= TF_ACKNOW;
8810 		}
8811 		if (SEQ_GT(th->th_ack, tp->iss)) {
8812 			/*
8813 			 * The SYN is acked
8814 			 * handle it specially.
8815 			 */
8816 			bbr_log_syn(tp, to);
8817 		}
8818 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
8819 			/*
8820 			 * We advance snd_una for the
8821 			 * fast open case. If th_ack is
8822 			 * acknowledging data beyond
8823 			 * snd_una we can't just call
8824 			 * ack-processing since the
8825 			 * data stream in our send-map
8826 			 * will start at snd_una + 1 (one
8827 			 * beyond the SYN). If its just
8828 			 * equal we don't need to do that
8829 			 * and there is no send_map.
8830 			 */
8831 			tp->snd_una++;
8832 		}
8833 		/*
8834 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
8835 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
8836 		 */
8837 		tp->t_starttime = ticks;
8838 		if (tp->t_flags & TF_NEEDFIN) {
8839 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
8840 			tp->t_flags &= ~TF_NEEDFIN;
8841 			thflags &= ~TH_SYN;
8842 		} else {
8843 			tcp_state_change(tp, TCPS_ESTABLISHED);
8844 			TCP_PROBE5(connect__established, NULL, tp,
8845 			    mtod(m, const char *), tp, th);
8846 			cc_conn_init(tp);
8847 		}
8848 	} else {
8849 		/*
8850 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
8851 		 * open.  If segment contains CC option and there is a
8852 		 * cached CC, apply TAO test. If it succeeds, connection is *
8853 		 * half-synchronized. Otherwise, do 3-way handshake:
8854 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
8855 		 * there was no CC option, clear cached CC value.
8856 		 */
8857 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN | TF_SONOTCONN);
8858 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
8859 	}
8860 	/*
8861 	 * Advance th->th_seq to correspond to first data byte. If data,
8862 	 * trim to stay within window, dropping FIN if necessary.
8863 	 */
8864 	th->th_seq++;
8865 	if (tlen > tp->rcv_wnd) {
8866 		todrop = tlen - tp->rcv_wnd;
8867 		m_adj(m, -todrop);
8868 		tlen = tp->rcv_wnd;
8869 		thflags &= ~TH_FIN;
8870 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
8871 		KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
8872 	}
8873 	tp->snd_wl1 = th->th_seq - 1;
8874 	tp->rcv_up = th->th_seq;
8875 	/*
8876 	 * Client side of transaction: already sent SYN and data. If the
8877 	 * remote host used T/TCP to validate the SYN, our data will be
8878 	 * ACK'd; if so, enter normal data segment processing in the middle
8879 	 * of step 5, ack processing. Otherwise, goto step 6.
8880 	 */
8881 	if (thflags & TH_ACK) {
8882 		if ((to->to_flags & TOF_TS) != 0) {
8883 			uint32_t t, rtt;
8884 
8885 			t = tcp_tv_to_mssectick(&bbr->rc_tv);
8886 			if (TSTMP_GEQ(t, to->to_tsecr)) {
8887 				rtt = t - to->to_tsecr;
8888 				if (rtt == 0) {
8889 					rtt = 1;
8890 				}
8891 				rtt *= MS_IN_USEC;
8892 				tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
8893 				apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
8894 						       rtt, bbr->r_ctl.rc_rcvtime);
8895 			}
8896 		}
8897 		if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
8898 			return (ret_val);
8899 		/* We may have changed to FIN_WAIT_1 above */
8900 		if (tp->t_state == TCPS_FIN_WAIT_1) {
8901 			/*
8902 			 * In FIN_WAIT_1 STATE in addition to the processing
8903 			 * for the ESTABLISHED state if our FIN is now
8904 			 * acknowledged then enter FIN_WAIT_2.
8905 			 */
8906 			if (ourfinisacked) {
8907 				/*
8908 				 * If we can't receive any more data, then
8909 				 * closing user can proceed. Starting the
8910 				 * timer is contrary to the specification,
8911 				 * but if we don't get a FIN we'll hang
8912 				 * forever.
8913 				 *
8914 				 * XXXjl: we should release the tp also, and
8915 				 * use a compressed state.
8916 				 */
8917 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8918 					soisdisconnected(so);
8919 					tcp_timer_activate(tp, TT_2MSL,
8920 					    (tcp_fast_finwait2_recycle ?
8921 					    tcp_finwait2_timeout :
8922 					    TP_MAXIDLE(tp)));
8923 				}
8924 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
8925 			}
8926 		}
8927 	}
8928 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
8929 	    tiwin, thflags, nxt_pkt));
8930 }
8931 
8932 /*
8933  * Return value of 1, the TCB is unlocked and most
8934  * likely gone, return value of 0, the TCB is still
8935  * locked.
8936  */
8937 static int
bbr_do_syn_recv(struct mbuf * m,struct tcphdr * th,struct socket * so,struct tcpcb * tp,struct tcpopt * to,int32_t drop_hdrlen,int32_t tlen,uint32_t tiwin,int32_t thflags,int32_t nxt_pkt,uint8_t iptos)8938 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
8939 		struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8940 		uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8941 {
8942 	int32_t ourfinisacked = 0;
8943 	int32_t ret_val;
8944 	struct tcp_bbr *bbr;
8945 
8946 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8947 
8948 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8949 	ctf_calc_rwin(so, tp);
8950 	if ((thflags & TH_RST) ||
8951 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
8952 		return (ctf_process_rst(m, th, so, tp));
8953 	if ((thflags & TH_ACK) &&
8954 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
8955 	     SEQ_GT(th->th_ack, tp->snd_max))) {
8956 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8957 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8958 		return (1);
8959 	}
8960 	if (IS_FASTOPEN(tp->t_flags)) {
8961 		/*
8962 		 * When a TFO connection is in SYN_RECEIVED, the only valid
8963 		 * packets are the initial SYN, a retransmit/copy of the
8964 		 * initial SYN (possibly with a subset of the original
8965 		 * data), a valid ACK, a FIN, or a RST.
8966 		 */
8967 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
8968 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8969 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8970 			return (1);
8971 		} else if (thflags & TH_SYN) {
8972 			/* non-initial SYN is ignored */
8973 			if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
8974 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
8975 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
8976 				ctf_do_drop(m, NULL);
8977 				return (0);
8978 			}
8979 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
8980 			ctf_do_drop(m, NULL);
8981 			return (0);
8982 		}
8983 	}
8984 	/*
8985 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
8986 	 * it's less than ts_recent, drop it.
8987 	 */
8988 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
8989 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
8990 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
8991 			return (ret_val);
8992 	}
8993 	/*
8994 	 * In the SYN-RECEIVED state, validate that the packet belongs to
8995 	 * this connection before trimming the data to fit the receive
8996 	 * window.  Check the sequence number versus IRS since we know the
8997 	 * sequence numbers haven't wrapped.  This is a partial fix for the
8998 	 * "LAND" DoS attack.
8999 	 */
9000 	if (SEQ_LT(th->th_seq, tp->irs)) {
9001 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9002 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9003 		return (1);
9004 	}
9005 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9006 		return (ret_val);
9007 	}
9008 	/*
9009 	 * If last ACK falls within this segment's sequence numbers, record
9010 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9011 	 * from the latest proposal of the tcplw@cray.com list (Braden
9012 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9013 	 * with our earlier PAWS tests, so this check should be solely
9014 	 * predicated on the sequence space of this segment. 3) That we
9015 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9016 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9017 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9018 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9019 	 * p.869. In such cases, we can still calculate the RTT correctly
9020 	 * when RCV.NXT == Last.ACK.Sent.
9021 	 */
9022 	if ((to->to_flags & TOF_TS) != 0 &&
9023 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9024 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9025 		    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9026 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9027 		tp->ts_recent = to->to_tsval;
9028 	}
9029 	tp->snd_wnd = tiwin;
9030 	/*
9031 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9032 	 * is on (half-synchronized state), then queue data for later
9033 	 * processing; else drop segment and return.
9034 	 */
9035 	if ((thflags & TH_ACK) == 0) {
9036 		if (IS_FASTOPEN(tp->t_flags)) {
9037 			cc_conn_init(tp);
9038 		}
9039 		return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9040 					 tiwin, thflags, nxt_pkt));
9041 	}
9042 	KMOD_TCPSTAT_INC(tcps_connects);
9043 	if (tp->t_flags & TF_SONOTCONN) {
9044 		tp->t_flags &= ~TF_SONOTCONN;
9045 		soisconnected(so);
9046 	}
9047 	/* Do window scaling? */
9048 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9049 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9050 		tp->rcv_scale = tp->request_r_scale;
9051 	}
9052 	/*
9053 	 * ok for the first time in lets see if we can use the ts to figure
9054 	 * out what the initial RTT was.
9055 	 */
9056 	if ((to->to_flags & TOF_TS) != 0) {
9057 		uint32_t t, rtt;
9058 
9059 		t = tcp_tv_to_mssectick(&bbr->rc_tv);
9060 		if (TSTMP_GEQ(t, to->to_tsecr)) {
9061 			rtt = t - to->to_tsecr;
9062 			if (rtt == 0) {
9063 				rtt = 1;
9064 			}
9065 			rtt *= MS_IN_USEC;
9066 			tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9067 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9068 		}
9069 	}
9070 	/* Drop off any SYN in the send map (probably not there)  */
9071 	if (thflags & TH_ACK)
9072 		bbr_log_syn(tp, to);
9073 	if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
9074 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9075 		tp->t_tfo_pending = NULL;
9076 	}
9077 	/*
9078 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9079 	 * FIN-WAIT-1
9080 	 */
9081 	tp->t_starttime = ticks;
9082 	if (tp->t_flags & TF_NEEDFIN) {
9083 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
9084 		tp->t_flags &= ~TF_NEEDFIN;
9085 	} else {
9086 		tcp_state_change(tp, TCPS_ESTABLISHED);
9087 		TCP_PROBE5(accept__established, NULL, tp,
9088 			   mtod(m, const char *), tp, th);
9089 		/*
9090 		 * TFO connections call cc_conn_init() during SYN
9091 		 * processing.  Calling it again here for such connections
9092 		 * is not harmless as it would undo the snd_cwnd reduction
9093 		 * that occurs when a TFO SYN|ACK is retransmitted.
9094 		 */
9095 		if (!IS_FASTOPEN(tp->t_flags))
9096 			cc_conn_init(tp);
9097 	}
9098 	/*
9099 	 * Account for the ACK of our SYN prior to
9100 	 * regular ACK processing below, except for
9101 	 * simultaneous SYN, which is handled later.
9102 	 */
9103 	if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
9104 		tp->snd_una++;
9105 	/*
9106 	 * If segment contains data or ACK, will call tcp_reass() later; if
9107 	 * not, do so now to pass queued data to user.
9108 	 */
9109 	if (tlen == 0 && (thflags & TH_FIN) == 0) {
9110 		(void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9111 			(struct mbuf *)0);
9112 		if (tp->t_flags & TF_WAKESOR) {
9113 			tp->t_flags &= ~TF_WAKESOR;
9114 			/* NB: sorwakeup_locked() does an implicit unlock. */
9115 			sorwakeup_locked(so);
9116 		}
9117 	}
9118 	tp->snd_wl1 = th->th_seq - 1;
9119 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9120 		return (ret_val);
9121 	}
9122 	if (tp->t_state == TCPS_FIN_WAIT_1) {
9123 		/* We could have went to FIN_WAIT_1 (or EST) above */
9124 		/*
9125 		 * In FIN_WAIT_1 STATE in addition to the processing for the
9126 		 * ESTABLISHED state if our FIN is now acknowledged then
9127 		 * enter FIN_WAIT_2.
9128 		 */
9129 		if (ourfinisacked) {
9130 			/*
9131 			 * If we can't receive any more data, then closing
9132 			 * user can proceed. Starting the timer is contrary
9133 			 * to the specification, but if we don't get a FIN
9134 			 * we'll hang forever.
9135 			 *
9136 			 * XXXjl: we should release the tp also, and use a
9137 			 * compressed state.
9138 			 */
9139 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9140 				soisdisconnected(so);
9141 				tcp_timer_activate(tp, TT_2MSL,
9142 						   (tcp_fast_finwait2_recycle ?
9143 						    tcp_finwait2_timeout :
9144 						    TP_MAXIDLE(tp)));
9145 			}
9146 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
9147 		}
9148 	}
9149 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9150 				 tiwin, thflags, nxt_pkt));
9151 }
9152 
9153 /*
9154  * Return value of 1, the TCB is unlocked and most
9155  * likely gone, return value of 0, the TCB is still
9156  * locked.
9157  */
9158 static int
bbr_do_established(struct mbuf * m,struct tcphdr * th,struct socket * so,struct tcpcb * tp,struct tcpopt * to,int32_t drop_hdrlen,int32_t tlen,uint32_t tiwin,int32_t thflags,int32_t nxt_pkt,uint8_t iptos)9159 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9160     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9161     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9162 {
9163 	struct tcp_bbr *bbr;
9164 	int32_t ret_val;
9165 
9166 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9167 
9168 	/*
9169 	 * Header prediction: check for the two common cases of a
9170 	 * uni-directional data xfer.  If the packet has no control flags,
9171 	 * is in-sequence, the window didn't change and we're not
9172 	 * retransmitting, it's a candidate.  If the length is zero and the
9173 	 * ack moved forward, we're the sender side of the xfer.  Just free
9174 	 * the data acked & wake any higher level process that was blocked
9175 	 * waiting for space.  If the length is non-zero and the ack didn't
9176 	 * move, we're the receiver side.  If we're getting packets in-order
9177 	 * (the reassembly queue is empty), add the data toc The socket
9178 	 * buffer and note that we need a delayed ack. Make sure that the
9179 	 * hidden state-flags are also off. Since we check for
9180 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9181 	 */
9182 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9183 	if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9184 		/*
9185 		 * If we have delived under 4 segments increase the initial
9186 		 * window if raised by the peer. We use this to determine
9187 		 * dynamic and static rwnd's at the end of a connection.
9188 		 */
9189 		bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9190 	}
9191 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9192 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9193 	    __predict_true(SEGQ_EMPTY(tp)) &&
9194 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
9195 		if (tlen == 0) {
9196 			if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9197 			    tiwin, nxt_pkt, iptos)) {
9198 				return (0);
9199 			}
9200 		} else {
9201 			if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9202 			    tiwin, nxt_pkt)) {
9203 				return (0);
9204 			}
9205 		}
9206 	}
9207 	ctf_calc_rwin(so, tp);
9208 
9209 	if ((thflags & TH_RST) ||
9210 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9211 		return (ctf_process_rst(m, th, so, tp));
9212 	/*
9213 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9214 	 * synchronized state.
9215 	 */
9216 	if (thflags & TH_SYN) {
9217 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9218 		return (ret_val);
9219 	}
9220 	/*
9221 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9222 	 * it's less than ts_recent, drop it.
9223 	 */
9224 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9225 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9226 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9227 			return (ret_val);
9228 	}
9229 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9230 		return (ret_val);
9231 	}
9232 	/*
9233 	 * If last ACK falls within this segment's sequence numbers, record
9234 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9235 	 * from the latest proposal of the tcplw@cray.com list (Braden
9236 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9237 	 * with our earlier PAWS tests, so this check should be solely
9238 	 * predicated on the sequence space of this segment. 3) That we
9239 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9240 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9241 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9242 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9243 	 * p.869. In such cases, we can still calculate the RTT correctly
9244 	 * when RCV.NXT == Last.ACK.Sent.
9245 	 */
9246 	if ((to->to_flags & TOF_TS) != 0 &&
9247 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9248 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9249 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9250 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9251 		tp->ts_recent = to->to_tsval;
9252 	}
9253 	/*
9254 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9255 	 * is on (half-synchronized state), then queue data for later
9256 	 * processing; else drop segment and return.
9257 	 */
9258 	if ((thflags & TH_ACK) == 0) {
9259 		if (tp->t_flags & TF_NEEDSYN) {
9260 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9261 			    tiwin, thflags, nxt_pkt));
9262 		} else if (tp->t_flags & TF_ACKNOW) {
9263 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9264 			bbr->r_wanted_output = 1;
9265 			return (ret_val);
9266 		} else {
9267 			ctf_do_drop(m, NULL);
9268 			return (0);
9269 		}
9270 	}
9271 	/*
9272 	 * Ack processing.
9273 	 */
9274 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9275 		return (ret_val);
9276 	}
9277 	if (sbavail(&so->so_snd)) {
9278 		if (ctf_progress_timeout_check(tp, true)) {
9279 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9280 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9281 			return (1);
9282 		}
9283 	}
9284 	/* State changes only happen in bbr_process_data() */
9285 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9286 	    tiwin, thflags, nxt_pkt));
9287 }
9288 
9289 /*
9290  * Return value of 1, the TCB is unlocked and most
9291  * likely gone, return value of 0, the TCB is still
9292  * locked.
9293  */
9294 static int
bbr_do_close_wait(struct mbuf * m,struct tcphdr * th,struct socket * so,struct tcpcb * tp,struct tcpopt * to,int32_t drop_hdrlen,int32_t tlen,uint32_t tiwin,int32_t thflags,int32_t nxt_pkt,uint8_t iptos)9295 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9296     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9297     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9298 {
9299 	struct tcp_bbr *bbr;
9300 	int32_t ret_val;
9301 
9302 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9303 
9304 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9305 	ctf_calc_rwin(so, tp);
9306 	if ((thflags & TH_RST) ||
9307 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9308 		return (ctf_process_rst(m, th, so, tp));
9309 	/*
9310 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9311 	 * synchronized state.
9312 	 */
9313 	if (thflags & TH_SYN) {
9314 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9315 		return (ret_val);
9316 	}
9317 	/*
9318 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9319 	 * it's less than ts_recent, drop it.
9320 	 */
9321 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9322 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9323 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9324 			return (ret_val);
9325 	}
9326 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9327 		return (ret_val);
9328 	}
9329 	/*
9330 	 * If last ACK falls within this segment's sequence numbers, record
9331 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9332 	 * from the latest proposal of the tcplw@cray.com list (Braden
9333 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9334 	 * with our earlier PAWS tests, so this check should be solely
9335 	 * predicated on the sequence space of this segment. 3) That we
9336 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9337 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9338 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9339 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9340 	 * p.869. In such cases, we can still calculate the RTT correctly
9341 	 * when RCV.NXT == Last.ACK.Sent.
9342 	 */
9343 	if ((to->to_flags & TOF_TS) != 0 &&
9344 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9345 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9346 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9347 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9348 		tp->ts_recent = to->to_tsval;
9349 	}
9350 	/*
9351 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9352 	 * is on (half-synchronized state), then queue data for later
9353 	 * processing; else drop segment and return.
9354 	 */
9355 	if ((thflags & TH_ACK) == 0) {
9356 		if (tp->t_flags & TF_NEEDSYN) {
9357 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9358 			    tiwin, thflags, nxt_pkt));
9359 		} else if (tp->t_flags & TF_ACKNOW) {
9360 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9361 			bbr->r_wanted_output = 1;
9362 			return (ret_val);
9363 		} else {
9364 			ctf_do_drop(m, NULL);
9365 			return (0);
9366 		}
9367 	}
9368 	/*
9369 	 * Ack processing.
9370 	 */
9371 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9372 		return (ret_val);
9373 	}
9374 	if (sbavail(&so->so_snd)) {
9375 		if (ctf_progress_timeout_check(tp, true)) {
9376 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9377 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9378 			return (1);
9379 		}
9380 	}
9381 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9382 	    tiwin, thflags, nxt_pkt));
9383 }
9384 
9385 static int
bbr_check_data_after_close(struct mbuf * m,struct tcp_bbr * bbr,struct tcpcb * tp,int32_t * tlen,struct tcphdr * th,struct socket * so)9386 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9387     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9388 {
9389 
9390 	if (bbr->rc_allow_data_af_clo == 0) {
9391 close_now:
9392 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
9393 		/* tcp_close will kill the inp pre-log the Reset */
9394 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
9395 		tp = tcp_close(tp);
9396 		KMOD_TCPSTAT_INC(tcps_rcvafterclose);
9397 		ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9398 		return (1);
9399 	}
9400 	if (sbavail(&so->so_snd) == 0)
9401 		goto close_now;
9402 	/* Ok we allow data that is ignored and a followup reset */
9403 	tp->rcv_nxt = th->th_seq + *tlen;
9404 	tp->t_flags2 |= TF2_DROP_AF_DATA;
9405 	bbr->r_wanted_output = 1;
9406 	*tlen = 0;
9407 	return (0);
9408 }
9409 
9410 /*
9411  * Return value of 1, the TCB is unlocked and most
9412  * likely gone, return value of 0, the TCB is still
9413  * locked.
9414  */
9415 static int
bbr_do_fin_wait_1(struct mbuf * m,struct tcphdr * th,struct socket * so,struct tcpcb * tp,struct tcpopt * to,int32_t drop_hdrlen,int32_t tlen,uint32_t tiwin,int32_t thflags,int32_t nxt_pkt,uint8_t iptos)9416 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9417     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9418     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9419 {
9420 	int32_t ourfinisacked = 0;
9421 	int32_t ret_val;
9422 	struct tcp_bbr *bbr;
9423 
9424 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9425 
9426 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9427 	ctf_calc_rwin(so, tp);
9428 	if ((thflags & TH_RST) ||
9429 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9430 		return (ctf_process_rst(m, th, so, tp));
9431 	/*
9432 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9433 	 * synchronized state.
9434 	 */
9435 	if (thflags & TH_SYN) {
9436 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9437 		return (ret_val);
9438 	}
9439 	/*
9440 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9441 	 * it's less than ts_recent, drop it.
9442 	 */
9443 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9444 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9445 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9446 			return (ret_val);
9447 	}
9448 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9449 		return (ret_val);
9450 	}
9451 	/*
9452 	 * If new data are received on a connection after the user processes
9453 	 * are gone, then RST the other end.
9454 	 * We call a new function now so we might continue and setup
9455 	 * to reset at all data being ack'd.
9456 	 */
9457 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9458 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9459 		return (1);
9460 	/*
9461 	 * If last ACK falls within this segment's sequence numbers, record
9462 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9463 	 * from the latest proposal of the tcplw@cray.com list (Braden
9464 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9465 	 * with our earlier PAWS tests, so this check should be solely
9466 	 * predicated on the sequence space of this segment. 3) That we
9467 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9468 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9469 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9470 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9471 	 * p.869. In such cases, we can still calculate the RTT correctly
9472 	 * when RCV.NXT == Last.ACK.Sent.
9473 	 */
9474 	if ((to->to_flags & TOF_TS) != 0 &&
9475 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9476 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9477 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9478 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9479 		tp->ts_recent = to->to_tsval;
9480 	}
9481 	/*
9482 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9483 	 * is on (half-synchronized state), then queue data for later
9484 	 * processing; else drop segment and return.
9485 	 */
9486 	if ((thflags & TH_ACK) == 0) {
9487 		if (tp->t_flags & TF_NEEDSYN) {
9488 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9489 			    tiwin, thflags, nxt_pkt));
9490 		} else if (tp->t_flags & TF_ACKNOW) {
9491 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9492 			bbr->r_wanted_output = 1;
9493 			return (ret_val);
9494 		} else {
9495 			ctf_do_drop(m, NULL);
9496 			return (0);
9497 		}
9498 	}
9499 	/*
9500 	 * Ack processing.
9501 	 */
9502 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9503 		return (ret_val);
9504 	}
9505 	if (ourfinisacked) {
9506 		/*
9507 		 * If we can't receive any more data, then closing user can
9508 		 * proceed. Starting the timer is contrary to the
9509 		 * specification, but if we don't get a FIN we'll hang
9510 		 * forever.
9511 		 *
9512 		 * XXXjl: we should release the tp also, and use a
9513 		 * compressed state.
9514 		 */
9515 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9516 			soisdisconnected(so);
9517 			tcp_timer_activate(tp, TT_2MSL,
9518 			    (tcp_fast_finwait2_recycle ?
9519 			    tcp_finwait2_timeout :
9520 			    TP_MAXIDLE(tp)));
9521 		}
9522 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
9523 	}
9524 	if (sbavail(&so->so_snd)) {
9525 		if (ctf_progress_timeout_check(tp, true)) {
9526 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9527 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9528 			return (1);
9529 		}
9530 	}
9531 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9532 	    tiwin, thflags, nxt_pkt));
9533 }
9534 
9535 /*
9536  * Return value of 1, the TCB is unlocked and most
9537  * likely gone, return value of 0, the TCB is still
9538  * locked.
9539  */
9540 static int
bbr_do_closing(struct mbuf * m,struct tcphdr * th,struct socket * so,struct tcpcb * tp,struct tcpopt * to,int32_t drop_hdrlen,int32_t tlen,uint32_t tiwin,int32_t thflags,int32_t nxt_pkt,uint8_t iptos)9541 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9542     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9543     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9544 {
9545 	int32_t ourfinisacked = 0;
9546 	int32_t ret_val;
9547 	struct tcp_bbr *bbr;
9548 
9549 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9550 
9551 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9552 	ctf_calc_rwin(so, tp);
9553 	if ((thflags & TH_RST) ||
9554 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9555 		return (ctf_process_rst(m, th, so, tp));
9556 	/*
9557 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9558 	 * synchronized state.
9559 	 */
9560 	if (thflags & TH_SYN) {
9561 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9562 		return (ret_val);
9563 	}
9564 	/*
9565 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9566 	 * it's less than ts_recent, drop it.
9567 	 */
9568 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9569 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9570 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9571 			return (ret_val);
9572 	}
9573 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9574 		return (ret_val);
9575 	}
9576 	/*
9577 	 * If last ACK falls within this segment's sequence numbers, record
9578 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9579 	 * from the latest proposal of the tcplw@cray.com list (Braden
9580 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9581 	 * with our earlier PAWS tests, so this check should be solely
9582 	 * predicated on the sequence space of this segment. 3) That we
9583 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9584 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9585 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9586 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9587 	 * p.869. In such cases, we can still calculate the RTT correctly
9588 	 * when RCV.NXT == Last.ACK.Sent.
9589 	 */
9590 	if ((to->to_flags & TOF_TS) != 0 &&
9591 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9592 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9593 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9594 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9595 		tp->ts_recent = to->to_tsval;
9596 	}
9597 	/*
9598 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9599 	 * is on (half-synchronized state), then queue data for later
9600 	 * processing; else drop segment and return.
9601 	 */
9602 	if ((thflags & TH_ACK) == 0) {
9603 		if (tp->t_flags & TF_NEEDSYN) {
9604 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9605 			    tiwin, thflags, nxt_pkt));
9606 		} else if (tp->t_flags & TF_ACKNOW) {
9607 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9608 			bbr->r_wanted_output = 1;
9609 			return (ret_val);
9610 		} else {
9611 			ctf_do_drop(m, NULL);
9612 			return (0);
9613 		}
9614 	}
9615 	/*
9616 	 * Ack processing.
9617 	 */
9618 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9619 		return (ret_val);
9620 	}
9621 	if (ourfinisacked) {
9622 		tcp_twstart(tp);
9623 		m_freem(m);
9624 		return (1);
9625 	}
9626 	if (sbavail(&so->so_snd)) {
9627 		if (ctf_progress_timeout_check(tp, true)) {
9628 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9629 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9630 			return (1);
9631 		}
9632 	}
9633 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9634 	    tiwin, thflags, nxt_pkt));
9635 }
9636 
9637 /*
9638  * Return value of 1, the TCB is unlocked and most
9639  * likely gone, return value of 0, the TCB is still
9640  * locked.
9641  */
9642 static int
bbr_do_lastack(struct mbuf * m,struct tcphdr * th,struct socket * so,struct tcpcb * tp,struct tcpopt * to,int32_t drop_hdrlen,int32_t tlen,uint32_t tiwin,int32_t thflags,int32_t nxt_pkt,uint8_t iptos)9643 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9644     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9645     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9646 {
9647 	int32_t ourfinisacked = 0;
9648 	int32_t ret_val;
9649 	struct tcp_bbr *bbr;
9650 
9651 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9652 
9653 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9654 	ctf_calc_rwin(so, tp);
9655 	if ((thflags & TH_RST) ||
9656 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9657 		return (ctf_process_rst(m, th, so, tp));
9658 	/*
9659 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9660 	 * synchronized state.
9661 	 */
9662 	if (thflags & TH_SYN) {
9663 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9664 		return (ret_val);
9665 	}
9666 	/*
9667 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9668 	 * it's less than ts_recent, drop it.
9669 	 */
9670 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9671 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9672 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9673 			return (ret_val);
9674 	}
9675 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9676 		return (ret_val);
9677 	}
9678 	/*
9679 	 * If last ACK falls within this segment's sequence numbers, record
9680 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9681 	 * from the latest proposal of the tcplw@cray.com list (Braden
9682 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9683 	 * with our earlier PAWS tests, so this check should be solely
9684 	 * predicated on the sequence space of this segment. 3) That we
9685 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9686 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9687 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9688 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9689 	 * p.869. In such cases, we can still calculate the RTT correctly
9690 	 * when RCV.NXT == Last.ACK.Sent.
9691 	 */
9692 	if ((to->to_flags & TOF_TS) != 0 &&
9693 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9694 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9695 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9696 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9697 		tp->ts_recent = to->to_tsval;
9698 	}
9699 	/*
9700 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9701 	 * is on (half-synchronized state), then queue data for later
9702 	 * processing; else drop segment and return.
9703 	 */
9704 	if ((thflags & TH_ACK) == 0) {
9705 		if (tp->t_flags & TF_NEEDSYN) {
9706 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9707 			    tiwin, thflags, nxt_pkt));
9708 		} else if (tp->t_flags & TF_ACKNOW) {
9709 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9710 			bbr->r_wanted_output = 1;
9711 			return (ret_val);
9712 		} else {
9713 			ctf_do_drop(m, NULL);
9714 			return (0);
9715 		}
9716 	}
9717 	/*
9718 	 * case TCPS_LAST_ACK: Ack processing.
9719 	 */
9720 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9721 		return (ret_val);
9722 	}
9723 	if (ourfinisacked) {
9724 		tp = tcp_close(tp);
9725 		ctf_do_drop(m, tp);
9726 		return (1);
9727 	}
9728 	if (sbavail(&so->so_snd)) {
9729 		if (ctf_progress_timeout_check(tp, true)) {
9730 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9731 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9732 			return (1);
9733 		}
9734 	}
9735 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9736 	    tiwin, thflags, nxt_pkt));
9737 }
9738 
9739 /*
9740  * Return value of 1, the TCB is unlocked and most
9741  * likely gone, return value of 0, the TCB is still
9742  * locked.
9743  */
9744 static int
bbr_do_fin_wait_2(struct mbuf * m,struct tcphdr * th,struct socket * so,struct tcpcb * tp,struct tcpopt * to,int32_t drop_hdrlen,int32_t tlen,uint32_t tiwin,int32_t thflags,int32_t nxt_pkt,uint8_t iptos)9745 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9746     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9747     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9748 {
9749 	int32_t ourfinisacked = 0;
9750 	int32_t ret_val;
9751 	struct tcp_bbr *bbr;
9752 
9753 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9754 
9755 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9756 	ctf_calc_rwin(so, tp);
9757 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
9758 	if ((thflags & TH_RST) ||
9759 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9760 		return (ctf_process_rst(m, th, so, tp));
9761 
9762 	/*
9763 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9764 	 * synchronized state.
9765 	 */
9766 	if (thflags & TH_SYN) {
9767 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9768 		return (ret_val);
9769 	}
9770 	/*
9771 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9772 	 * it's less than ts_recent, drop it.
9773 	 */
9774 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9775 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9776 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9777 			return (ret_val);
9778 	}
9779 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9780 		return (ret_val);
9781 	}
9782 	/*
9783 	 * If new data are received on a connection after the user processes
9784 	 * are gone, then we may RST the other end depending on the outcome
9785 	 * of bbr_check_data_after_close.
9786 	 * We call a new function now so we might continue and setup
9787 	 * to reset at all data being ack'd.
9788 	 */
9789 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9790 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9791 		return (1);
9792 	/*
9793 	 * If last ACK falls within this segment's sequence numbers, record
9794 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9795 	 * from the latest proposal of the tcplw@cray.com list (Braden
9796 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9797 	 * with our earlier PAWS tests, so this check should be solely
9798 	 * predicated on the sequence space of this segment. 3) That we
9799 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9800 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9801 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9802 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9803 	 * p.869. In such cases, we can still calculate the RTT correctly
9804 	 * when RCV.NXT == Last.ACK.Sent.
9805 	 */
9806 	if ((to->to_flags & TOF_TS) != 0 &&
9807 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9808 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9809 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9810 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9811 		tp->ts_recent = to->to_tsval;
9812 	}
9813 	/*
9814 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9815 	 * is on (half-synchronized state), then queue data for later
9816 	 * processing; else drop segment and return.
9817 	 */
9818 	if ((thflags & TH_ACK) == 0) {
9819 		if (tp->t_flags & TF_NEEDSYN) {
9820 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9821 			    tiwin, thflags, nxt_pkt));
9822 		} else if (tp->t_flags & TF_ACKNOW) {
9823 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9824 			bbr->r_wanted_output = 1;
9825 			return (ret_val);
9826 		} else {
9827 			ctf_do_drop(m, NULL);
9828 			return (0);
9829 		}
9830 	}
9831 	/*
9832 	 * Ack processing.
9833 	 */
9834 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9835 		return (ret_val);
9836 	}
9837 	if (sbavail(&so->so_snd)) {
9838 		if (ctf_progress_timeout_check(tp, true)) {
9839 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9840 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9841 			return (1);
9842 		}
9843 	}
9844 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9845 	    tiwin, thflags, nxt_pkt));
9846 }
9847 
9848 static void
bbr_stop_all_timers(struct tcpcb * tp,struct tcp_bbr * bbr)9849 bbr_stop_all_timers(struct tcpcb *tp, struct tcp_bbr *bbr)
9850 {
9851 	/*
9852 	 * Assure no timers are running.
9853 	 */
9854 	if (tcp_timer_active(tp, TT_PERSIST)) {
9855 		/* We enter in persists, set the flag appropriately */
9856 		bbr->rc_in_persist = 1;
9857 	}
9858 	if (tcp_in_hpts(bbr->rc_tp)) {
9859 		tcp_hpts_remove(bbr->rc_tp);
9860 	}
9861 }
9862 
9863 static void
bbr_google_mode_on(struct tcp_bbr * bbr)9864 bbr_google_mode_on(struct tcp_bbr *bbr)
9865 {
9866 	bbr->rc_use_google = 1;
9867 	bbr->rc_no_pacing = 0;
9868 	bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9869 	bbr->r_use_policer = bbr_policer_detection_enabled;
9870 	bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
9871 	bbr->bbr_use_rack_cheat = 0;
9872 	bbr->r_ctl.rc_incr_tmrs = 0;
9873 	bbr->r_ctl.rc_inc_tcp_oh = 0;
9874 	bbr->r_ctl.rc_inc_ip_oh = 0;
9875 	bbr->r_ctl.rc_inc_enet_oh = 0;
9876 	reset_time(&bbr->r_ctl.rc_delrate,
9877 		   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
9878 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9879 			 (11 * USECS_IN_SECOND));
9880 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9881 }
9882 
9883 static void
bbr_google_mode_off(struct tcp_bbr * bbr)9884 bbr_google_mode_off(struct tcp_bbr *bbr)
9885 {
9886 	bbr->rc_use_google = 0;
9887 	bbr->r_ctl.bbr_google_discount = 0;
9888 	bbr->no_pacing_until = bbr_no_pacing_until;
9889 	bbr->r_use_policer = 0;
9890 	if (bbr->no_pacing_until)
9891 		bbr->rc_no_pacing = 1;
9892 	else
9893 		bbr->rc_no_pacing = 0;
9894 	if (bbr_use_rack_resend_cheat)
9895 		bbr->bbr_use_rack_cheat = 1;
9896 	else
9897 		bbr->bbr_use_rack_cheat = 0;
9898 	if (bbr_incr_timers)
9899 		bbr->r_ctl.rc_incr_tmrs = 1;
9900 	else
9901 		bbr->r_ctl.rc_incr_tmrs = 0;
9902 	if (bbr_include_tcp_oh)
9903 		bbr->r_ctl.rc_inc_tcp_oh = 1;
9904 	else
9905 		bbr->r_ctl.rc_inc_tcp_oh = 0;
9906 	if (bbr_include_ip_oh)
9907 		bbr->r_ctl.rc_inc_ip_oh = 1;
9908 	else
9909 		bbr->r_ctl.rc_inc_ip_oh = 0;
9910 	if (bbr_include_enet_oh)
9911 		bbr->r_ctl.rc_inc_enet_oh = 1;
9912 	else
9913 		bbr->r_ctl.rc_inc_enet_oh = 0;
9914 	bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
9915 	reset_time(&bbr->r_ctl.rc_delrate,
9916 		   bbr_num_pktepo_for_del_limit);
9917 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9918 			 (bbr_filter_len_sec * USECS_IN_SECOND));
9919 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9920 }
9921 /*
9922  * Return 0 on success, non-zero on failure
9923  * which indicates the error (usually no memory).
9924  */
9925 static int
bbr_init(struct tcpcb * tp,void ** ptr)9926 bbr_init(struct tcpcb *tp, void **ptr)
9927 {
9928 	struct inpcb *inp = tptoinpcb(tp);
9929 	struct tcp_bbr *bbr = NULL;
9930 	uint32_t cts;
9931 
9932 	tcp_hpts_init(tp);
9933 
9934 	*ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
9935 	if (*ptr == NULL) {
9936 		/*
9937 		 * We need to allocate memory but cant. The INP and INP_INFO
9938 		 * locks and they are recursive (happens during setup. So a
9939 		 * scheme to drop the locks fails :(
9940 		 *
9941 		 */
9942 		return (ENOMEM);
9943 	}
9944 	bbr = (struct tcp_bbr *)*ptr;
9945 	bbr->rtt_valid = 0;
9946 	tp->t_flags2 |= TF2_CANNOT_DO_ECN;
9947 	tp->t_flags2 |= TF2_SUPPORTS_MBUFQ;
9948 	/* Take off any undesired flags */
9949 	tp->t_flags2 &= ~TF2_MBUF_QUEUE_READY;
9950 	tp->t_flags2 &= ~TF2_DONT_SACK_QUEUE;
9951 	tp->t_flags2 &= ~TF2_MBUF_ACKCMP;
9952 	tp->t_flags2 &= ~TF2_MBUF_L_ACKS;
9953 
9954 	TAILQ_INIT(&bbr->r_ctl.rc_map);
9955 	TAILQ_INIT(&bbr->r_ctl.rc_free);
9956 	TAILQ_INIT(&bbr->r_ctl.rc_tmap);
9957 	bbr->rc_tp = tp;
9958 	bbr->rc_inp = inp;
9959 	cts = tcp_get_usecs(&bbr->rc_tv);
9960 	tp->t_acktime = 0;
9961 	bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
9962 	bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
9963 	bbr->rc_tlp_threshold = bbr_tlp_thresh;
9964 	bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
9965 	bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
9966 	bbr->r_ctl.rc_min_to = bbr_min_to;
9967 	bbr->rc_bbr_state = BBR_STATE_STARTUP;
9968 	bbr->r_ctl.bbr_lost_at_state = 0;
9969 	bbr->r_ctl.rc_lost_at_startup = 0;
9970 	bbr->rc_all_timers_stopped = 0;
9971 	bbr->r_ctl.rc_bbr_lastbtlbw = 0;
9972 	bbr->r_ctl.rc_pkt_epoch_del = 0;
9973 	bbr->r_ctl.rc_pkt_epoch = 0;
9974 	bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
9975 	bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
9976 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
9977 	bbr->r_ctl.rc_went_idle_time = cts;
9978 	bbr->rc_pacer_started = cts;
9979 	bbr->r_ctl.rc_pkt_epoch_time = cts;
9980 	bbr->r_ctl.rc_rcvtime = cts;
9981 	bbr->r_ctl.rc_bbr_state_time = cts;
9982 	bbr->r_ctl.rc_del_time = cts;
9983 	bbr->r_ctl.rc_tlp_rxt_last_time = cts;
9984 	bbr->r_ctl.last_in_probertt = cts;
9985 	bbr->skip_gain = 0;
9986 	bbr->gain_is_limited = 0;
9987 	bbr->no_pacing_until = bbr_no_pacing_until;
9988 	if (bbr->no_pacing_until)
9989 		bbr->rc_no_pacing = 1;
9990 	if (bbr_use_google_algo) {
9991 		bbr->rc_no_pacing = 0;
9992 		bbr->rc_use_google = 1;
9993 		bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9994 		bbr->r_use_policer = bbr_policer_detection_enabled;
9995 	} else {
9996 		bbr->rc_use_google = 0;
9997 		bbr->r_ctl.bbr_google_discount = 0;
9998 		bbr->r_use_policer = 0;
9999 	}
10000 	if (bbr_ts_limiting)
10001 		bbr->rc_use_ts_limit = 1;
10002 	else
10003 		bbr->rc_use_ts_limit = 0;
10004 	if (bbr_ts_can_raise)
10005 		bbr->ts_can_raise = 1;
10006 	else
10007 		bbr->ts_can_raise = 0;
10008 	if (V_tcp_delack_enabled == 1)
10009 		tp->t_delayed_ack = 2;
10010 	else if (V_tcp_delack_enabled == 0)
10011 		tp->t_delayed_ack = 0;
10012 	else if (V_tcp_delack_enabled < 100)
10013 		tp->t_delayed_ack = V_tcp_delack_enabled;
10014 	else
10015 		tp->t_delayed_ack = 2;
10016 	if (bbr->rc_use_google == 0)
10017 		bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10018 	else
10019 		bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10020 	bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10021 	bbr->rc_max_rto_sec = bbr_rto_max_sec;
10022 	bbr->rc_init_win = bbr_def_init_win;
10023 	if (tp->t_flags & TF_REQ_TSTMP)
10024 		bbr->rc_last_options = TCP_TS_OVERHEAD;
10025 	bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10026 	bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10027 	bbr->r_init_rtt = 1;
10028 
10029 	counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10030 	if (bbr_allow_hdwr_pacing)
10031 		bbr->bbr_hdw_pace_ena = 1;
10032 	else
10033 		bbr->bbr_hdw_pace_ena = 0;
10034 	if (bbr_sends_full_iwnd)
10035 		bbr->bbr_init_win_cheat = 1;
10036 	else
10037 		bbr->bbr_init_win_cheat = 0;
10038 	bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10039 	bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10040 	bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10041 	bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10042 	bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10043 	bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10044 	bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10045 	bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10046 	bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10047 	bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10048 	bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10049 	bbr->r_ctl.rc_rtt_shrinks = cts;
10050 	if (bbr->rc_use_google) {
10051 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10052 				  FILTER_TYPE_MAX,
10053 				  BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10054 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10055 					FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10056 	} else {
10057 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10058 				  FILTER_TYPE_MAX,
10059 				  bbr_num_pktepo_for_del_limit);
10060 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10061 					FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10062 	}
10063 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10064 	if (bbr_uses_idle_restart)
10065 		bbr->rc_use_idle_restart = 1;
10066 	else
10067 		bbr->rc_use_idle_restart = 0;
10068 	bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10069 	bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10070 	if (bbr_resends_use_tso)
10071 		bbr->rc_resends_use_tso = 1;
10072 	if (tp->snd_una != tp->snd_max) {
10073 		/* Create a send map for the current outstanding data */
10074 		struct bbr_sendmap *rsm;
10075 
10076 		rsm = bbr_alloc(bbr);
10077 		if (rsm == NULL) {
10078 			uma_zfree(bbr_pcb_zone, *ptr);
10079 			*ptr = NULL;
10080 			return (ENOMEM);
10081 		}
10082 		rsm->r_rtt_not_allowed = 1;
10083 		rsm->r_tim_lastsent[0] = cts;
10084 		rsm->r_rtr_cnt = 1;
10085 		rsm->r_rtr_bytes = 0;
10086 		rsm->r_start = tp->snd_una;
10087 		rsm->r_end = tp->snd_max;
10088 		rsm->r_dupack = 0;
10089 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
10090 		rsm->r_ts_valid = 0;
10091 		rsm->r_del_ack_ts = tp->ts_recent;
10092 		rsm->r_del_time = cts;
10093 		if (bbr->r_ctl.r_app_limited_until)
10094 			rsm->r_app_limited = 1;
10095 		else
10096 			rsm->r_app_limited = 0;
10097 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10098 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10099 		rsm->r_in_tmap = 1;
10100 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10101 			rsm->r_bbr_state = bbr_state_val(bbr);
10102 		else
10103 			rsm->r_bbr_state = 8;
10104 	}
10105 	if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10106 		bbr->bbr_use_rack_cheat = 1;
10107 	if (bbr_incr_timers && (bbr->rc_use_google == 0))
10108 		bbr->r_ctl.rc_incr_tmrs = 1;
10109 	if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10110 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10111 	if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10112 		bbr->r_ctl.rc_inc_ip_oh = 1;
10113 	if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10114 		bbr->r_ctl.rc_inc_enet_oh = 1;
10115 
10116 	bbr_log_type_statechange(bbr, cts, __LINE__);
10117 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10118 	    (tp->t_srtt)) {
10119 		uint32_t rtt;
10120 
10121 		rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10122 		apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10123 	}
10124 	/* announce the settings and state */
10125 	bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10126 	tcp_bbr_tso_size_check(bbr, cts);
10127 	/*
10128 	 * Now call the generic function to start a timer. This will place
10129 	 * the TCB on the hptsi wheel if a timer is needed with appropriate
10130 	 * flags.
10131 	 */
10132 	bbr_stop_all_timers(tp, bbr);
10133 	/*
10134 	 * Validate the timers are not in usec, if they are convert.
10135 	 * BBR should in theory move to USEC and get rid of a
10136 	 * lot of the TICKS_2 calls.. but for now we stay
10137 	 * with tick timers.
10138 	 */
10139 	tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
10140 	TCPT_RANGESET(tp->t_rxtcur,
10141 	    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
10142 	    tp->t_rttmin, TCPTV_REXMTMAX);
10143 	bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10144 	return (0);
10145 }
10146 
10147 /*
10148  * Return 0 if we can accept the connection. Return
10149  * non-zero if we can't handle the connection. A EAGAIN
10150  * means you need to wait until the connection is up.
10151  * a EADDRNOTAVAIL means we can never handle the connection
10152  * (no SACK).
10153  */
10154 static int
bbr_handoff_ok(struct tcpcb * tp)10155 bbr_handoff_ok(struct tcpcb *tp)
10156 {
10157 	if ((tp->t_state == TCPS_CLOSED) ||
10158 	    (tp->t_state == TCPS_LISTEN)) {
10159 		/* Sure no problem though it may not stick */
10160 		return (0);
10161 	}
10162 	if ((tp->t_state == TCPS_SYN_SENT) ||
10163 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
10164 		/*
10165 		 * We really don't know you have to get to ESTAB or beyond
10166 		 * to tell.
10167 		 */
10168 		return (EAGAIN);
10169 	}
10170 	if (tp->t_flags & TF_SENTFIN)
10171 		return (EINVAL);
10172 	if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10173 		return (0);
10174 	}
10175 	/*
10176 	 * If we reach here we don't do SACK on this connection so we can
10177 	 * never do rack.
10178 	 */
10179 	return (EINVAL);
10180 }
10181 
10182 static void
bbr_fini(struct tcpcb * tp,int32_t tcb_is_purged)10183 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10184 {
10185 	if (tp->t_fb_ptr) {
10186 		uint32_t calc;
10187 		struct tcp_bbr *bbr;
10188 		struct bbr_sendmap *rsm;
10189 
10190 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10191 		if (bbr->r_ctl.crte)
10192 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10193 		bbr_log_flowend(bbr);
10194 		bbr->rc_tp = NULL;
10195 		if (bbr->bbr_hdrw_pacing)
10196 			counter_u64_add(bbr_flows_whdwr_pacing, -1);
10197 		else
10198 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10199 		if (bbr->r_ctl.crte != NULL) {
10200 			tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
10201 			bbr->r_ctl.crte = NULL;
10202 		}
10203 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10204 		while (rsm) {
10205 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10206 			uma_zfree(bbr_zone, rsm);
10207 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10208 		}
10209 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10210 		while (rsm) {
10211 			TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10212 			uma_zfree(bbr_zone, rsm);
10213 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10214 		}
10215 		calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10216 		if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10217 			BBR_STAT_INC(bbr_dynamic_rwnd);
10218 		else
10219 			BBR_STAT_INC(bbr_static_rwnd);
10220 		bbr->r_ctl.rc_free_cnt = 0;
10221 		uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10222 		tp->t_fb_ptr = NULL;
10223 	}
10224 	/* Make sure snd_nxt is correctly set */
10225 	tp->snd_nxt = tp->snd_max;
10226 }
10227 
10228 static void
bbr_set_state(struct tcpcb * tp,struct tcp_bbr * bbr,uint32_t win)10229 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10230 {
10231 	switch (tp->t_state) {
10232 	case TCPS_SYN_SENT:
10233 		bbr->r_state = TCPS_SYN_SENT;
10234 		bbr->r_substate = bbr_do_syn_sent;
10235 		break;
10236 	case TCPS_SYN_RECEIVED:
10237 		bbr->r_state = TCPS_SYN_RECEIVED;
10238 		bbr->r_substate = bbr_do_syn_recv;
10239 		break;
10240 	case TCPS_ESTABLISHED:
10241 		bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10242 		bbr->r_state = TCPS_ESTABLISHED;
10243 		bbr->r_substate = bbr_do_established;
10244 		break;
10245 	case TCPS_CLOSE_WAIT:
10246 		bbr->r_state = TCPS_CLOSE_WAIT;
10247 		bbr->r_substate = bbr_do_close_wait;
10248 		break;
10249 	case TCPS_FIN_WAIT_1:
10250 		bbr->r_state = TCPS_FIN_WAIT_1;
10251 		bbr->r_substate = bbr_do_fin_wait_1;
10252 		break;
10253 	case TCPS_CLOSING:
10254 		bbr->r_state = TCPS_CLOSING;
10255 		bbr->r_substate = bbr_do_closing;
10256 		break;
10257 	case TCPS_LAST_ACK:
10258 		bbr->r_state = TCPS_LAST_ACK;
10259 		bbr->r_substate = bbr_do_lastack;
10260 		break;
10261 	case TCPS_FIN_WAIT_2:
10262 		bbr->r_state = TCPS_FIN_WAIT_2;
10263 		bbr->r_substate = bbr_do_fin_wait_2;
10264 		break;
10265 	case TCPS_LISTEN:
10266 	case TCPS_CLOSED:
10267 	case TCPS_TIME_WAIT:
10268 	default:
10269 		break;
10270 	};
10271 }
10272 
10273 static void
bbr_substate_change(struct tcp_bbr * bbr,uint32_t cts,int32_t line,int dolog)10274 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10275 {
10276 	/*
10277 	 * Now what state are we going into now? Is there adjustments
10278 	 * needed?
10279 	 */
10280 	int32_t old_state;
10281 
10282 	old_state = bbr_state_val(bbr);
10283 	if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10284 		/* Save the lowest srtt we saw in our end of the sub-state */
10285 		bbr->rc_hit_state_1 = 0;
10286 		if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10287 			bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10288 	}
10289 	bbr->rc_bbr_substate++;
10290 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10291 		/*
10292 		 * We enter the gain(5/4) cycle (possibly less if
10293 		 * shallow buffer detection is enabled)
10294 		 */
10295 		if (bbr->skip_gain) {
10296 			/*
10297 			 * Hardware pacing has set our rate to
10298 			 * the max and limited our b/w just
10299 			 * do level i.e. no gain.
10300 			 */
10301 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10302 		} else if (bbr->gain_is_limited &&
10303 			   bbr->bbr_hdrw_pacing &&
10304 			   bbr->r_ctl.crte) {
10305 			/*
10306 			 * We can't gain above the hardware pacing
10307 			 * rate which is less than our rate + the gain
10308 			 * calculate the gain needed to reach the hardware
10309 			 * pacing rate..
10310 			 */
10311 			uint64_t bw, rate, gain_calc;
10312 
10313 			bw = bbr_get_bw(bbr);
10314 			rate = bbr->r_ctl.crte->rate;
10315 			if ((rate > bw) &&
10316 			    (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10317 				gain_calc = (rate * BBR_UNIT) / bw;
10318 				if (gain_calc < BBR_UNIT)
10319 					gain_calc = BBR_UNIT;
10320 				bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10321 			} else {
10322 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10323 			}
10324 		} else
10325 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10326 		if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10327 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10328 		} else
10329 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10330 	} else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10331 		bbr->rc_hit_state_1 = 1;
10332 		bbr->r_ctl.rc_exta_time_gd = 0;
10333 		bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10334 						     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10335 		if (bbr_state_drain_2_tar) {
10336 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10337 		} else
10338 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10339 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10340 	} else {
10341 		/* All other cycles hit here 2-7 */
10342 		if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10343 			if (bbr_sub_drain_slam_cwnd &&
10344 			    (bbr->rc_use_google == 0) &&
10345 			    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10346 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10347 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10348 			}
10349 			if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10350 				bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10351 							       bbr_get_rtt(bbr, BBR_RTT_PROP));
10352 			else
10353 				bbr->r_ctl.rc_exta_time_gd = 0;
10354 			if (bbr->r_ctl.rc_exta_time_gd) {
10355 				bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10356 				/* Now chop up the time for each state (div by 7) */
10357 				bbr->r_ctl.rc_level_state_extra /= 7;
10358 				if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10359 					/* Add a randomization */
10360 					bbr_randomize_extra_state_time(bbr);
10361 				}
10362 			}
10363 		}
10364 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10365 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10366 	}
10367 	if (bbr->rc_use_google) {
10368 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10369 	}
10370 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10371 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10372 	if (dolog)
10373 		bbr_log_type_statechange(bbr, cts, line);
10374 
10375 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10376 		uint32_t time_in;
10377 
10378 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10379 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10380 			counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10381 		} else {
10382 			counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10383 		}
10384 	}
10385 	bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10386 	bbr_set_state_target(bbr, __LINE__);
10387 	if (bbr_sub_drain_slam_cwnd &&
10388 	    (bbr->rc_use_google == 0) &&
10389 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10390 		/* Slam down the cwnd */
10391 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10392 		bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10393 		if (bbr_sub_drain_app_limit) {
10394 			/* Go app limited if we are on a long drain */
10395 			bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10396 							  ctf_flight_size(bbr->rc_tp,
10397 							      (bbr->r_ctl.rc_sacked +
10398 							       bbr->r_ctl.rc_lost_bytes)));
10399 		}
10400 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10401 	}
10402 	if (bbr->rc_lt_use_bw) {
10403 		/* In policed mode we clamp pacing_gain to BBR_UNIT */
10404 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10405 	}
10406 	/* Google changes TSO size every cycle */
10407 	if (bbr->rc_use_google)
10408 		tcp_bbr_tso_size_check(bbr, cts);
10409 	bbr->r_ctl.gain_epoch = cts;
10410 	bbr->r_ctl.rc_bbr_state_time = cts;
10411 	bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10412 }
10413 
10414 static void
bbr_set_probebw_google_gains(struct tcp_bbr * bbr,uint32_t cts,uint32_t losses)10415 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10416 {
10417 	if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10418 	    (google_allow_early_out == 1) &&
10419 	    (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10420 		/* We have reached out target flight size possibly early */
10421 		goto change_state;
10422 	}
10423 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10424 		return;
10425 	}
10426 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10427 		/*
10428 		 * Must be a rttProp movement forward before
10429 		 * we can change states.
10430 		 */
10431 		return;
10432 	}
10433 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10434 		/*
10435 		 * The needed time has passed but for
10436 		 * the gain cycle extra rules apply:
10437 		 * 1) If we have seen loss, we exit
10438 		 * 2) If we have not reached the target
10439 		 *    we stay in GAIN (gain-to-target).
10440 		 */
10441 		if (google_consider_lost && losses)
10442 			goto change_state;
10443 		if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10444 			return;
10445 		}
10446 	}
10447 change_state:
10448 	/* For gain we must reach our target, all others last 1 rttProp */
10449 	bbr_substate_change(bbr, cts, __LINE__, 1);
10450 }
10451 
10452 static void
bbr_set_probebw_gains(struct tcp_bbr * bbr,uint32_t cts,uint32_t losses)10453 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10454 {
10455 	uint32_t flight, bbr_cur_cycle_time;
10456 
10457 	if (bbr->rc_use_google) {
10458 		bbr_set_probebw_google_gains(bbr, cts, losses);
10459 		return;
10460 	}
10461 	if (cts == 0) {
10462 		/*
10463 		 * Never alow cts to be 0 we
10464 		 * do this so we can judge if
10465 		 * we have set a timestamp.
10466 		 */
10467 		cts = 1;
10468 	}
10469 	if (bbr_state_is_pkt_epoch)
10470 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10471 	else
10472 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10473 
10474 	if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10475 		if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10476 			flight = ctf_flight_size(bbr->rc_tp,
10477 				     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10478 			if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10479 				/* Keep it slam down */
10480 				if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10481 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10482 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10483 				}
10484 				if (bbr_sub_drain_app_limit) {
10485 					/* Go app limited if we are on a long drain */
10486 					bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10487 				}
10488 			}
10489 			if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10490 			    (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10491 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
10492 				/*
10493 				 * Still here after the same time as
10494 				 * the gain. We need to drain harder
10495 				 * for the next srtt. Reduce by a set amount
10496 				 * the gain drop is capped at DRAIN states
10497 				 * value (88).
10498 				 */
10499 				bbr->r_ctl.flightsize_at_drain = flight;
10500 				if (bbr_drain_drop_mul &&
10501 				    bbr_drain_drop_div &&
10502 				    (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10503 					/* Use your specific drop value (def 4/5 = 20%) */
10504 					bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10505 					bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10506 				} else {
10507 					/* You get drop of 20% */
10508 					bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10509 					bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10510 				}
10511 				if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10512 					/* Reduce our gain again to the bottom  */
10513 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10514 				}
10515 				bbr_log_exit_gain(bbr, cts, 4);
10516 				/*
10517 				 * Extend out so we wait another
10518 				 * epoch before dropping again.
10519 				 */
10520 				bbr->r_ctl.gain_epoch = cts;
10521 			}
10522 			if (flight <= bbr->r_ctl.rc_target_at_state) {
10523 				if (bbr_sub_drain_slam_cwnd &&
10524 				    (bbr->rc_use_google == 0) &&
10525 				    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10526 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10527 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10528 				}
10529 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10530 				bbr_log_exit_gain(bbr, cts, 3);
10531 			}
10532 		} else {
10533 			/* Its a gain  */
10534 			if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10535 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10536 				goto change_state;
10537 			}
10538 			if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10539 			    ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10540 			     bbr->rc_tp->snd_wnd)) {
10541 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10542 				bbr_log_exit_gain(bbr, cts, 2);
10543 			}
10544 		}
10545 		/**
10546 		 * We fall through and return always one of two things has
10547 		 * occurred.
10548 		 * 1) We are still not at target
10549 		 *    <or>
10550 		 * 2) We reached the target and set rc_bbr_state_atflight
10551 		 *    which means we no longer hit this block
10552 		 *    next time we are called.
10553 		 */
10554 		return;
10555 	}
10556 change_state:
10557 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10558 		return;
10559 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10560 		/* Less than a full time-period has passed */
10561 		return;
10562 	}
10563 	if (bbr->r_ctl.rc_level_state_extra &&
10564 	    (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10565 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10566 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10567 		/* Less than a full time-period + extra has passed */
10568 		return;
10569 	}
10570 	if (bbr_gain_gets_extra_too &&
10571 	    bbr->r_ctl.rc_level_state_extra &&
10572 	    (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10573 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10574 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10575 		/* Less than a full time-period + extra has passed */
10576 		return;
10577 	}
10578 	bbr_substate_change(bbr, cts, __LINE__, 1);
10579 }
10580 
10581 static uint32_t
bbr_get_a_state_target(struct tcp_bbr * bbr,uint32_t gain)10582 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10583 {
10584 	uint32_t mss, tar;
10585 
10586 	if (bbr->rc_use_google) {
10587 		/* Google just uses the cwnd target */
10588 		tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10589 	} else {
10590 		mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10591 			  bbr->r_ctl.rc_pace_max_segs);
10592 		/* Get the base cwnd with gain rounded to a mss */
10593 		tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10594 						      gain), mss);
10595 		/* Make sure it is within our min */
10596 		if (tar < get_min_cwnd(bbr))
10597 			return (get_min_cwnd(bbr));
10598 	}
10599 	return (tar);
10600 }
10601 
10602 static void
bbr_set_state_target(struct tcp_bbr * bbr,int line)10603 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10604 {
10605 	uint32_t tar, meth;
10606 
10607 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10608 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10609 		/* Special case using old probe-rtt method */
10610 		tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10611 		meth = 1;
10612 	} else {
10613 		/* Non-probe-rtt case and reduced probe-rtt  */
10614 		if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10615 		    (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10616 			/* For gain cycle we use the hptsi gain */
10617 			tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10618 			meth = 2;
10619 		} else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10620 			/*
10621 			 * If configured, or for google all other states
10622 			 * get BBR_UNIT.
10623 			 */
10624 			tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10625 			meth = 3;
10626 		} else {
10627 			/*
10628 			 * Or we set a target based on the pacing gain
10629 			 * for non-google mode and default (non-configured).
10630 			 * Note we don't set a target goal below drain (192).
10631 			 */
10632 			if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10633 				tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10634 				meth = 4;
10635 			} else {
10636 				tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10637 				meth = 5;
10638 			}
10639 		}
10640 	}
10641 	bbr_log_set_of_state_target(bbr, tar, line, meth);
10642 	bbr->r_ctl.rc_target_at_state = tar;
10643 }
10644 
10645 static void
bbr_enter_probe_rtt(struct tcp_bbr * bbr,uint32_t cts,int32_t line)10646 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10647 {
10648 	/* Change to probe_rtt */
10649 	uint32_t time_in;
10650 
10651 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10652 	bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10653 					     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10654 	bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10655 					  + bbr->r_ctl.rc_delivered);
10656 	/* Setup so we force feed the filter */
10657 	if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10658 		bbr->rc_prtt_set_ts = 1;
10659 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10660 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10661 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10662 	}
10663 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10664 	bbr->r_ctl.rc_rtt_shrinks = cts;
10665 	bbr->r_ctl.last_in_probertt = cts;
10666 	bbr->r_ctl.rc_probertt_srttchktim = cts;
10667 	bbr->r_ctl.rc_bbr_state_time = cts;
10668 	bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10669 	/* We need to force the filter to update */
10670 
10671 	if ((bbr_sub_drain_slam_cwnd) &&
10672 	    bbr->rc_hit_state_1 &&
10673 	    (bbr->rc_use_google == 0) &&
10674 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10675 		if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10676 			bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10677 	} else
10678 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10679 	/* Update the lost */
10680 	bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10681 	if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10682 		/* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10683 		bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10684 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10685 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10686 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10687 		bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10688 		bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10689 	} else {
10690 		/*
10691 		 * We bring it down slowly by using a hptsi gain that is
10692 		 * probably 75%. This will slowly float down our outstanding
10693 		 * without tampering with the cwnd.
10694 		 */
10695 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10696 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10697 		bbr_set_state_target(bbr, __LINE__);
10698 		if (bbr_prtt_slam_cwnd &&
10699 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10700 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10701 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10702 		}
10703 	}
10704 	if (ctf_flight_size(bbr->rc_tp,
10705 		(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10706 	    bbr->r_ctl.rc_target_at_state) {
10707 		/* We are at target */
10708 		bbr->r_ctl.rc_bbr_enters_probertt = cts;
10709 	} else {
10710 		/* We need to come down to reach target before our time begins */
10711 		bbr->r_ctl.rc_bbr_enters_probertt = 0;
10712 	}
10713 	bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10714 	BBR_STAT_INC(bbr_enter_probertt);
10715 	bbr_log_exit_gain(bbr, cts, 0);
10716 	bbr_log_type_statechange(bbr, cts, line);
10717 }
10718 
10719 static void
bbr_check_probe_rtt_limits(struct tcp_bbr * bbr,uint32_t cts)10720 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10721 {
10722 	/*
10723 	 * Sanity check on probe-rtt intervals.
10724 	 * In crazy situations where we are competing
10725 	 * against new-reno flows with huge buffers
10726 	 * our rtt-prop interval could come to dominate
10727 	 * things if we can't get through a full set
10728 	 * of cycles, we need to adjust it.
10729 	 */
10730 	if (bbr_can_adjust_probertt &&
10731 	    (bbr->rc_use_google == 0)) {
10732 		uint16_t val = 0;
10733 		uint32_t cur_rttp, fval, newval, baseval;
10734 
10735 		/* Are we to small and go into probe-rtt to often? */
10736 		baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10737 		cur_rttp = roundup(baseval, USECS_IN_SECOND);
10738 		fval = bbr_filter_len_sec * USECS_IN_SECOND;
10739 		if (bbr_is_ratio == 0) {
10740 			if (fval > bbr_rtt_probe_limit)
10741 				newval = cur_rttp + (fval - bbr_rtt_probe_limit);
10742 			else
10743 				newval = cur_rttp;
10744 		} else {
10745 			int mul;
10746 
10747 			mul = fval / bbr_rtt_probe_limit;
10748 			newval = cur_rttp * mul;
10749 		}
10750 		if (cur_rttp > 	bbr->r_ctl.rc_probertt_int) {
10751 			bbr->r_ctl.rc_probertt_int = cur_rttp;
10752 			reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10753 			val = 1;
10754 		} else {
10755 			/*
10756 			 * No adjustments were made
10757 			 * do we need to shrink it?
10758 			 */
10759 			if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
10760 				if (cur_rttp <= bbr_rtt_probe_limit) {
10761 					/*
10762 					 * Things have calmed down lets
10763 					 * shrink all the way to default
10764 					 */
10765 					bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10766 					reset_time_small(&bbr->r_ctl.rc_rttprop,
10767 							 (bbr_filter_len_sec * USECS_IN_SECOND));
10768 					cur_rttp = bbr_rtt_probe_limit;
10769 					newval = (bbr_filter_len_sec * USECS_IN_SECOND);
10770 					val = 2;
10771 				} else {
10772 					/*
10773 					 * Well does some adjustment make sense?
10774 					 */
10775 					if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
10776 						/* We can reduce interval time some */
10777 						bbr->r_ctl.rc_probertt_int = cur_rttp;
10778 						reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10779 						val = 3;
10780 					}
10781 				}
10782 			}
10783 		}
10784 		if (val)
10785 			bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
10786 	}
10787 }
10788 
10789 static void
bbr_exit_probe_rtt(struct tcpcb * tp,struct tcp_bbr * bbr,uint32_t cts)10790 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
10791 {
10792 	/* Exit probe-rtt */
10793 
10794 	if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
10795 		tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10796 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10797 	}
10798 	bbr_log_exit_gain(bbr, cts, 1);
10799 	bbr->rc_hit_state_1 = 0;
10800 	bbr->r_ctl.rc_rtt_shrinks = cts;
10801 	bbr->r_ctl.last_in_probertt = cts;
10802 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
10803 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10804 	bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
10805 					      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
10806 					  bbr->r_ctl.rc_delivered);
10807 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10808 		uint32_t time_in;
10809 
10810 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10811 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10812 	}
10813 	if (bbr->rc_filled_pipe) {
10814 		/* Switch to probe_bw */
10815 		bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
10816 		bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
10817 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10818 		bbr_substate_change(bbr, cts, __LINE__, 0);
10819 		bbr_log_type_statechange(bbr, cts, __LINE__);
10820 	} else {
10821 		/* Back to startup */
10822 		bbr->rc_bbr_state = BBR_STATE_STARTUP;
10823 		bbr->r_ctl.rc_bbr_state_time = cts;
10824 		/*
10825 		 * We don't want to give a complete free 3
10826 		 * measurements until we exit, so we use
10827 		 * the number of pe's we were in probe-rtt
10828 		 * to add to the startup_epoch. That way
10829 		 * we will still retain the old state.
10830 		 */
10831 		bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
10832 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10833 		/* Make sure to use the lower pg when shifting back in */
10834 		if (bbr->r_ctl.rc_lost &&
10835 		    bbr_use_lower_gain_in_startup &&
10836 		    (bbr->rc_use_google == 0))
10837 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10838 		else
10839 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
10840 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
10841 		/* Probably not needed but set it anyway */
10842 		bbr_set_state_target(bbr, __LINE__);
10843 		bbr_log_type_statechange(bbr, cts, __LINE__);
10844 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10845 		    bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 0);
10846 	}
10847 	bbr_check_probe_rtt_limits(bbr, cts);
10848 }
10849 
10850 static int32_t inline
bbr_should_enter_probe_rtt(struct tcp_bbr * bbr,uint32_t cts)10851 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
10852 {
10853 	if ((bbr->rc_past_init_win == 1) &&
10854 	    (bbr->rc_in_persist == 0) &&
10855 	    (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
10856 		return (1);
10857 	}
10858 	if (bbr_can_force_probertt &&
10859 	    (bbr->rc_in_persist == 0) &&
10860 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
10861 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
10862 		return (1);
10863 	}
10864 	return (0);
10865 }
10866 
10867 static int32_t
bbr_google_startup(struct tcp_bbr * bbr,uint32_t cts,int32_t pkt_epoch)10868 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
10869 {
10870 	uint64_t btlbw, gain;
10871 	if (pkt_epoch == 0) {
10872 		/*
10873 		 * Need to be on a pkt-epoch to continue.
10874 		 */
10875 		return (0);
10876 	}
10877 	btlbw = bbr_get_full_bw(bbr);
10878 	gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10879 		 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10880 	if (btlbw >= gain) {
10881 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10882 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10883 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10884 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10885 	}
10886 	if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
10887 		return (1);
10888 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10889 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
10890 	return(0);
10891 }
10892 
10893 static int32_t inline
bbr_state_startup(struct tcp_bbr * bbr,uint32_t cts,int32_t epoch,int32_t pkt_epoch)10894 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
10895 {
10896 	/* Have we gained 25% in the last 3 packet based epoch's? */
10897 	uint64_t btlbw, gain;
10898 	int do_exit;
10899 	int delta, rtt_gain;
10900 
10901 	if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
10902 	    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
10903 		/*
10904 		 * This qualifies as a RTT_PROBE session since we drop the
10905 		 * data outstanding to nothing and waited more than
10906 		 * bbr_rtt_probe_time.
10907 		 */
10908 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
10909 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
10910 	}
10911 	if (bbr_should_enter_probe_rtt(bbr, cts)) {
10912 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
10913 		return (0);
10914 	}
10915 	if (bbr->rc_use_google)
10916 		return (bbr_google_startup(bbr, cts,  pkt_epoch));
10917 
10918 	if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
10919 	    (bbr_use_lower_gain_in_startup)) {
10920 		/* Drop to a lower gain 1.5 x since we saw loss */
10921 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10922 	}
10923 	if (pkt_epoch == 0) {
10924 		/*
10925 		 * Need to be on a pkt-epoch to continue.
10926 		 */
10927 		return (0);
10928 	}
10929 	if (bbr_rtt_gain_thresh) {
10930 		/*
10931 		 * Do we allow a flow to stay
10932 		 * in startup with no loss and no
10933 		 * gain in rtt over a set threshold?
10934 		 */
10935 		if (bbr->r_ctl.rc_pkt_epoch_rtt &&
10936 		    bbr->r_ctl.startup_last_srtt &&
10937 		    (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
10938 			delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
10939 			rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
10940 		} else
10941 			rtt_gain = 0;
10942 		if ((bbr->r_ctl.startup_last_srtt == 0)  ||
10943 		    (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
10944 			/* First time or new lower value */
10945 			bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
10946 
10947 		if ((bbr->r_ctl.rc_lost == 0) &&
10948 		    (rtt_gain < bbr_rtt_gain_thresh)) {
10949 			/*
10950 			 * No loss, and we are under
10951 			 * our gain threhold for
10952 			 * increasing RTT.
10953 			 */
10954 			if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
10955 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
10956 			bbr_log_startup_event(bbr, cts, rtt_gain,
10957 					      delta, bbr->r_ctl.startup_last_srtt, 10);
10958 			return (0);
10959 		}
10960 	}
10961 	if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
10962 	    (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
10963 	    (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
10964 		/*
10965 		 * We only assess if we have a new measurement when
10966 		 * we have no loss and are not in recovery.
10967 		 * Drag up by one our last_startup epoch so we will hold
10968 		 * the number of non-gain we have already accumulated.
10969 		 */
10970 		if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
10971 			bbr->r_ctl.rc_bbr_last_startup_epoch++;
10972 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10973 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 9);
10974 		return (0);
10975 	}
10976 	/* Case where we reduced the lost (bad retransmit) */
10977 	if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
10978 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10979 	bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
10980 	btlbw = bbr_get_full_bw(bbr);
10981 	if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
10982 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10983 			 (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10984 	else
10985 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10986 			 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10987 	do_exit = 0;
10988 	if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
10989 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10990 	if (btlbw >= gain) {
10991 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10992 		/* Update the lost so we won't exit in next set of tests */
10993 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10994 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10995 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10996 	}
10997 	if ((bbr->rc_loss_exit &&
10998 	     (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
10999 	     (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
11000 	    ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
11001 		/*
11002 		 * If we had no gain,  we had loss and that loss was above
11003 		 * our threshould, the rwnd is not constrained, and we have
11004 		 * had at least 3 packet epochs exit. Note that this is
11005 		 * switched off by sysctl. Google does not do this by the
11006 		 * way.
11007 		 */
11008 		if ((ctf_flight_size(bbr->rc_tp,
11009 			 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11010 		     (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11011 			do_exit = 1;
11012 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11013 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11014 		} else {
11015 			/* Just record an updated loss value */
11016 			bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11017 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11018 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11019 		}
11020 	} else
11021 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11022 	if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11023 	    do_exit) {
11024 		/* Return 1 to exit the startup state. */
11025 		return (1);
11026 	}
11027 	/* Stay in startup */
11028 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11029 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11030 	return (0);
11031 }
11032 
11033 static void
bbr_state_change(struct tcp_bbr * bbr,uint32_t cts,int32_t epoch,int32_t pkt_epoch,uint32_t losses)11034 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11035 {
11036 	/*
11037 	 * A tick occurred in the rtt epoch do we need to do anything?
11038 	 */
11039 #ifdef BBR_INVARIANTS
11040 	if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11041 	    (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11042 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11043 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11044 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11045 		/* Debug code? */
11046 		panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11047 	}
11048 #endif
11049 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11050 		/* Do we exit the startup state? */
11051 		if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11052 			uint32_t time_in;
11053 
11054 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11055 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11056 			bbr->rc_filled_pipe = 1;
11057 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11058 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11059 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11060 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11061 			} else
11062 				time_in = 0;
11063 			if (bbr->rc_no_pacing)
11064 				bbr->rc_no_pacing = 0;
11065 			bbr->r_ctl.rc_bbr_state_time = cts;
11066 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11067 			bbr->rc_bbr_state = BBR_STATE_DRAIN;
11068 			bbr_set_state_target(bbr, __LINE__);
11069 			if ((bbr->rc_use_google == 0) &&
11070 			    bbr_slam_cwnd_in_main_drain) {
11071 				/* Here we don't have to worry about probe-rtt */
11072 				bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
11073 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11074 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11075 			}
11076 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11077 			bbr_log_type_statechange(bbr, cts, __LINE__);
11078 			if (ctf_flight_size(bbr->rc_tp,
11079 			        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11080 			    bbr->r_ctl.rc_target_at_state) {
11081 				/*
11082 				 * Switch to probe_bw if we are already
11083 				 * there
11084 				 */
11085 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11086 				bbr_substate_change(bbr, cts, __LINE__, 0);
11087 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11088 				bbr_log_type_statechange(bbr, cts, __LINE__);
11089 			}
11090 		}
11091 	} else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11092 		uint32_t inflight;
11093 		struct tcpcb *tp;
11094 
11095 		tp = bbr->rc_tp;
11096 		inflight = ctf_flight_size(tp,
11097 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11098 		if (inflight >= bbr->r_ctl.rc_target_at_state) {
11099 			/* We have reached a flight of the cwnd target */
11100 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11101 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11102 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11103 			bbr_set_state_target(bbr, __LINE__);
11104 			/*
11105 			 * Rig it so we don't do anything crazy and
11106 			 * start fresh with a new randomization.
11107 			 */
11108 			bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11109 			bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11110 			bbr_substate_change(bbr, cts, __LINE__, 1);
11111 		}
11112 	} else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11113 		/* Has in-flight reached the bdp (or less)? */
11114 		uint32_t inflight;
11115 		struct tcpcb *tp;
11116 
11117 		tp = bbr->rc_tp;
11118 		inflight = ctf_flight_size(tp,
11119 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11120 		if ((bbr->rc_use_google == 0) &&
11121 		    bbr_slam_cwnd_in_main_drain &&
11122 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11123 			/*
11124 			 * Here we don't have to worry about probe-rtt
11125 			 * re-slam it, but keep it slammed down.
11126 			 */
11127 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11128 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11129 		}
11130 		if (inflight <= bbr->r_ctl.rc_target_at_state) {
11131 			/* We have drained */
11132 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11133 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11134 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11135 				uint32_t time_in;
11136 
11137 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11138 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11139 			}
11140 			if ((bbr->rc_use_google == 0) &&
11141 			    bbr_slam_cwnd_in_main_drain &&
11142 			    (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11143 				/* Restore the cwnd */
11144 				tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11145 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11146 			}
11147 			/* Setup probe-rtt has being done now RRS-HERE */
11148 			bbr->r_ctl.rc_rtt_shrinks = cts;
11149 			bbr->r_ctl.last_in_probertt = cts;
11150 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11151 			/* Randomly pick a sub-state */
11152 			bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11153 			bbr_substate_change(bbr, cts, __LINE__, 0);
11154 			bbr_log_type_statechange(bbr, cts, __LINE__);
11155 		}
11156 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11157 		uint32_t flight;
11158 
11159 		flight = ctf_flight_size(bbr->rc_tp,
11160 			     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11161 		bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11162 		if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11163 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11164 			/*
11165 			 * We must keep cwnd at the desired MSS.
11166 			 */
11167 			bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11168 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11169 		} else if ((bbr_prtt_slam_cwnd) &&
11170 			   (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11171 			/* Re-slam it */
11172 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11173 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11174 		}
11175 		if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11176 			/* Has outstanding reached our target? */
11177 			if (flight <= bbr->r_ctl.rc_target_at_state) {
11178 				bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11179 				bbr->r_ctl.rc_bbr_enters_probertt = cts;
11180 				/* If time is exactly 0, be 1usec off */
11181 				if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11182 					bbr->r_ctl.rc_bbr_enters_probertt = 1;
11183 				if (bbr->rc_use_google == 0) {
11184 					/*
11185 					 * Restore any lowering that as occurred to
11186 					 * reach here
11187 					 */
11188 					if (bbr->r_ctl.bbr_rttprobe_gain_val)
11189 						bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11190 					else
11191 						bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11192 				}
11193 			}
11194 			if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11195 			    (bbr->rc_use_google == 0) &&
11196 			    bbr->r_ctl.bbr_rttprobe_gain_val &&
11197 			    (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11198 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
11199 				/*
11200 				 * We have doddled with our current hptsi
11201 				 * gain an srtt and have still not made it
11202 				 * to target, or we have increased our flight.
11203 				 * Lets reduce the gain by xx%
11204 				 * flooring the reduce at DRAIN (based on
11205 				 * mul/div)
11206 				 */
11207 				int red;
11208 
11209 				bbr->r_ctl.flightsize_at_drain = flight;
11210 				bbr->r_ctl.rc_probertt_srttchktim = cts;
11211 				red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11212 				if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11213 					/* Reduce our gain again */
11214 					bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11215 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11216 				} else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11217 					/* one more chance before we give up */
11218 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11219 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11220 				} else {
11221 					/* At the very bottom */
11222 					bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11223 				}
11224 			}
11225 		}
11226 		if (bbr->r_ctl.rc_bbr_enters_probertt &&
11227 		    (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11228 		    ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11229 			/* Time to exit probe RTT normally */
11230 			bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11231 		}
11232 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11233 		if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11234 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11235 			/*
11236 			 * This qualifies as a RTT_PROBE session since we
11237 			 * drop the data outstanding to nothing and waited
11238 			 * more than bbr_rtt_probe_time.
11239 			 */
11240 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11241 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
11242 		}
11243 		if (bbr_should_enter_probe_rtt(bbr, cts)) {
11244 			bbr_enter_probe_rtt(bbr, cts, __LINE__);
11245 		} else {
11246 			bbr_set_probebw_gains(bbr, cts, losses);
11247 		}
11248 	}
11249 }
11250 
11251 static void
bbr_check_bbr_for_state(struct tcp_bbr * bbr,uint32_t cts,int32_t line,uint32_t losses)11252 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11253 {
11254 	int32_t epoch = 0;
11255 
11256 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11257 		bbr_set_epoch(bbr, cts, line);
11258 		/* At each epoch doe lt bw sampling */
11259 		epoch = 1;
11260 	}
11261 	bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11262 }
11263 
11264 static int
bbr_do_segment_nounlock(struct tcpcb * tp,struct mbuf * m,struct tcphdr * th,int32_t drop_hdrlen,int32_t tlen,uint8_t iptos,int32_t nxt_pkt,struct timeval * tv)11265 bbr_do_segment_nounlock(struct tcpcb *tp, struct mbuf *m, struct tcphdr *th,
11266     int32_t drop_hdrlen, int32_t tlen, uint8_t iptos, int32_t nxt_pkt,
11267     struct timeval *tv)
11268 {
11269 	struct inpcb *inp = tptoinpcb(tp);
11270 	struct socket *so = tptosocket(tp);
11271 	int32_t thflags, retval;
11272 	uint32_t cts, lcts;
11273 	uint32_t tiwin;
11274 	struct tcpopt to;
11275 	struct tcp_bbr *bbr;
11276 	struct bbr_sendmap *rsm;
11277 	struct timeval ltv;
11278 	int32_t did_out = 0;
11279 	uint16_t nsegs;
11280 	int32_t prev_state;
11281 	uint32_t lost;
11282 
11283 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
11284 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11285 	/* add in our stats */
11286 	kern_prefetch(bbr, &prev_state);
11287 	prev_state = 0;
11288 	thflags = tcp_get_flags(th);
11289 	/*
11290 	 * If this is either a state-changing packet or current state isn't
11291 	 * established, we require a write lock on tcbinfo.  Otherwise, we
11292 	 * allow the tcbinfo to be in either alocked or unlocked, as the
11293 	 * caller may have unnecessarily acquired a write lock due to a
11294 	 * race.
11295 	 */
11296 	INP_WLOCK_ASSERT(tptoinpcb(tp));
11297 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11298 	    __func__));
11299 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11300 	    __func__));
11301 
11302 	tp->t_rcvtime = ticks;
11303 	/*
11304 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
11305 	 * the scale is zero.
11306 	 */
11307 	tiwin = th->th_win << tp->snd_scale;
11308 #ifdef STATS
11309 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11310 #endif
11311 
11312 	if (m->m_flags & M_TSTMP) {
11313 		/* Prefer the hardware timestamp if present */
11314 		struct timespec ts;
11315 
11316 		mbuf_tstmp2timespec(m, &ts);
11317 		bbr->rc_tv.tv_sec = ts.tv_sec;
11318 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11319 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11320 	} else if (m->m_flags & M_TSTMP_LRO) {
11321 		/* Next the arrival timestamp */
11322 		struct timespec ts;
11323 
11324 		mbuf_tstmp2timespec(m, &ts);
11325 		bbr->rc_tv.tv_sec = ts.tv_sec;
11326 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11327 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11328 	} else {
11329 		/*
11330 		 * Ok just get the current time.
11331 		 */
11332 		bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11333 	}
11334 	/*
11335 	 * Parse options on any incoming segment.
11336 	 */
11337 	tcp_dooptions(&to, (u_char *)(th + 1),
11338 	    (th->th_off << 2) - sizeof(struct tcphdr),
11339 	    (thflags & TH_SYN) ? TO_SYN : 0);
11340 
11341 	/*
11342 	 * If timestamps were negotiated during SYN/ACK and a
11343 	 * segment without a timestamp is received, silently drop
11344 	 * the segment, unless it is a RST segment or missing timestamps are
11345 	 * tolerated.
11346 	 * See section 3.2 of RFC 7323.
11347 	 */
11348 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
11349 	    ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
11350 		retval = 0;
11351 		m_freem(m);
11352 		goto done_with_input;
11353 	}
11354 	/*
11355 	 * If echoed timestamp is later than the current time, fall back to
11356 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
11357 	 * were used when this connection was established.
11358 	 */
11359 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
11360 		to.to_tsecr -= tp->ts_offset;
11361 		if (TSTMP_GT(to.to_tsecr, tcp_tv_to_mssectick(&bbr->rc_tv)))
11362 			to.to_tsecr = 0;
11363 	}
11364 	/*
11365 	 * If its the first time in we need to take care of options and
11366 	 * verify we can do SACK for rack!
11367 	 */
11368 	if (bbr->r_state == 0) {
11369 		/*
11370 		 * Process options only when we get SYN/ACK back. The SYN
11371 		 * case for incoming connections is handled in tcp_syncache.
11372 		 * According to RFC1323 the window field in a SYN (i.e., a
11373 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
11374 		 * this is traditional behavior, may need to be cleaned up.
11375 		 */
11376 		if (bbr->rc_inp == NULL) {
11377 			bbr->rc_inp = inp;
11378 		}
11379 		/*
11380 		 * We need to init rc_inp here since its not init'd when
11381 		 * bbr_init is called
11382 		 */
11383 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
11384 			if ((to.to_flags & TOF_SCALE) &&
11385 			    (tp->t_flags & TF_REQ_SCALE)) {
11386 				tp->t_flags |= TF_RCVD_SCALE;
11387 				tp->snd_scale = to.to_wscale;
11388 			} else
11389 				tp->t_flags &= ~TF_REQ_SCALE;
11390 			/*
11391 			 * Initial send window.  It will be updated with the
11392 			 * next incoming segment to the scaled value.
11393 			 */
11394 			tp->snd_wnd = th->th_win;
11395 			if ((to.to_flags & TOF_TS) &&
11396 			    (tp->t_flags & TF_REQ_TSTMP)) {
11397 				tp->t_flags |= TF_RCVD_TSTMP;
11398 				tp->ts_recent = to.to_tsval;
11399 				tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
11400 			} else
11401 			    tp->t_flags &= ~TF_REQ_TSTMP;
11402 			if (to.to_flags & TOF_MSS)
11403 				tcp_mss(tp, to.to_mss);
11404 			if ((tp->t_flags & TF_SACK_PERMIT) &&
11405 			    (to.to_flags & TOF_SACKPERM) == 0)
11406 				tp->t_flags &= ~TF_SACK_PERMIT;
11407 			if (IS_FASTOPEN(tp->t_flags)) {
11408 				if (to.to_flags & TOF_FASTOPEN) {
11409 					uint16_t mss;
11410 
11411 					if (to.to_flags & TOF_MSS)
11412 						mss = to.to_mss;
11413 					else
11414 						if ((inp->inp_vflag & INP_IPV6) != 0)
11415 							mss = TCP6_MSS;
11416 						else
11417 							mss = TCP_MSS;
11418 					tcp_fastopen_update_cache(tp, mss,
11419 					    to.to_tfo_len, to.to_tfo_cookie);
11420 				} else
11421 					tcp_fastopen_disable_path(tp);
11422 			}
11423 		}
11424 		/*
11425 		 * At this point we are at the initial call. Here we decide
11426 		 * if we are doing RACK or not. We do this by seeing if
11427 		 * TF_SACK_PERMIT is set, if not rack is *not* possible and
11428 		 * we switch to the default code.
11429 		 */
11430 		if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
11431 			/* Bail */
11432 			tcp_switch_back_to_default(tp);
11433 			(*tp->t_fb->tfb_tcp_do_segment)(tp, m, th, drop_hdrlen,
11434 			    tlen, iptos);
11435 			return (1);
11436 		}
11437 		/* Set the flag */
11438 		bbr->r_is_v6 = (inp->inp_vflag & INP_IPV6) != 0;
11439 		tcp_set_hpts(tp);
11440 		sack_filter_clear(&bbr->r_ctl.bbr_sf, th->th_ack);
11441 	}
11442 	if (thflags & TH_ACK) {
11443 		/* Track ack types */
11444 		if (to.to_flags & TOF_SACK)
11445 			BBR_STAT_INC(bbr_acks_with_sacks);
11446 		else
11447 			BBR_STAT_INC(bbr_plain_acks);
11448 	}
11449 	/*
11450 	 * This is the one exception case where we set the rack state
11451 	 * always. All other times (timers etc) we must have a rack-state
11452 	 * set (so we assure we have done the checks above for SACK).
11453 	 */
11454 	if (thflags & TH_FIN)
11455 		tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
11456 	if (bbr->r_state != tp->t_state)
11457 		bbr_set_state(tp, bbr, tiwin);
11458 
11459 	if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map)) != NULL)
11460 		kern_prefetch(rsm, &prev_state);
11461 	prev_state = bbr->r_state;
11462 	bbr->rc_ack_was_delayed = 0;
11463 	lost = bbr->r_ctl.rc_lost;
11464 	bbr->rc_is_pkt_epoch_now = 0;
11465 	if (m->m_flags & (M_TSTMP|M_TSTMP_LRO)) {
11466 		/* Get the real time into lcts and figure the real delay */
11467 		lcts = tcp_get_usecs(&ltv);
11468 		if (TSTMP_GT(lcts, cts)) {
11469 			bbr->r_ctl.rc_ack_hdwr_delay = lcts - cts;
11470 			bbr->rc_ack_was_delayed = 1;
11471 			if (TSTMP_GT(bbr->r_ctl.rc_ack_hdwr_delay,
11472 				     bbr->r_ctl.highest_hdwr_delay))
11473 				bbr->r_ctl.highest_hdwr_delay = bbr->r_ctl.rc_ack_hdwr_delay;
11474 		} else {
11475 			bbr->r_ctl.rc_ack_hdwr_delay = 0;
11476 			bbr->rc_ack_was_delayed = 0;
11477 		}
11478 	} else {
11479 		bbr->r_ctl.rc_ack_hdwr_delay = 0;
11480 		bbr->rc_ack_was_delayed = 0;
11481 	}
11482 	bbr_log_ack_event(bbr, th, &to, tlen, nsegs, cts, nxt_pkt, m);
11483 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
11484 		retval = 0;
11485 		m_freem(m);
11486 		goto done_with_input;
11487 	}
11488 	/*
11489 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
11490 	 * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
11491 	 */
11492 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
11493 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
11494 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11495 		ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11496 		return (1);
11497 	}
11498 	if (tiwin > bbr->r_ctl.rc_high_rwnd)
11499 		bbr->r_ctl.rc_high_rwnd = tiwin;
11500 	bbr->r_ctl.rc_flight_at_input = ctf_flight_size(tp,
11501 					    (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11502 	bbr->rtt_valid = 0;
11503 	if (to.to_flags & TOF_TS) {
11504 		bbr->rc_ts_valid = 1;
11505 		bbr->r_ctl.last_inbound_ts = to.to_tsval;
11506 	} else {
11507 		bbr->rc_ts_valid = 0;
11508 		bbr->r_ctl.last_inbound_ts = 0;
11509 	}
11510 	retval = (*bbr->r_substate) (m, th, so,
11511 	    tp, &to, drop_hdrlen,
11512 	    tlen, tiwin, thflags, nxt_pkt, iptos);
11513 	if (nxt_pkt == 0)
11514 		BBR_STAT_INC(bbr_rlock_left_ret0);
11515 	else
11516 		BBR_STAT_INC(bbr_rlock_left_ret1);
11517 	if (retval == 0) {
11518 		/*
11519 		 * If retval is 1 the tcb is unlocked and most likely the tp
11520 		 * is gone.
11521 		 */
11522 		INP_WLOCK_ASSERT(inp);
11523 		tcp_bbr_xmit_timer_commit(bbr, tp, cts);
11524 		if (bbr->rc_is_pkt_epoch_now)
11525 			bbr_set_pktepoch(bbr, cts, __LINE__);
11526 		bbr_check_bbr_for_state(bbr, cts, __LINE__, (bbr->r_ctl.rc_lost - lost));
11527 		if (nxt_pkt == 0) {
11528 			if (bbr->r_wanted_output != 0) {
11529 				bbr->rc_output_starts_timer = 0;
11530 				did_out = 1;
11531 				if (tcp_output(tp) < 0)
11532 					return (1);
11533 			} else
11534 				bbr_start_hpts_timer(bbr, tp, cts, 6, 0, 0);
11535 		}
11536 		if ((nxt_pkt == 0) &&
11537 		    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
11538 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
11539 		     (tp->t_flags & TF_DELACK) ||
11540 		     ((V_tcp_always_keepalive || bbr->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
11541 		      (tp->t_state <= TCPS_CLOSING)))) {
11542 			/*
11543 			 * We could not send (probably in the hpts but
11544 			 * stopped the timer)?
11545 			 */
11546 			if ((tp->snd_max == tp->snd_una) &&
11547 			    ((tp->t_flags & TF_DELACK) == 0) &&
11548 			    (tcp_in_hpts(tp)) &&
11549 			    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11550 				/*
11551 				 * keep alive not needed if we are hptsi
11552 				 * output yet
11553 				 */
11554 				;
11555 			} else {
11556 				if (tcp_in_hpts(tp)) {
11557 					tcp_hpts_remove(tp);
11558 					if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11559 					    (TSTMP_GT(lcts, bbr->rc_pacer_started))) {
11560 						uint32_t del;
11561 
11562 						del = lcts - bbr->rc_pacer_started;
11563 						if (bbr->r_ctl.rc_last_delay_val > del) {
11564 							BBR_STAT_INC(bbr_force_timer_start);
11565 							bbr->r_ctl.rc_last_delay_val -= del;
11566 							bbr->rc_pacer_started = lcts;
11567 						} else {
11568 							/* We are late */
11569 							bbr->r_ctl.rc_last_delay_val = 0;
11570 							BBR_STAT_INC(bbr_force_output);
11571 							if (tcp_output(tp) < 0)
11572 								return (1);
11573 						}
11574 					}
11575 				}
11576 				bbr_start_hpts_timer(bbr, tp, cts, 8, bbr->r_ctl.rc_last_delay_val,
11577 				    0);
11578 			}
11579 		} else if ((bbr->rc_output_starts_timer == 0) && (nxt_pkt == 0)) {
11580 			/* Do we have the correct timer running? */
11581 			bbr_timer_audit(tp, bbr, lcts, &so->so_snd);
11582 		}
11583 		/* Clear the flag, it may have been cleared by output but we may not have  */
11584 		if ((nxt_pkt == 0) && (tp->t_flags2 & TF2_HPTS_CALLS))
11585 			tp->t_flags2 &= ~TF2_HPTS_CALLS;
11586 		/* Do we have a new state */
11587 		if (bbr->r_state != tp->t_state)
11588 			bbr_set_state(tp, bbr, tiwin);
11589 done_with_input:
11590 		bbr_log_doseg_done(bbr, cts, nxt_pkt, did_out);
11591 		if (did_out)
11592 			bbr->r_wanted_output = 0;
11593 	}
11594 	return (retval);
11595 }
11596 
11597 static void
bbr_do_segment(struct tcpcb * tp,struct mbuf * m,struct tcphdr * th,int32_t drop_hdrlen,int32_t tlen,uint8_t iptos)11598 bbr_do_segment(struct tcpcb *tp, struct mbuf *m, struct tcphdr *th,
11599     int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
11600 {
11601 	struct timeval tv;
11602 	int retval;
11603 
11604 	/* First lets see if we have old packets */
11605 	if (!STAILQ_EMPTY(&tp->t_inqueue)) {
11606 		if (ctf_do_queued_segments(tp, 1)) {
11607 			m_freem(m);
11608 			return;
11609 		}
11610 	}
11611 	if (m->m_flags & M_TSTMP_LRO) {
11612 		mbuf_tstmp2timeval(m, &tv);
11613 	} else {
11614 		/* Should not be should we kassert instead? */
11615 		tcp_get_usecs(&tv);
11616 	}
11617 	retval = bbr_do_segment_nounlock(tp, m, th, drop_hdrlen, tlen, iptos,
11618 	    0, &tv);
11619 	if (retval == 0) {
11620 		INP_WUNLOCK(tptoinpcb(tp));
11621 	}
11622 }
11623 
11624 /*
11625  * Return how much data can be sent without violating the
11626  * cwnd or rwnd.
11627  */
11628 
11629 static inline uint32_t
bbr_what_can_we_send(struct tcpcb * tp,struct tcp_bbr * bbr,uint32_t sendwin,uint32_t avail,int32_t sb_offset,uint32_t cts)11630 bbr_what_can_we_send(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t sendwin,
11631     uint32_t avail, int32_t sb_offset, uint32_t cts)
11632 {
11633 	uint32_t len;
11634 
11635 	if (ctf_outstanding(tp) >= tp->snd_wnd) {
11636 		/* We never want to go over our peers rcv-window */
11637 		len = 0;
11638 	} else {
11639 		uint32_t flight;
11640 
11641 		flight = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11642 		if (flight >= sendwin) {
11643 			/*
11644 			 * We have in flight what we are allowed by cwnd (if
11645 			 * it was rwnd blocking it would have hit above out
11646 			 * >= tp->snd_wnd).
11647 			 */
11648 			return (0);
11649 		}
11650 		len = sendwin - flight;
11651 		if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
11652 			/* We would send too much (beyond the rwnd) */
11653 			len = tp->snd_wnd - ctf_outstanding(tp);
11654 		}
11655 		if ((len + sb_offset) > avail) {
11656 			/*
11657 			 * We don't have that much in the SB, how much is
11658 			 * there?
11659 			 */
11660 			len = avail - sb_offset;
11661 		}
11662 	}
11663 	return (len);
11664 }
11665 
11666 static inline void
bbr_do_send_accounting(struct tcpcb * tp,struct tcp_bbr * bbr,struct bbr_sendmap * rsm,int32_t len,int32_t error)11667 bbr_do_send_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11668 {
11669 	if (error) {
11670 		return;
11671 	}
11672 	if (rsm) {
11673 		if (rsm->r_flags & BBR_TLP) {
11674 			/*
11675 			 * TLP should not count in retran count, but in its
11676 			 * own bin
11677 			 */
11678 			KMOD_TCPSTAT_INC(tcps_tlpresends);
11679 			KMOD_TCPSTAT_ADD(tcps_tlpresend_bytes, len);
11680 		} else {
11681 			/* Retransmit */
11682 			tp->t_sndrexmitpack++;
11683 			KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
11684 			KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
11685 #ifdef STATS
11686 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
11687 			    len);
11688 #endif
11689 		}
11690 		/*
11691 		 * Logs in 0 - 8, 8 is all non probe_bw states 0-7 is
11692 		 * sub-state
11693 		 */
11694 		counter_u64_add(bbr_state_lost[rsm->r_bbr_state], len);
11695 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_BW) {
11696 			/* Non probe_bw log in 1, 2, or 4. */
11697 			counter_u64_add(bbr_state_resend[bbr->rc_bbr_state], len);
11698 		} else {
11699 			/*
11700 			 * Log our probe state 3, and log also 5-13 to show
11701 			 * us the recovery sub-state for the send. This
11702 			 * means that 3 == (5+6+7+8+9+10+11+12+13)
11703 			 */
11704 			counter_u64_add(bbr_state_resend[BBR_STATE_PROBE_BW], len);
11705 			counter_u64_add(bbr_state_resend[(bbr_state_val(bbr) + 5)], len);
11706 		}
11707 		/* Place in both 16's the totals of retransmitted */
11708 		counter_u64_add(bbr_state_lost[16], len);
11709 		counter_u64_add(bbr_state_resend[16], len);
11710 		/* Place in 17's the total sent */
11711 		counter_u64_add(bbr_state_resend[17], len);
11712 		counter_u64_add(bbr_state_lost[17], len);
11713 
11714 	} else {
11715 		/* New sends */
11716 		KMOD_TCPSTAT_INC(tcps_sndpack);
11717 		KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
11718 		/* Place in 17's the total sent */
11719 		counter_u64_add(bbr_state_resend[17], len);
11720 		counter_u64_add(bbr_state_lost[17], len);
11721 #ifdef STATS
11722 		stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
11723 		    len);
11724 #endif
11725 	}
11726 }
11727 
11728 static void
bbr_cwnd_limiting(struct tcpcb * tp,struct tcp_bbr * bbr,uint32_t in_level)11729 bbr_cwnd_limiting(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t in_level)
11730 {
11731 	if (bbr->rc_filled_pipe && bbr_target_cwnd_mult_limit && (bbr->rc_use_google == 0)) {
11732 		/*
11733 		 * Limit the cwnd to not be above N x the target plus whats
11734 		 * is outstanding. The target is based on the current b/w
11735 		 * estimate.
11736 		 */
11737 		uint32_t target;
11738 
11739 		target = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), BBR_UNIT);
11740 		target += ctf_outstanding(tp);
11741 		target *= bbr_target_cwnd_mult_limit;
11742 		if (tp->snd_cwnd > target)
11743 			tp->snd_cwnd = target;
11744 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 10, 0, 0, __LINE__);
11745 	}
11746 }
11747 
11748 static int
bbr_window_update_needed(struct tcpcb * tp,struct socket * so,uint32_t recwin,int32_t maxseg)11749 bbr_window_update_needed(struct tcpcb *tp, struct socket *so, uint32_t recwin, int32_t maxseg)
11750 {
11751 	/*
11752 	 * "adv" is the amount we could increase the window, taking into
11753 	 * account that we are limited by TCP_MAXWIN << tp->rcv_scale.
11754 	 */
11755 	int32_t adv;
11756 	int32_t oldwin;
11757 
11758 	adv = recwin;
11759 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
11760 		oldwin = (tp->rcv_adv - tp->rcv_nxt);
11761 		if (adv > oldwin)
11762 			adv -= oldwin;
11763 		else {
11764 			/* We can't increase the window */
11765 			adv = 0;
11766 		}
11767 	} else
11768 		oldwin = 0;
11769 
11770 	/*
11771 	 * If the new window size ends up being the same as or less
11772 	 * than the old size when it is scaled, then don't force
11773 	 * a window update.
11774 	 */
11775 	if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
11776 		return (0);
11777 
11778 	if (adv >= (2 * maxseg) &&
11779 	    (adv >= (so->so_rcv.sb_hiwat / 4) ||
11780 	    recwin <= (so->so_rcv.sb_hiwat / 8) ||
11781 	    so->so_rcv.sb_hiwat <= 8 * maxseg)) {
11782 		return (1);
11783 	}
11784 	if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
11785 		return (1);
11786 	return (0);
11787 }
11788 
11789 /*
11790  * Return 0 on success and a errno on failure to send.
11791  * Note that a 0 return may not mean we sent anything
11792  * if the TCB was on the hpts. A non-zero return
11793  * does indicate the error we got from ip[6]_output.
11794  */
11795 static int
bbr_output_wtime(struct tcpcb * tp,const struct timeval * tv)11796 bbr_output_wtime(struct tcpcb *tp, const struct timeval *tv)
11797 {
11798 	struct socket *so;
11799 	int32_t len;
11800 	uint32_t cts;
11801 	uint32_t recwin, sendwin;
11802 	int32_t sb_offset;
11803 	int32_t flags, abandon, error = 0;
11804 	struct tcp_log_buffer *lgb;
11805 	struct mbuf *m;
11806 	struct mbuf *mb;
11807 	uint32_t if_hw_tsomaxsegcount = 0;
11808 	uint32_t if_hw_tsomaxsegsize = 0;
11809 	uint32_t if_hw_tsomax = 0;
11810 	struct ip *ip = NULL;
11811 	struct tcp_bbr *bbr;
11812 	struct tcphdr *th;
11813 	struct udphdr *udp = NULL;
11814 	u_char opt[TCP_MAXOLEN];
11815 	unsigned ipoptlen, optlen, hdrlen;
11816 	unsigned ulen;
11817 	uint32_t bbr_seq;
11818 	uint32_t delay_calc=0;
11819 	uint8_t doing_tlp = 0;
11820 	uint8_t local_options;
11821 #ifdef BBR_INVARIANTS
11822 	uint8_t doing_retran_from = 0;
11823 	uint8_t picked_up_retran = 0;
11824 #endif
11825 	uint8_t wanted_cookie = 0;
11826 	uint8_t more_to_rxt=0;
11827 	int32_t prefetch_so_done = 0;
11828 	int32_t prefetch_rsm = 0;
11829 	uint32_t tot_len = 0;
11830 	uint32_t maxseg, pace_max_segs, p_maxseg;
11831 	int32_t csum_flags = 0;
11832  	int32_t hw_tls;
11833 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
11834 	unsigned ipsec_optlen = 0;
11835 
11836 #endif
11837 	volatile int32_t sack_rxmit;
11838 	struct bbr_sendmap *rsm = NULL;
11839 	int32_t tso, mtu;
11840 	struct tcpopt to;
11841 	int32_t slot = 0;
11842 	struct inpcb *inp;
11843 	struct sockbuf *sb;
11844 	bool hpts_calling;
11845 #ifdef INET6
11846 	struct ip6_hdr *ip6 = NULL;
11847 	int32_t isipv6;
11848 #endif
11849 	uint8_t app_limited = BBR_JR_SENT_DATA;
11850 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11851 	/* We take a cache hit here */
11852 	memcpy(&bbr->rc_tv, tv, sizeof(struct timeval));
11853 	cts = tcp_tv_to_usectick(&bbr->rc_tv);
11854 	inp = bbr->rc_inp;
11855 	hpts_calling = !!(tp->t_flags2 & TF2_HPTS_CALLS);
11856 	tp->t_flags2 &= ~TF2_HPTS_CALLS;
11857 	so = inp->inp_socket;
11858 	sb = &so->so_snd;
11859 	if (tp->t_nic_ktls_xmit)
11860  		hw_tls = 1;
11861  	else
11862  		hw_tls = 0;
11863 	kern_prefetch(sb, &maxseg);
11864 	maxseg = tp->t_maxseg - bbr->rc_last_options;
11865 	if (bbr_minseg(bbr) < maxseg) {
11866 		tcp_bbr_tso_size_check(bbr, cts);
11867 	}
11868 	/* Remove any flags that indicate we are pacing on the inp  */
11869 	pace_max_segs = bbr->r_ctl.rc_pace_max_segs;
11870 	p_maxseg = min(maxseg, pace_max_segs);
11871 	INP_WLOCK_ASSERT(inp);
11872 #ifdef TCP_OFFLOAD
11873 	if (tp->t_flags & TF_TOE)
11874 		return (tcp_offload_output(tp));
11875 #endif
11876 
11877 #ifdef INET6
11878 	if (bbr->r_state) {
11879 		/* Use the cache line loaded if possible */
11880 		isipv6 = bbr->r_is_v6;
11881 	} else {
11882 		isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
11883 	}
11884 #endif
11885 	if (((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
11886 	    tcp_in_hpts(tp)) {
11887 		/*
11888 		 * We are on the hpts for some timer but not hptsi output.
11889 		 * Possibly remove from the hpts so we can send/recv etc.
11890 		 */
11891 		if ((tp->t_flags & TF_ACKNOW) == 0) {
11892 			/*
11893 			 * No immediate demand right now to send an ack, but
11894 			 * the user may have read, making room for new data
11895 			 * (a window update). If so we may want to cancel
11896 			 * whatever timer is running (KEEP/DEL-ACK?) and
11897 			 * continue to send out a window update. Or we may
11898 			 * have gotten more data into the socket buffer to
11899 			 * send.
11900 			 */
11901 			recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
11902 				      (long)TCP_MAXWIN << tp->rcv_scale);
11903 			if ((bbr_window_update_needed(tp, so, recwin, maxseg) == 0) &&
11904 			    ((tcp_outflags[tp->t_state] & TH_RST) == 0) &&
11905 			    ((sbavail(sb) + ((tcp_outflags[tp->t_state] & TH_FIN) ? 1 : 0)) <=
11906 			    (tp->snd_max - tp->snd_una))) {
11907 				/*
11908 				 * Nothing new to send and no window update
11909 				 * is needed to send. Lets just return and
11910 				 * let the timer-run off.
11911 				 */
11912 				return (0);
11913 			}
11914 		}
11915 		tcp_hpts_remove(tp);
11916 		bbr_timer_cancel(bbr, __LINE__, cts);
11917 	}
11918 	if (bbr->r_ctl.rc_last_delay_val) {
11919 		/* Calculate a rough delay for early escape to sending  */
11920 		if (SEQ_GT(cts, bbr->rc_pacer_started))
11921 			delay_calc = cts - bbr->rc_pacer_started;
11922 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
11923 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
11924 		else
11925 			delay_calc = 0;
11926 	}
11927 	/* Mark that we have called bbr_output(). */
11928 	if ((bbr->r_timer_override) ||
11929 	    (tp->t_state < TCPS_ESTABLISHED)) {
11930 		/* Timeouts or early states are exempt */
11931 		if (tcp_in_hpts(tp))
11932 			tcp_hpts_remove(tp);
11933 	} else if (tcp_in_hpts(tp)) {
11934 		if ((bbr->r_ctl.rc_last_delay_val) &&
11935 		    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11936 		    delay_calc) {
11937 			/*
11938 			 * We were being paced for output and the delay has
11939 			 * already exceeded when we were supposed to be
11940 			 * called, lets go ahead and pull out of the hpts
11941 			 * and call output.
11942 			 */
11943 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_LATE], 1);
11944 			bbr->r_ctl.rc_last_delay_val = 0;
11945 			tcp_hpts_remove(tp);
11946 		} else if (tp->t_state == TCPS_CLOSED) {
11947 			bbr->r_ctl.rc_last_delay_val = 0;
11948 			tcp_hpts_remove(tp);
11949 		} else {
11950 			/*
11951 			 * On the hpts, you shall not pass! even if ACKNOW
11952 			 * is on, we will when the hpts fires, unless of
11953 			 * course we are overdue.
11954 			 */
11955 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_INPACE], 1);
11956 			return (0);
11957 		}
11958 	}
11959 	bbr->rc_cwnd_limited = 0;
11960 	if (bbr->r_ctl.rc_last_delay_val) {
11961 		/* recalculate the real delay and deal with over/under  */
11962 		if (SEQ_GT(cts, bbr->rc_pacer_started))
11963 			delay_calc = cts - bbr->rc_pacer_started;
11964 		else
11965 			delay_calc = 0;
11966 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
11967 			/* Setup the delay which will be added in */
11968 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
11969 		else {
11970 			/*
11971 			 * We are early setup to adjust
11972 			 * our slot time.
11973 			 */
11974 			uint64_t merged_val;
11975 
11976 			bbr->r_ctl.rc_agg_early += (bbr->r_ctl.rc_last_delay_val - delay_calc);
11977 			bbr->r_agg_early_set = 1;
11978 			if (bbr->r_ctl.rc_hptsi_agg_delay) {
11979 				if (bbr->r_ctl.rc_hptsi_agg_delay >= bbr->r_ctl.rc_agg_early) {
11980 					/* Nope our previous late cancels out the early */
11981 					bbr->r_ctl.rc_hptsi_agg_delay -= bbr->r_ctl.rc_agg_early;
11982 					bbr->r_agg_early_set = 0;
11983 					bbr->r_ctl.rc_agg_early = 0;
11984 				} else {
11985 					bbr->r_ctl.rc_agg_early -= bbr->r_ctl.rc_hptsi_agg_delay;
11986 					bbr->r_ctl.rc_hptsi_agg_delay = 0;
11987 				}
11988 			}
11989 			merged_val = bbr->rc_pacer_started;
11990 			merged_val <<= 32;
11991 			merged_val |= bbr->r_ctl.rc_last_delay_val;
11992 			bbr_log_pacing_delay_calc(bbr, hpts_calling,
11993 						 bbr->r_ctl.rc_agg_early, cts, delay_calc, merged_val,
11994 						 bbr->r_agg_early_set, 3);
11995 			bbr->r_ctl.rc_last_delay_val = 0;
11996 			BBR_STAT_INC(bbr_early);
11997 			delay_calc = 0;
11998 		}
11999 	} else {
12000 		/* We were not delayed due to hptsi */
12001 		if (bbr->r_agg_early_set)
12002 			bbr->r_ctl.rc_agg_early = 0;
12003 		bbr->r_agg_early_set = 0;
12004 		delay_calc = 0;
12005 	}
12006 	if (delay_calc) {
12007 		/*
12008 		 * We had a hptsi delay which means we are falling behind on
12009 		 * sending at the expected rate. Calculate an extra amount
12010 		 * of data we can send, if any, to put us back on track.
12011 		 */
12012 		if ((bbr->r_ctl.rc_hptsi_agg_delay + delay_calc) < bbr->r_ctl.rc_hptsi_agg_delay)
12013 			bbr->r_ctl.rc_hptsi_agg_delay = 0xffffffff;
12014 		else
12015 			bbr->r_ctl.rc_hptsi_agg_delay += delay_calc;
12016 	}
12017 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12018 	if ((tp->snd_una == tp->snd_max) &&
12019 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
12020 	    (sbavail(sb))) {
12021 		/*
12022 		 * Ok we have been idle with nothing outstanding
12023 		 * we possibly need to start fresh with either a new
12024 		 * suite of states or a fast-ramp up.
12025 		 */
12026 		bbr_restart_after_idle(bbr,
12027 				       cts, bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time));
12028 	}
12029 	/*
12030 	 * Now was there a hptsi delay where we are behind? We only count
12031 	 * being behind if: a) We are not in recovery. b) There was a delay.
12032 	 * <and> c) We had room to send something.
12033 	 *
12034 	 */
12035 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
12036 		int retval;
12037 
12038 		retval = bbr_process_timers(tp, bbr, cts, hpts_calling);
12039 		if (retval != 0) {
12040 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_ATIMER], 1);
12041 			/*
12042 			 * If timers want tcp_drop(), then pass error out,
12043 			 * otherwise suppress it.
12044 			 */
12045 			return (retval < 0 ? retval : 0);
12046 		}
12047 	}
12048 	bbr->rc_tp->t_flags2 &= ~TF2_MBUF_QUEUE_READY;
12049 	if (hpts_calling &&
12050 	    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
12051 		bbr->r_ctl.rc_last_delay_val = 0;
12052 	}
12053 	bbr->r_timer_override = 0;
12054 	bbr->r_wanted_output = 0;
12055 	/*
12056 	 * For TFO connections in SYN_RECEIVED, only allow the initial
12057 	 * SYN|ACK and those sent by the retransmit timer.
12058 	 */
12059 	if (IS_FASTOPEN(tp->t_flags) &&
12060 	    ((tp->t_state == TCPS_SYN_RECEIVED) ||
12061 	     (tp->t_state == TCPS_SYN_SENT)) &&
12062 	    SEQ_GT(tp->snd_max, tp->snd_una) &&	/* initial SYN or SYN|ACK sent */
12063 	    (tp->t_rxtshift == 0)) {	/* not a retransmit */
12064 		len = 0;
12065 		goto just_return_nolock;
12066 	}
12067 	/*
12068 	 * Before sending anything check for a state update. For hpts
12069 	 * calling without input this is important. If its input calling
12070 	 * then this was already done.
12071 	 */
12072 	if (bbr->rc_use_google == 0)
12073 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12074 again:
12075 	/*
12076 	 * If we've recently taken a timeout, snd_max will be greater than
12077 	 * snd_max. BBR in general does not pay much attention to snd_nxt
12078 	 * for historic reasons the persist timer still uses it. This means
12079 	 * we have to look at it. All retransmissions that are not persits
12080 	 * use the rsm that needs to be sent so snd_nxt is ignored. At the
12081 	 * end of this routine we pull snd_nxt always up to snd_max.
12082 	 */
12083 	doing_tlp = 0;
12084 #ifdef BBR_INVARIANTS
12085 	doing_retran_from = picked_up_retran = 0;
12086 #endif
12087 	error = 0;
12088 	tso = 0;
12089 	slot = 0;
12090 	mtu = 0;
12091 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12092 	sb_offset = tp->snd_max - tp->snd_una;
12093 	flags = tcp_outflags[tp->t_state];
12094 	sack_rxmit = 0;
12095 	len = 0;
12096 	rsm = NULL;
12097 	if (flags & TH_RST) {
12098 		SOCKBUF_LOCK(sb);
12099 		goto send;
12100 	}
12101 recheck_resend:
12102 	while (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
12103 		/* We need to always have one in reserve */
12104 		rsm = bbr_alloc(bbr);
12105 		if (rsm == NULL) {
12106 			error = ENOMEM;
12107 			/* Lie to get on the hpts */
12108 			tot_len = tp->t_maxseg;
12109 			if (hpts_calling)
12110 				/* Retry in a ms */
12111 				slot = 1001;
12112 			goto just_return_nolock;
12113 		}
12114 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
12115 		bbr->r_ctl.rc_free_cnt++;
12116 		rsm = NULL;
12117 	}
12118 	/* What do we send, a resend? */
12119 	if (bbr->r_ctl.rc_resend == NULL) {
12120 		/* Check for rack timeout */
12121 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
12122 		if (bbr->r_ctl.rc_resend) {
12123 #ifdef BBR_INVARIANTS
12124 			picked_up_retran = 1;
12125 #endif
12126 			bbr_cong_signal(tp, NULL, CC_NDUPACK, bbr->r_ctl.rc_resend);
12127 		}
12128 	}
12129 	if (bbr->r_ctl.rc_resend) {
12130 		rsm = bbr->r_ctl.rc_resend;
12131 #ifdef BBR_INVARIANTS
12132 		doing_retran_from = 1;
12133 #endif
12134 		/* Remove any TLP flags its a RACK or T-O */
12135 		rsm->r_flags &= ~BBR_TLP;
12136 		bbr->r_ctl.rc_resend = NULL;
12137 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
12138 #ifdef BBR_INVARIANTS
12139 			panic("Huh, tp:%p bbr:%p rsm:%p start:%u < snd_una:%u\n",
12140 			    tp, bbr, rsm, rsm->r_start, tp->snd_una);
12141 			goto recheck_resend;
12142 #else
12143 			/* TSNH */
12144 			rsm = NULL;
12145 			goto recheck_resend;
12146 #endif
12147 		}
12148 		if (rsm->r_flags & BBR_HAS_SYN) {
12149 			/* Only retransmit a SYN by itself */
12150 			len = 0;
12151 			if ((flags & TH_SYN) == 0) {
12152 				/* Huh something is wrong */
12153 				rsm->r_start++;
12154 				if (rsm->r_start == rsm->r_end) {
12155 					/* Clean it up, somehow we missed the ack? */
12156 					bbr_log_syn(tp, NULL);
12157 				} else {
12158 					/* TFO with data? */
12159 					rsm->r_flags &= ~BBR_HAS_SYN;
12160 					len = rsm->r_end - rsm->r_start;
12161 				}
12162 			} else {
12163 				/* Retransmitting SYN */
12164 				rsm = NULL;
12165 				SOCKBUF_LOCK(sb);
12166 				goto send;
12167 			}
12168 		} else
12169 			len = rsm->r_end - rsm->r_start;
12170 		if ((bbr->rc_resends_use_tso == 0) &&
12171 		    (len > maxseg)) {
12172 			len = maxseg;
12173 			more_to_rxt = 1;
12174 		}
12175 		sb_offset = rsm->r_start - tp->snd_una;
12176 		if (len > 0) {
12177 			sack_rxmit = 1;
12178 			KMOD_TCPSTAT_INC(tcps_sack_rexmits);
12179 			KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
12180 			    min(len, maxseg));
12181 		} else {
12182 			/* I dont think this can happen */
12183 			rsm = NULL;
12184 			goto recheck_resend;
12185 		}
12186 		BBR_STAT_INC(bbr_resends_set);
12187 	} else if (bbr->r_ctl.rc_tlp_send) {
12188 		/*
12189 		 * Tail loss probe
12190 		 */
12191 		doing_tlp = 1;
12192 		rsm = bbr->r_ctl.rc_tlp_send;
12193 		bbr->r_ctl.rc_tlp_send = NULL;
12194 		sack_rxmit = 1;
12195 		len = rsm->r_end - rsm->r_start;
12196 		if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12197 			len = maxseg;
12198 
12199 		if (SEQ_GT(tp->snd_una, rsm->r_start)) {
12200 #ifdef BBR_INVARIANTS
12201 			panic("tp:%p bbc:%p snd_una:%u rsm:%p r_start:%u",
12202 			    tp, bbr, tp->snd_una, rsm, rsm->r_start);
12203 #else
12204 			/* TSNH */
12205 			rsm = NULL;
12206 			goto recheck_resend;
12207 #endif
12208 		}
12209 		sb_offset = rsm->r_start - tp->snd_una;
12210 		BBR_STAT_INC(bbr_tlp_set);
12211 	}
12212 	/*
12213 	 * Enforce a connection sendmap count limit if set
12214 	 * as long as we are not retransmiting.
12215 	 */
12216 	if ((rsm == NULL) &&
12217 	    (V_tcp_map_entries_limit > 0) &&
12218 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
12219 		BBR_STAT_INC(bbr_alloc_limited);
12220 		if (!bbr->alloc_limit_reported) {
12221 			bbr->alloc_limit_reported = 1;
12222 			BBR_STAT_INC(bbr_alloc_limited_conns);
12223 		}
12224 		goto just_return_nolock;
12225 	}
12226 #ifdef BBR_INVARIANTS
12227 	if (rsm && SEQ_LT(rsm->r_start, tp->snd_una)) {
12228 		panic("tp:%p bbr:%p rsm:%p sb_offset:%u len:%u",
12229 		    tp, bbr, rsm, sb_offset, len);
12230 	}
12231 #endif
12232 	/*
12233 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
12234 	 * state flags.
12235 	 */
12236 	if (tp->t_flags & TF_NEEDFIN && (rsm == NULL))
12237 		flags |= TH_FIN;
12238 	if (tp->t_flags & TF_NEEDSYN)
12239 		flags |= TH_SYN;
12240 
12241 	if (rsm && (rsm->r_flags & BBR_HAS_FIN)) {
12242 		/* we are retransmitting the fin */
12243 		len--;
12244 		if (len) {
12245 			/*
12246 			 * When retransmitting data do *not* include the
12247 			 * FIN. This could happen from a TLP probe if we
12248 			 * allowed data with a FIN.
12249 			 */
12250 			flags &= ~TH_FIN;
12251 		}
12252 	} else if (rsm) {
12253 		if (flags & TH_FIN)
12254 			flags &= ~TH_FIN;
12255 	}
12256 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
12257 		void *end_rsm;
12258 
12259 		end_rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
12260 		if (end_rsm)
12261 			kern_prefetch(end_rsm, &prefetch_rsm);
12262 		prefetch_rsm = 1;
12263 	}
12264 	SOCKBUF_LOCK(sb);
12265 	/*
12266 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
12267 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
12268 	 * negative length.  This can also occur when TCP opens up its
12269 	 * congestion window while receiving additional duplicate acks after
12270 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
12271 	 * the fast-retransmit.
12272 	 *
12273 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
12274 	 * set to snd_una, the sb_offset will be 0, and the length may wind
12275 	 * up 0.
12276 	 *
12277 	 * If sack_rxmit is true we are retransmitting from the scoreboard
12278 	 * in which case len is already set.
12279 	 */
12280 	if (sack_rxmit == 0) {
12281 		uint32_t avail;
12282 
12283 		avail = sbavail(sb);
12284 		if (SEQ_GT(tp->snd_max, tp->snd_una))
12285 			sb_offset = tp->snd_max - tp->snd_una;
12286 		else
12287 			sb_offset = 0;
12288 		if (bbr->rc_tlp_new_data) {
12289 			/* TLP is forcing out new data */
12290 			uint32_t tlplen;
12291 
12292 			doing_tlp = 1;
12293 			tlplen = maxseg;
12294 
12295 			if (tlplen > (uint32_t)(avail - sb_offset)) {
12296 				tlplen = (uint32_t)(avail - sb_offset);
12297 			}
12298 			if (tlplen > tp->snd_wnd) {
12299 				len = tp->snd_wnd;
12300 			} else {
12301 				len = tlplen;
12302 			}
12303 			bbr->rc_tlp_new_data = 0;
12304 		} else {
12305 			len = bbr_what_can_we_send(tp, bbr, sendwin, avail, sb_offset, cts);
12306 			if ((len < p_maxseg) &&
12307 			    (bbr->rc_in_persist == 0) &&
12308 			    (ctf_outstanding(tp) >= (2 * p_maxseg)) &&
12309 			    ((avail - sb_offset) >= p_maxseg)) {
12310 				/*
12311 				 * We are not completing whats in the socket
12312 				 * buffer (i.e. there is at least a segment
12313 				 * waiting to send) and we have 2 or more
12314 				 * segments outstanding. There is no sense
12315 				 * of sending a little piece. Lets defer and
12316 				 * and wait until we can send a whole
12317 				 * segment.
12318 				 */
12319 				len = 0;
12320 			}
12321 			if (bbr->rc_in_persist) {
12322 				/*
12323 				 * We are in persists, figure out if
12324 				 * a retransmit is available (maybe the previous
12325 				 * persists we sent) or if we have to send new
12326 				 * data.
12327 				 */
12328 				rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
12329 				if (rsm) {
12330 					len = rsm->r_end - rsm->r_start;
12331 					if (rsm->r_flags & BBR_HAS_FIN)
12332 						len--;
12333 					if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12334 						len = maxseg;
12335 					if (len > 1)
12336 						BBR_STAT_INC(bbr_persist_reneg);
12337 					/*
12338 					 * XXXrrs we could force the len to
12339 					 * 1 byte here to cause the chunk to
12340 					 * split apart.. but that would then
12341 					 * mean we always retransmit it as
12342 					 * one byte even after the window
12343 					 * opens.
12344 					 */
12345 					sack_rxmit = 1;
12346 					sb_offset = rsm->r_start - tp->snd_una;
12347 				} else {
12348 					/*
12349 					 * First time through in persists or peer
12350 					 * acked our one byte. Though we do have
12351 					 * to have something in the sb.
12352 					 */
12353 					len = 1;
12354 					sb_offset = 0;
12355 					if (avail == 0)
12356 					    len = 0;
12357 				}
12358 			}
12359 		}
12360 	}
12361 	if (prefetch_so_done == 0) {
12362 		kern_prefetch(so, &prefetch_so_done);
12363 		prefetch_so_done = 1;
12364 	}
12365 	/*
12366 	 * Lop off SYN bit if it has already been sent.  However, if this is
12367 	 * SYN-SENT state and if segment contains data and if we don't know
12368 	 * that foreign host supports TAO, suppress sending segment.
12369 	 */
12370 	if ((flags & TH_SYN) && (rsm == NULL) &&
12371 	    SEQ_GT(tp->snd_max, tp->snd_una)) {
12372 		if (tp->t_state != TCPS_SYN_RECEIVED)
12373 			flags &= ~TH_SYN;
12374 		/*
12375 		 * When sending additional segments following a TFO SYN|ACK,
12376 		 * do not include the SYN bit.
12377 		 */
12378 		if (IS_FASTOPEN(tp->t_flags) &&
12379 		    (tp->t_state == TCPS_SYN_RECEIVED))
12380 			flags &= ~TH_SYN;
12381 		sb_offset--, len++;
12382 		if (sbavail(sb) == 0)
12383 			len = 0;
12384 	} else if ((flags & TH_SYN) && rsm) {
12385 		/*
12386 		 * Subtract one from the len for the SYN being
12387 		 * retransmitted.
12388 		 */
12389 		len--;
12390 	}
12391 	/*
12392 	 * Be careful not to send data and/or FIN on SYN segments. This
12393 	 * measure is needed to prevent interoperability problems with not
12394 	 * fully conformant TCP implementations.
12395 	 */
12396 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
12397 		len = 0;
12398 		flags &= ~TH_FIN;
12399 	}
12400 	/*
12401 	 * On TFO sockets, ensure no data is sent in the following cases:
12402 	 *
12403 	 *  - When retransmitting SYN|ACK on a passively-created socket
12404 	 *  - When retransmitting SYN on an actively created socket
12405 	 *  - When sending a zero-length cookie (cookie request) on an
12406 	 *    actively created socket
12407 	 *  - When the socket is in the CLOSED state (RST is being sent)
12408 	 */
12409 	if (IS_FASTOPEN(tp->t_flags) &&
12410 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
12411 	     ((tp->t_state == TCPS_SYN_SENT) &&
12412 	      (tp->t_tfo_client_cookie_len == 0)) ||
12413 	     (flags & TH_RST))) {
12414 		len = 0;
12415 		sack_rxmit = 0;
12416 		rsm = NULL;
12417 	}
12418 	/* Without fast-open there should never be data sent on a SYN */
12419 	if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags)))
12420 		len = 0;
12421 	if (len <= 0) {
12422 		/*
12423 		 * If FIN has been sent but not acked, but we haven't been
12424 		 * called to retransmit, len will be < 0.  Otherwise, window
12425 		 * shrank after we sent into it.  If window shrank to 0,
12426 		 * cancel pending retransmit, pull snd_nxt back to (closed)
12427 		 * window, and set the persist timer if it isn't already
12428 		 * going.  If the window didn't close completely, just wait
12429 		 * for an ACK.
12430 		 *
12431 		 * We also do a general check here to ensure that we will
12432 		 * set the persist timer when we have data to send, but a
12433 		 * 0-byte window. This makes sure the persist timer is set
12434 		 * even if the packet hits one of the "goto send" lines
12435 		 * below.
12436 		 */
12437 		len = 0;
12438 		if ((tp->snd_wnd == 0) &&
12439 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12440 		    (tp->snd_una == tp->snd_max) &&
12441 		    (sb_offset < (int)sbavail(sb))) {
12442 			/*
12443 			 * Not enough room in the rwnd to send
12444 			 * a paced segment out.
12445 			 */
12446 			bbr_enter_persist(tp, bbr, cts, __LINE__);
12447 		}
12448 	} else if ((rsm == NULL) &&
12449 		   (doing_tlp == 0) &&
12450 		   (len < bbr->r_ctl.rc_pace_max_segs)) {
12451 		/*
12452 		 * We are not sending a full segment for
12453 		 * some reason. Should we not send anything (think
12454 		 * sws or persists)?
12455 		 */
12456 		if ((tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12457 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12458 		    (len < (int)(sbavail(sb) - sb_offset))) {
12459 			/*
12460 			 * Here the rwnd is less than
12461 			 * the pacing size, this is not a retransmit,
12462 			 * we are established and
12463 			 * the send is not the last in the socket buffer
12464 			 * lets not send, and possibly enter persists.
12465 			 */
12466 			len = 0;
12467 			if (tp->snd_max == tp->snd_una)
12468 				bbr_enter_persist(tp, bbr, cts, __LINE__);
12469 		} else if ((tp->snd_cwnd >= bbr->r_ctl.rc_pace_max_segs) &&
12470 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12471 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12472 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12473 			   (len < bbr_minseg(bbr))) {
12474 			/*
12475 			 * Here we are not retransmitting, and
12476 			 * the cwnd is not so small that we could
12477 			 * not send at least a min size (rxt timer
12478 			 * not having gone off), We have 2 segments or
12479 			 * more already in flight, its not the tail end
12480 			 * of the socket buffer  and the cwnd is blocking
12481 			 * us from sending out minimum pacing segment size.
12482 			 * Lets not send anything.
12483 			 */
12484 			bbr->rc_cwnd_limited = 1;
12485 			len = 0;
12486 		} else if (((tp->snd_wnd - ctf_outstanding(tp)) <
12487 			    min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12488 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12489 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12490 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12491 			   (TCPS_HAVEESTABLISHED(tp->t_state))) {
12492 			/*
12493 			 * Here we have a send window but we have
12494 			 * filled it up and we can't send another pacing segment.
12495 			 * We also have in flight more than 2 segments
12496 			 * and we are not completing the sb i.e. we allow
12497 			 * the last bytes of the sb to go out even if
12498 			 * its not a full pacing segment.
12499 			 */
12500 			len = 0;
12501 		}
12502 	}
12503 	/* len will be >= 0 after this point. */
12504 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
12505 	tcp_sndbuf_autoscale(tp, so, sendwin);
12506 	/*
12507 	 *
12508 	 */
12509 	if (bbr->rc_in_persist &&
12510 	    len &&
12511 	    (rsm == NULL) &&
12512 	    (len < min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs))) {
12513 		/*
12514 		 * We are in persist, not doing a retransmit and don't have enough space
12515 		 * yet to send a full TSO. So is it at the end of the sb
12516 		 * if so we need to send else nuke to 0 and don't send.
12517 		 */
12518 		int sbleft;
12519 		if (sbavail(sb) > sb_offset)
12520 			sbleft = sbavail(sb) - sb_offset;
12521 		else
12522 			sbleft = 0;
12523 		if (sbleft >= min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs)) {
12524 			/* not at end of sb lets not send */
12525 			len = 0;
12526 		}
12527 	}
12528 	/*
12529 	 * Decide if we can use TCP Segmentation Offloading (if supported by
12530 	 * hardware).
12531 	 *
12532 	 * TSO may only be used if we are in a pure bulk sending state.  The
12533 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
12534 	 * options prevent using TSO.  With TSO the TCP header is the same
12535 	 * (except for the sequence number) for all generated packets.  This
12536 	 * makes it impossible to transmit any options which vary per
12537 	 * generated segment or packet.
12538 	 *
12539 	 * IPv4 handling has a clear separation of ip options and ip header
12540 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen()
12541 	 * does the right thing below to provide length of just ip options
12542 	 * and thus checking for ipoptlen is enough to decide if ip options
12543 	 * are present.
12544 	 */
12545 #ifdef INET6
12546 	if (isipv6)
12547 		ipoptlen = ip6_optlen(inp);
12548 	else
12549 #endif
12550 	if (inp->inp_options)
12551 		ipoptlen = inp->inp_options->m_len -
12552 		    offsetof(struct ipoption, ipopt_list);
12553 	else
12554 		ipoptlen = 0;
12555 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12556 	/*
12557 	 * Pre-calculate here as we save another lookup into the darknesses
12558 	 * of IPsec that way and can actually decide if TSO is ok.
12559 	 */
12560 #ifdef INET6
12561 	if (isipv6 && IPSEC_ENABLED(ipv6))
12562 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
12563 #ifdef INET
12564 	else
12565 #endif
12566 #endif				/* INET6 */
12567 #ifdef INET
12568 	if (IPSEC_ENABLED(ipv4))
12569 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
12570 #endif				/* INET */
12571 #endif				/* IPSEC */
12572 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12573 	ipoptlen += ipsec_optlen;
12574 #endif
12575 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
12576 	    (len > maxseg) &&
12577 	    (tp->t_port == 0) &&
12578 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
12579 	    tp->rcv_numsacks == 0 &&
12580 	    ipoptlen == 0)
12581 		tso = 1;
12582 
12583 	recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12584 	    (long)TCP_MAXWIN << tp->rcv_scale);
12585 	/*
12586 	 * Sender silly window avoidance.   We transmit under the following
12587 	 * conditions when len is non-zero:
12588 	 *
12589 	 * - We have a full segment (or more with TSO) - This is the last
12590 	 * buffer in a write()/send() and we are either idle or running
12591 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
12592 	 * then 1/2 the maximum send window's worth of data (receiver may be
12593 	 * limited the window size) - we need to retransmit
12594 	 */
12595 	if (rsm)
12596 		goto send;
12597 	if (len) {
12598 		if (sack_rxmit)
12599 			goto send;
12600 		if (len >= p_maxseg)
12601 			goto send;
12602 		/*
12603 		 * NOTE! on localhost connections an 'ack' from the remote
12604 		 * end may occur synchronously with the output and cause us
12605 		 * to flush a buffer queued with moretocome.  XXX
12606 		 *
12607 		 */
12608 		if (((tp->t_flags & TF_MORETOCOME) == 0) &&	/* normal case */
12609 		    ((tp->t_flags & TF_NODELAY) ||
12610 		    ((uint32_t)len + (uint32_t)sb_offset) >= sbavail(&so->so_snd)) &&
12611 		    (tp->t_flags & TF_NOPUSH) == 0) {
12612 			goto send;
12613 		}
12614 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
12615 			goto send;
12616 		}
12617 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
12618 			goto send;
12619 		}
12620 	}
12621 	/*
12622 	 * Sending of standalone window updates.
12623 	 *
12624 	 * Window updates are important when we close our window due to a
12625 	 * full socket buffer and are opening it again after the application
12626 	 * reads data from it.  Once the window has opened again and the
12627 	 * remote end starts to send again the ACK clock takes over and
12628 	 * provides the most current window information.
12629 	 *
12630 	 * We must avoid the silly window syndrome whereas every read from
12631 	 * the receive buffer, no matter how small, causes a window update
12632 	 * to be sent.  We also should avoid sending a flurry of window
12633 	 * updates when the socket buffer had queued a lot of data and the
12634 	 * application is doing small reads.
12635 	 *
12636 	 * Prevent a flurry of pointless window updates by only sending an
12637 	 * update when we can increase the advertized window by more than
12638 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
12639 	 * full or is very small be more aggressive and send an update
12640 	 * whenever we can increase by two mss sized segments. In all other
12641 	 * situations the ACK's to new incoming data will carry further
12642 	 * window increases.
12643 	 *
12644 	 * Don't send an independent window update if a delayed ACK is
12645 	 * pending (it will get piggy-backed on it) or the remote side
12646 	 * already has done a half-close and won't send more data.  Skip
12647 	 * this if the connection is in T/TCP half-open state.
12648 	 */
12649 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
12650 	    !(tp->t_flags & TF_DELACK) &&
12651 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
12652 		/* Check to see if we should do a window update */
12653 		if (bbr_window_update_needed(tp, so, recwin, maxseg))
12654 			goto send;
12655 	}
12656 	/*
12657 	 * Send if we owe the peer an ACK, RST, SYN.  ACKNOW
12658 	 * is also a catch-all for the retransmit timer timeout case.
12659 	 */
12660 	if (tp->t_flags & TF_ACKNOW) {
12661 		goto send;
12662 	}
12663 	if (flags & TH_RST) {
12664 		/* Always send a RST if one is due */
12665 		goto send;
12666 	}
12667 	if ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0) {
12668 		goto send;
12669 	}
12670 	/*
12671 	 * If our state indicates that FIN should be sent and we have not
12672 	 * yet done so, then we need to send.
12673 	 */
12674 	if (flags & TH_FIN &&
12675 	    ((tp->t_flags & TF_SENTFIN) == 0)) {
12676 		goto send;
12677 	}
12678 	/*
12679 	 * No reason to send a segment, just return.
12680 	 */
12681 just_return:
12682 	SOCKBUF_UNLOCK(sb);
12683 just_return_nolock:
12684 	if (tot_len)
12685 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
12686 	if (bbr->rc_no_pacing)
12687 		slot = 0;
12688 	if (tot_len == 0) {
12689 		if ((ctf_outstanding(tp) + min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) >=
12690 		    tp->snd_wnd) {
12691 			BBR_STAT_INC(bbr_rwnd_limited);
12692 			app_limited = BBR_JR_RWND_LIMITED;
12693 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12694 			if ((bbr->rc_in_persist == 0) &&
12695 			    TCPS_HAVEESTABLISHED(tp->t_state) &&
12696 			    (tp->snd_max == tp->snd_una) &&
12697 			    sbavail(&so->so_snd)) {
12698 				/* No send window.. we must enter persist */
12699 				bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
12700 			}
12701 		} else if (ctf_outstanding(tp) >= sbavail(sb)) {
12702 			BBR_STAT_INC(bbr_app_limited);
12703 			app_limited = BBR_JR_APP_LIMITED;
12704 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12705 		} else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12706 						 bbr->r_ctl.rc_lost_bytes)) + p_maxseg) >= tp->snd_cwnd) {
12707 			BBR_STAT_INC(bbr_cwnd_limited);
12708  			app_limited = BBR_JR_CWND_LIMITED;
12709 			bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12710 									bbr->r_ctl.rc_lost_bytes)));
12711 			bbr->rc_cwnd_limited = 1;
12712 		} else {
12713 			BBR_STAT_INC(bbr_app_limited);
12714 			app_limited = BBR_JR_APP_LIMITED;
12715 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12716 		}
12717 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
12718 		bbr->r_agg_early_set = 0;
12719 		bbr->r_ctl.rc_agg_early = 0;
12720 		bbr->r_ctl.rc_last_delay_val = 0;
12721 	} else if (bbr->rc_use_google == 0)
12722 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12723 	/* Are we app limited? */
12724 	if ((app_limited == BBR_JR_APP_LIMITED) ||
12725 	    (app_limited == BBR_JR_RWND_LIMITED)) {
12726 		/**
12727 		 * We are application limited.
12728 		 */
12729 		bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12730 								       bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_delivered);
12731 	}
12732 	if (tot_len == 0)
12733 		counter_u64_add(bbr_out_size[TCP_MSS_ACCT_JUSTRET], 1);
12734 	/* Dont update the time if we did not send */
12735 	bbr->r_ctl.rc_last_delay_val = 0;
12736 	bbr->rc_output_starts_timer = 1;
12737 	bbr_start_hpts_timer(bbr, tp, cts, 9, slot, tot_len);
12738 	bbr_log_type_just_return(bbr, cts, tot_len, hpts_calling, app_limited, p_maxseg, len);
12739 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
12740 		/* Make sure snd_nxt is drug up */
12741 		tp->snd_nxt = tp->snd_max;
12742 	}
12743 	return (error);
12744 
12745 send:
12746 	if (doing_tlp == 0) {
12747 		/*
12748 		 * Data not a TLP, and its not the rxt firing. If it is the
12749 		 * rxt firing, we want to leave the tlp_in_progress flag on
12750 		 * so we don't send another TLP. It has to be a rack timer
12751 		 * or normal send (response to acked data) to clear the tlp
12752 		 * in progress flag.
12753 		 */
12754 		bbr->rc_tlp_in_progress = 0;
12755 		bbr->rc_tlp_rtx_out = 0;
12756 	} else {
12757 		/*
12758 		 * Its a TLP.
12759 		 */
12760 		bbr->rc_tlp_in_progress = 1;
12761 	}
12762 	bbr_timer_cancel(bbr, __LINE__, cts);
12763 	if (rsm == NULL) {
12764 		if (sbused(sb) > 0) {
12765 			/*
12766 			 * This is sub-optimal. We only send a stand alone
12767 			 * FIN on its own segment.
12768 			 */
12769 			if (flags & TH_FIN) {
12770 				flags &= ~TH_FIN;
12771 				if ((len == 0) && ((tp->t_flags & TF_ACKNOW) == 0)) {
12772 					/* Lets not send this */
12773 					slot = 0;
12774 					goto just_return;
12775 				}
12776 			}
12777 		}
12778 	} else {
12779 		/*
12780 		 * We do *not* send a FIN on a retransmit if it has data.
12781 		 * The if clause here where len > 1 should never come true.
12782 		 */
12783 		if ((len > 0) &&
12784 		    (((rsm->r_flags & BBR_HAS_FIN) == 0) &&
12785 		    (flags & TH_FIN))) {
12786 			flags &= ~TH_FIN;
12787 			len--;
12788 		}
12789 	}
12790 	SOCKBUF_LOCK_ASSERT(sb);
12791 	if (len > 0) {
12792 		if ((tp->snd_una == tp->snd_max) &&
12793 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
12794 			/*
12795 			 * This qualifies as a RTT_PROBE session since we
12796 			 * drop the data outstanding to nothing and waited
12797 			 * more than bbr_rtt_probe_time.
12798 			 */
12799 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
12800 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
12801 		}
12802 		if (len >= maxseg)
12803 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
12804 		else
12805 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
12806 	}
12807 	/*
12808 	 * Before ESTABLISHED, force sending of initial options unless TCP
12809 	 * set not to do any options. NOTE: we assume that the IP/TCP header
12810 	 * plus TCP options always fit in a single mbuf, leaving room for a
12811 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
12812 	 * + optlen <= MCLBYTES
12813 	 */
12814 	optlen = 0;
12815 #ifdef INET6
12816 	if (isipv6)
12817 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
12818 	else
12819 #endif
12820 		hdrlen = sizeof(struct tcpiphdr);
12821 
12822 	/*
12823 	 * Compute options for segment. We only have to care about SYN and
12824 	 * established connection segments.  Options for SYN-ACK segments
12825 	 * are handled in TCP syncache.
12826 	 */
12827 	to.to_flags = 0;
12828 	local_options = 0;
12829 	if ((tp->t_flags & TF_NOOPT) == 0) {
12830 		/* Maximum segment size. */
12831 		if (flags & TH_SYN) {
12832 			to.to_mss = tcp_mssopt(&inp->inp_inc);
12833 			if (tp->t_port)
12834 				to.to_mss -= V_tcp_udp_tunneling_overhead;
12835 			to.to_flags |= TOF_MSS;
12836 			/*
12837 			 * On SYN or SYN|ACK transmits on TFO connections,
12838 			 * only include the TFO option if it is not a
12839 			 * retransmit, as the presence of the TFO option may
12840 			 * have caused the original SYN or SYN|ACK to have
12841 			 * been dropped by a middlebox.
12842 			 */
12843 			if (IS_FASTOPEN(tp->t_flags) &&
12844 			    (tp->t_rxtshift == 0)) {
12845 				if (tp->t_state == TCPS_SYN_RECEIVED) {
12846 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
12847 					to.to_tfo_cookie =
12848 					    (u_int8_t *)&tp->t_tfo_cookie.server;
12849 					to.to_flags |= TOF_FASTOPEN;
12850 					wanted_cookie = 1;
12851 				} else if (tp->t_state == TCPS_SYN_SENT) {
12852 					to.to_tfo_len =
12853 					    tp->t_tfo_client_cookie_len;
12854 					to.to_tfo_cookie =
12855 					    tp->t_tfo_cookie.client;
12856 					to.to_flags |= TOF_FASTOPEN;
12857 					wanted_cookie = 1;
12858 				}
12859 			}
12860 		}
12861 		/* Window scaling. */
12862 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
12863 			to.to_wscale = tp->request_r_scale;
12864 			to.to_flags |= TOF_SCALE;
12865 		}
12866 		/* Timestamps. */
12867 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
12868 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
12869 			to.to_tsval = 	tcp_tv_to_mssectick(&bbr->rc_tv) + tp->ts_offset;
12870 			to.to_tsecr = tp->ts_recent;
12871 			to.to_flags |= TOF_TS;
12872 			local_options += TCPOLEN_TIMESTAMP + 2;
12873 		}
12874 		/* Set receive buffer autosizing timestamp. */
12875 		if (tp->rfbuf_ts == 0 &&
12876 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
12877 			tp->rfbuf_ts = 	tcp_tv_to_mssectick(&bbr->rc_tv);
12878 		/* Selective ACK's. */
12879 		if (flags & TH_SYN)
12880 			to.to_flags |= TOF_SACKPERM;
12881 		else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
12882 		    tp->rcv_numsacks > 0) {
12883 			to.to_flags |= TOF_SACK;
12884 			to.to_nsacks = tp->rcv_numsacks;
12885 			to.to_sacks = (u_char *)tp->sackblks;
12886 		}
12887 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
12888 		/* TCP-MD5 (RFC2385). */
12889 		if (tp->t_flags & TF_SIGNATURE)
12890 			to.to_flags |= TOF_SIGNATURE;
12891 #endif				/* TCP_SIGNATURE */
12892 
12893 		/* Processing the options. */
12894 		hdrlen += (optlen = tcp_addoptions(&to, opt));
12895 		/*
12896 		 * If we wanted a TFO option to be added, but it was unable
12897 		 * to fit, ensure no data is sent.
12898 		 */
12899 		if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
12900 		    !(to.to_flags & TOF_FASTOPEN))
12901 			len = 0;
12902 	}
12903 	if (tp->t_port) {
12904 		if (V_tcp_udp_tunneling_port == 0) {
12905 			/* The port was removed?? */
12906 			SOCKBUF_UNLOCK(&so->so_snd);
12907 			return (EHOSTUNREACH);
12908 		}
12909 		hdrlen += sizeof(struct udphdr);
12910 	}
12911 #ifdef INET6
12912 	if (isipv6)
12913 		ipoptlen = ip6_optlen(inp);
12914 	else
12915 #endif
12916 	if (inp->inp_options)
12917 		ipoptlen = inp->inp_options->m_len -
12918 		    offsetof(struct ipoption, ipopt_list);
12919 	else
12920 		ipoptlen = 0;
12921 	ipoptlen = 0;
12922 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12923 	ipoptlen += ipsec_optlen;
12924 #endif
12925 	if (bbr->rc_last_options != local_options) {
12926 		/*
12927 		 * Cache the options length this generally does not change
12928 		 * on a connection. We use this to calculate TSO.
12929 		 */
12930 		bbr->rc_last_options = local_options;
12931 	}
12932 	maxseg = tp->t_maxseg - (ipoptlen + optlen);
12933 	p_maxseg = min(maxseg, pace_max_segs);
12934 	/*
12935 	 * Adjust data length if insertion of options will bump the packet
12936 	 * length beyond the t_maxseg length. Clear the FIN bit because we
12937 	 * cut off the tail of the segment.
12938 	 */
12939 	if (len > maxseg) {
12940 		if (len != 0 && (flags & TH_FIN)) {
12941 			flags &= ~TH_FIN;
12942 		}
12943 		if (tso) {
12944 			uint32_t moff;
12945 			int32_t max_len;
12946 
12947 			/* extract TSO information */
12948 			if_hw_tsomax = tp->t_tsomax;
12949 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
12950 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
12951 			KASSERT(ipoptlen == 0,
12952 			    ("%s: TSO can't do IP options", __func__));
12953 
12954 			/*
12955 			 * Check if we should limit by maximum payload
12956 			 * length:
12957 			 */
12958 			if (if_hw_tsomax != 0) {
12959 				/* compute maximum TSO length */
12960 				max_len = (if_hw_tsomax - hdrlen -
12961 				    max_linkhdr);
12962 				if (max_len <= 0) {
12963 					len = 0;
12964 				} else if (len > max_len) {
12965 					len = max_len;
12966 				}
12967 			}
12968 			/*
12969 			 * Prevent the last segment from being fractional
12970 			 * unless the send sockbuf can be emptied:
12971 			 */
12972 			if ((sb_offset + len) < sbavail(sb)) {
12973 				moff = len % (uint32_t)maxseg;
12974 				if (moff != 0) {
12975 					len -= moff;
12976 				}
12977 			}
12978 			/*
12979 			 * In case there are too many small fragments don't
12980 			 * use TSO:
12981 			 */
12982 			if (len <= maxseg) {
12983 				len = maxseg;
12984 				tso = 0;
12985 			}
12986 		} else {
12987 			/* Not doing TSO */
12988 			if (optlen + ipoptlen >= tp->t_maxseg) {
12989 				/*
12990 				 * Since we don't have enough space to put
12991 				 * the IP header chain and the TCP header in
12992 				 * one packet as required by RFC 7112, don't
12993 				 * send it. Also ensure that at least one
12994 				 * byte of the payload can be put into the
12995 				 * TCP segment.
12996 				 */
12997 				SOCKBUF_UNLOCK(&so->so_snd);
12998 				error = EMSGSIZE;
12999 				sack_rxmit = 0;
13000 				goto out;
13001 			}
13002 			len = maxseg;
13003 		}
13004 	} else {
13005 		/* Not doing TSO */
13006 		if_hw_tsomaxsegcount = 0;
13007 		tso = 0;
13008 	}
13009 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
13010 	    ("%s: len > IP_MAXPACKET", __func__));
13011 #ifdef DIAGNOSTIC
13012 #ifdef INET6
13013 	if (max_linkhdr + hdrlen > MCLBYTES)
13014 #else
13015 	if (max_linkhdr + hdrlen > MHLEN)
13016 #endif
13017 		panic("tcphdr too big");
13018 #endif
13019 	/*
13020 	 * This KASSERT is here to catch edge cases at a well defined place.
13021 	 * Before, those had triggered (random) panic conditions further
13022 	 * down.
13023 	 */
13024 #ifdef BBR_INVARIANTS
13025 	if (sack_rxmit) {
13026 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
13027 			panic("RSM:%p TP:%p bbr:%p start:%u is < snd_una:%u",
13028 			    rsm, tp, bbr, rsm->r_start, tp->snd_una);
13029 		}
13030 	}
13031 #endif
13032 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
13033 	if ((len == 0) &&
13034 	    (flags & TH_FIN) &&
13035 	    (sbused(sb))) {
13036 		/*
13037 		 * We have outstanding data, don't send a fin by itself!.
13038 		 */
13039 		slot = 0;
13040 		goto just_return;
13041 	}
13042 	/*
13043 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
13044 	 * and initialize the header from the template for sends on this
13045 	 * connection.
13046 	 */
13047 	if (len) {
13048 		uint32_t moff;
13049 
13050 		/*
13051 		 * We place a limit on sending with hptsi.
13052 		 */
13053 		if ((rsm == NULL) && len > pace_max_segs)
13054 			len = pace_max_segs;
13055 		if (len <= maxseg)
13056 			tso = 0;
13057 #ifdef INET6
13058 		if (MHLEN < hdrlen + max_linkhdr)
13059 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
13060 		else
13061 #endif
13062 			m = m_gethdr(M_NOWAIT, MT_DATA);
13063 
13064 		if (m == NULL) {
13065 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13066 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13067 			SOCKBUF_UNLOCK(sb);
13068 			error = ENOBUFS;
13069 			sack_rxmit = 0;
13070 			goto out;
13071 		}
13072 		m->m_data += max_linkhdr;
13073 		m->m_len = hdrlen;
13074 		/*
13075 		 * Start the m_copy functions from the closest mbuf to the
13076 		 * sb_offset in the socket buffer chain.
13077 		 */
13078 		if ((sb_offset > sbavail(sb)) || ((len + sb_offset) > sbavail(sb))) {
13079 #ifdef BBR_INVARIANTS
13080 			if ((len + sb_offset) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0)))
13081 				panic("tp:%p bbr:%p len:%u sb_offset:%u sbavail:%u rsm:%p %u:%u:%u",
13082 				    tp, bbr, len, sb_offset, sbavail(sb), rsm,
13083 				    doing_retran_from,
13084 				    picked_up_retran,
13085 				    doing_tlp);
13086 
13087 #endif
13088 			/*
13089 			 * In this messed up situation we have two choices,
13090 			 * a) pretend the send worked, and just start timers
13091 			 * and what not (not good since that may lead us
13092 			 * back here a lot). <or> b) Send the lowest segment
13093 			 * in the map. <or> c) Drop the connection. Lets do
13094 			 * <b> which if it continues to happen will lead to
13095 			 * <c> via timeouts.
13096 			 */
13097 			BBR_STAT_INC(bbr_offset_recovery);
13098 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
13099 			sb_offset = 0;
13100 			if (rsm == NULL) {
13101 				sack_rxmit = 0;
13102 				len = sbavail(sb);
13103 			} else {
13104 				sack_rxmit = 1;
13105 				if (rsm->r_start != tp->snd_una) {
13106 					/*
13107 					 * Things are really messed up, <c>
13108 					 * is the only thing to do.
13109 					 */
13110 					BBR_STAT_INC(bbr_offset_drop);
13111 					SOCKBUF_UNLOCK(sb);
13112 					(void)m_free(m);
13113 					return (-EFAULT); /* tcp_drop() */
13114 				}
13115 				len = rsm->r_end - rsm->r_start;
13116 			}
13117 			if (len > sbavail(sb))
13118 				len = sbavail(sb);
13119 			if (len > maxseg)
13120 				len = maxseg;
13121 		}
13122 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
13123 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
13124 			m_copydata(mb, moff, (int)len,
13125 			    mtod(m, caddr_t)+hdrlen);
13126 			if (rsm == NULL)
13127 				sbsndptr_adv(sb, mb, len);
13128 			m->m_len += len;
13129 		} else {
13130 			struct sockbuf *msb;
13131 
13132 			if (rsm)
13133 				msb = NULL;
13134 			else
13135 				msb = sb;
13136 #ifdef BBR_INVARIANTS
13137 			if ((len + moff) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0))) {
13138 				if (rsm) {
13139 					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 ",
13140 					    tp, bbr, len, moff,
13141 					    sbavail(sb), rsm,
13142 					    tp->snd_una, rsm->r_flags, rsm->r_start,
13143 					    doing_retran_from,
13144 					    picked_up_retran,
13145 					    doing_tlp, sack_rxmit);
13146 				} else {
13147 					panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u sb_offset:%u snd_una:%u",
13148 					    tp, bbr, len, moff, sbavail(sb), sb_offset, tp->snd_una);
13149 				}
13150 			}
13151 #endif
13152 			m->m_next = tcp_m_copym(
13153 				mb, moff, &len,
13154 				if_hw_tsomaxsegcount,
13155 				if_hw_tsomaxsegsize, msb,
13156 				((rsm == NULL) ? hw_tls : 0)
13157 #ifdef NETFLIX_COPY_ARGS
13158 				, NULL, NULL
13159 #endif
13160 				);
13161 			if (len <= maxseg) {
13162 				/*
13163 				 * Must have ran out of mbufs for the copy
13164 				 * shorten it to no longer need tso. Lets
13165 				 * not put on sendalot since we are low on
13166 				 * mbufs.
13167 				 */
13168 				tso = 0;
13169 			}
13170 			if (m->m_next == NULL) {
13171 				SOCKBUF_UNLOCK(sb);
13172 				(void)m_free(m);
13173 				error = ENOBUFS;
13174 				sack_rxmit = 0;
13175 				goto out;
13176 			}
13177 		}
13178 #ifdef BBR_INVARIANTS
13179 		if (tso && len < maxseg) {
13180 			panic("tp:%p tso on, but len:%d < maxseg:%d",
13181 			    tp, len, maxseg);
13182 		}
13183 		if (tso && if_hw_tsomaxsegcount) {
13184 			int32_t seg_cnt = 0;
13185 			struct mbuf *foo;
13186 
13187 			foo = m;
13188 			while (foo) {
13189 				seg_cnt++;
13190 				foo = foo->m_next;
13191 			}
13192 			if (seg_cnt > if_hw_tsomaxsegcount) {
13193 				panic("seg_cnt:%d > max:%d", seg_cnt, if_hw_tsomaxsegcount);
13194 			}
13195 		}
13196 #endif
13197 		/*
13198 		 * If we're sending everything we've got, set PUSH. (This
13199 		 * will keep happy those implementations which only give
13200 		 * data to the user when a buffer fills or a PUSH comes in.)
13201 		 */
13202 		if (sb_offset + len == sbused(sb) &&
13203 		    sbused(sb) &&
13204 		    !(flags & TH_SYN)) {
13205 			flags |= TH_PUSH;
13206 		}
13207 		SOCKBUF_UNLOCK(sb);
13208 	} else {
13209 		SOCKBUF_UNLOCK(sb);
13210 		if (tp->t_flags & TF_ACKNOW)
13211 			KMOD_TCPSTAT_INC(tcps_sndacks);
13212 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
13213 			KMOD_TCPSTAT_INC(tcps_sndctrl);
13214 		else
13215 			KMOD_TCPSTAT_INC(tcps_sndwinup);
13216 
13217 		m = m_gethdr(M_NOWAIT, MT_DATA);
13218 		if (m == NULL) {
13219 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13220 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13221 			error = ENOBUFS;
13222 			/* Fudge the send time since we could not send */
13223 			sack_rxmit = 0;
13224 			goto out;
13225 		}
13226 #ifdef INET6
13227 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
13228 		    MHLEN >= hdrlen) {
13229 			M_ALIGN(m, hdrlen);
13230 		} else
13231 #endif
13232 			m->m_data += max_linkhdr;
13233 		m->m_len = hdrlen;
13234 	}
13235 	SOCKBUF_UNLOCK_ASSERT(sb);
13236 	m->m_pkthdr.rcvif = (struct ifnet *)0;
13237 #ifdef MAC
13238 	mac_inpcb_create_mbuf(inp, m);
13239 #endif
13240 #ifdef INET6
13241 	if (isipv6) {
13242 		ip6 = mtod(m, struct ip6_hdr *);
13243 		if (tp->t_port) {
13244 			udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
13245 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13246 			udp->uh_dport = tp->t_port;
13247 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
13248 			udp->uh_ulen = htons(ulen);
13249 			th = (struct tcphdr *)(udp + 1);
13250 		} else {
13251 			th = (struct tcphdr *)(ip6 + 1);
13252 		}
13253 		tcpip_fillheaders(inp, tp->t_port, ip6, th);
13254 	} else
13255 #endif				/* INET6 */
13256 	{
13257 		ip = mtod(m, struct ip *);
13258 		if (tp->t_port) {
13259 			udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
13260 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13261 			udp->uh_dport = tp->t_port;
13262 			ulen = hdrlen + len - sizeof(struct ip);
13263 			udp->uh_ulen = htons(ulen);
13264 			th = (struct tcphdr *)(udp + 1);
13265 		} else {
13266 			th = (struct tcphdr *)(ip + 1);
13267 		}
13268 		tcpip_fillheaders(inp, tp->t_port, ip, th);
13269 	}
13270 	/*
13271 	 * If we are doing retransmissions, then snd_nxt will not reflect
13272 	 * the first unsent octet.  For ACK only packets, we do not want the
13273 	 * sequence number of the retransmitted packet, we want the sequence
13274 	 * number of the next unsent octet.  So, if there is no data (and no
13275 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
13276 	 * ti_seq.  But if we are in persist state, snd_max might reflect
13277 	 * one byte beyond the right edge of the window, so use snd_nxt in
13278 	 * that case, since we know we aren't doing a retransmission.
13279 	 * (retransmit and persist are mutually exclusive...)
13280 	 */
13281 	if (sack_rxmit == 0) {
13282 		if (len && ((flags & (TH_FIN | TH_SYN | TH_RST)) == 0)) {
13283 			/* New data (including new persists) */
13284 			th->th_seq = htonl(tp->snd_max);
13285 			bbr_seq = tp->snd_max;
13286 		} else if (flags & TH_SYN) {
13287 			/* Syn's always send from iss */
13288 			th->th_seq = htonl(tp->iss);
13289 			bbr_seq = tp->iss;
13290 		} else if (flags & TH_FIN) {
13291 			if (flags & TH_FIN && tp->t_flags & TF_SENTFIN) {
13292 				/*
13293 				 * If we sent the fin already its 1 minus
13294 				 * snd_max
13295 				 */
13296 				th->th_seq = (htonl(tp->snd_max - 1));
13297 				bbr_seq = (tp->snd_max - 1);
13298 			} else {
13299 				/* First time FIN use snd_max */
13300 				th->th_seq = htonl(tp->snd_max);
13301 				bbr_seq = tp->snd_max;
13302 			}
13303 		} else {
13304 			/*
13305 			 * len == 0 and not persist we use snd_max, sending
13306 			 * an ack unless we have sent the fin then its 1
13307 			 * minus.
13308 			 */
13309 			/*
13310 			 * XXXRRS Question if we are in persists and we have
13311 			 * nothing outstanding to send and we have not sent
13312 			 * a FIN, we will send an ACK. In such a case it
13313 			 * might be better to send (tp->snd_una - 1) which
13314 			 * would force the peer to ack.
13315 			 */
13316 			if (tp->t_flags & TF_SENTFIN) {
13317 				th->th_seq = htonl(tp->snd_max - 1);
13318 				bbr_seq = (tp->snd_max - 1);
13319 			} else {
13320 				th->th_seq = htonl(tp->snd_max);
13321 				bbr_seq = tp->snd_max;
13322 			}
13323 		}
13324 	} else {
13325 		/* All retransmits use the rsm to guide the send */
13326 		th->th_seq = htonl(rsm->r_start);
13327 		bbr_seq = rsm->r_start;
13328 	}
13329 	th->th_ack = htonl(tp->rcv_nxt);
13330 	if (optlen) {
13331 		bcopy(opt, th + 1, optlen);
13332 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
13333 	}
13334 	tcp_set_flags(th, flags);
13335 	/*
13336 	 * Calculate receive window.  Don't shrink window, but avoid silly
13337 	 * window syndrome.
13338 	 */
13339 	if ((flags & TH_RST) || ((recwin < (so->so_rcv.sb_hiwat / 4) &&
13340 				  recwin < maxseg)))
13341 		recwin = 0;
13342 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
13343 	    recwin < (tp->rcv_adv - tp->rcv_nxt))
13344 		recwin = (tp->rcv_adv - tp->rcv_nxt);
13345 	if (recwin > TCP_MAXWIN << tp->rcv_scale)
13346 		recwin = TCP_MAXWIN << tp->rcv_scale;
13347 
13348 	/*
13349 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
13350 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
13351 	 * handled in syncache.
13352 	 */
13353 	if (flags & TH_SYN)
13354 		th->th_win = htons((u_short)
13355 		    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
13356 	else {
13357 		/* Avoid shrinking window with window scaling. */
13358 		recwin = roundup2(recwin, 1 << tp->rcv_scale);
13359 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
13360 	}
13361 	/*
13362 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
13363 	 * window.  This may cause the remote transmitter to stall.  This
13364 	 * flag tells soreceive() to disable delayed acknowledgements when
13365 	 * draining the buffer.  This can occur if the receiver is
13366 	 * attempting to read more data than can be buffered prior to
13367 	 * transmitting on the connection.
13368 	 */
13369 	if (th->th_win == 0) {
13370 		tp->t_sndzerowin++;
13371 		tp->t_flags |= TF_RXWIN0SENT;
13372 	} else
13373 		tp->t_flags &= ~TF_RXWIN0SENT;
13374 	/*
13375 	 * We don't support urgent data, but drag along
13376 	 * the pointer in case of a stack switch.
13377 	 */
13378 	tp->snd_up = tp->snd_una;
13379 	/*
13380 	 * Put TCP length in extended header, and then checksum extended
13381 	 * header and data.
13382 	 */
13383 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
13384 
13385 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13386 	if (to.to_flags & TOF_SIGNATURE) {
13387 		/*
13388 		 * Calculate MD5 signature and put it into the place
13389 		 * determined before. NOTE: since TCP options buffer doesn't
13390 		 * point into mbuf's data, calculate offset and use it.
13391 		 */
13392 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
13393 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
13394 			/*
13395 			 * Do not send segment if the calculation of MD5
13396 			 * digest has failed.
13397 			 */
13398 			goto out;
13399 		}
13400 	}
13401 #endif
13402 
13403 #ifdef INET6
13404 	if (isipv6) {
13405 		/*
13406 		 * ip6_plen is not need to be filled now, and will be filled
13407 		 * in ip6_output.
13408 		 */
13409 		if (tp->t_port) {
13410 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
13411 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13412 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
13413 			th->th_sum = htons(0);
13414 			UDPSTAT_INC(udps_opackets);
13415 		} else {
13416 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
13417 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13418 			th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
13419 			    optlen + len, IPPROTO_TCP, 0);
13420 		}
13421 	}
13422 #endif
13423 #if defined(INET6) && defined(INET)
13424 	else
13425 #endif
13426 #ifdef INET
13427 	{
13428 		if (tp->t_port) {
13429 			m->m_pkthdr.csum_flags = CSUM_UDP;
13430 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13431 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
13432 			    ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
13433 			th->th_sum = htons(0);
13434 			UDPSTAT_INC(udps_opackets);
13435 		} else {
13436 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP;
13437 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13438 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
13439 			    ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
13440 			    IPPROTO_TCP + len + optlen));
13441 		}
13442 		/* IP version must be set here for ipv4/ipv6 checking later */
13443 		KASSERT(ip->ip_v == IPVERSION,
13444 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
13445 	}
13446 #endif
13447 
13448 	/*
13449 	 * Enable TSO and specify the size of the segments. The TCP pseudo
13450 	 * header checksum is always provided. XXX: Fixme: This is currently
13451 	 * not the case for IPv6.
13452 	 */
13453 	if (tso) {
13454 		KASSERT(len > maxseg,
13455 		    ("%s: len:%d <= tso_segsz:%d", __func__, len, maxseg));
13456 		m->m_pkthdr.csum_flags |= CSUM_TSO;
13457 		csum_flags |= CSUM_TSO;
13458 		m->m_pkthdr.tso_segsz = maxseg;
13459 	}
13460 	KASSERT(len + hdrlen == m_length(m, NULL),
13461 	    ("%s: mbuf chain different than expected: %d + %u != %u",
13462 	    __func__, len, hdrlen, m_length(m, NULL)));
13463 
13464 #ifdef TCP_HHOOK
13465 	/* Run HHOOK_TC_ESTABLISHED_OUT helper hooks. */
13466 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
13467 #endif
13468 
13469 	/* Log to the black box */
13470 	if (tcp_bblogging_on(tp)) {
13471 		union tcp_log_stackspecific log;
13472 
13473 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
13474 		/* Record info on type of transmission */
13475 		log.u_bbr.flex1 = bbr->r_ctl.rc_hptsi_agg_delay;
13476 		log.u_bbr.flex2 = (bbr->r_recovery_bw << 3);
13477 		log.u_bbr.flex3 = maxseg;
13478 		log.u_bbr.flex4 = delay_calc;
13479 		log.u_bbr.flex5 = bbr->rc_past_init_win;
13480 		log.u_bbr.flex5 <<= 1;
13481 		log.u_bbr.flex5 |= bbr->rc_no_pacing;
13482 		log.u_bbr.flex5 <<= 29;
13483 		log.u_bbr.flex5 |= tp->t_maxseg;
13484 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_max_segs;
13485 		log.u_bbr.flex7 = (bbr->rc_bbr_state << 8) | bbr_state_val(bbr);
13486 		/* lets poke in the low and the high here for debugging */
13487 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
13488 		if (rsm || sack_rxmit) {
13489 			if (doing_tlp)
13490 				log.u_bbr.flex8 = 2;
13491 			else
13492 				log.u_bbr.flex8 = 1;
13493 		} else {
13494 			log.u_bbr.flex8 = 0;
13495 		}
13496 		lgb = tcp_log_event(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
13497 		    len, &log, false, NULL, NULL, 0, tv);
13498 	} else {
13499 		lgb = NULL;
13500 	}
13501 	/*
13502 	 * Fill in IP length and desired time to live and send to IP level.
13503 	 * There should be a better way to handle ttl and tos; we could keep
13504 	 * them in the template, but need a way to checksum without them.
13505 	 */
13506 	/*
13507 	 * m->m_pkthdr.len should have been set before cksum calcuration,
13508 	 * because in6_cksum() need it.
13509 	 */
13510 #ifdef INET6
13511 	if (isipv6) {
13512 		/*
13513 		 * we separately set hoplimit for every segment, since the
13514 		 * user might want to change the value via setsockopt. Also,
13515 		 * desired default hop limit might be changed via Neighbor
13516 		 * Discovery.
13517 		 */
13518 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
13519 
13520 		/*
13521 		 * Set the packet size here for the benefit of DTrace
13522 		 * probes. ip6_output() will set it properly; it's supposed
13523 		 * to include the option header lengths as well.
13524 		 */
13525 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
13526 
13527 		if (V_path_mtu_discovery && maxseg > V_tcp_minmss)
13528 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13529 		else
13530 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13531 
13532 		if (tp->t_state == TCPS_SYN_SENT)
13533 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
13534 
13535 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
13536 		/* TODO: IPv6 IP6TOS_ECT bit on */
13537 		error = ip6_output(m, inp->in6p_outputopts,
13538 		    &inp->inp_route6,
13539 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
13540 		    NULL, NULL, inp);
13541 
13542 		if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
13543 			mtu = inp->inp_route6.ro_nh->nh_mtu;
13544 	}
13545 #endif				/* INET6 */
13546 #if defined(INET) && defined(INET6)
13547 	else
13548 #endif
13549 #ifdef INET
13550 	{
13551 		ip->ip_len = htons(m->m_pkthdr.len);
13552 #ifdef INET6
13553 		if (isipv6)
13554 			ip->ip_ttl = in6_selecthlim(inp, NULL);
13555 #endif				/* INET6 */
13556 		/*
13557 		 * If we do path MTU discovery, then we set DF on every
13558 		 * packet. This might not be the best thing to do according
13559 		 * to RFC3390 Section 2. However the tcp hostcache migitates
13560 		 * the problem so it affects only the first tcp connection
13561 		 * with a host.
13562 		 *
13563 		 * NB: Don't set DF on small MTU/MSS to have a safe
13564 		 * fallback.
13565 		 */
13566 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
13567 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13568 			if (tp->t_port == 0 || len < V_tcp_minmss) {
13569 				ip->ip_off |= htons(IP_DF);
13570 			}
13571 		} else {
13572 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13573 		}
13574 
13575 		if (tp->t_state == TCPS_SYN_SENT)
13576 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
13577 
13578 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
13579 
13580 		error = ip_output(m, inp->inp_options, &inp->inp_route,
13581 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
13582 		    inp);
13583 		if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
13584 			mtu = inp->inp_route.ro_nh->nh_mtu;
13585 	}
13586 #endif				/* INET */
13587 	if (lgb) {
13588 		lgb->tlb_errno = error;
13589 		lgb = NULL;
13590 	}
13591 
13592 out:
13593 	/*
13594 	 * In transmit state, time the transmission and arrange for the
13595 	 * retransmit.  In persist state, just set snd_max.
13596 	 */
13597 	if (error == 0) {
13598 		tcp_account_for_send(tp, len, (rsm != NULL), doing_tlp, hw_tls);
13599 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13600 		    (tp->t_flags & TF_SACK_PERMIT) &&
13601 		    tp->rcv_numsacks > 0)
13602 			tcp_clean_dsack_blocks(tp);
13603 		/* We sent an ack clear the bbr_segs_rcvd count */
13604 		bbr->output_error_seen = 0;
13605 		bbr->oerror_cnt = 0;
13606 		bbr->bbr_segs_rcvd = 0;
13607 		if (len == 0)
13608 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_SNDACK], 1);
13609 		/* Do accounting for new sends */
13610 		if ((len > 0) && (rsm == NULL)) {
13611 			int idx;
13612 			if (tp->snd_una == tp->snd_max) {
13613 				/*
13614 				 * Special case to match google, when
13615 				 * nothing is in flight the delivered
13616 				 * time does get updated to the current
13617 				 * time (see tcp_rate_bsd.c).
13618 				 */
13619 				bbr->r_ctl.rc_del_time = cts;
13620 			}
13621 			if (len >= maxseg) {
13622 				idx = (len / maxseg) + 3;
13623 				if (idx >= TCP_MSS_ACCT_ATIMER)
13624 					counter_u64_add(bbr_out_size[(TCP_MSS_ACCT_ATIMER - 1)], 1);
13625 				else
13626 					counter_u64_add(bbr_out_size[idx], 1);
13627 			} else {
13628 				/* smaller than a MSS */
13629 				idx = len / (bbr_hptsi_bytes_min - bbr->rc_last_options);
13630 				if (idx >= TCP_MSS_SMALL_MAX_SIZE_DIV)
13631 					idx = (TCP_MSS_SMALL_MAX_SIZE_DIV - 1);
13632 				counter_u64_add(bbr_out_size[(idx + TCP_MSS_SMALL_SIZE_OFF)], 1);
13633 			}
13634 		}
13635 	}
13636 	abandon = 0;
13637 	/*
13638 	 * We must do the send accounting before we log the output,
13639 	 * otherwise the state of the rsm could change and we account to the
13640 	 * wrong bucket.
13641 	 */
13642 	if (len > 0) {
13643 		bbr_do_send_accounting(tp, bbr, rsm, len, error);
13644 		if (error == 0) {
13645 			if (tp->snd_una == tp->snd_max)
13646 				bbr->r_ctl.rc_tlp_rxt_last_time = cts;
13647 		}
13648 	}
13649 	bbr_log_output(bbr, tp, &to, len, bbr_seq, (uint8_t) flags, error,
13650 	    cts, mb, &abandon, rsm, 0, sb);
13651 	if (abandon) {
13652 		/*
13653 		 * If bbr_log_output destroys the TCB or sees a TH_RST being
13654 		 * sent we should hit this condition.
13655 		 */
13656 		return (0);
13657 	}
13658 	if (bbr->rc_in_persist == 0) {
13659 		/*
13660 		 * Advance snd_nxt over sequence space of this segment.
13661 		 */
13662 		if (error)
13663 			/* We don't log or do anything with errors */
13664 			goto skip_upd;
13665 
13666 		if (tp->snd_una == tp->snd_max &&
13667 		    (len || (flags & (TH_SYN | TH_FIN)))) {
13668 			/*
13669 			 * Update the time we just added data since none was
13670 			 * outstanding.
13671 			 */
13672 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13673 			bbr->rc_tp->t_acktime  = ticks;
13674 		}
13675 		if (flags & (TH_SYN | TH_FIN) && (rsm == NULL)) {
13676 			if (flags & TH_SYN) {
13677 				/*
13678 				 * Smack the snd_max to iss + 1
13679 				 * if its a FO we will add len below.
13680 				 */
13681 				tp->snd_max = tp->iss + 1;
13682 			}
13683 			if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13684 				tp->snd_max++;
13685 				tp->t_flags |= TF_SENTFIN;
13686 			}
13687 		}
13688 		if (sack_rxmit == 0)
13689 			tp->snd_max += len;
13690 skip_upd:
13691 		if ((error == 0) && len)
13692 			tot_len += len;
13693 	} else {
13694 		/* Persists case */
13695 		int32_t xlen = len;
13696 
13697 		if (error)
13698 			goto nomore;
13699 
13700 		if (flags & TH_SYN)
13701 			++xlen;
13702 		if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13703 			++xlen;
13704 			tp->t_flags |= TF_SENTFIN;
13705 		}
13706 		if (xlen && (tp->snd_una == tp->snd_max)) {
13707 			/*
13708 			 * Update the time we just added data since none was
13709 			 * outstanding.
13710 			 */
13711 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13712 			bbr->rc_tp->t_acktime = ticks;
13713 		}
13714 		if (sack_rxmit == 0)
13715 			tp->snd_max += xlen;
13716 		tot_len += (len + optlen + ipoptlen);
13717 	}
13718 nomore:
13719 	if (error) {
13720 		/*
13721 		 * Failures do not advance the seq counter above. For the
13722 		 * case of ENOBUFS we will fall out and become ack-clocked.
13723 		 * capping the cwnd at the current flight.
13724 		 * Everything else will just have to retransmit with the timer
13725 		 * (no pacer).
13726 		 */
13727 		SOCKBUF_UNLOCK_ASSERT(sb);
13728 		BBR_STAT_INC(bbr_saw_oerr);
13729 		/* Clear all delay/early tracks */
13730 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
13731 		bbr->r_ctl.rc_agg_early = 0;
13732 		bbr->r_agg_early_set = 0;
13733 		bbr->output_error_seen = 1;
13734 		if (bbr->oerror_cnt < 0xf)
13735 			bbr->oerror_cnt++;
13736 		if (bbr_max_net_error_cnt && (bbr->oerror_cnt >= bbr_max_net_error_cnt)) {
13737 			/* drop the session */
13738 			return (-ENETDOWN);
13739 		}
13740 		switch (error) {
13741 		case ENOBUFS:
13742 			/*
13743 			 * Make this guy have to get ack's to send
13744 			 * more but lets make sure we don't
13745 			 * slam him below a T-O (1MSS).
13746 			 */
13747 			if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
13748 				tp->snd_cwnd = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13749 								    bbr->r_ctl.rc_lost_bytes)) - maxseg;
13750 				if (tp->snd_cwnd < maxseg)
13751 					tp->snd_cwnd = maxseg;
13752 			}
13753 			slot = (bbr_error_base_paceout + 1) << bbr->oerror_cnt;
13754 			BBR_STAT_INC(bbr_saw_enobuf);
13755 			if (bbr->bbr_hdrw_pacing)
13756 				counter_u64_add(bbr_hdwr_pacing_enobuf, 1);
13757 			else
13758 				counter_u64_add(bbr_nohdwr_pacing_enobuf, 1);
13759 			/*
13760 			 * Here even in the enobuf's case we want to do our
13761 			 * state update. The reason being we may have been
13762 			 * called by the input function. If so we have had
13763 			 * things change.
13764 			 */
13765 			error = 0;
13766 			goto enobufs;
13767 		case EMSGSIZE:
13768 			/*
13769 			 * For some reason the interface we used initially
13770 			 * to send segments changed to another or lowered
13771 			 * its MTU. If TSO was active we either got an
13772 			 * interface without TSO capabilits or TSO was
13773 			 * turned off. If we obtained mtu from ip_output()
13774 			 * then update it and try again.
13775 			 */
13776 			/* Turn on tracing (or try to) */
13777 			{
13778 				int old_maxseg;
13779 
13780 				old_maxseg = tp->t_maxseg;
13781 				BBR_STAT_INC(bbr_saw_emsgsiz);
13782 				bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, csum_flags, tso, cts);
13783 				if (mtu != 0)
13784 					tcp_mss_update(tp, -1, mtu, NULL, NULL);
13785 				if (old_maxseg <= tp->t_maxseg) {
13786 					/* Huh it did not shrink? */
13787 					tp->t_maxseg = old_maxseg - 40;
13788 					bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
13789 				}
13790 				/*
13791 				 * Nuke all other things that can interfere
13792 				 * with slot
13793 				 */
13794 				if ((tot_len + len) && (len >= tp->t_maxseg)) {
13795 					slot = bbr_get_pacing_delay(bbr,
13796 					    bbr->r_ctl.rc_bbr_hptsi_gain,
13797 					    (tot_len + len), cts, 0);
13798 					if (slot < bbr_error_base_paceout)
13799 						slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13800 				} else
13801 					slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13802 				bbr->rc_output_starts_timer = 1;
13803 				bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
13804 				    tot_len);
13805 				return (error);
13806 			}
13807 		case EPERM:
13808 		case EACCES:
13809 			tp->t_softerror = error;
13810 			/* FALLTHROUGH */
13811 		case EHOSTDOWN:
13812 		case EHOSTUNREACH:
13813 		case ENETDOWN:
13814 		case ENETUNREACH:
13815 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
13816 				tp->t_softerror = error;
13817 				error = 0;
13818 			}
13819 			/* FALLTHROUGH */
13820 		default:
13821 			slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
13822 			bbr->rc_output_starts_timer = 1;
13823 			bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
13824 			return (error);
13825 		}
13826 #ifdef STATS
13827 	} else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
13828 		    len &&
13829 		    (rsm == NULL) &&
13830 	    (bbr->rc_in_persist == 0)) {
13831 		tp->gput_seq = bbr_seq;
13832 		tp->gput_ack = bbr_seq +
13833 		    min(sbavail(&so->so_snd) - sb_offset, sendwin);
13834 		tp->gput_ts = cts;
13835 		tp->t_flags |= TF_GPUTINPROG;
13836 #endif
13837 	}
13838 	KMOD_TCPSTAT_INC(tcps_sndtotal);
13839 	if ((bbr->bbr_hdw_pace_ena) &&
13840 	    (bbr->bbr_attempt_hdwr_pace == 0) &&
13841 	    (bbr->rc_past_init_win) &&
13842 	    (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
13843 	    (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
13844 	    (inp->inp_route.ro_nh &&
13845 	     inp->inp_route.ro_nh->nh_ifp)) {
13846 		/*
13847 		 * We are past the initial window and
13848 		 * have at least one measurement so we
13849 		 * could use hardware pacing if its available.
13850 		 * We have an interface and we have not attempted
13851 		 * to setup hardware pacing, lets try to now.
13852 		 */
13853 		uint64_t rate_wanted;
13854 		int err = 0;
13855 
13856 		rate_wanted = bbr_get_hardware_rate(bbr);
13857 		bbr->bbr_attempt_hdwr_pace = 1;
13858 		bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp,
13859 						      inp->inp_route.ro_nh->nh_ifp,
13860 						      rate_wanted,
13861 						      (RS_PACING_GEQ|RS_PACING_SUB_OK),
13862 						      &err, NULL);
13863 		if (bbr->r_ctl.crte) {
13864 			bbr_type_log_hdwr_pacing(bbr,
13865 						 bbr->r_ctl.crte->ptbl->rs_ifp,
13866 						 rate_wanted,
13867 						 bbr->r_ctl.crte->rate,
13868 						 __LINE__, cts, err);
13869 			BBR_STAT_INC(bbr_hdwr_rl_add_ok);
13870 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
13871 			counter_u64_add(bbr_flows_whdwr_pacing, 1);
13872 			bbr->bbr_hdrw_pacing = 1;
13873 			/* Now what is our gain status? */
13874 			if (bbr->r_ctl.crte->rate < rate_wanted) {
13875 				/* We have a problem */
13876 				bbr_setup_less_of_rate(bbr, cts,
13877 						       bbr->r_ctl.crte->rate, rate_wanted);
13878 			} else {
13879 				/* We are good */
13880 				bbr->gain_is_limited = 0;
13881 				bbr->skip_gain = 0;
13882 			}
13883 			tcp_bbr_tso_size_check(bbr, cts);
13884 		} else {
13885 			bbr_type_log_hdwr_pacing(bbr,
13886 						 inp->inp_route.ro_nh->nh_ifp,
13887 						 rate_wanted,
13888 						 0,
13889 						 __LINE__, cts, err);
13890 			BBR_STAT_INC(bbr_hdwr_rl_add_fail);
13891 		}
13892 	}
13893 	if (bbr->bbr_hdrw_pacing) {
13894 		/*
13895 		 * Worry about cases where the route
13896 		 * changes or something happened that we
13897 		 * lost our hardware pacing possibly during
13898 		 * the last ip_output call.
13899 		 */
13900 		if (inp->inp_snd_tag == NULL) {
13901 			/* A change during ip output disabled hw pacing? */
13902 			bbr->bbr_hdrw_pacing = 0;
13903 		} else if ((inp->inp_route.ro_nh == NULL) ||
13904 		    (inp->inp_route.ro_nh->nh_ifp != inp->inp_snd_tag->ifp)) {
13905 			/*
13906 			 * We had an interface or route change,
13907 			 * detach from the current hdwr pacing
13908 			 * and setup to re-attempt next go
13909 			 * round.
13910 			 */
13911 			bbr->bbr_hdrw_pacing = 0;
13912 			bbr->bbr_attempt_hdwr_pace = 0;
13913 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
13914 			tcp_bbr_tso_size_check(bbr, cts);
13915 		}
13916 	}
13917 	/*
13918 	 * Data sent (as far as we can tell). If this advertises a larger
13919 	 * window than any other segment, then remember the size of the
13920 	 * advertised window. Any pending ACK has now been sent.
13921 	 */
13922 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
13923 		tp->rcv_adv = tp->rcv_nxt + recwin;
13924 
13925 	tp->last_ack_sent = tp->rcv_nxt;
13926 	if ((error == 0) &&
13927 	    (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
13928 	    (doing_tlp == 0) &&
13929 	    (tso == 0) &&
13930 	    (len > 0) &&
13931 	    ((flags & TH_RST) == 0) &&
13932 	    ((flags & TH_SYN) == 0) &&
13933 	    (IN_RECOVERY(tp->t_flags) == 0) &&
13934 	    (bbr->rc_in_persist == 0) &&
13935 	    (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
13936 		/*
13937 		 * For non-tso we need to goto again until we have sent out
13938 		 * enough data to match what we are hptsi out every hptsi
13939 		 * interval.
13940 		 */
13941 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
13942 			/* Make sure snd_nxt is drug up */
13943 			tp->snd_nxt = tp->snd_max;
13944 		}
13945 		if (rsm != NULL) {
13946 			rsm = NULL;
13947 			goto skip_again;
13948 		}
13949 		rsm = NULL;
13950 		sack_rxmit = 0;
13951 		tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
13952 		goto again;
13953 	}
13954 skip_again:
13955 	if ((error == 0) && (flags & TH_FIN))
13956 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
13957 	if ((error == 0) && (flags & TH_RST))
13958 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
13959 	if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
13960 		/*
13961 		 * Calculate/Re-Calculate the hptsi slot in usecs based on
13962 		 * what we have sent so far
13963 		 */
13964 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
13965 		if (bbr->rc_no_pacing)
13966 			slot = 0;
13967 	}
13968 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
13969 enobufs:
13970 	if (bbr->rc_use_google == 0)
13971 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
13972 	bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13973 							bbr->r_ctl.rc_lost_bytes)));
13974 	bbr->rc_output_starts_timer = 1;
13975 	if (bbr->bbr_use_rack_cheat &&
13976 	    (more_to_rxt ||
13977 	     ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
13978 		/* Rack cheats and shotguns out all rxt's 1ms apart */
13979 		if (slot > 1000)
13980 			slot = 1000;
13981 	}
13982 	if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
13983 		/*
13984 		 * We don't change the tso size until some number of sends
13985 		 * to give the hardware commands time to get down
13986 		 * to the interface.
13987 		 */
13988 		bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
13989 		if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
13990 			bbr->hw_pacing_set = 1;
13991 			tcp_bbr_tso_size_check(bbr, cts);
13992 		}
13993 	}
13994 	bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
13995 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
13996 		/* Make sure snd_nxt is drug up */
13997 		tp->snd_nxt = tp->snd_max;
13998 	}
13999 	return (error);
14000 
14001 }
14002 
14003 /*
14004  * See bbr_output_wtime() for return values.
14005  */
14006 static int
bbr_output(struct tcpcb * tp)14007 bbr_output(struct tcpcb *tp)
14008 {
14009 	int32_t ret;
14010 	struct timeval tv;
14011 
14012 	NET_EPOCH_ASSERT();
14013 
14014 	INP_WLOCK_ASSERT(tptoinpcb(tp));
14015 	(void)tcp_get_usecs(&tv);
14016 	ret = bbr_output_wtime(tp, &tv);
14017 	return (ret);
14018 }
14019 
14020 static void
bbr_mtu_chg(struct tcpcb * tp)14021 bbr_mtu_chg(struct tcpcb *tp)
14022 {
14023 	struct tcp_bbr *bbr;
14024 	struct bbr_sendmap *rsm, *frsm = NULL;
14025 	uint32_t maxseg;
14026 
14027 	/*
14028 	 * The MTU has changed. a) Clear the sack filter. b) Mark everything
14029 	 * over the current size as SACK_PASS so a retransmit will occur.
14030 	 */
14031 
14032 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14033 	maxseg = tp->t_maxseg - bbr->rc_last_options;
14034 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14035 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14036 		/* Don't mess with ones acked (by sack?) */
14037 		if (rsm->r_flags & BBR_ACKED)
14038 			continue;
14039 		if ((rsm->r_end - rsm->r_start) > maxseg) {
14040 			/*
14041 			 * We mark sack-passed on all the previous large
14042 			 * sends we did. This will force them to retransmit.
14043 			 */
14044 			rsm->r_flags |= BBR_SACK_PASSED;
14045 			if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14046 			    bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14047 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14048 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14049 				rsm->r_flags |= BBR_MARKED_LOST;
14050 			}
14051 			if (frsm == NULL)
14052 				frsm = rsm;
14053 		}
14054 	}
14055 	if (frsm) {
14056 		bbr->r_ctl.rc_resend = frsm;
14057 	}
14058 }
14059 
14060 static int
bbr_pru_options(struct tcpcb * tp,int flags)14061 bbr_pru_options(struct tcpcb *tp, int flags)
14062 {
14063 	if (flags & PRUS_OOB)
14064 		return (EOPNOTSUPP);
14065 	return (0);
14066 }
14067 
14068 static void
bbr_switch_failed(struct tcpcb * tp)14069 bbr_switch_failed(struct tcpcb *tp)
14070 {
14071 	/*
14072 	 * If a switch fails we only need to
14073 	 * make sure mbuf_queuing is still in place.
14074 	 * We also need to make sure we are still in
14075 	 * ticks granularity (though we should probably
14076 	 * change bbr to go to USECs).
14077 	 *
14078 	 * For timers we need to see if we are still in the
14079 	 * pacer (if our flags are up) if so we are good, if
14080 	 * not we need to get back into the pacer.
14081 	 */
14082 	struct timeval tv;
14083 	uint32_t cts;
14084 	uint32_t toval;
14085 	struct tcp_bbr *bbr;
14086 	struct hpts_diag diag;
14087 
14088 	tp->t_flags2 |= TF2_CANNOT_DO_ECN;
14089 	tp->t_flags2 |= TF2_SUPPORTS_MBUFQ;
14090 	tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
14091 	if (tp->t_in_hpts > IHPTS_NONE) {
14092 		return;
14093 	}
14094 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14095 	cts = tcp_get_usecs(&tv);
14096 	if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
14097 		if (TSTMP_GT(bbr->rc_pacer_started, cts)) {
14098 			toval = bbr->rc_pacer_started - cts;
14099 		} else {
14100 			/* one slot please */
14101 			toval = HPTS_TICKS_PER_SLOT;
14102 		}
14103 	} else if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
14104 		if (TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
14105 			toval = bbr->r_ctl.rc_timer_exp - cts;
14106 		} else {
14107 			/* one slot please */
14108 			toval = HPTS_TICKS_PER_SLOT;
14109 		}
14110 	} else
14111 		toval = HPTS_TICKS_PER_SLOT;
14112 	(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(toval),
14113 				   __LINE__, &diag);
14114 	bbr_log_hpts_diag(bbr, cts, &diag);
14115 }
14116 
14117 struct tcp_function_block __tcp_bbr = {
14118 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
14119 	.tfb_tcp_output = bbr_output,
14120 	.tfb_do_queued_segments = ctf_do_queued_segments,
14121 	.tfb_do_segment_nounlock = bbr_do_segment_nounlock,
14122 	.tfb_tcp_do_segment = bbr_do_segment,
14123 	.tfb_tcp_ctloutput = bbr_ctloutput,
14124 	.tfb_tcp_fb_init = bbr_init,
14125 	.tfb_tcp_fb_fini = bbr_fini,
14126 	.tfb_tcp_timer_stop_all = bbr_stopall,
14127 	.tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
14128 	.tfb_tcp_handoff_ok = bbr_handoff_ok,
14129 	.tfb_tcp_mtu_chg = bbr_mtu_chg,
14130 	.tfb_pru_options = bbr_pru_options,
14131 	.tfb_switch_failed = bbr_switch_failed,
14132 	.tfb_flags = TCP_FUNC_OUTPUT_CANDROP | TCP_FUNC_DEFAULT_OK,
14133 };
14134 
14135 /*
14136  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14137  * socket option arguments.  When it re-acquires the lock after the copy, it
14138  * has to revalidate that the connection is still valid for the socket
14139  * option.
14140  */
14141 static int
bbr_set_sockopt(struct tcpcb * tp,struct sockopt * sopt)14142 bbr_set_sockopt(struct tcpcb *tp, struct sockopt *sopt)
14143 {
14144 	struct epoch_tracker et;
14145 	struct inpcb *inp = tptoinpcb(tp);
14146 	struct tcp_bbr *bbr;
14147 	int32_t error = 0, optval;
14148 
14149 	switch (sopt->sopt_level) {
14150 	case IPPROTO_IPV6:
14151 	case IPPROTO_IP:
14152 		return (tcp_default_ctloutput(tp, sopt));
14153 	}
14154 
14155 	switch (sopt->sopt_name) {
14156 	case TCP_RACK_PACE_MAX_SEG:
14157 	case TCP_RACK_MIN_TO:
14158 	case TCP_RACK_REORD_THRESH:
14159 	case TCP_RACK_REORD_FADE:
14160 	case TCP_RACK_TLP_THRESH:
14161 	case TCP_RACK_PKT_DELAY:
14162 	case TCP_BBR_ALGORITHM:
14163 	case TCP_BBR_TSLIMITS:
14164 	case TCP_BBR_IWINTSO:
14165 	case TCP_BBR_RECFORCE:
14166 	case TCP_BBR_STARTUP_PG:
14167 	case TCP_BBR_DRAIN_PG:
14168 	case TCP_BBR_RWND_IS_APP:
14169 	case TCP_BBR_PROBE_RTT_INT:
14170 	case TCP_BBR_PROBE_RTT_GAIN:
14171 	case TCP_BBR_PROBE_RTT_LEN:
14172 	case TCP_BBR_STARTUP_LOSS_EXIT:
14173 	case TCP_BBR_USEDEL_RATE:
14174 	case TCP_BBR_MIN_RTO:
14175 	case TCP_BBR_MAX_RTO:
14176 	case TCP_BBR_PACE_PER_SEC:
14177 	case TCP_DELACK:
14178 	case TCP_BBR_PACE_DEL_TAR:
14179 	case TCP_BBR_SEND_IWND_IN_TSO:
14180 	case TCP_BBR_EXTRA_STATE:
14181 	case TCP_BBR_UTTER_MAX_TSO:
14182 	case TCP_BBR_MIN_TOPACEOUT:
14183 	case TCP_BBR_FLOOR_MIN_TSO:
14184 	case TCP_BBR_TSTMP_RAISES:
14185 	case TCP_BBR_POLICER_DETECT:
14186 	case TCP_BBR_USE_RACK_CHEAT:
14187 	case TCP_DATA_AFTER_CLOSE:
14188 	case TCP_BBR_HDWR_PACE:
14189 	case TCP_BBR_PACE_SEG_MAX:
14190 	case TCP_BBR_PACE_SEG_MIN:
14191 	case TCP_BBR_PACE_CROSS:
14192 	case TCP_BBR_PACE_OH:
14193 	case TCP_BBR_TMR_PACE_OH:
14194 	case TCP_BBR_RACK_RTT_USE:
14195 	case TCP_BBR_RETRAN_WTSO:
14196 		break;
14197 	default:
14198 		return (tcp_default_ctloutput(tp, sopt));
14199 		break;
14200 	}
14201 	INP_WUNLOCK(inp);
14202 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14203 	if (error)
14204 		return (error);
14205 	INP_WLOCK(inp);
14206 	if (inp->inp_flags & INP_DROPPED) {
14207 		INP_WUNLOCK(inp);
14208 		return (ECONNRESET);
14209 	}
14210 	if (tp->t_fb != &__tcp_bbr) {
14211 		INP_WUNLOCK(inp);
14212 		return (ENOPROTOOPT);
14213 	}
14214 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14215 	switch (sopt->sopt_name) {
14216 	case TCP_BBR_PACE_PER_SEC:
14217 		BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14218 		bbr->r_ctl.bbr_hptsi_per_second = optval;
14219 		break;
14220 	case TCP_BBR_PACE_DEL_TAR:
14221 		BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14222 		bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14223 		break;
14224 	case TCP_BBR_PACE_SEG_MAX:
14225 		BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14226 		bbr->r_ctl.bbr_hptsi_segments_max = optval;
14227 		break;
14228 	case TCP_BBR_PACE_SEG_MIN:
14229 		BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14230 		bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14231 		break;
14232 	case TCP_BBR_PACE_CROSS:
14233 		BBR_OPTS_INC(tcp_bbr_pace_cross);
14234 		bbr->r_ctl.bbr_cross_over = optval;
14235 		break;
14236 	case TCP_BBR_ALGORITHM:
14237 		BBR_OPTS_INC(tcp_bbr_algorithm);
14238 		if (optval && (bbr->rc_use_google == 0)) {
14239 			/* Turn on the google mode */
14240 			bbr_google_mode_on(bbr);
14241 			if ((optval > 3) && (optval < 500)) {
14242 				/*
14243 				 * Must be at least greater than .3%
14244 				 * and must be less than 50.0%.
14245 				 */
14246 				bbr->r_ctl.bbr_google_discount = optval;
14247 			}
14248 		} else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14249 			/* Turn off the google mode */
14250 			bbr_google_mode_off(bbr);
14251 		}
14252 		break;
14253 	case TCP_BBR_TSLIMITS:
14254 		BBR_OPTS_INC(tcp_bbr_tslimits);
14255 		if (optval == 1)
14256 			bbr->rc_use_ts_limit = 1;
14257 		else if (optval == 0)
14258 			bbr->rc_use_ts_limit = 0;
14259 		else
14260 			error = EINVAL;
14261 		break;
14262 
14263 	case TCP_BBR_IWINTSO:
14264 		BBR_OPTS_INC(tcp_bbr_iwintso);
14265 		if ((optval >= 0) && (optval < 128)) {
14266 			uint32_t twin;
14267 
14268 			bbr->rc_init_win = optval;
14269 			twin = bbr_initial_cwnd(bbr, tp);
14270 			if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14271 				tp->snd_cwnd = twin;
14272 			else
14273 				error = EBUSY;
14274 		} else
14275 			error = EINVAL;
14276 		break;
14277 	case TCP_BBR_STARTUP_PG:
14278 		BBR_OPTS_INC(tcp_bbr_startup_pg);
14279 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14280 			bbr->r_ctl.rc_startup_pg = optval;
14281 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14282 				bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14283 			}
14284 		} else
14285 			error = EINVAL;
14286 		break;
14287 	case TCP_BBR_DRAIN_PG:
14288 		BBR_OPTS_INC(tcp_bbr_drain_pg);
14289 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14290 			bbr->r_ctl.rc_drain_pg = optval;
14291 		else
14292 			error = EINVAL;
14293 		break;
14294 	case TCP_BBR_PROBE_RTT_LEN:
14295 		BBR_OPTS_INC(tcp_bbr_probertt_len);
14296 		if (optval <= 1)
14297 			reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14298 		else
14299 			error = EINVAL;
14300 		break;
14301 	case TCP_BBR_PROBE_RTT_GAIN:
14302 		BBR_OPTS_INC(tcp_bbr_probertt_gain);
14303 		if (optval <= BBR_UNIT)
14304 			bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14305 		else
14306 			error = EINVAL;
14307 		break;
14308 	case TCP_BBR_PROBE_RTT_INT:
14309 		BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14310 		if (optval > 1000)
14311 			bbr->r_ctl.rc_probertt_int = optval;
14312 		else
14313 			error = EINVAL;
14314 		break;
14315 	case TCP_BBR_MIN_TOPACEOUT:
14316 		BBR_OPTS_INC(tcp_bbr_topaceout);
14317 		if (optval == 0) {
14318 			bbr->no_pacing_until = 0;
14319 			bbr->rc_no_pacing = 0;
14320 		} else if (optval <= 0x00ff) {
14321 			bbr->no_pacing_until = optval;
14322 			if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14323 			    (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14324 				/* Turn on no pacing */
14325 				bbr->rc_no_pacing = 1;
14326 			}
14327 		} else
14328 			error = EINVAL;
14329 		break;
14330 	case TCP_BBR_STARTUP_LOSS_EXIT:
14331 		BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14332 		bbr->rc_loss_exit = optval;
14333 		break;
14334 	case TCP_BBR_USEDEL_RATE:
14335 		error = EINVAL;
14336 		break;
14337 	case TCP_BBR_MIN_RTO:
14338 		BBR_OPTS_INC(tcp_bbr_min_rto);
14339 		bbr->r_ctl.rc_min_rto_ms = optval;
14340 		break;
14341 	case TCP_BBR_MAX_RTO:
14342 		BBR_OPTS_INC(tcp_bbr_max_rto);
14343 		bbr->rc_max_rto_sec = optval;
14344 		break;
14345 	case TCP_RACK_MIN_TO:
14346 		/* Minimum time between rack t-o's in ms */
14347 		BBR_OPTS_INC(tcp_rack_min_to);
14348 		bbr->r_ctl.rc_min_to = optval;
14349 		break;
14350 	case TCP_RACK_REORD_THRESH:
14351 		/* RACK reorder threshold (shift amount) */
14352 		BBR_OPTS_INC(tcp_rack_reord_thresh);
14353 		if ((optval > 0) && (optval < 31))
14354 			bbr->r_ctl.rc_reorder_shift = optval;
14355 		else
14356 			error = EINVAL;
14357 		break;
14358 	case TCP_RACK_REORD_FADE:
14359 		/* Does reordering fade after ms time */
14360 		BBR_OPTS_INC(tcp_rack_reord_fade);
14361 		bbr->r_ctl.rc_reorder_fade = optval;
14362 		break;
14363 	case TCP_RACK_TLP_THRESH:
14364 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14365 		BBR_OPTS_INC(tcp_rack_tlp_thresh);
14366 		if (optval)
14367 			bbr->rc_tlp_threshold = optval;
14368 		else
14369 			error = EINVAL;
14370 		break;
14371 	case TCP_BBR_USE_RACK_CHEAT:
14372 		BBR_OPTS_INC(tcp_use_rackcheat);
14373 		if (bbr->rc_use_google) {
14374 			error = EINVAL;
14375 			break;
14376 		}
14377 		BBR_OPTS_INC(tcp_rack_cheat);
14378 		if (optval)
14379 			bbr->bbr_use_rack_cheat = 1;
14380 		else
14381 			bbr->bbr_use_rack_cheat = 0;
14382 		break;
14383 	case TCP_BBR_FLOOR_MIN_TSO:
14384 		BBR_OPTS_INC(tcp_utter_max_tso);
14385 		if ((optval >= 0) && (optval < 40))
14386 			bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14387 		else
14388 			error = EINVAL;
14389 		break;
14390 	case TCP_BBR_UTTER_MAX_TSO:
14391 		BBR_OPTS_INC(tcp_utter_max_tso);
14392 		if ((optval >= 0) && (optval < 0xffff))
14393 			bbr->r_ctl.bbr_utter_max = optval;
14394 		else
14395 			error = EINVAL;
14396 		break;
14397 
14398 	case TCP_BBR_EXTRA_STATE:
14399 		BBR_OPTS_INC(tcp_extra_state);
14400 		if (optval)
14401 			bbr->rc_use_idle_restart = 1;
14402 		else
14403 			bbr->rc_use_idle_restart = 0;
14404 		break;
14405 	case TCP_BBR_SEND_IWND_IN_TSO:
14406 		BBR_OPTS_INC(tcp_iwnd_tso);
14407 		if (optval) {
14408 			bbr->bbr_init_win_cheat = 1;
14409 			if (bbr->rc_past_init_win == 0) {
14410 				uint32_t cts;
14411 				cts = tcp_get_usecs(&bbr->rc_tv);
14412 				tcp_bbr_tso_size_check(bbr, cts);
14413 			}
14414 		} else
14415 			bbr->bbr_init_win_cheat = 0;
14416 		break;
14417 	case TCP_BBR_HDWR_PACE:
14418 		BBR_OPTS_INC(tcp_hdwr_pacing);
14419 		if (optval){
14420 			bbr->bbr_hdw_pace_ena = 1;
14421 			bbr->bbr_attempt_hdwr_pace = 0;
14422 		} else {
14423 			bbr->bbr_hdw_pace_ena = 0;
14424 #ifdef RATELIMIT
14425 			if (bbr->r_ctl.crte != NULL) {
14426 				tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
14427 				bbr->r_ctl.crte = NULL;
14428 			}
14429 #endif
14430 		}
14431 		break;
14432 
14433 	case TCP_DELACK:
14434 		BBR_OPTS_INC(tcp_delack);
14435 		if (optval < 100) {
14436 			if (optval == 0) /* off */
14437 				tp->t_delayed_ack = 0;
14438 			else if (optval == 1) /* on which is 2 */
14439 				tp->t_delayed_ack = 2;
14440 			else /* higher than 2 and less than 100 */
14441 				tp->t_delayed_ack = optval;
14442 			if (tp->t_flags & TF_DELACK) {
14443 				tp->t_flags &= ~TF_DELACK;
14444 				tp->t_flags |= TF_ACKNOW;
14445 				NET_EPOCH_ENTER(et);
14446 				bbr_output(tp);
14447 				NET_EPOCH_EXIT(et);
14448 			}
14449 		} else
14450 			error = EINVAL;
14451 		break;
14452 	case TCP_RACK_PKT_DELAY:
14453 		/* RACK added ms i.e. rack-rtt + reord + N */
14454 		BBR_OPTS_INC(tcp_rack_pkt_delay);
14455 		bbr->r_ctl.rc_pkt_delay = optval;
14456 		break;
14457 
14458 	case TCP_BBR_RETRAN_WTSO:
14459 		BBR_OPTS_INC(tcp_retran_wtso);
14460 		if (optval)
14461 			bbr->rc_resends_use_tso = 1;
14462 		else
14463 			bbr->rc_resends_use_tso = 0;
14464 		break;
14465 	case TCP_DATA_AFTER_CLOSE:
14466 		BBR_OPTS_INC(tcp_data_ac);
14467 		if (optval)
14468 			bbr->rc_allow_data_af_clo = 1;
14469 		else
14470 			bbr->rc_allow_data_af_clo = 0;
14471 		break;
14472 	case TCP_BBR_POLICER_DETECT:
14473 		BBR_OPTS_INC(tcp_policer_det);
14474 		if (bbr->rc_use_google == 0)
14475 			error = EINVAL;
14476 		else if (optval)
14477 			bbr->r_use_policer = 1;
14478 		else
14479 			bbr->r_use_policer = 0;
14480 		break;
14481 
14482 	case TCP_BBR_TSTMP_RAISES:
14483 		BBR_OPTS_INC(tcp_ts_raises);
14484 		if (optval)
14485 			bbr->ts_can_raise = 1;
14486 		else
14487 			bbr->ts_can_raise = 0;
14488 		break;
14489 	case TCP_BBR_TMR_PACE_OH:
14490 		BBR_OPTS_INC(tcp_pacing_oh_tmr);
14491 		if (bbr->rc_use_google) {
14492 			error = EINVAL;
14493 		} else {
14494 			if (optval)
14495 				bbr->r_ctl.rc_incr_tmrs = 1;
14496 			else
14497 				bbr->r_ctl.rc_incr_tmrs = 0;
14498 		}
14499 		break;
14500 	case TCP_BBR_PACE_OH:
14501 		BBR_OPTS_INC(tcp_pacing_oh);
14502 		if (bbr->rc_use_google) {
14503 			error = EINVAL;
14504 		} else {
14505 			if (optval > (BBR_INCL_TCP_OH|
14506 				      BBR_INCL_IP_OH|
14507 				      BBR_INCL_ENET_OH)) {
14508 				error = EINVAL;
14509 				break;
14510 			}
14511 			if (optval & BBR_INCL_TCP_OH)
14512 				bbr->r_ctl.rc_inc_tcp_oh = 1;
14513 			else
14514 				bbr->r_ctl.rc_inc_tcp_oh = 0;
14515 			if (optval & BBR_INCL_IP_OH)
14516 				bbr->r_ctl.rc_inc_ip_oh = 1;
14517 			else
14518 				bbr->r_ctl.rc_inc_ip_oh = 0;
14519 			if (optval & BBR_INCL_ENET_OH)
14520 				bbr->r_ctl.rc_inc_enet_oh = 1;
14521 			else
14522 				bbr->r_ctl.rc_inc_enet_oh = 0;
14523 		}
14524 		break;
14525 	default:
14526 		return (tcp_default_ctloutput(tp, sopt));
14527 		break;
14528 	}
14529 	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14530 	INP_WUNLOCK(inp);
14531 	return (error);
14532 }
14533 
14534 /*
14535  * return 0 on success, error-num on failure
14536  */
14537 static int
bbr_get_sockopt(struct tcpcb * tp,struct sockopt * sopt)14538 bbr_get_sockopt(struct tcpcb *tp, struct sockopt *sopt)
14539 {
14540 	struct inpcb *inp = tptoinpcb(tp);
14541 	struct tcp_bbr *bbr;
14542 	uint64_t loptval;
14543 	int32_t error, optval;
14544 
14545 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14546 	if (bbr == NULL) {
14547 		INP_WUNLOCK(inp);
14548 		return (EINVAL);
14549 	}
14550 	/*
14551 	 * Because all our options are either boolean or an int, we can just
14552 	 * pull everything into optval and then unlock and copy. If we ever
14553 	 * add a option that is not a int, then this will have quite an
14554 	 * impact to this routine.
14555 	 */
14556 	switch (sopt->sopt_name) {
14557 	case TCP_BBR_PACE_PER_SEC:
14558 		optval = bbr->r_ctl.bbr_hptsi_per_second;
14559 		break;
14560 	case TCP_BBR_PACE_DEL_TAR:
14561 		optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14562 		break;
14563 	case TCP_BBR_PACE_SEG_MAX:
14564 		optval = bbr->r_ctl.bbr_hptsi_segments_max;
14565 		break;
14566 	case TCP_BBR_MIN_TOPACEOUT:
14567 		optval = bbr->no_pacing_until;
14568 		break;
14569 	case TCP_BBR_PACE_SEG_MIN:
14570 		optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14571 		break;
14572 	case TCP_BBR_PACE_CROSS:
14573 		optval = bbr->r_ctl.bbr_cross_over;
14574 		break;
14575 	case TCP_BBR_ALGORITHM:
14576 		optval = bbr->rc_use_google;
14577 		break;
14578 	case TCP_BBR_TSLIMITS:
14579 		optval = bbr->rc_use_ts_limit;
14580 		break;
14581 	case TCP_BBR_IWINTSO:
14582 		optval = bbr->rc_init_win;
14583 		break;
14584 	case TCP_BBR_STARTUP_PG:
14585 		optval = bbr->r_ctl.rc_startup_pg;
14586 		break;
14587 	case TCP_BBR_DRAIN_PG:
14588 		optval = bbr->r_ctl.rc_drain_pg;
14589 		break;
14590 	case TCP_BBR_PROBE_RTT_INT:
14591 		optval = bbr->r_ctl.rc_probertt_int;
14592 		break;
14593 	case TCP_BBR_PROBE_RTT_LEN:
14594 		optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14595 		break;
14596 	case TCP_BBR_PROBE_RTT_GAIN:
14597 		optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14598 		break;
14599 	case TCP_BBR_STARTUP_LOSS_EXIT:
14600 		optval = bbr->rc_loss_exit;
14601 		break;
14602 	case TCP_BBR_USEDEL_RATE:
14603 		loptval = get_filter_value(&bbr->r_ctl.rc_delrate);
14604 		break;
14605 	case TCP_BBR_MIN_RTO:
14606 		optval = bbr->r_ctl.rc_min_rto_ms;
14607 		break;
14608 	case TCP_BBR_MAX_RTO:
14609 		optval = bbr->rc_max_rto_sec;
14610 		break;
14611 	case TCP_RACK_PACE_MAX_SEG:
14612 		/* Max segments in a pace */
14613 		optval = bbr->r_ctl.rc_pace_max_segs;
14614 		break;
14615 	case TCP_RACK_MIN_TO:
14616 		/* Minimum time between rack t-o's in ms */
14617 		optval = bbr->r_ctl.rc_min_to;
14618 		break;
14619 	case TCP_RACK_REORD_THRESH:
14620 		/* RACK reorder threshold (shift amount) */
14621 		optval = bbr->r_ctl.rc_reorder_shift;
14622 		break;
14623 	case TCP_RACK_REORD_FADE:
14624 		/* Does reordering fade after ms time */
14625 		optval = bbr->r_ctl.rc_reorder_fade;
14626 		break;
14627 	case TCP_BBR_USE_RACK_CHEAT:
14628 		/* Do we use the rack cheat for rxt */
14629 		optval = bbr->bbr_use_rack_cheat;
14630 		break;
14631 	case TCP_BBR_FLOOR_MIN_TSO:
14632 		optval = bbr->r_ctl.bbr_hptsi_segments_floor;
14633 		break;
14634 	case TCP_BBR_UTTER_MAX_TSO:
14635 		optval = bbr->r_ctl.bbr_utter_max;
14636 		break;
14637 	case TCP_BBR_SEND_IWND_IN_TSO:
14638 		/* Do we send TSO size segments initially */
14639 		optval = bbr->bbr_init_win_cheat;
14640 		break;
14641 	case TCP_BBR_EXTRA_STATE:
14642 		optval = bbr->rc_use_idle_restart;
14643 		break;
14644 	case TCP_RACK_TLP_THRESH:
14645 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14646 		optval = bbr->rc_tlp_threshold;
14647 		break;
14648 	case TCP_RACK_PKT_DELAY:
14649 		/* RACK added ms i.e. rack-rtt + reord + N */
14650 		optval = bbr->r_ctl.rc_pkt_delay;
14651 		break;
14652 	case TCP_BBR_RETRAN_WTSO:
14653 		optval = bbr->rc_resends_use_tso;
14654 		break;
14655 	case TCP_DATA_AFTER_CLOSE:
14656 		optval = bbr->rc_allow_data_af_clo;
14657 		break;
14658 	case TCP_DELACK:
14659 		optval = tp->t_delayed_ack;
14660 		break;
14661 	case TCP_BBR_HDWR_PACE:
14662 		optval = bbr->bbr_hdw_pace_ena;
14663 		break;
14664 	case TCP_BBR_POLICER_DETECT:
14665 		optval = bbr->r_use_policer;
14666 		break;
14667 	case TCP_BBR_TSTMP_RAISES:
14668 		optval = bbr->ts_can_raise;
14669 		break;
14670 	case TCP_BBR_TMR_PACE_OH:
14671 		optval = bbr->r_ctl.rc_incr_tmrs;
14672 		break;
14673 	case TCP_BBR_PACE_OH:
14674 		optval = 0;
14675 		if (bbr->r_ctl.rc_inc_tcp_oh)
14676 			optval |= BBR_INCL_TCP_OH;
14677 		if (bbr->r_ctl.rc_inc_ip_oh)
14678 			optval |= BBR_INCL_IP_OH;
14679 		if (bbr->r_ctl.rc_inc_enet_oh)
14680 			optval |= BBR_INCL_ENET_OH;
14681 		break;
14682 	default:
14683 		return (tcp_default_ctloutput(tp, sopt));
14684 		break;
14685 	}
14686 	INP_WUNLOCK(inp);
14687 	if (sopt->sopt_name == TCP_BBR_USEDEL_RATE)
14688 		error = sooptcopyout(sopt, &loptval, sizeof loptval);
14689 	else
14690 		error = sooptcopyout(sopt, &optval, sizeof optval);
14691 	return (error);
14692 }
14693 
14694 /*
14695  * return 0 on success, error-num on failure
14696  */
14697 static int
bbr_ctloutput(struct tcpcb * tp,struct sockopt * sopt)14698 bbr_ctloutput(struct tcpcb *tp, struct sockopt *sopt)
14699 {
14700 	if (sopt->sopt_dir == SOPT_SET) {
14701 		return (bbr_set_sockopt(tp, sopt));
14702 	} else if (sopt->sopt_dir == SOPT_GET) {
14703 		return (bbr_get_sockopt(tp, sopt));
14704 	} else {
14705 		panic("%s: sopt_dir $%d", __func__, sopt->sopt_dir);
14706 	}
14707 }
14708 
14709 static const char *bbr_stack_names[] = {
14710 	__XSTRING(STACKNAME),
14711 #ifdef STACKALIAS
14712 	__XSTRING(STACKALIAS),
14713 #endif
14714 };
14715 
14716 static bool bbr_mod_inited = false;
14717 
14718 static int
tcp_addbbr(module_t mod,int32_t type,void * data)14719 tcp_addbbr(module_t mod, int32_t type, void *data)
14720 {
14721 	int32_t err = 0;
14722 	int num_stacks;
14723 
14724 	switch (type) {
14725 	case MOD_LOAD:
14726 		printf("Attempting to load " __XSTRING(MODNAME) "\n");
14727 		bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
14728 		    sizeof(struct bbr_sendmap),
14729 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
14730 		bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
14731 		    sizeof(struct tcp_bbr),
14732 		    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
14733 		sysctl_ctx_init(&bbr_sysctl_ctx);
14734 		bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
14735 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
14736 		    OID_AUTO,
14737 #ifdef STACKALIAS
14738 		    __XSTRING(STACKALIAS),
14739 #else
14740 		    __XSTRING(STACKNAME),
14741 #endif
14742 		    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
14743 		    "");
14744 		if (bbr_sysctl_root == NULL) {
14745 			printf("Failed to add sysctl node\n");
14746 			err = EFAULT;
14747 			goto free_uma;
14748 		}
14749 		bbr_init_sysctls();
14750 		num_stacks = nitems(bbr_stack_names);
14751 		err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
14752 		    bbr_stack_names, &num_stacks);
14753 		if (err) {
14754 			printf("Failed to register %s stack name for "
14755 			    "%s module\n", bbr_stack_names[num_stacks],
14756 			    __XSTRING(MODNAME));
14757 			sysctl_ctx_free(&bbr_sysctl_ctx);
14758 	free_uma:
14759 			uma_zdestroy(bbr_zone);
14760 			uma_zdestroy(bbr_pcb_zone);
14761 			bbr_counter_destroy();
14762 			printf("Failed to register " __XSTRING(MODNAME)
14763 			    " module err:%d\n", err);
14764 			return (err);
14765 		}
14766 		tcp_lro_reg_mbufq();
14767 		bbr_mod_inited = true;
14768 		printf(__XSTRING(MODNAME) " is now available\n");
14769 		break;
14770 	case MOD_QUIESCE:
14771 		err = deregister_tcp_functions(&__tcp_bbr, true, false);
14772 		break;
14773 	case MOD_UNLOAD:
14774 		err = deregister_tcp_functions(&__tcp_bbr, false, true);
14775 		if (err == EBUSY)
14776 			break;
14777 		if (bbr_mod_inited) {
14778 			uma_zdestroy(bbr_zone);
14779 			uma_zdestroy(bbr_pcb_zone);
14780 			sysctl_ctx_free(&bbr_sysctl_ctx);
14781 			bbr_counter_destroy();
14782 			printf(__XSTRING(MODNAME)
14783 			    " is now no longer available\n");
14784 			bbr_mod_inited = false;
14785 		}
14786 		tcp_lro_dereg_mbufq();
14787 		err = 0;
14788 		break;
14789 	default:
14790 		return (EOPNOTSUPP);
14791 	}
14792 	return (err);
14793 }
14794 
14795 static moduledata_t tcp_bbr = {
14796 	.name = __XSTRING(MODNAME),
14797 	    .evhand = tcp_addbbr,
14798 	    .priv = 0
14799 };
14800 
14801 MODULE_VERSION(MODNAME, 1);
14802 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
14803 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
14804