]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/tcp_stacks/bbr.c
Merge llvm-project main llvmorg-12-init-17869-g8e464dd76bef
[FreeBSD/FreeBSD.git] / sys / netinet / tcp_stacks / bbr.c
1 /*-
2  * Copyright (c) 2016-2020 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  */
26 /**
27  * Author: Randall Stewart <rrs@netflix.com>
28  * This work is based on the ACM Queue paper
29  * BBR - Congestion Based Congestion Control
30  * and also numerous discussions with Neal, Yuchung and Van.
31  */
32
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35
36 #include "opt_inet.h"
37 #include "opt_inet6.h"
38 #include "opt_ipsec.h"
39 #include "opt_tcpdebug.h"
40 #include "opt_ratelimit.h"
41 #include <sys/param.h>
42 #include <sys/arb.h>
43 #include <sys/module.h>
44 #include <sys/kernel.h>
45 #include <sys/libkern.h>
46 #ifdef TCP_HHOOK
47 #include <sys/hhook.h>
48 #endif
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>
51 #include <sys/proc.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/sysctl.h>
55 #include <sys/systm.h>
56 #ifdef STATS
57 #include <sys/qmath.h>
58 #include <sys/tree.h>
59 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
60 #endif
61 #include <sys/refcount.h>
62 #include <sys/queue.h>
63 #include <sys/eventhandler.h>
64 #include <sys/smp.h>
65 #include <sys/kthread.h>
66 #include <sys/lock.h>
67 #include <sys/mutex.h>
68 #include <sys/tim_filter.h>
69 #include <sys/time.h>
70 #include <sys/protosw.h>
71 #include <vm/uma.h>
72 #include <sys/kern_prefetch.h>
73
74 #include <net/route.h>
75 #include <net/route/nhop.h>
76 #include <net/vnet.h>
77
78 #define TCPSTATES               /* for logging */
79
80 #include <netinet/in.h>
81 #include <netinet/in_kdtrace.h>
82 #include <netinet/in_pcb.h>
83 #include <netinet/ip.h>
84 #include <netinet/ip_icmp.h>    /* required for icmp_var.h */
85 #include <netinet/icmp_var.h>   /* for ICMP_BANDLIM */
86 #include <netinet/ip_var.h>
87 #include <netinet/ip6.h>
88 #include <netinet6/in6_pcb.h>
89 #include <netinet6/ip6_var.h>
90 #define TCPOUTFLAGS
91 #include <netinet/tcp.h>
92 #include <netinet/tcp_fsm.h>
93 #include <netinet/tcp_seq.h>
94 #include <netinet/tcp_timer.h>
95 #include <netinet/tcp_var.h>
96 #include <netinet/tcpip.h>
97 #include <netinet/tcp_hpts.h>
98 #include <netinet/cc/cc.h>
99 #include <netinet/tcp_log_buf.h>
100 #include <netinet/tcp_ratelimit.h>
101 #include <netinet/tcp_lro.h>
102 #ifdef TCPDEBUG
103 #include <netinet/tcp_debug.h>
104 #endif                          /* TCPDEBUG */
105 #ifdef TCP_OFFLOAD
106 #include <netinet/tcp_offload.h>
107 #endif
108 #ifdef INET6
109 #include <netinet6/tcp6_var.h>
110 #endif
111 #include <netinet/tcp_fastopen.h>
112
113 #include <netipsec/ipsec_support.h>
114 #include <net/if.h>
115 #include <net/if_var.h>
116 #include <net/ethernet.h>
117
118 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
119 #include <netipsec/ipsec.h>
120 #include <netipsec/ipsec6.h>
121 #endif                          /* IPSEC */
122
123 #include <netinet/udp.h>
124 #include <netinet/udp_var.h>
125 #include <machine/in_cksum.h>
126
127 #ifdef MAC
128 #include <security/mac/mac_framework.h>
129 #endif
130
131 #include "sack_filter.h"
132 #include "tcp_bbr.h"
133 #include "rack_bbr_common.h"
134 uma_zone_t bbr_zone;
135 uma_zone_t bbr_pcb_zone;
136
137 struct sysctl_ctx_list bbr_sysctl_ctx;
138 struct sysctl_oid *bbr_sysctl_root;
139
140 #define TCPT_RANGESET_NOSLOP(tv, value, tvmin, tvmax) do { \
141         (tv) = (value); \
142         if ((u_long)(tv) < (u_long)(tvmin)) \
143                 (tv) = (tvmin); \
144         if ((u_long)(tv) > (u_long)(tvmax)) \
145                 (tv) = (tvmax); \
146 } while(0)
147
148 /*#define BBR_INVARIANT 1*/
149
150 /*
151  * initial window
152  */
153 static uint32_t bbr_def_init_win = 10;
154 static int32_t bbr_persist_min = 250000;        /* 250ms */
155 static int32_t bbr_persist_max = 1000000;       /* 1 Second */
156 static int32_t bbr_cwnd_may_shrink = 0;
157 static int32_t bbr_cwndtarget_rtt_touse = BBR_RTT_PROP;
158 static int32_t bbr_num_pktepo_for_del_limit = BBR_NUM_RTTS_FOR_DEL_LIMIT;
159 static int32_t bbr_hardware_pacing_limit = 8000;
160 static int32_t bbr_quanta = 3;  /* How much extra quanta do we get? */
161 static int32_t bbr_no_retran = 0;
162
163 static int32_t bbr_error_base_paceout = 10000; /* usec to pace */
164 static int32_t bbr_max_net_error_cnt = 10;
165 /* Should the following be dynamic too -- loss wise */
166 static int32_t bbr_rtt_gain_thresh = 0;
167 /* Measurement controls */
168 static int32_t bbr_use_google_algo = 1;
169 static int32_t bbr_ts_limiting = 1;
170 static int32_t bbr_ts_can_raise = 0;
171 static int32_t bbr_do_red = 600;
172 static int32_t bbr_red_scale = 20000;
173 static int32_t bbr_red_mul = 1;
174 static int32_t bbr_red_div = 2;
175 static int32_t bbr_red_growth_restrict = 1;
176 static int32_t  bbr_target_is_bbunit = 0;
177 static int32_t bbr_drop_limit = 0;
178 /*
179  * How much gain do we need to see to
180  * stay in startup?
181  */
182 static int32_t bbr_marks_rxt_sack_passed = 0;
183 static int32_t bbr_start_exit = 25;
184 static int32_t bbr_low_start_exit = 25; /* When we are in reduced gain */
185 static int32_t bbr_startup_loss_thresh = 2000;  /* 20.00% loss */
186 static int32_t bbr_hptsi_max_mul = 1;   /* These two mul/div assure a min pacing */
187 static int32_t bbr_hptsi_max_div = 2;   /* time, 0 means turned off. We need this
188                                          * if we go back ever to where the pacer
189                                          * has priority over timers.
190                                          */
191 static int32_t bbr_policer_call_from_rack_to = 0;
192 static int32_t bbr_policer_detection_enabled = 1;
193 static int32_t bbr_min_measurements_req = 1;    /* We need at least 2
194                                                  * measurments before we are
195                                                  * "good" note that 2 == 1.
196                                                  * This is because we use a >
197                                                  * comparison. This means if
198                                                  * min_measure was 0, it takes
199                                                  * num-measures > min(0) and
200                                                  * you get 1 measurement and
201                                                  * you are good. Set to 1, you
202                                                  * have to have two
203                                                  * measurements (this is done
204                                                  * to prevent it from being ok
205                                                  * to have no measurements). */
206 static int32_t bbr_no_pacing_until = 4;
207
208 static int32_t bbr_min_usec_delta = 20000;      /* 20,000 usecs */
209 static int32_t bbr_min_peer_delta = 20;         /* 20 units */
210 static int32_t bbr_delta_percent = 150;         /* 15.0 % */
211
212 static int32_t bbr_target_cwnd_mult_limit = 8;
213 /*
214  * bbr_cwnd_min_val is the number of
215  * segments we hold to in the RTT probe
216  * state typically 4.
217  */
218 static int32_t bbr_cwnd_min_val = BBR_PROBERTT_NUM_MSS;
219
220 static int32_t bbr_cwnd_min_val_hs = BBR_HIGHSPEED_NUM_MSS;
221
222 static int32_t bbr_gain_to_target = 1;
223 static int32_t bbr_gain_gets_extra_too = 1;
224 /*
225  * bbr_high_gain is the 2/ln(2) value we need
226  * to double the sending rate in startup. This
227  * is used for both cwnd and hptsi gain's.
228  */
229 static int32_t bbr_high_gain = BBR_UNIT * 2885 / 1000 + 1;
230 static int32_t bbr_startup_lower = BBR_UNIT * 1500 / 1000 + 1;
231 static int32_t bbr_use_lower_gain_in_startup = 1;
232
233 /* thresholds for reduction on drain in sub-states/drain */
234 static int32_t bbr_drain_rtt = BBR_SRTT;
235 static int32_t bbr_drain_floor = 88;
236 static int32_t google_allow_early_out = 1;
237 static int32_t google_consider_lost = 1;
238 static int32_t bbr_drain_drop_mul = 4;
239 static int32_t bbr_drain_drop_div = 5;
240 static int32_t bbr_rand_ot = 50;
241 static int32_t bbr_can_force_probertt = 0;
242 static int32_t bbr_can_adjust_probertt = 1;
243 static int32_t bbr_probertt_sets_rtt = 0;
244 static int32_t bbr_can_use_ts_for_rtt = 1;
245 static int32_t bbr_is_ratio = 0;
246 static int32_t bbr_sub_drain_app_limit = 1;
247 static int32_t bbr_prtt_slam_cwnd = 1;
248 static int32_t bbr_sub_drain_slam_cwnd = 1;
249 static int32_t bbr_slam_cwnd_in_main_drain = 1;
250 static int32_t bbr_filter_len_sec = 6;  /* How long does the rttProp filter
251                                          * hold */
252 static uint32_t bbr_rtt_probe_limit = (USECS_IN_SECOND * 4);
253 /*
254  * bbr_drain_gain is the reverse of the high_gain
255  * designed to drain back out the standing queue
256  * that is formed in startup by causing a larger
257  * hptsi gain and thus drainging the packets
258  * in flight.
259  */
260 static int32_t bbr_drain_gain = BBR_UNIT * 1000 / 2885;
261 static int32_t bbr_rttprobe_gain = 192;
262
263 /*
264  * The cwnd_gain is the default cwnd gain applied when
265  * calculating a target cwnd. Note that the cwnd is
266  * a secondary factor in the way BBR works (see the
267  * paper and think about it, it will take some time).
268  * Basically the hptsi_gain spreads the packets out
269  * so you never get more than BDP to the peer even
270  * if the cwnd is high. In our implemenation that
271  * means in non-recovery/retransmission scenarios
272  * cwnd will never be reached by the flight-size.
273  */
274 static int32_t bbr_cwnd_gain = BBR_UNIT * 2;
275 static int32_t bbr_tlp_type_to_use = BBR_SRTT;
276 static int32_t bbr_delack_time = 100000;        /* 100ms in useconds */
277 static int32_t bbr_sack_not_required = 0;       /* set to one to allow non-sack to use bbr */
278 static int32_t bbr_initial_bw_bps = 62500;      /* 500kbps in bytes ps */
279 static int32_t bbr_ignore_data_after_close = 1;
280 static int16_t bbr_hptsi_gain[] = {
281         (BBR_UNIT *5 / 4),
282         (BBR_UNIT * 3 / 4),
283         BBR_UNIT,
284         BBR_UNIT,
285         BBR_UNIT,
286         BBR_UNIT,
287         BBR_UNIT,
288         BBR_UNIT
289 };
290 int32_t bbr_use_rack_resend_cheat = 1;
291 int32_t bbr_sends_full_iwnd = 1;
292
293 #define BBR_HPTSI_GAIN_MAX 8
294 /*
295  * The BBR module incorporates a number of
296  * TCP ideas that have been put out into the IETF
297  * over the last few years:
298  * - Yuchung Cheng's RACK TCP (for which its named) that
299  *    will stop us using the number of dup acks and instead
300  *    use time as the gage of when we retransmit.
301  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
302  *    of Dukkipati et.al.
303  * - Van Jacobson's et.al BBR.
304  *
305  * RACK depends on SACK, so if an endpoint arrives that
306  * cannot do SACK the state machine below will shuttle the
307  * connection back to using the "default" TCP stack that is
308  * in FreeBSD.
309  *
310  * To implement BBR and RACK the original TCP stack was first decomposed
311  * into a functional state machine with individual states
312  * for each of the possible TCP connection states. The do_segement
313  * functions role in life is to mandate the connection supports SACK
314  * initially and then assure that the RACK state matches the conenction
315  * state before calling the states do_segment function. Data processing
316  * of inbound segments also now happens in the hpts_do_segment in general
317  * with only one exception. This is so we can keep the connection on
318  * a single CPU.
319  *
320  * Each state is simplified due to the fact that the original do_segment
321  * has been decomposed and we *know* what state we are in (no
322  * switches on the state) and all tests for SACK are gone. This
323  * greatly simplifies what each state does.
324  *
325  * TCP output is also over-written with a new version since it
326  * must maintain the new rack scoreboard and has had hptsi
327  * integrated as a requirment. Still todo is to eliminate the
328  * use of the callout_() system and use the hpts for all
329  * timers as well.
330  */
331 static uint32_t bbr_rtt_probe_time = 200000;    /* 200ms in micro seconds */
332 static uint32_t bbr_rtt_probe_cwndtarg = 4;     /* How many mss's outstanding */
333 static const int32_t bbr_min_req_free = 2;      /* The min we must have on the
334                                                  * free list */
335 static int32_t bbr_tlp_thresh = 1;
336 static int32_t bbr_reorder_thresh = 2;
337 static int32_t bbr_reorder_fade = 60000000;     /* 0 - never fade, def
338                                                  * 60,000,000 - 60 seconds */
339 static int32_t bbr_pkt_delay = 1000;
340 static int32_t bbr_min_to = 1000;       /* Number of usec's minimum timeout */
341 static int32_t bbr_incr_timers = 1;
342
343 static int32_t bbr_tlp_min = 10000;     /* 10ms in usecs */
344 static int32_t bbr_delayed_ack_time = 200000;   /* 200ms in usecs */
345 static int32_t bbr_exit_startup_at_loss = 1;
346
347 /*
348  * bbr_lt_bw_ratio is 1/8th
349  * bbr_lt_bw_diff is  < 4 Kbit/sec
350  */
351 static uint64_t bbr_lt_bw_diff = 4000 / 8;      /* In bytes per second */
352 static uint64_t bbr_lt_bw_ratio = 8;    /* For 1/8th */
353 static uint32_t bbr_lt_bw_max_rtts = 48;        /* How many rtt's do we use
354                                                  * the lt_bw for */
355 static uint32_t bbr_lt_intvl_min_rtts = 4;      /* Min num of RTT's to measure
356                                                  * lt_bw */
357 static int32_t bbr_lt_intvl_fp = 0;             /* False positive epoch diff */
358 static int32_t bbr_lt_loss_thresh = 196;        /* Lost vs delivered % */
359 static int32_t bbr_lt_fd_thresh = 100;          /* false detection % */
360
361 static int32_t bbr_verbose_logging = 0;
362 /*
363  * Currently regular tcp has a rto_min of 30ms
364  * the backoff goes 12 times so that ends up
365  * being a total of 122.850 seconds before a
366  * connection is killed.
367  */
368 static int32_t bbr_rto_min_ms = 30;     /* 30ms same as main freebsd */
369 static int32_t bbr_rto_max_sec = 4;     /* 4 seconds */
370
371 /****************************************************/
372 /* DEFAULT TSO SIZING  (cpu performance impacting)  */
373 /****************************************************/
374 /* What amount is our formula using to get TSO size */
375 static int32_t bbr_hptsi_per_second = 1000;
376
377 /*
378  * For hptsi under bbr_cross_over connections what is delay
379  * target 7ms (in usec) combined with a seg_max of 2
380  * gets us close to identical google behavior in
381  * TSO size selection (possibly more 1MSS sends).
382  */
383 static int32_t bbr_hptsi_segments_delay_tar = 7000;
384
385 /* Does pacing delay include overhead's in its time calculations? */
386 static int32_t bbr_include_enet_oh = 0;
387 static int32_t bbr_include_ip_oh = 1;
388 static int32_t bbr_include_tcp_oh = 1;
389 static int32_t bbr_google_discount = 10;
390
391 /* Do we use (nf mode) pkt-epoch to drive us or rttProp? */
392 static int32_t bbr_state_is_pkt_epoch = 0;
393 static int32_t bbr_state_drain_2_tar = 1;
394 /* What is the max the 0 - bbr_cross_over MBPS TSO target
395  * can reach using our delay target. Note that this
396  * value becomes the floor for the cross over
397  * algorithm.
398  */
399 static int32_t bbr_hptsi_segments_max = 2;
400 static int32_t bbr_hptsi_segments_floor = 1;
401 static int32_t bbr_hptsi_utter_max = 0;
402
403 /* What is the min the 0 - bbr_cross-over MBPS  TSO target can be */
404 static int32_t bbr_hptsi_bytes_min = 1460;
405 static int32_t bbr_all_get_min = 0;
406
407 /* Cross over point from algo-a to algo-b */
408 static uint32_t bbr_cross_over = TWENTY_THREE_MBPS;
409
410 /* Do we deal with our restart state? */
411 static int32_t bbr_uses_idle_restart = 0;
412 static int32_t bbr_idle_restart_threshold = 100000;     /* 100ms in useconds */
413
414 /* Do we allow hardware pacing? */
415 static int32_t bbr_allow_hdwr_pacing = 0;
416 static int32_t bbr_hdwr_pace_adjust = 2;        /* multipler when we calc the tso size */
417 static int32_t bbr_hdwr_pace_floor = 1;
418 static int32_t bbr_hdwr_pacing_delay_cnt = 10;
419
420 /****************************************************/
421 static int32_t bbr_resends_use_tso = 0;
422 static int32_t bbr_tlp_max_resend = 2;
423 static int32_t bbr_sack_block_limit = 128;
424
425 #define  BBR_MAX_STAT 19
426 counter_u64_t bbr_state_time[BBR_MAX_STAT];
427 counter_u64_t bbr_state_lost[BBR_MAX_STAT];
428 counter_u64_t bbr_state_resend[BBR_MAX_STAT];
429 counter_u64_t bbr_stat_arry[BBR_STAT_SIZE];
430 counter_u64_t bbr_opts_arry[BBR_OPTS_SIZE];
431 counter_u64_t bbr_out_size[TCP_MSS_ACCT_SIZE];
432 counter_u64_t bbr_flows_whdwr_pacing;
433 counter_u64_t bbr_flows_nohdwr_pacing;
434
435 counter_u64_t bbr_nohdwr_pacing_enobuf;
436 counter_u64_t bbr_hdwr_pacing_enobuf;
437
438 static inline uint64_t bbr_get_bw(struct tcp_bbr *bbr);
439
440 /*
441  * Static defintions we need for forward declarations.
442  */
443 static uint32_t
444 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain,
445     uint32_t useconds_time, uint64_t bw);
446 static uint32_t
447 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain);
448 static void
449      bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win);
450 static void
451 bbr_set_probebw_gains(struct tcp_bbr *bbr,  uint32_t cts, uint32_t losses);
452 static void
453 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int line,
454                     int dolog);
455 static uint32_t
456 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain);
457 static void
458 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch,
459                  int32_t pkt_epoch, uint32_t losses);
460 static uint32_t
461 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm);
462 static uint32_t bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp);
463 static uint32_t
464 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
465     struct bbr_sendmap *rsm, uint32_t srtt,
466     uint32_t cts);
467 static void
468 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
469     int32_t line);
470 static void
471      bbr_set_state_target(struct tcp_bbr *bbr, int line);
472 static void
473      bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line);
474
475 static void
476      bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line);
477
478 static void
479      tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts);
480
481 static void
482      bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts);
483
484 static void
485      bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied, uint32_t rtt,
486                          uint32_t line, uint8_t is_start, uint16_t set);
487
488 static struct bbr_sendmap *
489             bbr_find_lowest_rsm(struct tcp_bbr *bbr);
490 static __inline uint32_t
491 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type);
492 static void
493      bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which);
494
495 static void
496 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
497     uint32_t thresh, uint32_t to);
498 static void
499      bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag);
500
501 static void
502 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot,
503     uint32_t del_by, uint32_t cts, uint32_t sloton, uint32_t prev_delay);
504
505 static void
506 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr,
507     uint32_t cts, int32_t line);
508 static void
509      bbr_stop_all_timers(struct tcpcb *tp);
510 static void
511      bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts);
512 static void
513      bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts);
514 static void
515      bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts);
516
517 static void
518 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
519     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod);
520
521 static int
522 bbr_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp,
523     struct tcpcb *tp);
524
525 static inline uint8_t
526 bbr_state_val(struct tcp_bbr *bbr)
527 {
528         return(bbr->rc_bbr_substate);
529 }
530
531 static inline uint32_t
532 get_min_cwnd(struct tcp_bbr *bbr)
533 {
534         int mss;
535
536         mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
537         if (bbr_get_rtt(bbr, BBR_RTT_PROP) < BBR_HIGH_SPEED)
538                 return (bbr_cwnd_min_val_hs * mss);
539         else
540                 return (bbr_cwnd_min_val * mss);
541 }
542
543 static uint32_t
544 bbr_get_persists_timer_val(struct tcpcb *tp, struct tcp_bbr *bbr)
545 {
546         uint64_t srtt, var;
547         uint64_t ret_val;
548
549         bbr->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
550         if (tp->t_srtt == 0) {
551                 srtt = (uint64_t)BBR_INITIAL_RTO;
552                 var = 0;
553         } else {
554                 srtt = ((uint64_t)TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
555                 var = ((uint64_t)TICKS_2_USEC(tp->t_rttvar) >> TCP_RTT_SHIFT);
556         }
557         TCPT_RANGESET_NOSLOP(ret_val, ((srtt + var) * tcp_backoff[tp->t_rxtshift]),
558             bbr_persist_min, bbr_persist_max);
559         return ((uint32_t)ret_val);
560 }
561
562 static uint32_t
563 bbr_timer_start(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
564 {
565         /*
566          * Start the FR timer, we do this based on getting the first one in
567          * the rc_tmap. Note that if its NULL we must stop the timer. in all
568          * events we need to stop the running timer (if its running) before
569          * starting the new one.
570          */
571         uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
572         int32_t idx;
573         int32_t is_tlp_timer = 0;
574         struct bbr_sendmap *rsm;
575
576         if (bbr->rc_all_timers_stopped) {
577                 /* All timers have been stopped none are to run */
578                 return (0);
579         }
580         if (bbr->rc_in_persist) {
581                 /* We can't start any timer in persists */
582                 return (bbr_get_persists_timer_val(tp, bbr));
583         }
584         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
585         if ((rsm == NULL) ||
586             ((tp->t_flags & TF_SACK_PERMIT) == 0) ||
587             (tp->t_state < TCPS_ESTABLISHED)) {
588                 /* Nothing on the send map */
589 activate_rxt:
590                 if (SEQ_LT(tp->snd_una, tp->snd_max) || sbavail(&(tp->t_inpcb->inp_socket->so_snd))) {
591                         uint64_t tov;
592
593                         time_since_sent = 0;
594                         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
595                         if (rsm) {
596                                 idx = rsm->r_rtr_cnt - 1;
597                                 if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
598                                         tstmp_touse = rsm->r_tim_lastsent[idx];
599                                 else
600                                         tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
601                                 if (TSTMP_GT(tstmp_touse, cts))
602                                     time_since_sent = cts - tstmp_touse;
603                         }
604                         bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
605                         if (tp->t_srtt == 0)
606                                 tov = BBR_INITIAL_RTO;
607                         else
608                                 tov = ((uint64_t)(TICKS_2_USEC(tp->t_srtt) +
609                                     ((uint64_t)TICKS_2_USEC(tp->t_rttvar) * (uint64_t)4)) >> TCP_RTT_SHIFT);
610                         if (tp->t_rxtshift)
611                                 tov *= tcp_backoff[tp->t_rxtshift];
612                         if (tov > time_since_sent)
613                                 tov -= time_since_sent;
614                         else
615                                 tov = bbr->r_ctl.rc_min_to;
616                         TCPT_RANGESET_NOSLOP(to, tov,
617                             (bbr->r_ctl.rc_min_rto_ms * MS_IN_USEC),
618                             (bbr->rc_max_rto_sec * USECS_IN_SECOND));
619                         bbr_log_timer_var(bbr, 2, cts, 0, srtt, 0, to);
620                         return (to);
621                 }
622                 return (0);
623         }
624         if (rsm->r_flags & BBR_ACKED) {
625                 rsm = bbr_find_lowest_rsm(bbr);
626                 if (rsm == NULL) {
627                         /* No lowest? */
628                         goto activate_rxt;
629                 }
630         }
631         /* Convert from ms to usecs */
632         if (rsm->r_flags & BBR_SACK_PASSED) {
633                 if ((tp->t_flags & TF_SENTFIN) &&
634                     ((tp->snd_max - tp->snd_una) == 1) &&
635                     (rsm->r_flags & BBR_HAS_FIN)) {
636                         /*
637                          * We don't start a bbr rack timer if all we have is
638                          * a FIN outstanding.
639                          */
640                         goto activate_rxt;
641                 }
642                 srtt = bbr_get_rtt(bbr, BBR_RTT_RACK);
643                 thresh = bbr_calc_thresh_rack(bbr, srtt, cts, rsm);
644                 idx = rsm->r_rtr_cnt - 1;
645                 exp = rsm->r_tim_lastsent[idx] + thresh;
646                 if (SEQ_GEQ(exp, cts)) {
647                         to = exp - cts;
648                         if (to < bbr->r_ctl.rc_min_to) {
649                                 to = bbr->r_ctl.rc_min_to;
650                         }
651                 } else {
652                         to = bbr->r_ctl.rc_min_to;
653                 }
654         } else {
655                 /* Ok we need to do a TLP not RACK */
656                 if (bbr->rc_tlp_in_progress != 0) {
657                         /*
658                          * The previous send was a TLP.
659                          */
660                         goto activate_rxt;
661                 }
662                 rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
663                 if (rsm == NULL) {
664                         /* We found no rsm to TLP with. */
665                         goto activate_rxt;
666                 }
667                 if (rsm->r_flags & BBR_HAS_FIN) {
668                         /* If its a FIN we don't do TLP */
669                         rsm = NULL;
670                         goto activate_rxt;
671                 }
672                 time_since_sent = 0;
673                 idx = rsm->r_rtr_cnt - 1;
674                 if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
675                         tstmp_touse = rsm->r_tim_lastsent[idx];
676                 else
677                         tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
678                 if (TSTMP_GT(tstmp_touse, cts))
679                     time_since_sent = cts - tstmp_touse;
680                 is_tlp_timer = 1;
681                 srtt = bbr_get_rtt(bbr, bbr_tlp_type_to_use);
682                 thresh = bbr_calc_thresh_tlp(tp, bbr, rsm, srtt, cts);
683                 if (thresh > time_since_sent)
684                         to = thresh - time_since_sent;
685                 else
686                         to = bbr->r_ctl.rc_min_to;
687                 if (to > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
688                         /*
689                          * If the TLP time works out to larger than the max
690                          * RTO lets not do TLP.. just RTO.
691                          */
692                         goto activate_rxt;
693                 }
694                 if ((bbr->rc_tlp_rtx_out == 1) &&
695                     (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq)) {
696                         /*
697                          * Second retransmit of the same TLP
698                          * lets not.
699                          */
700                         bbr->rc_tlp_rtx_out = 0;
701                         goto activate_rxt;
702                 }
703                 if (rsm->r_start != bbr->r_ctl.rc_last_tlp_seq) {
704                         /*
705                          * The tail is no longer the last one I did a probe
706                          * on
707                          */
708                         bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
709                         bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
710                 }
711         }
712         if (is_tlp_timer == 0) {
713                 BBR_STAT_INC(bbr_to_arm_rack);
714                 bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
715         } else {
716                 bbr_log_timer_var(bbr, 1, cts, time_since_sent, srtt, thresh, to);
717                 if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
718                         /*
719                          * We have exceeded how many times we can retran the
720                          * current TLP timer, switch to the RTO timer.
721                          */
722                         goto activate_rxt;
723                 } else {
724                         BBR_STAT_INC(bbr_to_arm_tlp);
725                         bbr->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
726                 }
727         }
728         return (to);
729 }
730
731 static inline int32_t
732 bbr_minseg(struct tcp_bbr *bbr)
733 {
734         return (bbr->r_ctl.rc_pace_min_segs - bbr->rc_last_options);
735 }
736
737 static void
738 bbr_start_hpts_timer(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts, int32_t frm, int32_t slot, uint32_t tot_len)
739 {
740         struct inpcb *inp;
741         struct hpts_diag diag;
742         uint32_t delayed_ack = 0;
743         uint32_t left = 0;
744         uint32_t hpts_timeout;
745         uint8_t stopped;
746         int32_t delay_calc = 0;
747         uint32_t prev_delay = 0;
748
749         inp = tp->t_inpcb;
750         if (inp->inp_in_hpts) {
751                 /* A previous call is already set up */
752                 return;
753         }
754         if ((tp->t_state == TCPS_CLOSED) ||
755             (tp->t_state == TCPS_LISTEN)) {
756                 return;
757         }
758         stopped = bbr->rc_tmr_stopped;
759         if (stopped && TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
760                 left = bbr->r_ctl.rc_timer_exp - cts;
761         }
762         bbr->r_ctl.rc_hpts_flags = 0;
763         bbr->r_ctl.rc_timer_exp = 0;
764         prev_delay = bbr->r_ctl.rc_last_delay_val;
765         if (bbr->r_ctl.rc_last_delay_val &&
766             (slot == 0)) {
767                 /*
768                  * If a previous pacer delay was in place we
769                  * are not coming from the output side (where
770                  * we calculate a delay, more likely a timer).
771                  */
772                 slot = bbr->r_ctl.rc_last_delay_val;
773                 if (TSTMP_GT(cts, bbr->rc_pacer_started)) {
774                         /* Compensate for time passed  */
775                         delay_calc = cts - bbr->rc_pacer_started;
776                         if (delay_calc <= slot)
777                                 slot -= delay_calc;
778                 }
779         }
780         /* Do we have early to make up for by pushing out the pacing time? */
781         if (bbr->r_agg_early_set) {
782                 bbr_log_pacing_delay_calc(bbr, 0, bbr->r_ctl.rc_agg_early, cts, slot, 0, bbr->r_agg_early_set, 2);
783                 slot += bbr->r_ctl.rc_agg_early;
784                 bbr->r_ctl.rc_agg_early = 0;
785                 bbr->r_agg_early_set = 0;
786         }
787         /* Are we running a total debt that needs to be compensated for? */
788         if (bbr->r_ctl.rc_hptsi_agg_delay) {
789                 if (slot > bbr->r_ctl.rc_hptsi_agg_delay) {
790                         /* We nuke the delay */
791                         slot -= bbr->r_ctl.rc_hptsi_agg_delay;
792                         bbr->r_ctl.rc_hptsi_agg_delay = 0;
793                 } else {
794                         /* We nuke some of the delay, put in a minimal 100usecs  */
795                         bbr->r_ctl.rc_hptsi_agg_delay -= slot;
796                         bbr->r_ctl.rc_last_delay_val = slot = 100;
797                 }
798         }
799         bbr->r_ctl.rc_last_delay_val = slot;
800         hpts_timeout = bbr_timer_start(tp, bbr, cts);
801         if (tp->t_flags & TF_DELACK) {
802                 if (bbr->rc_in_persist == 0) {
803                         delayed_ack = bbr_delack_time;
804                 } else {
805                         /*
806                          * We are in persists and have
807                          * gotten a new data element.
808                          */
809                         if (hpts_timeout > bbr_delack_time) {
810                                 /*
811                                  * Lets make the persists timer (which acks)
812                                  * be the smaller of hpts_timeout and bbr_delack_time.
813                                  */
814                                 hpts_timeout = bbr_delack_time;
815                         }
816                 }
817         }
818         if (delayed_ack &&
819             ((hpts_timeout == 0) ||
820              (delayed_ack < hpts_timeout))) {
821                 /* We need a Delayed ack timer */
822                 bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
823                 hpts_timeout = delayed_ack;
824         }
825         if (slot) {
826                 /* Mark that we have a pacing timer up */
827                 BBR_STAT_INC(bbr_paced_segments);
828                 bbr->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
829         }
830         /*
831          * If no timers are going to run and we will fall off thfe hptsi
832          * wheel, we resort to a keep-alive timer if its configured.
833          */
834         if ((hpts_timeout == 0) &&
835             (slot == 0)) {
836                 if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
837                     (tp->t_state <= TCPS_CLOSING)) {
838                         /*
839                          * Ok we have no timer (persists, rack, tlp, rxt  or
840                          * del-ack), we don't have segments being paced. So
841                          * all that is left is the keepalive timer.
842                          */
843                         if (TCPS_HAVEESTABLISHED(tp->t_state)) {
844                                 hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
845                         } else {
846                                 hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
847                         }
848                         bbr->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
849                 }
850         }
851         if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
852             (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
853                 /*
854                  * RACK, TLP, persists and RXT timers all are restartable
855                  * based on actions input .. i.e we received a packet (ack
856                  * or sack) and that changes things (rw, or snd_una etc).
857                  * Thus we can restart them with a new value. For
858                  * keep-alive, delayed_ack we keep track of what was left
859                  * and restart the timer with a smaller value.
860                  */
861                 if (left < hpts_timeout)
862                         hpts_timeout = left;
863         }
864         if (bbr->r_ctl.rc_incr_tmrs && slot &&
865             (bbr->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
866                 /*
867                  * If configured to do so, and the timer is either
868                  * the TLP or RXT timer, we need to increase the timeout
869                  * by the pacing time. Consider the bottleneck at my
870                  * machine as an example, we are sending something
871                  * to start a TLP on. The last packet won't be emitted
872                  * fully until the pacing time (the bottleneck will hold
873                  * the data in place). Once the packet is emitted that
874                  * is when we want to start waiting for the TLP. This
875                  * is most evident with hardware pacing (where the nic
876                  * is holding the packet(s) before emitting). But it
877                  * can also show up in the network so we do it for all
878                  * cases. Technically we would take off one packet from
879                  * this extra delay but this is easier and being more
880                  * conservative is probably better.
881                  */
882                 hpts_timeout += slot;
883         }
884         if (hpts_timeout) {
885                 /*
886                  * Hack alert for now we can't time-out over 2147 seconds (a
887                  * bit more than 35min)
888                  */
889                 if (hpts_timeout > 0x7ffffffe)
890                         hpts_timeout = 0x7ffffffe;
891                 bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
892         } else
893                 bbr->r_ctl.rc_timer_exp = 0;
894         if ((slot) &&
895             (bbr->rc_use_google ||
896              bbr->output_error_seen ||
897              (slot <= hpts_timeout))  ) {
898                 /*
899                  * Tell LRO that it can queue packets while
900                  * we pace.
901                  */
902                 bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
903                 if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
904                     (bbr->rc_cwnd_limited == 0)) {
905                         /*
906                          * If we are not cwnd limited and we
907                          * are running a rack timer we put on
908                          * the do not disturbe even for sack.
909                          */
910                         inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
911                 } else
912                         inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
913                 bbr->rc_pacer_started = cts;
914
915                 (void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(slot),
916                                            __LINE__, &diag);
917                 bbr->rc_timer_first = 0;
918                 bbr->bbr_timer_src = frm;
919                 bbr_log_to_start(bbr, cts, hpts_timeout, slot, 1);
920                 bbr_log_hpts_diag(bbr, cts, &diag);
921         } else if (hpts_timeout) {
922                 (void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(hpts_timeout),
923                                            __LINE__, &diag);
924                 /*
925                  * We add the flag here as well if the slot is set,
926                  * since hpts will call in to clear the queue first before
927                  * calling the output routine (which does our timers).
928                  * We don't want to set the flag if its just a timer
929                  * else the arrival of data might (that causes us
930                  * to send more) might get delayed. Imagine being
931                  * on a keep-alive timer and a request comes in for
932                  * more data.
933                  */
934                 if (slot)
935                         bbr->rc_pacer_started = cts;
936                 if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
937                     (bbr->rc_cwnd_limited == 0)) {
938                         /*
939                          * For a rack timer, don't wake us even
940                          * if a sack arrives as long as we are
941                          * not cwnd limited.
942                          */
943                         bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
944                         inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
945                 } else {
946                         /* All other timers wake us up */
947                         bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
948                         inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
949                 }
950                 bbr->bbr_timer_src = frm;
951                 bbr_log_to_start(bbr, cts, hpts_timeout, slot, 0);
952                 bbr_log_hpts_diag(bbr, cts, &diag);
953                 bbr->rc_timer_first = 1;
954         }
955         bbr->rc_tmr_stopped = 0;
956         bbr_log_type_bbrsnd(bbr, tot_len, slot, delay_calc, cts, frm, prev_delay);
957 }
958
959 static void
960 bbr_timer_audit(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, struct sockbuf *sb)
961 {
962         /*
963          * We received an ack, and then did not call send or were bounced
964          * out due to the hpts was running. Now a timer is up as well, is it
965          * the right timer?
966          */
967         struct inpcb *inp;
968         struct bbr_sendmap *rsm;
969         uint32_t hpts_timeout;
970         int tmr_up;
971
972         tmr_up = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
973         if (bbr->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
974                 return;
975         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
976         if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
977             (tmr_up == PACE_TMR_RXT)) {
978                 /* Should be an RXT */
979                 return;
980         }
981         inp = bbr->rc_inp;
982         if (rsm == NULL) {
983                 /* Nothing outstanding? */
984                 if (tp->t_flags & TF_DELACK) {
985                         if (tmr_up == PACE_TMR_DELACK)
986                                 /*
987                                  * We are supposed to have delayed ack up
988                                  * and we do
989                                  */
990                                 return;
991                 } else if (sbavail(&inp->inp_socket->so_snd) &&
992                     (tmr_up == PACE_TMR_RXT)) {
993                         /*
994                          * if we hit enobufs then we would expect the
995                          * possiblity of nothing outstanding and the RXT up
996                          * (and the hptsi timer).
997                          */
998                         return;
999                 } else if (((V_tcp_always_keepalive ||
1000                             inp->inp_socket->so_options & SO_KEEPALIVE) &&
1001                             (tp->t_state <= TCPS_CLOSING)) &&
1002                             (tmr_up == PACE_TMR_KEEP) &&
1003                     (tp->snd_max == tp->snd_una)) {
1004                         /* We should have keep alive up and we do */
1005                         return;
1006                 }
1007         }
1008         if (rsm && (rsm->r_flags & BBR_SACK_PASSED)) {
1009                 if ((tp->t_flags & TF_SENTFIN) &&
1010                     ((tp->snd_max - tp->snd_una) == 1) &&
1011                     (rsm->r_flags & BBR_HAS_FIN)) {
1012                         /* needs to be a RXT */
1013                         if (tmr_up == PACE_TMR_RXT)
1014                                 return;
1015                         else
1016                                 goto wrong_timer;
1017                 } else if (tmr_up == PACE_TMR_RACK)
1018                         return;
1019                 else
1020                         goto wrong_timer;
1021         } else if (rsm && (tmr_up == PACE_TMR_RACK)) {
1022                 /* Rack timer has priority if we have data out */
1023                 return;
1024         } else if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1025                     ((tmr_up == PACE_TMR_TLP) ||
1026             (tmr_up == PACE_TMR_RXT))) {
1027                 /*
1028                  * Either a TLP or RXT is fine if no sack-passed is in place
1029                  * and data is outstanding.
1030                  */
1031                 return;
1032         } else if (tmr_up == PACE_TMR_DELACK) {
1033                 /*
1034                  * If the delayed ack was going to go off before the
1035                  * rtx/tlp/rack timer were going to expire, then that would
1036                  * be the timer in control. Note we don't check the time
1037                  * here trusting the code is correct.
1038                  */
1039                 return;
1040         }
1041         if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1042             ((tmr_up == PACE_TMR_RXT) ||
1043              (tmr_up == PACE_TMR_TLP) ||
1044              (tmr_up == PACE_TMR_RACK))) {
1045                 /*
1046                  * We have outstanding data and
1047                  * we *do* have a RACK, TLP or RXT
1048                  * timer running. We won't restart
1049                  * anything here since thats probably ok we
1050                  * will get called with some timer here shortly.
1051                  */
1052                 return;
1053         }
1054         /*
1055          * Ok the timer originally started is not what we want now. We will
1056          * force the hpts to be stopped if any, and restart with the slot
1057          * set to what was in the saved slot.
1058          */
1059 wrong_timer:
1060         if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) {
1061                 if (inp->inp_in_hpts)
1062                         tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
1063                 bbr_timer_cancel(bbr, __LINE__, cts);
1064                 bbr_start_hpts_timer(bbr, tp, cts, 1, bbr->r_ctl.rc_last_delay_val,
1065                     0);
1066         } else {
1067                 /*
1068                  * Output is hptsi so we just need to switch the type of
1069                  * timer. We don't bother with keep-alive, since when we
1070                  * jump through the output, it will start the keep-alive if
1071                  * nothing is sent.
1072                  *
1073                  * We only need a delayed-ack added and or the hpts_timeout.
1074                  */
1075                 hpts_timeout = bbr_timer_start(tp, bbr, cts);
1076                 if (tp->t_flags & TF_DELACK) {
1077                         if (hpts_timeout == 0) {
1078                                 hpts_timeout = bbr_delack_time;
1079                                 bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1080                         }
1081                         else if (hpts_timeout > bbr_delack_time) {
1082                                 hpts_timeout = bbr_delack_time;
1083                                 bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1084                         }
1085                 }
1086                 if (hpts_timeout) {
1087                         if (hpts_timeout > 0x7ffffffe)
1088                                 hpts_timeout = 0x7ffffffe;
1089                         bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
1090                 }
1091         }
1092 }
1093
1094 int32_t bbr_clear_lost = 0;
1095
1096 /*
1097  * Considers the two time values now (cts) and earlier.
1098  * If cts is smaller than earlier, we could have
1099  * had a sequence wrap (our counter wraps every
1100  * 70 min or so) or it could be just clock skew
1101  * getting us two differnt time values. Clock skew
1102  * will show up within 10ms or so. So in such
1103  * a case (where cts is behind earlier time by
1104  * less than 10ms) we return 0. Otherwise we
1105  * return the true difference between them.
1106  */
1107 static inline uint32_t
1108 bbr_calc_time(uint32_t cts, uint32_t earlier_time) {
1109         /*
1110          * Given two timestamps, the current time stamp cts, and some other
1111          * time-stamp taken in theory earlier return the difference. The
1112          * trick is here sometimes locking will get the other timestamp
1113          * after the cts. If this occurs we need to return 0.
1114          */
1115         if (TSTMP_GEQ(cts, earlier_time))
1116                 return (cts - earlier_time);
1117         /*
1118          * cts is behind earlier_time if its less than 10ms consider it 0.
1119          * If its more than 10ms difference then we had a time wrap. Else
1120          * its just the normal locking foo. I wonder if we should not go to
1121          * 64bit TS and get rid of this issue.
1122          */
1123         if (TSTMP_GEQ((cts + 10000), earlier_time))
1124                 return (0);
1125         /*
1126          * Ok the time must have wrapped. So we need to answer a large
1127          * amount of time, which the normal subtraction should do.
1128          */
1129         return (cts - earlier_time);
1130 }
1131
1132 static int
1133 sysctl_bbr_clear_lost(SYSCTL_HANDLER_ARGS)
1134 {
1135         uint32_t stat;
1136         int32_t error;
1137
1138         error = SYSCTL_OUT(req, &bbr_clear_lost, sizeof(uint32_t));
1139         if (error || req->newptr == NULL)
1140                 return error;
1141
1142         error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
1143         if (error)
1144                 return (error);
1145         if (stat == 1) {
1146 #ifdef BBR_INVARIANTS
1147                 printf("Clearing BBR lost counters\n");
1148 #endif
1149                 COUNTER_ARRAY_ZERO(bbr_state_lost, BBR_MAX_STAT);
1150                 COUNTER_ARRAY_ZERO(bbr_state_time, BBR_MAX_STAT);
1151                 COUNTER_ARRAY_ZERO(bbr_state_resend, BBR_MAX_STAT);
1152         } else if (stat == 2) {
1153 #ifdef BBR_INVARIANTS
1154                 printf("Clearing BBR option counters\n");
1155 #endif
1156                 COUNTER_ARRAY_ZERO(bbr_opts_arry, BBR_OPTS_SIZE);
1157         } else if (stat == 3) {
1158 #ifdef BBR_INVARIANTS
1159                 printf("Clearing BBR stats counters\n");
1160 #endif
1161                 COUNTER_ARRAY_ZERO(bbr_stat_arry, BBR_STAT_SIZE);
1162         } else if (stat == 4) {
1163 #ifdef BBR_INVARIANTS
1164                 printf("Clearing BBR out-size counters\n");
1165 #endif
1166                 COUNTER_ARRAY_ZERO(bbr_out_size, TCP_MSS_ACCT_SIZE);
1167         }
1168         bbr_clear_lost = 0;
1169         return (0);
1170 }
1171
1172 static void
1173 bbr_init_sysctls(void)
1174 {
1175         struct sysctl_oid *bbr_probertt;
1176         struct sysctl_oid *bbr_hptsi;
1177         struct sysctl_oid *bbr_measure;
1178         struct sysctl_oid *bbr_cwnd;
1179         struct sysctl_oid *bbr_timeout;
1180         struct sysctl_oid *bbr_states;
1181         struct sysctl_oid *bbr_startup;
1182         struct sysctl_oid *bbr_policer;
1183
1184         /* Probe rtt controls */
1185         bbr_probertt = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1186             SYSCTL_CHILDREN(bbr_sysctl_root),
1187             OID_AUTO,
1188             "probertt",
1189             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1190             "");
1191         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1192             SYSCTL_CHILDREN(bbr_probertt),
1193             OID_AUTO, "gain", CTLFLAG_RW,
1194             &bbr_rttprobe_gain, 192,
1195             "What is the filter gain drop in probe_rtt (0=disable)?");
1196         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1197             SYSCTL_CHILDREN(bbr_probertt),
1198             OID_AUTO, "cwnd", CTLFLAG_RW,
1199             &bbr_rtt_probe_cwndtarg, 4,
1200             "How many mss's are outstanding during probe-rtt");
1201         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1202             SYSCTL_CHILDREN(bbr_probertt),
1203             OID_AUTO, "int", CTLFLAG_RW,
1204             &bbr_rtt_probe_limit, 4000000,
1205             "If RTT has not shrank in this many micro-seconds enter probe-rtt");
1206         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1207             SYSCTL_CHILDREN(bbr_probertt),
1208             OID_AUTO, "mintime", CTLFLAG_RW,
1209             &bbr_rtt_probe_time, 200000,
1210             "How many microseconds in probe-rtt");
1211         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1212             SYSCTL_CHILDREN(bbr_probertt),
1213             OID_AUTO, "filter_len_sec", CTLFLAG_RW,
1214             &bbr_filter_len_sec, 6,
1215             "How long in seconds does the rttProp filter run?");
1216         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1217             SYSCTL_CHILDREN(bbr_probertt),
1218             OID_AUTO, "drain_rtt", CTLFLAG_RW,
1219             &bbr_drain_rtt, BBR_SRTT,
1220             "What is the drain rtt to use in probeRTT (rtt_prop=0, rtt_rack=1, rtt_pkt=2, rtt_srtt=3?");
1221         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1222             SYSCTL_CHILDREN(bbr_probertt),
1223             OID_AUTO, "can_force", CTLFLAG_RW,
1224             &bbr_can_force_probertt, 0,
1225             "If we keep setting new low rtt's but delay going in probe-rtt can we force in??");
1226         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1227             SYSCTL_CHILDREN(bbr_probertt),
1228             OID_AUTO, "enter_sets_force", CTLFLAG_RW,
1229             &bbr_probertt_sets_rtt, 0,
1230             "In NF mode, do we imitate google_mode and set the rttProp on entry to probe-rtt?");
1231         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1232             SYSCTL_CHILDREN(bbr_probertt),
1233             OID_AUTO, "can_adjust", CTLFLAG_RW,
1234             &bbr_can_adjust_probertt, 1,
1235             "Can we dynamically adjust the probe-rtt limits and times?");
1236         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1237             SYSCTL_CHILDREN(bbr_probertt),
1238             OID_AUTO, "is_ratio", CTLFLAG_RW,
1239             &bbr_is_ratio, 0,
1240             "is the limit to filter a ratio?");
1241         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1242             SYSCTL_CHILDREN(bbr_probertt),
1243             OID_AUTO, "use_cwnd", CTLFLAG_RW,
1244             &bbr_prtt_slam_cwnd, 0,
1245             "Should we set/recover cwnd?");
1246         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1247             SYSCTL_CHILDREN(bbr_probertt),
1248             OID_AUTO, "can_use_ts", CTLFLAG_RW,
1249             &bbr_can_use_ts_for_rtt, 1,
1250             "Can we use the ms timestamp if available for retransmistted rtt calculations?");
1251
1252         /* Pacing controls */
1253         bbr_hptsi = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1254             SYSCTL_CHILDREN(bbr_sysctl_root),
1255             OID_AUTO,
1256             "pacing",
1257             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1258             "");
1259         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1260             SYSCTL_CHILDREN(bbr_hptsi),
1261             OID_AUTO, "hw_pacing", CTLFLAG_RW,
1262             &bbr_allow_hdwr_pacing, 1,
1263             "Do we allow hardware pacing?");
1264         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1265             SYSCTL_CHILDREN(bbr_hptsi),
1266             OID_AUTO, "hw_pacing_limit", CTLFLAG_RW,
1267             &bbr_hardware_pacing_limit, 4000,
1268             "Do we have a limited number of connections for pacing chelsio (0=no limit)?");
1269         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1270             SYSCTL_CHILDREN(bbr_hptsi),
1271             OID_AUTO, "hw_pacing_adj", CTLFLAG_RW,
1272             &bbr_hdwr_pace_adjust, 2,
1273             "Multiplier to calculated tso size?");
1274         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1275             SYSCTL_CHILDREN(bbr_hptsi),
1276             OID_AUTO, "hw_pacing_floor", CTLFLAG_RW,
1277             &bbr_hdwr_pace_floor, 1,
1278             "Do we invoke the hardware pacing floor?");
1279         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1280             SYSCTL_CHILDREN(bbr_hptsi),
1281             OID_AUTO, "hw_pacing_delay_cnt", CTLFLAG_RW,
1282             &bbr_hdwr_pacing_delay_cnt, 10,
1283             "How many packets must be sent after hdwr pacing is enabled");
1284         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1285             SYSCTL_CHILDREN(bbr_hptsi),
1286             OID_AUTO, "bw_cross", CTLFLAG_RW,
1287             &bbr_cross_over, 3000000,
1288             "What is the point where we cross over to linux like TSO size set");
1289         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1290             SYSCTL_CHILDREN(bbr_hptsi),
1291             OID_AUTO, "seg_deltarg", CTLFLAG_RW,
1292             &bbr_hptsi_segments_delay_tar, 7000,
1293             "What is the worse case delay target for hptsi < 48Mbp connections");
1294         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1295             SYSCTL_CHILDREN(bbr_hptsi),
1296             OID_AUTO, "enet_oh", CTLFLAG_RW,
1297             &bbr_include_enet_oh, 0,
1298             "Do we include the ethernet overhead in calculating pacing delay?");
1299         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1300             SYSCTL_CHILDREN(bbr_hptsi),
1301             OID_AUTO, "ip_oh", CTLFLAG_RW,
1302             &bbr_include_ip_oh, 1,
1303             "Do we include the IP overhead in calculating pacing delay?");
1304         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1305             SYSCTL_CHILDREN(bbr_hptsi),
1306             OID_AUTO, "tcp_oh", CTLFLAG_RW,
1307             &bbr_include_tcp_oh, 0,
1308             "Do we include the TCP overhead in calculating pacing delay?");
1309         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1310             SYSCTL_CHILDREN(bbr_hptsi),
1311             OID_AUTO, "google_discount", CTLFLAG_RW,
1312             &bbr_google_discount, 10,
1313             "What is the default google discount percentage wise for pacing (11 = 1.1%%)?");
1314         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1315             SYSCTL_CHILDREN(bbr_hptsi),
1316             OID_AUTO, "all_get_min", CTLFLAG_RW,
1317             &bbr_all_get_min, 0,
1318             "If you are less than a MSS do you just get the min?");
1319         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1320             SYSCTL_CHILDREN(bbr_hptsi),
1321             OID_AUTO, "tso_min", CTLFLAG_RW,
1322             &bbr_hptsi_bytes_min, 1460,
1323             "For 0 -> 24Mbps what is floor number of segments for TSO");
1324         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1325             SYSCTL_CHILDREN(bbr_hptsi),
1326             OID_AUTO, "seg_tso_max", CTLFLAG_RW,
1327             &bbr_hptsi_segments_max, 6,
1328             "For 0 -> 24Mbps what is top number of segments for TSO");
1329         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1330             SYSCTL_CHILDREN(bbr_hptsi),
1331             OID_AUTO, "seg_floor", CTLFLAG_RW,
1332             &bbr_hptsi_segments_floor, 1,
1333             "Minimum TSO size we will fall too in segments");
1334         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1335             SYSCTL_CHILDREN(bbr_hptsi),
1336             OID_AUTO, "utter_max", CTLFLAG_RW,
1337             &bbr_hptsi_utter_max, 0,
1338             "The absolute maximum that any pacing (outside of hardware) can be");
1339         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1340             SYSCTL_CHILDREN(bbr_hptsi),
1341             OID_AUTO, "seg_divisor", CTLFLAG_RW,
1342             &bbr_hptsi_per_second, 100,
1343             "What is the divisor in our hptsi TSO calculation 512Mbps < X > 24Mbps ");
1344         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1345             SYSCTL_CHILDREN(bbr_hptsi),
1346             OID_AUTO, "srtt_mul", CTLFLAG_RW,
1347             &bbr_hptsi_max_mul, 1,
1348             "The multiplier for pace len max");
1349         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1350             SYSCTL_CHILDREN(bbr_hptsi),
1351             OID_AUTO, "srtt_div", CTLFLAG_RW,
1352             &bbr_hptsi_max_div, 2,
1353             "The divisor for pace len max");
1354         /* Measurement controls */
1355         bbr_measure = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1356             SYSCTL_CHILDREN(bbr_sysctl_root),
1357             OID_AUTO,
1358             "measure",
1359             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1360             "Measurement controls");
1361         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1362             SYSCTL_CHILDREN(bbr_measure),
1363             OID_AUTO, "min_i_bw", CTLFLAG_RW,
1364             &bbr_initial_bw_bps, 62500,
1365             "Minimum initial b/w in bytes per second");
1366         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1367             SYSCTL_CHILDREN(bbr_measure),
1368             OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1369             &bbr_sack_not_required, 0,
1370             "Do we allow bbr to run on connections not supporting SACK?");
1371         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1372             SYSCTL_CHILDREN(bbr_measure),
1373             OID_AUTO, "use_google", CTLFLAG_RW,
1374             &bbr_use_google_algo, 0,
1375             "Use has close to google V1.0 has possible?");
1376         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1377             SYSCTL_CHILDREN(bbr_measure),
1378             OID_AUTO, "ts_limiting", CTLFLAG_RW,
1379             &bbr_ts_limiting, 1,
1380             "Do we attempt to use the peers timestamp to limit b/w caculations?");
1381         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1382             SYSCTL_CHILDREN(bbr_measure),
1383             OID_AUTO, "ts_can_raise", CTLFLAG_RW,
1384             &bbr_ts_can_raise, 0,
1385             "Can we raise the b/w via timestamp b/w calculation?");
1386         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1387             SYSCTL_CHILDREN(bbr_measure),
1388             OID_AUTO, "ts_delta", CTLFLAG_RW,
1389             &bbr_min_usec_delta, 20000,
1390             "How long in usec between ts of our sends in ts validation code?");
1391         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1392             SYSCTL_CHILDREN(bbr_measure),
1393             OID_AUTO, "ts_peer_delta", CTLFLAG_RW,
1394             &bbr_min_peer_delta, 20,
1395             "What min numerical value should be between the peer deltas?");
1396         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1397             SYSCTL_CHILDREN(bbr_measure),
1398             OID_AUTO, "ts_delta_percent", CTLFLAG_RW,
1399             &bbr_delta_percent, 150,
1400             "What percentage (150 = 15.0) do we allow variance for?");
1401         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1402             SYSCTL_CHILDREN(bbr_measure),
1403             OID_AUTO, "min_measure_good_bw", CTLFLAG_RW,
1404             &bbr_min_measurements_req, 1,
1405             "What is the minimum measurment count we need before we switch to our b/w estimate");
1406         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1407             SYSCTL_CHILDREN(bbr_measure),
1408             OID_AUTO, "min_measure_before_pace", CTLFLAG_RW,
1409             &bbr_no_pacing_until, 4,
1410             "How many pkt-epoch's (0 is off) do we need before pacing is on?");
1411         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1412             SYSCTL_CHILDREN(bbr_measure),
1413             OID_AUTO, "quanta", CTLFLAG_RW,
1414             &bbr_quanta, 2,
1415             "Extra quanta to add when calculating the target (ID section 4.2.3.2).");
1416         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1417             SYSCTL_CHILDREN(bbr_measure),
1418             OID_AUTO, "noretran", CTLFLAG_RW,
1419             &bbr_no_retran, 0,
1420             "Should google mode not use retransmission measurements for the b/w estimation?");
1421         /* State controls */
1422         bbr_states = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1423             SYSCTL_CHILDREN(bbr_sysctl_root),
1424             OID_AUTO,
1425             "states",
1426             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1427             "State controls");
1428         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1429             SYSCTL_CHILDREN(bbr_states),
1430             OID_AUTO, "idle_restart", CTLFLAG_RW,
1431             &bbr_uses_idle_restart, 0,
1432             "Do we use a new special idle_restart state to ramp back up quickly?");
1433         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1434             SYSCTL_CHILDREN(bbr_states),
1435             OID_AUTO, "idle_restart_threshold", CTLFLAG_RW,
1436             &bbr_idle_restart_threshold, 100000,
1437             "How long must we be idle before we restart??");
1438         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1439             SYSCTL_CHILDREN(bbr_states),
1440             OID_AUTO, "use_pkt_epoch", CTLFLAG_RW,
1441             &bbr_state_is_pkt_epoch, 0,
1442             "Do we use a pkt-epoch for substate if 0 rttProp?");
1443         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1444             SYSCTL_CHILDREN(bbr_states),
1445             OID_AUTO, "startup_rtt_gain", CTLFLAG_RW,
1446             &bbr_rtt_gain_thresh, 0,
1447             "What increase in RTT triggers us to stop ignoring no-loss and possibly exit startup?");
1448         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1449             SYSCTL_CHILDREN(bbr_states),
1450             OID_AUTO, "drain_floor", CTLFLAG_RW,
1451             &bbr_drain_floor, 88,
1452             "What is the lowest we can drain (pg) too?");
1453         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1454             SYSCTL_CHILDREN(bbr_states),
1455             OID_AUTO, "drain_2_target", CTLFLAG_RW,
1456             &bbr_state_drain_2_tar, 1,
1457             "Do we drain to target in drain substate?");
1458         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1459             SYSCTL_CHILDREN(bbr_states),
1460             OID_AUTO, "gain_2_target", CTLFLAG_RW,
1461             &bbr_gain_to_target, 1,
1462             "Does probe bw gain to target??");
1463         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1464             SYSCTL_CHILDREN(bbr_states),
1465             OID_AUTO, "gain_extra_time", CTLFLAG_RW,
1466             &bbr_gain_gets_extra_too, 1,
1467             "Does probe bw gain get the extra time too?");
1468         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1469             SYSCTL_CHILDREN(bbr_states),
1470             OID_AUTO, "ld_div", CTLFLAG_RW,
1471             &bbr_drain_drop_div, 5,
1472             "Long drain drop divider?");
1473         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1474             SYSCTL_CHILDREN(bbr_states),
1475             OID_AUTO, "ld_mul", CTLFLAG_RW,
1476             &bbr_drain_drop_mul, 4,
1477             "Long drain drop multiplier?");
1478         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1479             SYSCTL_CHILDREN(bbr_states),
1480             OID_AUTO, "rand_ot_disc", CTLFLAG_RW,
1481             &bbr_rand_ot, 50,
1482             "Random discount of the ot?");
1483         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1484             SYSCTL_CHILDREN(bbr_states),
1485             OID_AUTO, "dr_filter_life", CTLFLAG_RW,
1486             &bbr_num_pktepo_for_del_limit, BBR_NUM_RTTS_FOR_DEL_LIMIT,
1487             "How many packet-epochs does the b/w delivery rate last?");
1488         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1489             SYSCTL_CHILDREN(bbr_states),
1490             OID_AUTO, "subdrain_applimited", CTLFLAG_RW,
1491             &bbr_sub_drain_app_limit, 0,
1492             "Does our sub-state drain invoke app limited if its long?");
1493         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1494             SYSCTL_CHILDREN(bbr_states),
1495             OID_AUTO, "use_cwnd_subdrain", CTLFLAG_RW,
1496             &bbr_sub_drain_slam_cwnd, 0,
1497             "Should we set/recover cwnd for sub-state drain?");
1498         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1499             SYSCTL_CHILDREN(bbr_states),
1500             OID_AUTO, "use_cwnd_maindrain", CTLFLAG_RW,
1501             &bbr_slam_cwnd_in_main_drain, 0,
1502             "Should we set/recover cwnd for main-state drain?");
1503         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1504             SYSCTL_CHILDREN(bbr_states),
1505             OID_AUTO, "google_gets_earlyout", CTLFLAG_RW,
1506             &google_allow_early_out, 1,
1507             "Should we allow google probe-bw/drain to exit early at flight target?");
1508         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1509             SYSCTL_CHILDREN(bbr_states),
1510             OID_AUTO, "google_exit_loss", CTLFLAG_RW,
1511             &google_consider_lost, 1,
1512             "Should we have losses exit gain of probebw in google mode??");
1513         /* Startup controls */
1514         bbr_startup = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1515             SYSCTL_CHILDREN(bbr_sysctl_root),
1516             OID_AUTO,
1517             "startup",
1518             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1519             "Startup controls");
1520         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1521             SYSCTL_CHILDREN(bbr_startup),
1522             OID_AUTO, "cheat_iwnd", CTLFLAG_RW,
1523             &bbr_sends_full_iwnd, 1,
1524             "Do we not pace but burst out initial windows has our TSO size?");
1525         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1526             SYSCTL_CHILDREN(bbr_startup),
1527             OID_AUTO, "loss_threshold", CTLFLAG_RW,
1528             &bbr_startup_loss_thresh, 2000,
1529             "In startup what is the loss threshold in a pe that will exit us from startup?");
1530         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1531             SYSCTL_CHILDREN(bbr_startup),
1532             OID_AUTO, "use_lowerpg", CTLFLAG_RW,
1533             &bbr_use_lower_gain_in_startup, 1,
1534             "Should we use a lower hptsi gain if we see loss in startup?");
1535         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1536             SYSCTL_CHILDREN(bbr_startup),
1537             OID_AUTO, "gain", CTLFLAG_RW,
1538             &bbr_start_exit, 25,
1539             "What gain percent do we need to see to stay in startup??");
1540         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1541             SYSCTL_CHILDREN(bbr_startup),
1542             OID_AUTO, "low_gain", CTLFLAG_RW,
1543             &bbr_low_start_exit, 15,
1544             "What gain percent do we need to see to stay in the lower gain startup??");
1545         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1546             SYSCTL_CHILDREN(bbr_startup),
1547             OID_AUTO, "loss_exit", CTLFLAG_RW,
1548             &bbr_exit_startup_at_loss, 1,
1549             "Should we exit startup at loss in an epoch if we are not gaining?");
1550         /* CWND controls */
1551         bbr_cwnd = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1552             SYSCTL_CHILDREN(bbr_sysctl_root),
1553             OID_AUTO,
1554             "cwnd",
1555             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1556             "Cwnd controls");
1557         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1558             SYSCTL_CHILDREN(bbr_cwnd),
1559             OID_AUTO, "tar_rtt", CTLFLAG_RW,
1560             &bbr_cwndtarget_rtt_touse, 0,
1561             "Target cwnd rtt measurment to use (0=rtt_prop, 1=rtt_rack, 2=pkt_rtt, 3=srtt)?");
1562         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1563             SYSCTL_CHILDREN(bbr_cwnd),
1564             OID_AUTO, "may_shrink", CTLFLAG_RW,
1565             &bbr_cwnd_may_shrink, 0,
1566             "Can the cwnd shrink if it would grow to more than the target?");
1567         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1568             SYSCTL_CHILDREN(bbr_cwnd),
1569             OID_AUTO, "max_target_limit", CTLFLAG_RW,
1570             &bbr_target_cwnd_mult_limit, 8,
1571             "Do we limit the cwnd to some multiple of the cwnd target if cwnd can't shrink 0=no?");
1572         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1573             SYSCTL_CHILDREN(bbr_cwnd),
1574             OID_AUTO, "highspeed_min", CTLFLAG_RW,
1575             &bbr_cwnd_min_val_hs, BBR_HIGHSPEED_NUM_MSS,
1576             "What is the high-speed min cwnd (rttProp under 1ms)");
1577         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1578             SYSCTL_CHILDREN(bbr_cwnd),
1579             OID_AUTO, "lowspeed_min", CTLFLAG_RW,
1580             &bbr_cwnd_min_val, BBR_PROBERTT_NUM_MSS,
1581             "What is the min cwnd (rttProp > 1ms)");
1582         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1583             SYSCTL_CHILDREN(bbr_cwnd),
1584             OID_AUTO, "initwin", CTLFLAG_RW,
1585             &bbr_def_init_win, 10,
1586             "What is the BBR initial window, if 0 use tcp version");
1587         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1588             SYSCTL_CHILDREN(bbr_cwnd),
1589             OID_AUTO, "do_loss_red", CTLFLAG_RW,
1590             &bbr_do_red, 600,
1591             "Do we reduce the b/w at exit from recovery based on ratio of prop/srtt (800=80.0, 0=off)?");
1592         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1593             SYSCTL_CHILDREN(bbr_cwnd),
1594             OID_AUTO, "red_scale", CTLFLAG_RW,
1595             &bbr_red_scale, 20000,
1596             "What RTT do we scale with?");
1597         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1598             SYSCTL_CHILDREN(bbr_cwnd),
1599             OID_AUTO, "red_growslow", CTLFLAG_RW,
1600             &bbr_red_growth_restrict, 1,
1601             "Do we restrict cwnd growth for whats in flight?");
1602         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1603             SYSCTL_CHILDREN(bbr_cwnd),
1604             OID_AUTO, "red_div", CTLFLAG_RW,
1605             &bbr_red_div, 2,
1606             "If we reduce whats the divisor?");
1607         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1608             SYSCTL_CHILDREN(bbr_cwnd),
1609             OID_AUTO, "red_mul", CTLFLAG_RW,
1610             &bbr_red_mul, 1,
1611             "If we reduce whats the mulitiplier?");
1612         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1613             SYSCTL_CHILDREN(bbr_cwnd),
1614             OID_AUTO, "target_is_unit", CTLFLAG_RW,
1615             &bbr_target_is_bbunit, 0,
1616             "Is the state target the pacing_gain or BBR_UNIT?");
1617         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1618             SYSCTL_CHILDREN(bbr_cwnd),
1619             OID_AUTO, "drop_limit", CTLFLAG_RW,
1620             &bbr_drop_limit, 0,
1621             "Number of segments limit for drop (0=use min_cwnd w/flight)?");
1622
1623         /* Timeout controls */
1624         bbr_timeout = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1625             SYSCTL_CHILDREN(bbr_sysctl_root),
1626             OID_AUTO,
1627             "timeout",
1628             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1629             "Time out controls");
1630         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1631             SYSCTL_CHILDREN(bbr_timeout),
1632             OID_AUTO, "delack", CTLFLAG_RW,
1633             &bbr_delack_time, 100000,
1634             "BBR's delayed ack time");
1635         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1636             SYSCTL_CHILDREN(bbr_timeout),
1637             OID_AUTO, "tlp_uses", CTLFLAG_RW,
1638             &bbr_tlp_type_to_use, 3,
1639             "RTT that TLP uses in its calculations, 0=rttProp, 1=Rack_rtt, 2=pkt_rtt and 3=srtt");
1640         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1641             SYSCTL_CHILDREN(bbr_timeout),
1642             OID_AUTO, "persmin", CTLFLAG_RW,
1643             &bbr_persist_min, 250000,
1644             "What is the minimum time in microseconds between persists");
1645         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1646             SYSCTL_CHILDREN(bbr_timeout),
1647             OID_AUTO, "persmax", CTLFLAG_RW,
1648             &bbr_persist_max, 1000000,
1649             "What is the largest delay in microseconds between persists");
1650         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1651             SYSCTL_CHILDREN(bbr_timeout),
1652             OID_AUTO, "tlp_minto", CTLFLAG_RW,
1653             &bbr_tlp_min, 10000,
1654             "TLP Min timeout in usecs");
1655         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1656             SYSCTL_CHILDREN(bbr_timeout),
1657             OID_AUTO, "tlp_dack_time", CTLFLAG_RW,
1658             &bbr_delayed_ack_time, 200000,
1659             "TLP delayed ack compensation value");
1660         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1661             SYSCTL_CHILDREN(bbr_sysctl_root),
1662             OID_AUTO, "minrto", CTLFLAG_RW,
1663             &bbr_rto_min_ms, 30,
1664             "Minimum RTO in ms");
1665         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1666             SYSCTL_CHILDREN(bbr_timeout),
1667             OID_AUTO, "maxrto", CTLFLAG_RW,
1668             &bbr_rto_max_sec, 4,
1669             "Maxiumum RTO in seconds -- should be at least as large as min_rto");
1670         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1671             SYSCTL_CHILDREN(bbr_timeout),
1672             OID_AUTO, "tlp_retry", CTLFLAG_RW,
1673             &bbr_tlp_max_resend, 2,
1674             "How many times does TLP retry a single segment or multiple with no ACK");
1675         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1676             SYSCTL_CHILDREN(bbr_timeout),
1677             OID_AUTO, "minto", CTLFLAG_RW,
1678             &bbr_min_to, 1000,
1679             "Minimum rack timeout in useconds");
1680         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1681             SYSCTL_CHILDREN(bbr_timeout),
1682             OID_AUTO, "pktdelay", CTLFLAG_RW,
1683             &bbr_pkt_delay, 1000,
1684             "Extra RACK time (in useconds) besides reordering thresh");
1685         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1686             SYSCTL_CHILDREN(bbr_timeout),
1687             OID_AUTO, "incr_tmrs", CTLFLAG_RW,
1688             &bbr_incr_timers, 1,
1689             "Increase the RXT/TLP timer by the pacing time used?");
1690         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1691             SYSCTL_CHILDREN(bbr_timeout),
1692             OID_AUTO, "rxtmark_sackpassed", CTLFLAG_RW,
1693             &bbr_marks_rxt_sack_passed, 0,
1694             "Mark sack passed on all those not ack'd when a RXT hits?");
1695         /* Policer controls */
1696         bbr_policer = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1697             SYSCTL_CHILDREN(bbr_sysctl_root),
1698             OID_AUTO,
1699             "policer",
1700             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1701             "Policer controls");
1702         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1703             SYSCTL_CHILDREN(bbr_policer),
1704             OID_AUTO, "detect_enable", CTLFLAG_RW,
1705             &bbr_policer_detection_enabled, 1,
1706             "Is policer detection enabled??");
1707         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1708             SYSCTL_CHILDREN(bbr_policer),
1709             OID_AUTO, "min_pes", CTLFLAG_RW,
1710             &bbr_lt_intvl_min_rtts, 4,
1711             "Minimum number of PE's?");
1712         SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1713             SYSCTL_CHILDREN(bbr_policer),
1714             OID_AUTO, "bwdiff", CTLFLAG_RW,
1715             &bbr_lt_bw_diff, (4000/8),
1716             "Minimal bw diff?");
1717         SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1718             SYSCTL_CHILDREN(bbr_policer),
1719             OID_AUTO, "bwratio", CTLFLAG_RW,
1720             &bbr_lt_bw_ratio, 8,
1721             "Minimal bw diff?");
1722         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1723             SYSCTL_CHILDREN(bbr_policer),
1724             OID_AUTO, "from_rack_rxt", CTLFLAG_RW,
1725             &bbr_policer_call_from_rack_to, 0,
1726             "Do we call the policer detection code from a rack-timeout?");
1727         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1728             SYSCTL_CHILDREN(bbr_policer),
1729             OID_AUTO, "false_postive", CTLFLAG_RW,
1730             &bbr_lt_intvl_fp, 0,
1731             "What packet epoch do we do false-postive detection at (0=no)?");
1732         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1733             SYSCTL_CHILDREN(bbr_policer),
1734             OID_AUTO, "loss_thresh", CTLFLAG_RW,
1735             &bbr_lt_loss_thresh, 196,
1736             "Loss threshold 196 = 19.6%?");
1737         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1738             SYSCTL_CHILDREN(bbr_policer),
1739             OID_AUTO, "false_postive_thresh", CTLFLAG_RW,
1740             &bbr_lt_fd_thresh, 100,
1741             "What percentage is the false detection threshold (150=15.0)?");
1742         /* All the rest */
1743         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1744             SYSCTL_CHILDREN(bbr_sysctl_root),
1745             OID_AUTO, "cheat_rxt", CTLFLAG_RW,
1746             &bbr_use_rack_resend_cheat, 0,
1747             "Do we burst 1ms between sends on retransmissions (like rack)?");
1748         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1749             SYSCTL_CHILDREN(bbr_sysctl_root),
1750             OID_AUTO, "error_paceout", CTLFLAG_RW,
1751             &bbr_error_base_paceout, 10000,
1752             "When we hit an error what is the min to pace out in usec's?");
1753         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1754             SYSCTL_CHILDREN(bbr_sysctl_root),
1755             OID_AUTO, "kill_paceout", CTLFLAG_RW,
1756             &bbr_max_net_error_cnt, 10,
1757             "When we hit this many errors in a row, kill the session?");
1758         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1759             SYSCTL_CHILDREN(bbr_sysctl_root),
1760             OID_AUTO, "data_after_close", CTLFLAG_RW,
1761             &bbr_ignore_data_after_close, 1,
1762             "Do we hold off sending a RST until all pending data is ack'd");
1763         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1764             SYSCTL_CHILDREN(bbr_sysctl_root),
1765             OID_AUTO, "resend_use_tso", CTLFLAG_RW,
1766             &bbr_resends_use_tso, 0,
1767             "Can resends use TSO?");
1768         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1769             SYSCTL_CHILDREN(bbr_sysctl_root),
1770             OID_AUTO, "sblklimit", CTLFLAG_RW,
1771             &bbr_sack_block_limit, 128,
1772             "When do we start ignoring small sack blocks");
1773         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1774             SYSCTL_CHILDREN(bbr_sysctl_root),
1775             OID_AUTO, "bb_verbose", CTLFLAG_RW,
1776             &bbr_verbose_logging, 0,
1777             "Should BBR black box logging be verbose");
1778         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1779             SYSCTL_CHILDREN(bbr_sysctl_root),
1780             OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1781             &bbr_reorder_thresh, 2,
1782             "What factor for rack will be added when seeing reordering (shift right)");
1783         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1784             SYSCTL_CHILDREN(bbr_sysctl_root),
1785             OID_AUTO, "reorder_fade", CTLFLAG_RW,
1786             &bbr_reorder_fade, 0,
1787             "Does reorder detection fade, if so how many ms (0 means never)");
1788         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1789             SYSCTL_CHILDREN(bbr_sysctl_root),
1790             OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1791             &bbr_tlp_thresh, 1,
1792             "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1793         /* Stats and counters */
1794         /* The pacing counters for hdwr/software can't be in the array */
1795         bbr_nohdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1796         bbr_hdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1797         SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1798             SYSCTL_CHILDREN(bbr_sysctl_root),
1799             OID_AUTO, "enob_hdwr_pacing", CTLFLAG_RD,
1800             &bbr_hdwr_pacing_enobuf,
1801             "Total number of enobufs for hardware paced flows");
1802         SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1803             SYSCTL_CHILDREN(bbr_sysctl_root),
1804             OID_AUTO, "enob_no_hdwr_pacing", CTLFLAG_RD,
1805             &bbr_nohdwr_pacing_enobuf,
1806             "Total number of enobufs for non-hardware paced flows");
1807
1808         bbr_flows_whdwr_pacing = counter_u64_alloc(M_WAITOK);
1809         SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1810             SYSCTL_CHILDREN(bbr_sysctl_root),
1811             OID_AUTO, "hdwr_pacing", CTLFLAG_RD,
1812             &bbr_flows_whdwr_pacing,
1813             "Total number of hardware paced flows");
1814         bbr_flows_nohdwr_pacing = counter_u64_alloc(M_WAITOK);
1815         SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1816             SYSCTL_CHILDREN(bbr_sysctl_root),
1817             OID_AUTO, "software_pacing", CTLFLAG_RD,
1818             &bbr_flows_nohdwr_pacing,
1819             "Total number of software paced flows");
1820         COUNTER_ARRAY_ALLOC(bbr_stat_arry, BBR_STAT_SIZE, M_WAITOK);
1821         SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1822             OID_AUTO, "stats", CTLFLAG_RD,
1823             bbr_stat_arry, BBR_STAT_SIZE, "BBR Stats");
1824         COUNTER_ARRAY_ALLOC(bbr_opts_arry, BBR_OPTS_SIZE, M_WAITOK);
1825         SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1826             OID_AUTO, "opts", CTLFLAG_RD,
1827             bbr_opts_arry, BBR_OPTS_SIZE, "BBR Option Stats");
1828         COUNTER_ARRAY_ALLOC(bbr_state_lost, BBR_MAX_STAT, M_WAITOK);
1829         SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1830             OID_AUTO, "lost", CTLFLAG_RD,
1831             bbr_state_lost, BBR_MAX_STAT, "Stats of when losses occur");
1832         COUNTER_ARRAY_ALLOC(bbr_state_resend, BBR_MAX_STAT, M_WAITOK);
1833         SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1834             OID_AUTO, "stateresend", CTLFLAG_RD,
1835             bbr_state_resend, BBR_MAX_STAT, "Stats of what states resend");
1836         COUNTER_ARRAY_ALLOC(bbr_state_time, BBR_MAX_STAT, M_WAITOK);
1837         SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1838             OID_AUTO, "statetime", CTLFLAG_RD,
1839             bbr_state_time, BBR_MAX_STAT, "Stats of time spent in the states");
1840         COUNTER_ARRAY_ALLOC(bbr_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1841         SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1842             OID_AUTO, "outsize", CTLFLAG_RD,
1843             bbr_out_size, TCP_MSS_ACCT_SIZE, "Size of output calls");
1844         SYSCTL_ADD_PROC(&bbr_sysctl_ctx,
1845             SYSCTL_CHILDREN(bbr_sysctl_root),
1846             OID_AUTO, "clrlost", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1847             &bbr_clear_lost, 0, sysctl_bbr_clear_lost, "IU", "Clear lost counters");
1848 }
1849
1850 static void
1851 bbr_counter_destroy(void)
1852 {
1853         COUNTER_ARRAY_FREE(bbr_stat_arry, BBR_STAT_SIZE);
1854         COUNTER_ARRAY_FREE(bbr_opts_arry, BBR_OPTS_SIZE);
1855         COUNTER_ARRAY_FREE(bbr_out_size, TCP_MSS_ACCT_SIZE);
1856         COUNTER_ARRAY_FREE(bbr_state_lost, BBR_MAX_STAT);
1857         COUNTER_ARRAY_FREE(bbr_state_time, BBR_MAX_STAT);
1858         COUNTER_ARRAY_FREE(bbr_state_resend, BBR_MAX_STAT);
1859         counter_u64_free(bbr_nohdwr_pacing_enobuf);
1860         counter_u64_free(bbr_hdwr_pacing_enobuf);
1861         counter_u64_free(bbr_flows_whdwr_pacing);
1862         counter_u64_free(bbr_flows_nohdwr_pacing);
1863
1864 }
1865
1866 static __inline void
1867 bbr_fill_in_logging_data(struct tcp_bbr *bbr, struct tcp_log_bbr *l, uint32_t cts)
1868 {
1869         memset(l, 0, sizeof(union tcp_log_stackspecific));
1870         l->cur_del_rate = bbr->r_ctl.rc_bbr_cur_del_rate;
1871         l->delRate = get_filter_value(&bbr->r_ctl.rc_delrate);
1872         l->rttProp = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
1873         l->bw_inuse = bbr_get_bw(bbr);
1874         l->inflight = ctf_flight_size(bbr->rc_tp,
1875                           (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
1876         l->applimited = bbr->r_ctl.r_app_limited_until;
1877         l->delivered = bbr->r_ctl.rc_delivered;
1878         l->timeStamp = cts;
1879         l->lost = bbr->r_ctl.rc_lost;
1880         l->bbr_state = bbr->rc_bbr_state;
1881         l->bbr_substate = bbr_state_val(bbr);
1882         l->epoch = bbr->r_ctl.rc_rtt_epoch;
1883         l->lt_epoch = bbr->r_ctl.rc_lt_epoch;
1884         l->pacing_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
1885         l->cwnd_gain = bbr->r_ctl.rc_bbr_cwnd_gain;
1886         l->inhpts = bbr->rc_inp->inp_in_hpts;
1887         l->ininput = bbr->rc_inp->inp_in_input;
1888         l->use_lt_bw = bbr->rc_lt_use_bw;
1889         l->pkts_out = bbr->r_ctl.rc_flight_at_input;
1890         l->pkt_epoch = bbr->r_ctl.rc_pkt_epoch;
1891 }
1892
1893 static void
1894 bbr_log_type_bw_reduce(struct tcp_bbr *bbr, int reason)
1895 {
1896         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1897                 union tcp_log_stackspecific log;
1898
1899                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1900                 log.u_bbr.flex1 = 0;
1901                 log.u_bbr.flex2 = 0;
1902                 log.u_bbr.flex5 = 0;
1903                 log.u_bbr.flex3 = 0;
1904                 log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_loss_rate;
1905                 log.u_bbr.flex7 = reason;
1906                 log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_enters_probertt;
1907                 log.u_bbr.flex8 = 0;
1908                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1909                     &bbr->rc_inp->inp_socket->so_rcv,
1910                     &bbr->rc_inp->inp_socket->so_snd,
1911                     BBR_LOG_BW_RED_EV, 0,
1912                     0, &log, false, &bbr->rc_tv);
1913         }
1914 }
1915
1916 static void
1917 bbr_log_type_rwnd_collapse(struct tcp_bbr *bbr, int seq, int mode, uint32_t count)
1918 {
1919         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1920                 union tcp_log_stackspecific log;
1921
1922                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1923                 log.u_bbr.flex1 = seq;
1924                 log.u_bbr.flex2 = count;
1925                 log.u_bbr.flex8 = mode;
1926                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1927                     &bbr->rc_inp->inp_socket->so_rcv,
1928                     &bbr->rc_inp->inp_socket->so_snd,
1929                     BBR_LOG_LOWGAIN, 0,
1930                     0, &log, false, &bbr->rc_tv);
1931         }
1932 }
1933
1934 static void
1935 bbr_log_type_just_return(struct tcp_bbr *bbr, uint32_t cts, uint32_t tlen, uint8_t hpts_calling,
1936     uint8_t reason, uint32_t p_maxseg, int len)
1937 {
1938         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1939                 union tcp_log_stackspecific log;
1940
1941                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1942                 log.u_bbr.flex1 = p_maxseg;
1943                 log.u_bbr.flex2 = bbr->r_ctl.rc_hpts_flags;
1944                 log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
1945                 log.u_bbr.flex4 = reason;
1946                 log.u_bbr.flex5 = bbr->rc_in_persist;
1947                 log.u_bbr.flex6 = bbr->r_ctl.rc_last_delay_val;
1948                 log.u_bbr.flex7 = p_maxseg;
1949                 log.u_bbr.flex8 = bbr->rc_in_persist;
1950                 log.u_bbr.pkts_out = 0;
1951                 log.u_bbr.applimited = len;
1952                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1953                     &bbr->rc_inp->inp_socket->so_rcv,
1954                     &bbr->rc_inp->inp_socket->so_snd,
1955                     BBR_LOG_JUSTRET, 0,
1956                     tlen, &log, false, &bbr->rc_tv);
1957         }
1958 }
1959
1960 static void
1961 bbr_log_type_enter_rec(struct tcp_bbr *bbr, uint32_t seq)
1962 {
1963         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1964                 union tcp_log_stackspecific log;
1965
1966                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1967                 log.u_bbr.flex1 = seq;
1968                 log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
1969                 log.u_bbr.flex3 = bbr->r_ctl.rc_recovery_start;
1970                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1971                     &bbr->rc_inp->inp_socket->so_rcv,
1972                     &bbr->rc_inp->inp_socket->so_snd,
1973                     BBR_LOG_ENTREC, 0,
1974                     0, &log, false, &bbr->rc_tv);
1975         }
1976 }
1977
1978 static void
1979 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)
1980 {
1981         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
1982                 union tcp_log_stackspecific log;
1983
1984                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1985                 log.u_bbr.flex1 = tso;
1986                 log.u_bbr.flex2 = maxseg;
1987                 log.u_bbr.flex3 = mtu;
1988                 log.u_bbr.flex4 = csum_flags;
1989                 TCP_LOG_EVENTP(tp, NULL,
1990                     &bbr->rc_inp->inp_socket->so_rcv,
1991                     &bbr->rc_inp->inp_socket->so_snd,
1992                     BBR_LOG_MSGSIZE, 0,
1993                     0, &log, false, &bbr->rc_tv);
1994         }
1995 }
1996
1997 static void
1998 bbr_log_flowend(struct tcp_bbr *bbr)
1999 {
2000         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2001                 union tcp_log_stackspecific log;
2002                 struct sockbuf *r, *s;
2003                 struct timeval tv;
2004
2005                 if (bbr->rc_inp->inp_socket) {
2006                         r = &bbr->rc_inp->inp_socket->so_rcv;
2007                         s = &bbr->rc_inp->inp_socket->so_snd;
2008                 } else {
2009                         r = s = NULL;
2010                 }
2011                 bbr_fill_in_logging_data(bbr, &log.u_bbr, tcp_get_usecs(&tv));
2012                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2013                     r, s,
2014                     TCP_LOG_FLOWEND, 0,
2015                     0, &log, false, &tv);
2016         }
2017 }
2018
2019 static void
2020 bbr_log_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line,
2021     uint32_t lost, uint32_t del)
2022 {
2023         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2024                 union tcp_log_stackspecific log;
2025
2026                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2027                 log.u_bbr.flex1 = lost;
2028                 log.u_bbr.flex2 = del;
2029                 log.u_bbr.flex3 = bbr->r_ctl.rc_bbr_lastbtlbw;
2030                 log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_rtt;
2031                 log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2032                 log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2033                 log.u_bbr.flex7 = line;
2034                 log.u_bbr.flex8 = 0;
2035                 log.u_bbr.inflight = bbr->r_ctl.r_measurement_count;
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_PKT_EPOCH, 0,
2040                     0, &log, false, &bbr->rc_tv);
2041         }
2042 }
2043
2044 static void
2045 bbr_log_time_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line, uint32_t epoch_time)
2046 {
2047         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2048                 union tcp_log_stackspecific log;
2049
2050                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2051                 log.u_bbr.flex1 = bbr->r_ctl.rc_lost;
2052                 log.u_bbr.flex2 = bbr->rc_inp->inp_socket->so_snd.sb_lowat;
2053                 log.u_bbr.flex3 = bbr->rc_inp->inp_socket->so_snd.sb_hiwat;
2054                 log.u_bbr.flex7 = line;
2055                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2056                     &bbr->rc_inp->inp_socket->so_rcv,
2057                     &bbr->rc_inp->inp_socket->so_snd,
2058                     BBR_LOG_TIME_EPOCH, 0,
2059                     0, &log, false, &bbr->rc_tv);
2060         }
2061 }
2062
2063 static void
2064 bbr_log_set_of_state_target(struct tcp_bbr *bbr, uint32_t new_tar, int line, int meth)
2065 {
2066         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2067                 union tcp_log_stackspecific log;
2068
2069                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2070                 log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2071                 log.u_bbr.flex2 = new_tar;
2072                 log.u_bbr.flex3 = line;
2073                 log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2074                 log.u_bbr.flex5 = bbr_quanta;
2075                 log.u_bbr.flex6 = bbr->r_ctl.rc_pace_min_segs;
2076                 log.u_bbr.flex7 = bbr->rc_last_options;
2077                 log.u_bbr.flex8 = meth;
2078                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2079                     &bbr->rc_inp->inp_socket->so_rcv,
2080                     &bbr->rc_inp->inp_socket->so_snd,
2081                     BBR_LOG_STATE_TARGET, 0,
2082                     0, &log, false, &bbr->rc_tv);
2083         }
2084
2085 }
2086
2087 static void
2088 bbr_log_type_statechange(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2089 {
2090         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2091                 union tcp_log_stackspecific log;
2092
2093                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2094                 log.u_bbr.flex1 = line;
2095                 log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2096                 log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2097                 if (bbr_state_is_pkt_epoch)
2098                         log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
2099                 else
2100                         log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PROP);
2101                 log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2102                 log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2103                 log.u_bbr.flex7 = (bbr->r_ctl.rc_target_at_state/1000);
2104                 log.u_bbr.lt_epoch = bbr->r_ctl.rc_level_state_extra;
2105                 log.u_bbr.pkts_out = bbr->r_ctl.rc_target_at_state;
2106                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2107                     &bbr->rc_inp->inp_socket->so_rcv,
2108                     &bbr->rc_inp->inp_socket->so_snd,
2109                     BBR_LOG_STATE, 0,
2110                     0, &log, false, &bbr->rc_tv);
2111         }
2112 }
2113
2114 static void
2115 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
2116                     uint32_t rtt, uint32_t line, uint8_t reas, uint16_t cond)
2117 {
2118         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2119                 union tcp_log_stackspecific log;
2120
2121                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2122                 log.u_bbr.flex1 = line;
2123                 log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2124                 log.u_bbr.flex3 = bbr->r_ctl.last_in_probertt;
2125                 log.u_bbr.flex4 = applied;
2126                 log.u_bbr.flex5 = rtt;
2127                 log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2128                 log.u_bbr.flex7 = cond;
2129                 log.u_bbr.flex8 = reas;
2130                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2131                     &bbr->rc_inp->inp_socket->so_rcv,
2132                     &bbr->rc_inp->inp_socket->so_snd,
2133                     BBR_LOG_RTT_SHRINKS, 0,
2134                     0, &log, false, &bbr->rc_tv);
2135         }
2136 }
2137
2138 static void
2139 bbr_log_type_exit_rec(struct tcp_bbr *bbr)
2140 {
2141         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
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 = bbr->r_ctl.rc_recovery_start;
2146                 log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
2147                 log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2148                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2149                     &bbr->rc_inp->inp_socket->so_rcv,
2150                     &bbr->rc_inp->inp_socket->so_snd,
2151                     BBR_LOG_EXITREC, 0,
2152                     0, &log, false, &bbr->rc_tv);
2153         }
2154 }
2155
2156 static void
2157 bbr_log_type_cwndupd(struct tcp_bbr *bbr, uint32_t bytes_this_ack, uint32_t chg,
2158     uint32_t prev_acked, int32_t meth, uint32_t target, uint32_t th_ack, int32_t line)
2159 {
2160         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2161                 union tcp_log_stackspecific log;
2162
2163                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2164                 log.u_bbr.flex1 = line;
2165                 log.u_bbr.flex2 = prev_acked;
2166                 log.u_bbr.flex3 = bytes_this_ack;
2167                 log.u_bbr.flex4 = chg;
2168                 log.u_bbr.flex5 = th_ack;
2169                 log.u_bbr.flex6 = target;
2170                 log.u_bbr.flex8 = meth;
2171                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2172                     &bbr->rc_inp->inp_socket->so_rcv,
2173                     &bbr->rc_inp->inp_socket->so_snd,
2174                     BBR_LOG_CWND, 0,
2175                     0, &log, false, &bbr->rc_tv);
2176         }
2177 }
2178
2179 static void
2180 bbr_log_rtt_sample(struct tcp_bbr *bbr, uint32_t rtt, uint32_t tsin)
2181 {
2182         /*
2183          * Log the rtt sample we are applying to the srtt algorithm in
2184          * useconds.
2185          */
2186         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2187                 union tcp_log_stackspecific log;
2188
2189                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2190                 log.u_bbr.flex1 = rtt;
2191                 log.u_bbr.flex2 = bbr->r_ctl.rc_bbr_state_time;
2192                 log.u_bbr.flex3 = bbr->r_ctl.rc_ack_hdwr_delay;
2193                 log.u_bbr.flex4 = bbr->rc_tp->ts_offset;
2194                 log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2195                 log.u_bbr.pkts_out = tcp_tv_to_mssectick(&bbr->rc_tv);
2196                 log.u_bbr.flex6 = tsin;
2197                 log.u_bbr.flex7 = 0;
2198                 log.u_bbr.flex8 = bbr->rc_ack_was_delayed;
2199                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2200                     &bbr->rc_inp->inp_socket->so_rcv,
2201                     &bbr->rc_inp->inp_socket->so_snd,
2202                     TCP_LOG_RTT, 0,
2203                     0, &log, false, &bbr->rc_tv);
2204         }
2205 }
2206
2207 static void
2208 bbr_log_type_pesist(struct tcp_bbr *bbr, uint32_t cts, uint32_t time_in, int32_t line, uint8_t enter_exit)
2209 {
2210         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2211                 union tcp_log_stackspecific log;
2212
2213                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2214                 log.u_bbr.flex1 = time_in;
2215                 log.u_bbr.flex2 = line;
2216                 log.u_bbr.flex8 = enter_exit;
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_PERSIST, 0,
2221                     0, &log, false, &bbr->rc_tv);
2222         }
2223 }
2224 static void
2225 bbr_log_ack_clear(struct tcp_bbr *bbr, uint32_t cts)
2226 {
2227         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2228                 union tcp_log_stackspecific log;
2229
2230                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2231                 log.u_bbr.flex1 = bbr->rc_tp->ts_recent_age;
2232                 log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2233                 log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2234                 log.u_bbr.flex4 = bbr->r_ctl.rc_went_idle_time;
2235                 log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2236                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2237                     &bbr->rc_inp->inp_socket->so_rcv,
2238                     &bbr->rc_inp->inp_socket->so_snd,
2239                     BBR_LOG_ACKCLEAR, 0,
2240                     0, &log, false, &bbr->rc_tv);
2241         }
2242 }
2243
2244 static void
2245 bbr_log_ack_event(struct tcp_bbr *bbr, struct tcphdr *th, struct tcpopt *to, uint32_t tlen,
2246                   uint16_t nsegs, uint32_t cts, int32_t nxt_pkt, struct mbuf *m)
2247 {
2248         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2249                 union tcp_log_stackspecific log;
2250                 struct timeval tv;
2251
2252                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2253                 log.u_bbr.flex1 = nsegs;
2254                 log.u_bbr.flex2 = bbr->r_ctl.rc_lost_bytes;
2255                 if (m) {
2256                         struct timespec ts;
2257
2258                         log.u_bbr.flex3 = m->m_flags;
2259                         if (m->m_flags & M_TSTMP) {
2260                                 mbuf_tstmp2timespec(m, &ts);
2261                                 tv.tv_sec = ts.tv_sec;
2262                                 tv.tv_usec = ts.tv_nsec / 1000;
2263                                 log.u_bbr.lt_epoch = tcp_tv_to_usectick(&tv);
2264                         } else {
2265                                 log.u_bbr.lt_epoch = 0;
2266                         }
2267                         if (m->m_flags & M_TSTMP_LRO) {
2268                                 tv.tv_sec = m->m_pkthdr.rcv_tstmp / 1000000000;
2269                                 tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000) / 1000;
2270                                 log.u_bbr.flex5 = tcp_tv_to_usectick(&tv);
2271                         } else {
2272                                 /* No arrival timestamp */
2273                                 log.u_bbr.flex5 = 0;
2274                         }
2275
2276                         log.u_bbr.pkts_out = tcp_get_usecs(&tv);
2277                 } else {
2278                         log.u_bbr.flex3 = 0;
2279                         log.u_bbr.flex5 = 0;
2280                         log.u_bbr.flex6 = 0;
2281                         log.u_bbr.pkts_out = 0;
2282                 }
2283                 log.u_bbr.flex4 = bbr->r_ctl.rc_target_at_state;
2284                 log.u_bbr.flex7 = bbr->r_wanted_output;
2285                 log.u_bbr.flex8 = bbr->rc_in_persist;
2286                 TCP_LOG_EVENTP(bbr->rc_tp, th,
2287                     &bbr->rc_inp->inp_socket->so_rcv,
2288                     &bbr->rc_inp->inp_socket->so_snd,
2289                     TCP_LOG_IN, 0,
2290                     tlen, &log, true, &bbr->rc_tv);
2291         }
2292 }
2293
2294 static void
2295 bbr_log_doseg_done(struct tcp_bbr *bbr, uint32_t cts, int32_t nxt_pkt, int32_t did_out)
2296 {
2297         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2298                 union tcp_log_stackspecific log;
2299
2300                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2301                 log.u_bbr.flex1 = did_out;
2302                 log.u_bbr.flex2 = nxt_pkt;
2303                 log.u_bbr.flex3 = bbr->r_ctl.rc_last_delay_val;
2304                 log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2305                 log.u_bbr.flex5 = bbr->r_ctl.rc_timer_exp;
2306                 log.u_bbr.flex6 = bbr->r_ctl.rc_lost_bytes;
2307                 log.u_bbr.flex7 = bbr->r_wanted_output;
2308                 log.u_bbr.flex8 = bbr->rc_in_persist;
2309                 log.u_bbr.pkts_out = bbr->r_ctl.highest_hdwr_delay;
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_DOSEG_DONE, 0,
2314                     0, &log, true, &bbr->rc_tv);
2315         }
2316 }
2317
2318 static void
2319 bbr_log_enobuf_jmp(struct tcp_bbr *bbr, uint32_t len, uint32_t cts,
2320     int32_t line, uint32_t o_len, uint32_t segcnt, uint32_t segsiz)
2321 {
2322         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2323                 union tcp_log_stackspecific log;
2324
2325                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2326                 log.u_bbr.flex1 = line;
2327                 log.u_bbr.flex2 = o_len;
2328                 log.u_bbr.flex3 = segcnt;
2329                 log.u_bbr.flex4 = segsiz;
2330                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2331                     &bbr->rc_inp->inp_socket->so_rcv,
2332                     &bbr->rc_inp->inp_socket->so_snd,
2333                     BBR_LOG_ENOBUF_JMP, ENOBUFS,
2334                     len, &log, true, &bbr->rc_tv);
2335         }
2336 }
2337
2338 static void
2339 bbr_log_to_processing(struct tcp_bbr *bbr, uint32_t cts, int32_t ret, int32_t timers, uint8_t hpts_calling)
2340 {
2341         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2342                 union tcp_log_stackspecific log;
2343
2344                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2345                 log.u_bbr.flex1 = timers;
2346                 log.u_bbr.flex2 = ret;
2347                 log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
2348                 log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2349                 log.u_bbr.flex5 = cts;
2350                 log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2351                 log.u_bbr.flex8 = hpts_calling;
2352                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2353                     &bbr->rc_inp->inp_socket->so_rcv,
2354                     &bbr->rc_inp->inp_socket->so_snd,
2355                     BBR_LOG_TO_PROCESS, 0,
2356                     0, &log, false, &bbr->rc_tv);
2357         }
2358 }
2359
2360 static void
2361 bbr_log_to_event(struct tcp_bbr *bbr, uint32_t cts, int32_t to_num)
2362 {
2363         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2364                 union tcp_log_stackspecific log;
2365                 uint64_t ar;
2366
2367                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2368                 log.u_bbr.flex1 = bbr->bbr_timer_src;
2369                 log.u_bbr.flex2 = 0;
2370                 log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2371                 ar = (uint64_t)(bbr->r_ctl.rc_resend);
2372                 ar >>= 32;
2373                 ar &= 0x00000000ffffffff;
2374                 log.u_bbr.flex4 = (uint32_t)ar;
2375                 ar = (uint64_t)bbr->r_ctl.rc_resend;
2376                 ar &= 0x00000000ffffffff;
2377                 log.u_bbr.flex5 = (uint32_t)ar;
2378                 log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2379                 log.u_bbr.flex8 = to_num;
2380                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2381                     &bbr->rc_inp->inp_socket->so_rcv,
2382                     &bbr->rc_inp->inp_socket->so_snd,
2383                     BBR_LOG_RTO, 0,
2384                     0, &log, false, &bbr->rc_tv);
2385         }
2386 }
2387
2388 static void
2389 bbr_log_startup_event(struct tcp_bbr *bbr, uint32_t cts, uint32_t flex1, uint32_t flex2, uint32_t flex3, uint8_t reason)
2390 {
2391         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2392                 union tcp_log_stackspecific log;
2393
2394                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2395                 log.u_bbr.flex1 = flex1;
2396                 log.u_bbr.flex2 = flex2;
2397                 log.u_bbr.flex3 = flex3;
2398                 log.u_bbr.flex4 = 0;
2399                 log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2400                 log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2401                 log.u_bbr.flex8 = reason;
2402                 log.u_bbr.cur_del_rate = bbr->r_ctl.rc_bbr_lastbtlbw;
2403                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2404                     &bbr->rc_inp->inp_socket->so_rcv,
2405                     &bbr->rc_inp->inp_socket->so_snd,
2406                     BBR_LOG_REDUCE, 0,
2407                     0, &log, false, &bbr->rc_tv);
2408         }
2409 }
2410
2411 static void
2412 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag)
2413 {
2414         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2415                 union tcp_log_stackspecific log;
2416
2417                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2418                 log.u_bbr.flex1 = diag->p_nxt_slot;
2419                 log.u_bbr.flex2 = diag->p_cur_slot;
2420                 log.u_bbr.flex3 = diag->slot_req;
2421                 log.u_bbr.flex4 = diag->inp_hptsslot;
2422                 log.u_bbr.flex5 = diag->slot_remaining;
2423                 log.u_bbr.flex6 = diag->need_new_to;
2424                 log.u_bbr.flex7 = diag->p_hpts_active;
2425                 log.u_bbr.flex8 = diag->p_on_min_sleep;
2426                 /* Hijack other fields as needed  */
2427                 log.u_bbr.epoch = diag->have_slept;
2428                 log.u_bbr.lt_epoch = diag->yet_to_sleep;
2429                 log.u_bbr.pkts_out = diag->co_ret;
2430                 log.u_bbr.applimited = diag->hpts_sleep_time;
2431                 log.u_bbr.delivered = diag->p_prev_slot;
2432                 log.u_bbr.inflight = diag->p_runningtick;
2433                 log.u_bbr.bw_inuse = diag->wheel_tick;
2434                 log.u_bbr.rttProp = diag->wheel_cts;
2435                 log.u_bbr.delRate = diag->maxticks;
2436                 log.u_bbr.cur_del_rate = diag->p_curtick;
2437                 log.u_bbr.cur_del_rate <<= 32;
2438                 log.u_bbr.cur_del_rate |= diag->p_lasttick;
2439                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2440                     &bbr->rc_inp->inp_socket->so_rcv,
2441                     &bbr->rc_inp->inp_socket->so_snd,
2442                     BBR_LOG_HPTSDIAG, 0,
2443                     0, &log, false, &bbr->rc_tv);
2444         }
2445 }
2446
2447 static void
2448 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
2449     uint32_t thresh, uint32_t to)
2450 {
2451         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2452                 union tcp_log_stackspecific log;
2453
2454                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2455                 log.u_bbr.flex1 = bbr->rc_tp->t_rttvar;
2456                 log.u_bbr.flex2 = time_since_sent;
2457                 log.u_bbr.flex3 = srtt;
2458                 log.u_bbr.flex4 = thresh;
2459                 log.u_bbr.flex5 = to;
2460                 log.u_bbr.flex6 = bbr->rc_tp->t_srtt;
2461                 log.u_bbr.flex8 = mode;
2462                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2463                     &bbr->rc_inp->inp_socket->so_rcv,
2464                     &bbr->rc_inp->inp_socket->so_snd,
2465                     BBR_LOG_TIMERPREP, 0,
2466                     0, &log, false, &bbr->rc_tv);
2467         }
2468 }
2469
2470 static void
2471 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
2472     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod)
2473 {
2474         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2475                 union tcp_log_stackspecific log;
2476
2477                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2478                 log.u_bbr.flex1 = usecs;
2479                 log.u_bbr.flex2 = len;
2480                 log.u_bbr.flex3 = (uint32_t)((bw >> 32) & 0x00000000ffffffff);
2481                 log.u_bbr.flex4 = (uint32_t)(bw & 0x00000000ffffffff);
2482                 if (override)
2483                         log.u_bbr.flex5 = (1 << 2);
2484                 else
2485                         log.u_bbr.flex5 = 0;
2486                 log.u_bbr.flex6 = override;
2487                 log.u_bbr.flex7 = gain;
2488                 log.u_bbr.flex8 = mod;
2489                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2490                     &bbr->rc_inp->inp_socket->so_rcv,
2491                     &bbr->rc_inp->inp_socket->so_snd,
2492                     BBR_LOG_HPTSI_CALC, 0,
2493                     len, &log, false, &bbr->rc_tv);
2494         }
2495 }
2496
2497 static void
2498 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2499 {
2500         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2501                 union tcp_log_stackspecific log;
2502
2503                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2504
2505                 log.u_bbr.flex1 = bbr->bbr_timer_src;
2506                 log.u_bbr.flex2 = to;
2507                 log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2508                 log.u_bbr.flex4 = slot;
2509                 log.u_bbr.flex5 = bbr->rc_inp->inp_hptsslot;
2510                 log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2511                 log.u_bbr.pkts_out = bbr->rc_inp->inp_flags2;
2512                 log.u_bbr.flex8 = which;
2513                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2514                     &bbr->rc_inp->inp_socket->so_rcv,
2515                     &bbr->rc_inp->inp_socket->so_snd,
2516                     BBR_LOG_TIMERSTAR, 0,
2517                     0, &log, false, &bbr->rc_tv);
2518         }
2519 }
2520
2521 static void
2522 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)
2523 {
2524         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2525                 union tcp_log_stackspecific log;
2526
2527                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2528                 log.u_bbr.flex1 = thresh;
2529                 log.u_bbr.flex2 = lro;
2530                 log.u_bbr.flex3 = bbr->r_ctl.rc_reorder_ts;
2531                 log.u_bbr.flex4 = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
2532                 log.u_bbr.flex5 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2533                 log.u_bbr.flex6 = srtt;
2534                 log.u_bbr.flex7 = bbr->r_ctl.rc_reorder_shift;
2535                 log.u_bbr.flex8 = frm;
2536                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2537                     &bbr->rc_inp->inp_socket->so_rcv,
2538                     &bbr->rc_inp->inp_socket->so_snd,
2539                     BBR_LOG_THRESH_CALC, 0,
2540                     0, &log, false, &bbr->rc_tv);
2541         }
2542 }
2543
2544 static void
2545 bbr_log_to_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts, uint8_t hpts_removed)
2546 {
2547         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2548                 union tcp_log_stackspecific log;
2549
2550                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2551                 log.u_bbr.flex1 = line;
2552                 log.u_bbr.flex2 = bbr->bbr_timer_src;
2553                 log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2554                 log.u_bbr.flex4 = bbr->rc_in_persist;
2555                 log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2556                 log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2557                 log.u_bbr.flex8 = hpts_removed;
2558                 log.u_bbr.pkts_out = bbr->rc_pacer_started;
2559                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2560                     &bbr->rc_inp->inp_socket->so_rcv,
2561                     &bbr->rc_inp->inp_socket->so_snd,
2562                     BBR_LOG_TIMERCANC, 0,
2563                     0, &log, false, &bbr->rc_tv);
2564         }
2565 }
2566
2567 static void
2568 bbr_log_tstmp_validation(struct tcp_bbr *bbr, uint64_t peer_delta, uint64_t delta)
2569 {
2570         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2571                 union tcp_log_stackspecific log;
2572
2573                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2574                 log.u_bbr.flex1 = bbr->r_ctl.bbr_peer_tsratio;
2575                 log.u_bbr.flex2 = (peer_delta >> 32);
2576                 log.u_bbr.flex3 = (peer_delta & 0x00000000ffffffff);
2577                 log.u_bbr.flex4 = (delta >> 32);
2578                 log.u_bbr.flex5 = (delta & 0x00000000ffffffff);
2579                 log.u_bbr.flex7 = bbr->rc_ts_clock_set;
2580                 log.u_bbr.flex8 = bbr->rc_ts_cant_be_used;
2581                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2582                     &bbr->rc_inp->inp_socket->so_rcv,
2583                     &bbr->rc_inp->inp_socket->so_snd,
2584                     BBR_LOG_TSTMP_VAL, 0,
2585                     0, &log, false, &bbr->rc_tv);
2586         }
2587 }
2588
2589 static void
2590 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)
2591 {
2592         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2593                 union tcp_log_stackspecific log;
2594
2595                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2596                 log.u_bbr.flex1 = tsosz;
2597                 log.u_bbr.flex2 = tls;
2598                 log.u_bbr.flex3 = tcp_min_hptsi_time;
2599                 log.u_bbr.flex4 = bbr->r_ctl.bbr_hptsi_bytes_min;
2600                 log.u_bbr.flex5 = old_val;
2601                 log.u_bbr.flex6 = maxseg;
2602                 log.u_bbr.flex7 = bbr->rc_no_pacing;
2603                 log.u_bbr.flex7 <<= 1;
2604                 log.u_bbr.flex7 |= bbr->rc_past_init_win;
2605                 if (hdwr)
2606                         log.u_bbr.flex8 = 0x80 | bbr->rc_use_google;
2607                 else
2608                         log.u_bbr.flex8 = bbr->rc_use_google;
2609                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2610                     &bbr->rc_inp->inp_socket->so_rcv,
2611                     &bbr->rc_inp->inp_socket->so_snd,
2612                     BBR_LOG_BBRTSO, 0,
2613                     0, &log, false, &bbr->rc_tv);
2614         }
2615 }
2616
2617 static void
2618 bbr_log_type_rsmclear(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm,
2619                       uint32_t flags, uint32_t line)
2620 {
2621         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2622                 union tcp_log_stackspecific log;
2623
2624                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2625                 log.u_bbr.flex1 = line;
2626                 log.u_bbr.flex2 = rsm->r_start;
2627                 log.u_bbr.flex3 = rsm->r_end;
2628                 log.u_bbr.flex4 = rsm->r_delivered;
2629                 log.u_bbr.flex5 = rsm->r_rtr_cnt;
2630                 log.u_bbr.flex6 = rsm->r_dupack;
2631                 log.u_bbr.flex7 = rsm->r_tim_lastsent[0];
2632                 log.u_bbr.flex8 = rsm->r_flags;
2633                 /* Hijack the pkts_out fids */
2634                 log.u_bbr.applimited = flags;
2635                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2636                     &bbr->rc_inp->inp_socket->so_rcv,
2637                     &bbr->rc_inp->inp_socket->so_snd,
2638                     BBR_RSM_CLEARED, 0,
2639                     0, &log, false, &bbr->rc_tv);
2640         }
2641 }
2642
2643 static void
2644 bbr_log_type_bbrupd(struct tcp_bbr *bbr, uint8_t flex8, uint32_t cts,
2645     uint32_t flex3, uint32_t flex2, uint32_t flex5,
2646     uint32_t flex6, uint32_t pkts_out, int flex7,
2647     uint32_t flex4, uint32_t flex1)
2648 {
2649
2650         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2651                 union tcp_log_stackspecific log;
2652
2653                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2654                 log.u_bbr.flex1 = flex1;
2655                 log.u_bbr.flex2 = flex2;
2656                 log.u_bbr.flex3 = flex3;
2657                 log.u_bbr.flex4 = flex4;
2658                 log.u_bbr.flex5 = flex5;
2659                 log.u_bbr.flex6 = flex6;
2660                 log.u_bbr.flex7 = flex7;
2661                 /* Hijack the pkts_out fids */
2662                 log.u_bbr.pkts_out = pkts_out;
2663                 log.u_bbr.flex8 = flex8;
2664                 if (bbr->rc_ack_was_delayed)
2665                         log.u_bbr.epoch = bbr->r_ctl.rc_ack_hdwr_delay;
2666                 else
2667                         log.u_bbr.epoch = 0;
2668                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2669                     &bbr->rc_inp->inp_socket->so_rcv,
2670                     &bbr->rc_inp->inp_socket->so_snd,
2671                     BBR_LOG_BBRUPD, 0,
2672                     flex2, &log, false, &bbr->rc_tv);
2673         }
2674 }
2675
2676 static void
2677 bbr_log_type_ltbw(struct tcp_bbr *bbr, uint32_t cts, int32_t reason,
2678         uint32_t newbw, uint32_t obw, uint32_t diff,
2679         uint32_t tim)
2680 {
2681         if (/*bbr_verbose_logging && */(bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2682                 union tcp_log_stackspecific log;
2683
2684                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2685                 log.u_bbr.flex1 = reason;
2686                 log.u_bbr.flex2 = newbw;
2687                 log.u_bbr.flex3 = obw;
2688                 log.u_bbr.flex4 = diff;
2689                 log.u_bbr.flex5 = bbr->r_ctl.rc_lt_lost;
2690                 log.u_bbr.flex6 = bbr->r_ctl.rc_lt_del;
2691                 log.u_bbr.flex7 = bbr->rc_lt_is_sampling;
2692                 log.u_bbr.pkts_out = tim;
2693                 log.u_bbr.bw_inuse = bbr->r_ctl.rc_lt_bw;
2694                 if (bbr->rc_lt_use_bw == 0)
2695                         log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
2696                 else
2697                         log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
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_BWSAMP, 0,
2702                     0, &log, false, &bbr->rc_tv);
2703         }
2704 }
2705
2706 static inline void
2707 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line)
2708 {
2709         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2710                 union tcp_log_stackspecific log;
2711
2712                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2713                 log.u_bbr.flex1 = line;
2714                 log.u_bbr.flex2 = tick;
2715                 log.u_bbr.flex3 = tp->t_maxunacktime;
2716                 log.u_bbr.flex4 = tp->t_acktime;
2717                 log.u_bbr.flex8 = event;
2718                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2719                     &bbr->rc_inp->inp_socket->so_rcv,
2720                     &bbr->rc_inp->inp_socket->so_snd,
2721                     BBR_LOG_PROGRESS, 0,
2722                     0, &log, false, &bbr->rc_tv);
2723         }
2724 }
2725
2726 static void
2727 bbr_type_log_hdwr_pacing(struct tcp_bbr *bbr, const struct ifnet *ifp,
2728                          uint64_t rate, uint64_t hw_rate, int line, uint32_t cts,
2729                          int error)
2730 {
2731         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2732                 union tcp_log_stackspecific log;
2733
2734                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2735                 log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2736                 log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2737                 log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2738                 log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2739                 log.u_bbr.bw_inuse = rate;
2740                 log.u_bbr.flex5 = line;
2741                 log.u_bbr.flex6 = error;
2742                 log.u_bbr.flex8 = bbr->skip_gain;
2743                 log.u_bbr.flex8 <<= 1;
2744                 log.u_bbr.flex8 |= bbr->gain_is_limited;
2745                 log.u_bbr.flex8 <<= 1;
2746                 log.u_bbr.flex8 |= bbr->bbr_hdrw_pacing;
2747                 log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
2748                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2749                     &bbr->rc_inp->inp_socket->so_rcv,
2750                     &bbr->rc_inp->inp_socket->so_snd,
2751                     BBR_LOG_HDWR_PACE, 0,
2752                     0, &log, false, &bbr->rc_tv);
2753         }
2754 }
2755
2756 static void
2757 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)
2758 {
2759         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2760                 union tcp_log_stackspecific log;
2761
2762                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2763                 log.u_bbr.flex1 = slot;
2764                 log.u_bbr.flex2 = del_by;
2765                 log.u_bbr.flex3 = prev_delay;
2766                 log.u_bbr.flex4 = line;
2767                 log.u_bbr.flex5 = bbr->r_ctl.rc_last_delay_val;
2768                 log.u_bbr.flex6 = bbr->r_ctl.rc_hptsi_agg_delay;
2769                 log.u_bbr.flex7 = (0x0000ffff & bbr->r_ctl.rc_hpts_flags);
2770                 log.u_bbr.flex8 = bbr->rc_in_persist;
2771                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2772                     &bbr->rc_inp->inp_socket->so_rcv,
2773                     &bbr->rc_inp->inp_socket->so_snd,
2774                     BBR_LOG_BBRSND, 0,
2775                     len, &log, false, &bbr->rc_tv);
2776         }
2777 }
2778
2779 static void
2780 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)
2781 {
2782         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2783                 union tcp_log_stackspecific log;
2784
2785                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2786                 log.u_bbr.flex1 = bbr->r_ctl.rc_delivered;
2787                 log.u_bbr.flex2 = 0;
2788                 log.u_bbr.flex3 = bbr->r_ctl.rc_lowest_rtt;
2789                 log.u_bbr.flex4 = end;
2790                 log.u_bbr.flex5 = seq;
2791                 log.u_bbr.flex6 = t;
2792                 log.u_bbr.flex7 = match;
2793                 log.u_bbr.flex8 = flags;
2794                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2795                     &bbr->rc_inp->inp_socket->so_rcv,
2796                     &bbr->rc_inp->inp_socket->so_snd,
2797                     BBR_LOG_BBRRTT, 0,
2798                     0, &log, false, &bbr->rc_tv);
2799         }
2800 }
2801
2802 static void
2803 bbr_log_exit_gain(struct tcp_bbr *bbr, uint32_t cts, int32_t entry_method)
2804 {
2805         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2806                 union tcp_log_stackspecific log;
2807
2808                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2809                 log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2810                 log.u_bbr.flex2 = (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
2811                 log.u_bbr.flex3 = bbr->r_ctl.gain_epoch;
2812                 log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2813                 log.u_bbr.flex5 = bbr->r_ctl.rc_pace_min_segs;
2814                 log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_state_atflight;
2815                 log.u_bbr.flex7 = 0;
2816                 log.u_bbr.flex8 = entry_method;
2817                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2818                     &bbr->rc_inp->inp_socket->so_rcv,
2819                     &bbr->rc_inp->inp_socket->so_snd,
2820                     BBR_LOG_EXIT_GAIN, 0,
2821                     0, &log, false, &bbr->rc_tv);
2822         }
2823 }
2824
2825 static void
2826 bbr_log_settings_change(struct tcp_bbr *bbr, int settings_desired)
2827 {
2828         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2829                 union tcp_log_stackspecific log;
2830
2831                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2832                 /* R-HU */
2833                 log.u_bbr.flex1 = 0;
2834                 log.u_bbr.flex2 = 0;
2835                 log.u_bbr.flex3 = 0;
2836                 log.u_bbr.flex4 = 0;
2837                 log.u_bbr.flex7 = 0;
2838                 log.u_bbr.flex8 = settings_desired;
2839
2840                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2841                     &bbr->rc_inp->inp_socket->so_rcv,
2842                     &bbr->rc_inp->inp_socket->so_snd,
2843                     BBR_LOG_SETTINGS_CHG, 0,
2844                     0, &log, false, &bbr->rc_tv);
2845         }
2846 }
2847
2848 /*
2849  * Returns the bw from the our filter.
2850  */
2851 static inline uint64_t
2852 bbr_get_full_bw(struct tcp_bbr *bbr)
2853 {
2854         uint64_t bw;
2855
2856         bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2857
2858         return (bw);
2859 }
2860
2861 static inline void
2862 bbr_set_pktepoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2863 {
2864         uint64_t calclr;
2865         uint32_t lost, del;
2866
2867         if (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_pktepoch)
2868                 lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lost_at_pktepoch;
2869         else
2870                 lost = 0;
2871         del = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_pkt_epoch_del;
2872         if (lost == 0)  {
2873                 calclr = 0;
2874         } else if (del) {
2875                 calclr = lost;
2876                 calclr *= (uint64_t)1000;
2877                 calclr /= (uint64_t)del;
2878         } else {
2879                 /* Nothing delivered? 100.0% loss */
2880                 calclr = 1000;
2881         }
2882         bbr->r_ctl.rc_pkt_epoch_loss_rate =  (uint32_t)calclr;
2883         if (IN_RECOVERY(bbr->rc_tp->t_flags))
2884                 bbr->r_ctl.recovery_lr += (uint32_t)calclr;
2885         bbr->r_ctl.rc_pkt_epoch++;
2886         if (bbr->rc_no_pacing &&
2887             (bbr->r_ctl.rc_pkt_epoch >= bbr->no_pacing_until)) {
2888                 bbr->rc_no_pacing = 0;
2889                 tcp_bbr_tso_size_check(bbr, cts);
2890         }
2891         bbr->r_ctl.rc_pkt_epoch_rtt = bbr_calc_time(cts, bbr->r_ctl.rc_pkt_epoch_time);
2892         bbr->r_ctl.rc_pkt_epoch_time = cts;
2893         /* What was our loss rate */
2894         bbr_log_pkt_epoch(bbr, cts, line, lost, del);
2895         bbr->r_ctl.rc_pkt_epoch_del = bbr->r_ctl.rc_delivered;
2896         bbr->r_ctl.rc_lost_at_pktepoch = bbr->r_ctl.rc_lost;
2897 }
2898
2899 static inline void
2900 bbr_set_epoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2901 {
2902         uint32_t epoch_time;
2903
2904         /* Tick the RTT clock */
2905         bbr->r_ctl.rc_rtt_epoch++;
2906         epoch_time = cts - bbr->r_ctl.rc_rcv_epoch_start;
2907         bbr_log_time_epoch(bbr, cts, line, epoch_time);
2908         bbr->r_ctl.rc_rcv_epoch_start = cts;
2909 }
2910
2911 static inline void
2912 bbr_isit_a_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm, int32_t line, int32_t cum_acked)
2913 {
2914         if (SEQ_GEQ(rsm->r_delivered, bbr->r_ctl.rc_pkt_epoch_del)) {
2915                 bbr->rc_is_pkt_epoch_now = 1;
2916         }
2917 }
2918
2919 /*
2920  * Returns the bw from either the b/w filter
2921  * or from the lt_bw (if the connection is being
2922  * policed).
2923  */
2924 static inline uint64_t
2925 __bbr_get_bw(struct tcp_bbr *bbr)
2926 {
2927         uint64_t bw, min_bw;
2928         uint64_t rtt;
2929         int gm_measure_cnt = 1;
2930
2931         /*
2932          * For startup we make, like google, a
2933          * minimum b/w. This is generated from the
2934          * IW and the rttProp. We do fall back to srtt
2935          * if for some reason (initial handshake) we don't
2936          * have a rttProp. We, in the worst case, fall back
2937          * to the configured min_bw (rc_initial_hptsi_bw).
2938          */
2939         if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
2940                 /* Attempt first to use rttProp */
2941                 rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2942                 if (rtt && (rtt < 0xffffffff)) {
2943 measure:
2944                         min_bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2945                                 ((uint64_t)1000000);
2946                         min_bw /= rtt;
2947                         if (min_bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2948                                 min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2949                         }
2950
2951                 } else if (bbr->rc_tp->t_srtt != 0) {
2952                         /* No rttProp, use srtt? */
2953                         rtt = bbr_get_rtt(bbr, BBR_SRTT);
2954                         goto measure;
2955                 } else {
2956                         min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2957                 }
2958         } else
2959                 min_bw = 0;
2960
2961         if ((bbr->rc_past_init_win == 0) &&
2962             (bbr->r_ctl.rc_delivered > bbr_initial_cwnd(bbr, bbr->rc_tp)))
2963                 bbr->rc_past_init_win = 1;
2964         if ((bbr->rc_use_google)  && (bbr->r_ctl.r_measurement_count >= 1))
2965                 gm_measure_cnt = 0;
2966         if (gm_measure_cnt &&
2967             ((bbr->r_ctl.r_measurement_count < bbr_min_measurements_req) ||
2968              (bbr->rc_past_init_win == 0))) {
2969                 /* For google we use our guess rate until we get 1 measurement */
2970
2971 use_initial_window:
2972                 rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2973                 if (rtt && (rtt < 0xffffffff)) {
2974                         /*
2975                          * We have an RTT measurment. Use that in
2976                          * combination with our initial window to calculate
2977                          * a b/w.
2978                          */
2979                         bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2980                                 ((uint64_t)1000000);
2981                         bw /= rtt;
2982                         if (bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2983                                 bw = bbr->r_ctl.rc_initial_hptsi_bw;
2984                         }
2985                 } else {
2986                         /* Drop back to the 40 and punt to a default */
2987                         bw = bbr->r_ctl.rc_initial_hptsi_bw;
2988                 }
2989                 if (bw < 1)
2990                         /* Probably should panic */
2991                         bw = 1;
2992                 if (bw > min_bw)
2993                         return (bw);
2994                 else
2995                         return (min_bw);
2996         }
2997         if (bbr->rc_lt_use_bw)
2998                 bw = bbr->r_ctl.rc_lt_bw;
2999         else if (bbr->r_recovery_bw && (bbr->rc_use_google == 0))
3000                 bw = bbr->r_ctl.red_bw;
3001         else
3002                 bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3003         if (bbr->rc_tp->t_peakrate_thr && (bbr->rc_use_google == 0)) {
3004                 /*
3005                  * Enforce user set rate limit, keep in mind that
3006                  * t_peakrate_thr is in B/s already
3007                  */
3008                 bw = uqmin((uint64_t)bbr->rc_tp->t_peakrate_thr, bw);
3009         }
3010         if (bw == 0) {
3011                 /* We should not be at 0, go to the initial window then  */
3012                 goto use_initial_window;
3013         }
3014         if (bw < 1)
3015                 /* Probably should panic */
3016                 bw = 1;
3017         if (bw < min_bw)
3018                 bw = min_bw;
3019         return (bw);
3020 }
3021
3022 static inline uint64_t
3023 bbr_get_bw(struct tcp_bbr *bbr)
3024 {
3025         uint64_t bw;
3026
3027         bw = __bbr_get_bw(bbr);
3028         return (bw);
3029 }
3030
3031 static inline void
3032 bbr_reset_lt_bw_interval(struct tcp_bbr *bbr, uint32_t cts)
3033 {
3034         bbr->r_ctl.rc_lt_epoch = bbr->r_ctl.rc_pkt_epoch;
3035         bbr->r_ctl.rc_lt_time = bbr->r_ctl.rc_del_time;
3036         bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3037         bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3038 }
3039
3040 static inline void
3041 bbr_reset_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts)
3042 {
3043         bbr->rc_lt_is_sampling = 0;
3044         bbr->rc_lt_use_bw = 0;
3045         bbr->r_ctl.rc_lt_bw = 0;
3046         bbr_reset_lt_bw_interval(bbr, cts);
3047 }
3048
3049 static inline void
3050 bbr_lt_bw_samp_done(struct tcp_bbr *bbr, uint64_t bw, uint32_t cts, uint32_t timin)
3051 {
3052         uint64_t diff;
3053
3054         /* Do we have a previous sample? */
3055         if (bbr->r_ctl.rc_lt_bw) {
3056                 /* Get the diff in bytes per second */
3057                 if (bbr->r_ctl.rc_lt_bw > bw)
3058                         diff = bbr->r_ctl.rc_lt_bw - bw;
3059                 else
3060                         diff = bw - bbr->r_ctl.rc_lt_bw;
3061                 if ((diff <= bbr_lt_bw_diff) ||
3062                     (diff <= (bbr->r_ctl.rc_lt_bw / bbr_lt_bw_ratio))) {
3063                         /* Consider us policed */
3064                         uint32_t saved_bw;
3065
3066                         saved_bw = (uint32_t)bbr->r_ctl.rc_lt_bw;
3067                         bbr->r_ctl.rc_lt_bw = (bw + bbr->r_ctl.rc_lt_bw) / 2;   /* average of two */
3068                         bbr->rc_lt_use_bw = 1;
3069                         bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
3070                         /*
3071                          * Use pkt based epoch for measuring length of
3072                          * policer up
3073                          */
3074                         bbr->r_ctl.rc_lt_epoch_use = bbr->r_ctl.rc_pkt_epoch;
3075                         /*
3076                          * reason 4 is we need to start consider being
3077                          * policed
3078                          */
3079                         bbr_log_type_ltbw(bbr, cts, 4, (uint32_t)bw, saved_bw, (uint32_t)diff, timin);
3080                         return;
3081                 }
3082         }
3083         bbr->r_ctl.rc_lt_bw = bw;
3084         bbr_reset_lt_bw_interval(bbr, cts);
3085         bbr_log_type_ltbw(bbr, cts, 5, 0, (uint32_t)bw, 0, timin);
3086 }
3087
3088 static void
3089 bbr_randomize_extra_state_time(struct tcp_bbr *bbr)
3090 {
3091         uint32_t ran, deduct;
3092
3093         ran = arc4random_uniform(bbr_rand_ot);
3094         if (ran) {
3095                 deduct = bbr->r_ctl.rc_level_state_extra / ran;
3096                 bbr->r_ctl.rc_level_state_extra -= deduct;
3097         }
3098 }
3099 /*
3100  * Return randomly the starting state
3101  * to use in probebw.
3102  */
3103 static uint8_t
3104 bbr_pick_probebw_substate(struct tcp_bbr *bbr, uint32_t cts)
3105 {
3106         uint32_t ran;
3107         uint8_t ret_val;
3108
3109         /* Initialize the offset to 0 */
3110         bbr->r_ctl.rc_exta_time_gd = 0;
3111         bbr->rc_hit_state_1 = 0;
3112         bbr->r_ctl.rc_level_state_extra = 0;
3113         ran = arc4random_uniform((BBR_SUBSTATE_COUNT-1));
3114         /*
3115          * The math works funny here :) the return value is used to set the
3116          * substate and then the state change is called which increments by
3117          * one. So if we return 1 (DRAIN) we will increment to 2 (LEVEL1) when
3118          * we fully enter the state. Note that the (8 - 1 - ran) assures that
3119          * we return 1 - 7, so we dont return 0 and end up starting in
3120          * state 1 (DRAIN).
3121          */
3122         ret_val = BBR_SUBSTATE_COUNT - 1 - ran;
3123         /* Set an epoch */
3124         if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP))
3125                 bbr_set_epoch(bbr, cts, __LINE__);
3126
3127         bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
3128         return (ret_val);
3129 }
3130
3131 static void
3132 bbr_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts, int32_t loss_detected)
3133 {
3134         uint32_t diff, d_time;
3135         uint64_t del_time, bw, lost, delivered;
3136
3137         if (bbr->r_use_policer == 0)
3138                 return;
3139         if (bbr->rc_lt_use_bw) {
3140                 /* We are using lt bw do we stop yet? */
3141                 diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
3142                 if (diff > bbr_lt_bw_max_rtts) {
3143                         /* Reset it all */
3144 reset_all:
3145                         bbr_reset_lt_bw_sampling(bbr, cts);
3146                         if (bbr->rc_filled_pipe) {
3147                                 bbr_set_epoch(bbr, cts, __LINE__);
3148                                 bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
3149                                 bbr_substate_change(bbr, cts, __LINE__, 0);
3150                                 bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
3151                                 bbr_log_type_statechange(bbr, cts, __LINE__);
3152                         } else {
3153                                 /*
3154                                  * This should not happen really
3155                                  * unless we remove the startup/drain
3156                                  * restrictions above.
3157                                  */
3158                                 bbr->rc_bbr_state = BBR_STATE_STARTUP;
3159                                 bbr_set_epoch(bbr, cts, __LINE__);
3160                                 bbr->r_ctl.rc_bbr_state_time = cts;
3161                                 bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
3162                                 bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
3163                                 bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
3164                                 bbr_set_state_target(bbr, __LINE__);
3165                                 bbr_log_type_statechange(bbr, cts, __LINE__);
3166                         }
3167                         /* reason 0 is to stop using lt-bw */
3168                         bbr_log_type_ltbw(bbr, cts, 0, 0, 0, 0, 0);
3169                         return;
3170                 }
3171                 if (bbr_lt_intvl_fp == 0) {
3172                         /* Not doing false-postive detection */
3173                         return;
3174                 }
3175                 /* False positive detection */
3176                 if (diff == bbr_lt_intvl_fp) {
3177                         /* At bbr_lt_intvl_fp we record the lost */
3178                         bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3179                         bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3180                 } else if (diff > (bbr_lt_intvl_min_rtts + bbr_lt_intvl_fp)) {
3181                         /* Now is our loss rate still high? */
3182                         lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3183                         delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3184                         if ((delivered == 0) ||
3185                             (((lost * 1000)/delivered) < bbr_lt_fd_thresh)) {
3186                                 /* No still below our threshold */
3187                                 bbr_log_type_ltbw(bbr, cts, 7, lost, delivered, 0, 0);
3188                         } else {
3189                                 /* Yikes its still high, it must be a false positive */
3190                                 bbr_log_type_ltbw(bbr, cts, 8, lost, delivered, 0, 0);
3191                                 goto reset_all;
3192                         }
3193                 }
3194                 return;
3195         }
3196         /*
3197          * Wait for the first loss before sampling, to let the policer
3198          * exhaust its tokens and estimate the steady-state rate allowed by
3199          * the policer. Starting samples earlier includes bursts that
3200          * over-estimate the bw.
3201          */
3202         if (bbr->rc_lt_is_sampling == 0) {
3203                 /* reason 1 is to begin doing the sampling  */
3204                 if (loss_detected == 0)
3205                         return;
3206                 bbr_reset_lt_bw_interval(bbr, cts);
3207                 bbr->rc_lt_is_sampling = 1;
3208                 bbr_log_type_ltbw(bbr, cts, 1, 0, 0, 0, 0);
3209                 return;
3210         }
3211         /* Now how long were we delivering long term last> */
3212         if (TSTMP_GEQ(bbr->r_ctl.rc_del_time, bbr->r_ctl.rc_lt_time))
3213                 d_time = bbr->r_ctl.rc_del_time - bbr->r_ctl.rc_lt_time;
3214         else
3215                 d_time = 0;
3216
3217         /* To avoid underestimates, reset sampling if we run out of data. */
3218         if (bbr->r_ctl.r_app_limited_until) {
3219                 /* Can not measure in app-limited state */
3220                 bbr_reset_lt_bw_sampling(bbr, cts);
3221                 /* reason 2 is to reset sampling due to app limits  */
3222                 bbr_log_type_ltbw(bbr, cts, 2, 0, 0, 0, d_time);
3223                 return;
3224         }
3225         diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
3226         if (diff < bbr_lt_intvl_min_rtts) {
3227                 /*
3228                  * need more samples (we don't
3229                  * start on a round like linux so
3230                  * we need 1 more).
3231                  */
3232                 /* 6 is not_enough time or no-loss */
3233                 bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3234                 return;
3235         }
3236         if (diff > (4 * bbr_lt_intvl_min_rtts)) {
3237                 /*
3238                  * For now if we wait too long, reset all sampling. We need
3239                  * to do some research here, its possible that we should
3240                  * base this on how much loss as occurred.. something like
3241                  * if its under 10% (or some thresh) reset all otherwise
3242                  * don't.  Thats for phase II I guess.
3243                  */
3244                 bbr_reset_lt_bw_sampling(bbr, cts);
3245                 /* reason 3 is to reset sampling due too long of sampling */
3246                 bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3247                 return;
3248         }
3249         /*
3250          * End sampling interval when a packet is lost, so we estimate the
3251          * policer tokens were exhausted. Stopping the sampling before the
3252          * tokens are exhausted under-estimates the policed rate.
3253          */
3254         if (loss_detected == 0) {
3255                 /* 6 is not_enough time or no-loss */
3256                 bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3257                 return;
3258         }
3259         /* Calculate packets lost and delivered in sampling interval. */
3260         lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3261         delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3262         if ((delivered == 0) ||
3263             (((lost * 1000)/delivered) < bbr_lt_loss_thresh)) {
3264                 bbr_log_type_ltbw(bbr, cts, 6, lost, delivered, 0, d_time);
3265                 return;
3266         }
3267         if (d_time < 1000) {
3268                 /* Not enough time. wait */
3269                 /* 6 is not_enough time or no-loss */
3270                 bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3271                 return;
3272         }
3273         if (d_time >= (0xffffffff / USECS_IN_MSEC)) {
3274                 /* Too long */
3275                 bbr_reset_lt_bw_sampling(bbr, cts);
3276                 /* reason 3 is to reset sampling due too long of sampling */
3277                 bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3278                 return;
3279         }
3280         del_time = d_time;
3281         bw = delivered;
3282         bw *= (uint64_t)USECS_IN_SECOND;
3283         bw /= del_time;
3284         bbr_lt_bw_samp_done(bbr, bw, cts, d_time);
3285 }
3286
3287 /*
3288  * Allocate a sendmap from our zone.
3289  */
3290 static struct bbr_sendmap *
3291 bbr_alloc(struct tcp_bbr *bbr)
3292 {
3293         struct bbr_sendmap *rsm;
3294
3295         BBR_STAT_INC(bbr_to_alloc);
3296         rsm = uma_zalloc(bbr_zone, (M_NOWAIT | M_ZERO));
3297         if (rsm) {
3298                 bbr->r_ctl.rc_num_maps_alloced++;
3299                 return (rsm);
3300         }
3301         if (bbr->r_ctl.rc_free_cnt) {
3302                 BBR_STAT_INC(bbr_to_alloc_emerg);
3303                 rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
3304                 TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
3305                 bbr->r_ctl.rc_free_cnt--;
3306                 return (rsm);
3307         }
3308         BBR_STAT_INC(bbr_to_alloc_failed);
3309         return (NULL);
3310 }
3311
3312 static struct bbr_sendmap *
3313 bbr_alloc_full_limit(struct tcp_bbr *bbr)
3314 {
3315         if ((V_tcp_map_entries_limit > 0) &&
3316             (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
3317                 BBR_STAT_INC(bbr_alloc_limited);
3318                 if (!bbr->alloc_limit_reported) {
3319                         bbr->alloc_limit_reported = 1;
3320                         BBR_STAT_INC(bbr_alloc_limited_conns);
3321                 }
3322                 return (NULL);
3323         }
3324         return (bbr_alloc(bbr));
3325 }
3326
3327 /* wrapper to allocate a sendmap entry, subject to a specific limit */
3328 static struct bbr_sendmap *
3329 bbr_alloc_limit(struct tcp_bbr *bbr, uint8_t limit_type)
3330 {
3331         struct bbr_sendmap *rsm;
3332
3333         if (limit_type) {
3334                 /* currently there is only one limit type */
3335                 if (V_tcp_map_split_limit > 0 &&
3336                     bbr->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
3337                         BBR_STAT_INC(bbr_split_limited);
3338                         if (!bbr->alloc_limit_reported) {
3339                                 bbr->alloc_limit_reported = 1;
3340                                 BBR_STAT_INC(bbr_alloc_limited_conns);
3341                         }
3342                         return (NULL);
3343                 }
3344         }
3345
3346         /* allocate and mark in the limit type, if set */
3347         rsm = bbr_alloc(bbr);
3348         if (rsm != NULL && limit_type) {
3349                 rsm->r_limit_type = limit_type;
3350                 bbr->r_ctl.rc_num_split_allocs++;
3351         }
3352         return (rsm);
3353 }
3354
3355 static void
3356 bbr_free(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
3357 {
3358         if (rsm->r_limit_type) {
3359                 /* currently there is only one limit type */
3360                 bbr->r_ctl.rc_num_split_allocs--;
3361         }
3362         if (rsm->r_is_smallmap)
3363                 bbr->r_ctl.rc_num_small_maps_alloced--;
3364         if (bbr->r_ctl.rc_tlp_send == rsm)
3365                 bbr->r_ctl.rc_tlp_send = NULL;
3366         if (bbr->r_ctl.rc_resend == rsm) {
3367                 bbr->r_ctl.rc_resend = NULL;
3368         }
3369         if (bbr->r_ctl.rc_next == rsm)
3370                 bbr->r_ctl.rc_next = NULL;
3371         if (bbr->r_ctl.rc_sacklast == rsm)
3372                 bbr->r_ctl.rc_sacklast = NULL;
3373         if (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
3374                 memset(rsm, 0, sizeof(struct bbr_sendmap));
3375                 TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
3376                 rsm->r_limit_type = 0;
3377                 bbr->r_ctl.rc_free_cnt++;
3378                 return;
3379         }
3380         bbr->r_ctl.rc_num_maps_alloced--;
3381         uma_zfree(bbr_zone, rsm);
3382 }
3383
3384 /*
3385  * Returns the BDP.
3386  */
3387 static uint64_t
3388 bbr_get_bw_delay_prod(uint64_t rtt, uint64_t bw) {
3389         /*
3390          * Calculate the bytes in flight needed given the bw (in bytes per
3391          * second) and the specifyed rtt in useconds. We need to put out the
3392          * returned value per RTT to match that rate. Gain will normally
3393          * raise it up from there.
3394          *
3395          * This should not overflow as long as the bandwidth is below 1
3396          * TByte per second (bw < 10**12 = 2**40) and the rtt is smaller
3397          * than 1000 seconds (rtt < 10**3 * 10**6 = 10**9 = 2**30).
3398          */
3399         uint64_t usec_per_sec;
3400
3401         usec_per_sec = USECS_IN_SECOND;
3402         return ((rtt * bw) / usec_per_sec);
3403 }
3404
3405 /*
3406  * Return the initial cwnd.
3407  */
3408 static uint32_t
3409 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp)
3410 {
3411         uint32_t i_cwnd;
3412
3413         if (bbr->rc_init_win) {
3414                 i_cwnd = bbr->rc_init_win * tp->t_maxseg;
3415         } else if (V_tcp_initcwnd_segments)
3416                 i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
3417                     max(2 * tp->t_maxseg, 14600));
3418         else if (V_tcp_do_rfc3390)
3419                 i_cwnd = min(4 * tp->t_maxseg,
3420                     max(2 * tp->t_maxseg, 4380));
3421         else {
3422                 /* Per RFC5681 Section 3.1 */
3423                 if (tp->t_maxseg > 2190)
3424                         i_cwnd = 2 * tp->t_maxseg;
3425                 else if (tp->t_maxseg > 1095)
3426                         i_cwnd = 3 * tp->t_maxseg;
3427                 else
3428                         i_cwnd = 4 * tp->t_maxseg;
3429         }
3430         return (i_cwnd);
3431 }
3432
3433 /*
3434  * Given a specified gain, return the target
3435  * cwnd based on that gain.
3436  */
3437 static uint32_t
3438 bbr_get_raw_target_cwnd(struct tcp_bbr *bbr, uint32_t gain, uint64_t bw)
3439 {
3440         uint64_t bdp, rtt;
3441         uint32_t cwnd;
3442
3443         if ((get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) ||
3444             (bbr_get_full_bw(bbr) == 0)) {
3445                 /* No measurements yet */
3446                 return (bbr_initial_cwnd(bbr, bbr->rc_tp));
3447         }
3448         /*
3449          * Get bytes per RTT needed (rttProp is normally in
3450          * bbr_cwndtarget_rtt_touse)
3451          */
3452         rtt = bbr_get_rtt(bbr, bbr_cwndtarget_rtt_touse);
3453         /* Get the bdp from the two values */
3454         bdp = bbr_get_bw_delay_prod(rtt, bw);
3455         /* Now apply the gain */
3456         cwnd = (uint32_t)(((bdp * ((uint64_t)gain)) + (uint64_t)(BBR_UNIT - 1)) / ((uint64_t)BBR_UNIT));
3457
3458         return (cwnd);
3459 }
3460
3461 static uint32_t
3462 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain)
3463 {
3464         uint32_t cwnd, mss;
3465
3466         mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
3467         /* Get the base cwnd with gain rounded to a mss */
3468         cwnd = roundup(bbr_get_raw_target_cwnd(bbr, bw, gain), mss);
3469         /*
3470          * Add in N (2 default since we do not have a
3471          * fq layer to trap packets in) quanta's per the I-D
3472          * section 4.2.3.2 quanta adjust.
3473          */
3474         cwnd += (bbr_quanta * bbr->r_ctl.rc_pace_max_segs);
3475         if (bbr->rc_use_google) {
3476                 if((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3477                    (bbr_state_val(bbr) == BBR_SUB_GAIN)) {
3478                         /*
3479                          * The linux implementation adds
3480                          * an extra 2 x mss in gain cycle which
3481                          * is documented no-where except in the code.
3482                          * so we add more for Neal undocumented feature
3483                          */
3484                         cwnd += 2 * mss;
3485                 }
3486                 if ((cwnd / mss) & 0x1) {
3487                         /* Round up for odd num mss */
3488                         cwnd += mss;
3489                 }
3490         }
3491         /* Are we below the min cwnd? */
3492         if (cwnd < get_min_cwnd(bbr))
3493                 return (get_min_cwnd(bbr));
3494         return (cwnd);
3495 }
3496
3497 static uint16_t
3498 bbr_gain_adjust(struct tcp_bbr *bbr, uint16_t gain)
3499 {
3500         if (gain < 1)
3501                 gain = 1;
3502         return (gain);
3503 }
3504
3505 static uint32_t
3506 bbr_get_header_oh(struct tcp_bbr *bbr)
3507 {
3508         int seg_oh;
3509
3510         seg_oh = 0;
3511         if (bbr->r_ctl.rc_inc_tcp_oh) {
3512                 /* Do we include TCP overhead? */
3513                 seg_oh = (bbr->rc_last_options + sizeof(struct tcphdr));
3514         }
3515         if (bbr->r_ctl.rc_inc_ip_oh) {
3516                 /* Do we include IP overhead? */
3517 #ifdef INET6
3518                 if (bbr->r_is_v6)
3519                         seg_oh += sizeof(struct ip6_hdr);
3520                 else
3521 #endif
3522 #ifdef INET
3523                         seg_oh += sizeof(struct ip);
3524 #endif
3525         }
3526         if (bbr->r_ctl.rc_inc_enet_oh) {
3527                 /* Do we include the ethernet overhead?  */
3528                 seg_oh += sizeof(struct ether_header);
3529         }
3530         return(seg_oh);
3531 }
3532
3533 static uint32_t
3534 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain, uint32_t useconds_time, uint64_t bw)
3535 {
3536         uint64_t divor, res, tim;
3537
3538         if (useconds_time == 0)
3539                 return (0);
3540         gain = bbr_gain_adjust(bbr, gain);
3541         divor = (uint64_t)USECS_IN_SECOND * (uint64_t)BBR_UNIT;
3542         tim = useconds_time;
3543         res = (tim * bw * gain) / divor;
3544         if (res == 0)
3545                 res = 1;
3546         return ((uint32_t)res);
3547 }
3548
3549 /*
3550  * Given a gain and a length return the delay in useconds that
3551  * should be used to evenly space out packets
3552  * on the connection (based on the gain factor).
3553  */
3554 static uint32_t
3555 bbr_get_pacing_delay(struct tcp_bbr *bbr, uint16_t gain, int32_t len, uint32_t cts, int nolog)
3556 {
3557         uint64_t bw, lentim, res;
3558         uint32_t usecs, srtt, over = 0;
3559         uint32_t seg_oh, num_segs, maxseg;
3560
3561         if (len == 0)
3562                 return (0);
3563
3564         maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
3565         num_segs = (len + maxseg - 1) / maxseg;
3566         if (bbr->rc_use_google == 0) {
3567                 seg_oh = bbr_get_header_oh(bbr);
3568                 len += (num_segs * seg_oh);
3569         }
3570         gain = bbr_gain_adjust(bbr, gain);
3571         bw = bbr_get_bw(bbr);
3572         if (bbr->rc_use_google) {
3573                 uint64_t cbw;
3574
3575                 /*
3576                  * Reduce the b/w by the google discount
3577                  * factor 10 = 1%.
3578                  */
3579                 cbw = bw *  (uint64_t)(1000 - bbr->r_ctl.bbr_google_discount);
3580                 cbw /= (uint64_t)1000;
3581                 /* We don't apply a discount if it results in 0 */
3582                 if (cbw > 0)
3583                         bw = cbw;
3584         }
3585         lentim = ((uint64_t)len *
3586                   (uint64_t)USECS_IN_SECOND *
3587                   (uint64_t)BBR_UNIT);
3588         res = lentim / ((uint64_t)gain * bw);
3589         if (res == 0)
3590                 res = 1;
3591         usecs = (uint32_t)res;
3592         srtt = bbr_get_rtt(bbr, BBR_SRTT);
3593         if (bbr_hptsi_max_mul && bbr_hptsi_max_div &&
3594             (bbr->rc_use_google == 0) &&
3595             (usecs > ((srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div))) {
3596                 /*
3597                  * We cannot let the delay be more than 1/2 the srtt time.
3598                  * Otherwise we cannot pace out or send properly.
3599                  */
3600                 over = usecs = (srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div;
3601                 BBR_STAT_INC(bbr_hpts_min_time);
3602         }
3603         if (!nolog)
3604                 bbr_log_pacing_delay_calc(bbr, gain, len, cts, usecs, bw, over, 1);
3605         return (usecs);
3606 }
3607
3608 static void
3609 bbr_ack_received(struct tcpcb *tp, struct tcp_bbr *bbr, struct tcphdr *th, uint32_t bytes_this_ack,
3610                  uint32_t sack_changed, uint32_t prev_acked, int32_t line, uint32_t losses)
3611 {
3612         INP_WLOCK_ASSERT(tp->t_inpcb);
3613         uint64_t bw;
3614         uint32_t cwnd, target_cwnd, saved_bytes, maxseg;
3615         int32_t meth;
3616
3617 #ifdef STATS
3618         if ((tp->t_flags & TF_GPUTINPROG) &&
3619             SEQ_GEQ(th->th_ack, tp->gput_ack)) {
3620                 /*
3621                  * Strech acks and compressed acks will cause this to
3622                  * oscillate but we are doing it the same way as the main
3623                  * stack so it will be compariable (though possibly not
3624                  * ideal).
3625                  */
3626                 int32_t cgput;
3627                 int64_t gput, time_stamp;
3628
3629                 gput = (int64_t) (th->th_ack - tp->gput_seq) * 8;
3630                 time_stamp = max(1, ((bbr->r_ctl.rc_rcvtime - tp->gput_ts) / 1000));
3631                 cgput = gput / time_stamp;
3632                 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
3633                                          cgput);
3634                 if (tp->t_stats_gput_prev > 0)
3635                         stats_voi_update_abs_s32(tp->t_stats,
3636                                                  VOI_TCP_GPUT_ND,
3637                                                  ((gput - tp->t_stats_gput_prev) * 100) /
3638                                                  tp->t_stats_gput_prev);
3639                 tp->t_flags &= ~TF_GPUTINPROG;
3640                 tp->t_stats_gput_prev = cgput;
3641         }
3642 #endif
3643         if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3644             ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
3645                 /* We don't change anything in probe-rtt */
3646                 return;
3647         }
3648         maxseg = tp->t_maxseg - bbr->rc_last_options;
3649         saved_bytes = bytes_this_ack;
3650         bytes_this_ack += sack_changed;
3651         if (bytes_this_ack > prev_acked) {
3652                 bytes_this_ack -= prev_acked;
3653                 /*
3654                  * A byte ack'd gives us a full mss
3655                  * to be like linux i.e. they count packets.
3656                  */
3657                 if ((bytes_this_ack < maxseg) && bbr->rc_use_google)
3658                         bytes_this_ack = maxseg;
3659         } else {
3660                 /* Unlikely */
3661                 bytes_this_ack = 0;
3662         }
3663         cwnd = tp->snd_cwnd;
3664         bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3665         if (bw)
3666                 target_cwnd = bbr_get_target_cwnd(bbr,
3667                                                   bw,
3668                                                   (uint32_t)bbr->r_ctl.rc_bbr_cwnd_gain);
3669         else
3670                 target_cwnd = bbr_initial_cwnd(bbr, bbr->rc_tp);
3671         if (IN_RECOVERY(tp->t_flags) &&
3672             (bbr->bbr_prev_in_rec == 0)) {
3673                 /*
3674                  * We are entering recovery and
3675                  * thus packet conservation.
3676                  */
3677                 bbr->pkt_conservation = 1;
3678                 bbr->r_ctl.rc_recovery_start = bbr->r_ctl.rc_rcvtime;
3679                 cwnd = ctf_flight_size(tp,
3680                                        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3681                         bytes_this_ack;
3682         }
3683         if (IN_RECOVERY(tp->t_flags)) {
3684                 uint32_t flight;
3685
3686                 bbr->bbr_prev_in_rec = 1;
3687                 if (cwnd > losses) {
3688                         cwnd -= losses;
3689                         if (cwnd < maxseg)
3690                                 cwnd = maxseg;
3691                 } else
3692                         cwnd = maxseg;
3693                 flight = ctf_flight_size(tp,
3694                                          (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3695                 bbr_log_type_cwndupd(bbr, flight, 0,
3696                                      losses, 10, 0, 0, line);
3697                 if (bbr->pkt_conservation) {
3698                         uint32_t time_in;
3699
3700                         if (TSTMP_GEQ(bbr->r_ctl.rc_rcvtime, bbr->r_ctl.rc_recovery_start))
3701                                 time_in = bbr->r_ctl.rc_rcvtime - bbr->r_ctl.rc_recovery_start;
3702                         else
3703                                 time_in = 0;
3704
3705                         if (time_in >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
3706                                 /* Clear packet conservation after an rttProp */
3707                                 bbr->pkt_conservation = 0;
3708                         } else {
3709                                 if ((flight + bytes_this_ack) > cwnd)
3710                                         cwnd = flight + bytes_this_ack;
3711                                 if (cwnd < get_min_cwnd(bbr))
3712                                         cwnd = get_min_cwnd(bbr);
3713                                 tp->snd_cwnd = cwnd;
3714                                 bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed,
3715                                                      prev_acked, 1, target_cwnd, th->th_ack, line);
3716                                 return;
3717                         }
3718                 }
3719         } else
3720                 bbr->bbr_prev_in_rec = 0;
3721         if ((bbr->rc_use_google == 0) && bbr->r_ctl.restrict_growth) {
3722                 bbr->r_ctl.restrict_growth--;
3723                 if (bytes_this_ack > maxseg)
3724                         bytes_this_ack = maxseg;
3725         }
3726         if (bbr->rc_filled_pipe) {
3727                 /*
3728                  * Here we have exited startup and filled the pipe. We will
3729                  * thus allow the cwnd to shrink to the target. We hit here
3730                  * mostly.
3731                  */
3732                 uint32_t s_cwnd;
3733
3734                 meth = 2;
3735                 s_cwnd = min((cwnd + bytes_this_ack), target_cwnd);
3736                 if (s_cwnd > cwnd)
3737                         cwnd = s_cwnd;
3738                 else if (bbr_cwnd_may_shrink || bbr->rc_use_google || bbr->rc_no_pacing)
3739                         cwnd = s_cwnd;
3740         } else {
3741                 /*
3742                  * Here we are still in startup, we increase cwnd by what
3743                  * has been acked.
3744                  */
3745                 if ((cwnd < target_cwnd) ||
3746                     (bbr->rc_past_init_win == 0)) {
3747                         meth = 3;
3748                         cwnd += bytes_this_ack;
3749                 } else {
3750                         /*
3751                          * Method 4 means we are at target so no gain in
3752                          * startup and past the initial window.
3753                          */
3754                         meth = 4;
3755                 }
3756         }
3757         tp->snd_cwnd = max(cwnd, get_min_cwnd(bbr));
3758         bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed, prev_acked, meth, target_cwnd, th->th_ack, line);
3759 }
3760
3761 static void
3762 tcp_bbr_partialack(struct tcpcb *tp)
3763 {
3764         struct tcp_bbr *bbr;
3765
3766         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3767         INP_WLOCK_ASSERT(tp->t_inpcb);
3768         if (ctf_flight_size(tp,
3769                 (bbr->r_ctl.rc_sacked  + bbr->r_ctl.rc_lost_bytes)) <=
3770             tp->snd_cwnd) {
3771                 bbr->r_wanted_output = 1;
3772         }
3773 }
3774
3775 static void
3776 bbr_post_recovery(struct tcpcb *tp)
3777 {
3778         struct tcp_bbr *bbr;
3779         uint32_t  flight;
3780
3781         INP_WLOCK_ASSERT(tp->t_inpcb);
3782         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3783         /*
3784          * Here we just exit recovery.
3785          */
3786         EXIT_RECOVERY(tp->t_flags);
3787         /* Lock in our b/w reduction for the specified number of pkt-epochs */
3788         bbr->r_recovery_bw = 0;
3789         tp->snd_recover = tp->snd_una;
3790         tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3791         bbr->pkt_conservation = 0;
3792         if (bbr->rc_use_google == 0) {
3793                 /*
3794                  * For non-google mode lets
3795                  * go ahead and make sure we clear
3796                  * the recovery state so if we
3797                  * bounce back in to recovery we
3798                  * will do PC.
3799                  */
3800                 bbr->bbr_prev_in_rec = 0;
3801         }
3802         bbr_log_type_exit_rec(bbr);
3803         if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3804                 tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3805                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 15, 0, 0, __LINE__);
3806         } else {
3807                 /* For probe-rtt case lets fix up its saved_cwnd */
3808                 if (bbr->r_ctl.rc_saved_cwnd < bbr->r_ctl.rc_cwnd_on_ent) {
3809                         bbr->r_ctl.rc_saved_cwnd = bbr->r_ctl.rc_cwnd_on_ent;
3810                         bbr_log_type_cwndupd(bbr, 0, 0, 0, 16, 0, 0, __LINE__);
3811                 }
3812         }
3813         flight = ctf_flight_size(tp,
3814                      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3815         if ((bbr->rc_use_google == 0) &&
3816             bbr_do_red) {
3817                 uint64_t val, lr2use;
3818                 uint32_t maxseg, newcwnd, acks_inflight, ratio, cwnd;
3819                 uint32_t *cwnd_p;
3820
3821                 if (bbr_get_rtt(bbr, BBR_SRTT)) {
3822                         val = ((uint64_t)bbr_get_rtt(bbr, BBR_RTT_PROP) * (uint64_t)1000);
3823                         val /= bbr_get_rtt(bbr, BBR_SRTT);
3824                         ratio = (uint32_t)val;
3825                 } else
3826                         ratio = 1000;
3827
3828                 bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div,
3829                                      bbr->r_ctl.recovery_lr, 21,
3830                                      ratio,
3831                                      bbr->r_ctl.rc_red_cwnd_pe,
3832                                      __LINE__);
3833                 if ((ratio < bbr_do_red) || (bbr_do_red == 0))
3834                         goto done;
3835                 if (((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3836                      bbr_prtt_slam_cwnd) ||
3837                     (bbr_sub_drain_slam_cwnd &&
3838                      (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3839                      bbr->rc_hit_state_1 &&
3840                      (bbr_state_val(bbr) == BBR_SUB_DRAIN)) ||
3841                     ((bbr->rc_bbr_state == BBR_STATE_DRAIN) &&
3842                      bbr_slam_cwnd_in_main_drain)) {
3843                         /*
3844                          * Here we must poke at the saved cwnd
3845                          * as well as the cwnd.
3846                          */
3847                         cwnd = bbr->r_ctl.rc_saved_cwnd;
3848                         cwnd_p = &bbr->r_ctl.rc_saved_cwnd;
3849                 } else {
3850                         cwnd = tp->snd_cwnd;
3851                         cwnd_p = &tp->snd_cwnd;
3852                 }
3853                 maxseg = tp->t_maxseg - bbr->rc_last_options;
3854                 /* Add the overall lr with the recovery lr */
3855                 if (bbr->r_ctl.rc_lost == 0)
3856                         lr2use = 0;
3857                 else if (bbr->r_ctl.rc_delivered == 0)
3858                         lr2use = 1000;
3859                 else {
3860                         lr2use = bbr->r_ctl.rc_lost * 1000;
3861                         lr2use /= bbr->r_ctl.rc_delivered;
3862                 }
3863                 lr2use += bbr->r_ctl.recovery_lr;
3864                 acks_inflight = (flight / (maxseg * 2));
3865                 if (bbr_red_scale) {
3866                         lr2use *= bbr_get_rtt(bbr, BBR_SRTT);
3867                         lr2use /= bbr_red_scale;
3868                         if ((bbr_red_growth_restrict) &&
3869                             ((bbr_get_rtt(bbr, BBR_SRTT)/bbr_red_scale) > 1))
3870                             bbr->r_ctl.restrict_growth += acks_inflight;
3871                 }
3872                 if (lr2use) {
3873                         val = (uint64_t)cwnd * lr2use;
3874                         val /= 1000;
3875                         if (cwnd > val)
3876                                 newcwnd = roundup((cwnd - val), maxseg);
3877                         else
3878                                 newcwnd = maxseg;
3879                 } else {
3880                         val = (uint64_t)cwnd * (uint64_t)bbr_red_mul;
3881                         val /= (uint64_t)bbr_red_div;
3882                         newcwnd = roundup((uint32_t)val, maxseg);
3883                 }
3884                 /* with standard delayed acks how many acks can I expect? */
3885                 if (bbr_drop_limit == 0) {
3886                         /*
3887                          * Anticpate how much we will
3888                          * raise the cwnd based on the acks.
3889                          */
3890                         if ((newcwnd + (acks_inflight * maxseg)) < get_min_cwnd(bbr)) {
3891                                 /* We do enforce the min (with the acks) */
3892                                 newcwnd = (get_min_cwnd(bbr) - acks_inflight);
3893                         }
3894                 } else {
3895                         /*
3896                          * A strict drop limit of N is is inplace
3897                          */
3898                         if (newcwnd < (bbr_drop_limit * maxseg)) {
3899                                 newcwnd = bbr_drop_limit * maxseg;
3900                         }
3901                 }
3902                 /* For the next N acks do we restrict the growth */
3903                 *cwnd_p = newcwnd;
3904                 if (tp->snd_cwnd > newcwnd)
3905                         tp->snd_cwnd = newcwnd;
3906                 bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div, val, 22,
3907                                      (uint32_t)lr2use,
3908                                      bbr_get_rtt(bbr, BBR_SRTT), __LINE__);
3909                 bbr->r_ctl.rc_red_cwnd_pe = bbr->r_ctl.rc_pkt_epoch;
3910         }
3911 done:
3912         bbr->r_ctl.recovery_lr = 0;
3913         if (flight <= tp->snd_cwnd) {
3914                 bbr->r_wanted_output = 1;
3915         }
3916         tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3917 }
3918
3919 static void
3920 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts)
3921 {
3922         bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3923         /* Limit the drop in b/w to 1/2 our current filter. */
3924         if (bbr->r_ctl.red_bw > bbr->r_ctl.rc_bbr_cur_del_rate)
3925                 bbr->r_ctl.red_bw = bbr->r_ctl.rc_bbr_cur_del_rate;
3926         if (bbr->r_ctl.red_bw < (get_filter_value(&bbr->r_ctl.rc_delrate) / 2))
3927                 bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate) / 2;
3928         tcp_bbr_tso_size_check(bbr, cts);
3929 }
3930
3931 static void
3932 bbr_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type, struct bbr_sendmap *rsm)
3933 {
3934         struct tcp_bbr *bbr;
3935
3936         INP_WLOCK_ASSERT(tp->t_inpcb);
3937 #ifdef STATS
3938         stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
3939 #endif
3940         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3941         switch (type) {
3942         case CC_NDUPACK:
3943                 if (!IN_RECOVERY(tp->t_flags)) {
3944                         tp->snd_recover = tp->snd_max;
3945                         /* Start a new epoch */
3946                         bbr_set_pktepoch(bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
3947                         if (bbr->rc_lt_is_sampling || bbr->rc_lt_use_bw) {
3948                                 /*
3949                                  * Move forward the lt epoch
3950                                  * so it won't count the truncated
3951                                  * epoch.
3952                                  */
3953                                 bbr->r_ctl.rc_lt_epoch++;
3954                         }
3955                         if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
3956                                 /*
3957                                  * Just like the policer detection code
3958                                  * if we are in startup we must push
3959                                  * forward the last startup epoch
3960                                  * to hide the truncated PE.
3961                                  */
3962                                 bbr->r_ctl.rc_bbr_last_startup_epoch++;
3963                         }
3964                         bbr->r_ctl.rc_cwnd_on_ent = tp->snd_cwnd;
3965                         ENTER_RECOVERY(tp->t_flags);
3966                         bbr->rc_tlp_rtx_out = 0;
3967                         bbr->r_ctl.recovery_lr = bbr->r_ctl.rc_pkt_epoch_loss_rate;
3968                         tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3969                         if (bbr->rc_inp->inp_in_hpts &&
3970                             ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) == 0)) {
3971                                 /*
3972                                  * When we enter recovery, we need to restart
3973                                  * any timers. This may mean we gain an agg
3974                                  * early, which will be made up for at the last
3975                                  * rxt out.
3976                                  */
3977                                 bbr->rc_timer_first = 1;
3978                                 bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
3979                         }
3980                         /*
3981                          * Calculate a new cwnd based on to the current
3982                          * delivery rate with no gain. We get the bdp
3983                          * without gaining it up like we normally would and
3984                          * we use the last cur_del_rate.
3985                          */
3986                         if ((bbr->rc_use_google == 0) &&
3987                             (bbr->r_ctl.bbr_rttprobe_gain_val ||
3988                              (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT))) {
3989                                 tp->snd_cwnd = ctf_flight_size(tp,
3990                                                    (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3991                                         (tp->t_maxseg - bbr->rc_last_options);
3992                                 if (tp->snd_cwnd < get_min_cwnd(bbr)) {
3993                                         /* We always gate to min cwnd */
3994                                         tp->snd_cwnd = get_min_cwnd(bbr);
3995                                 }
3996                                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 14, 0, 0, __LINE__);
3997                         }
3998                         bbr_log_type_enter_rec(bbr, rsm->r_start);
3999                 }
4000                 break;
4001         case CC_RTO_ERR:
4002                 KMOD_TCPSTAT_INC(tcps_sndrexmitbad);
4003                 /* RTO was unnecessary, so reset everything. */
4004                 bbr_reset_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime);
4005                 if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
4006                         tp->snd_cwnd = tp->snd_cwnd_prev;
4007                         tp->snd_ssthresh = tp->snd_ssthresh_prev;
4008                         tp->snd_recover = tp->snd_recover_prev;
4009                         tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
4010                         bbr_log_type_cwndupd(bbr, 0, 0, 0, 13, 0, 0, __LINE__);
4011                 }
4012                 tp->t_badrxtwin = 0;
4013                 break;
4014         }
4015 }
4016
4017 /*
4018  * Indicate whether this ack should be delayed.  We can delay the ack if
4019  * following conditions are met:
4020  *      - There is no delayed ack timer in progress.
4021  *      - Our last ack wasn't a 0-sized window. We never want to delay
4022  *        the ack that opens up a 0-sized window.
4023  *      - LRO wasn't used for this segment. We make sure by checking that the
4024  *        segment size is not larger than the MSS.
4025  *      - Delayed acks are enabled or this is a half-synchronized T/TCP
4026  *        connection.
4027  *      - The data being acked is less than a full segment (a stretch ack
4028  *        of more than a segment we should ack.
4029  *      - nsegs is 1 (if its more than that we received more than 1 ack).
4030  */
4031 #define DELAY_ACK(tp, bbr, nsegs)                               \
4032         (((tp->t_flags & TF_RXWIN0SENT) == 0) &&                \
4033          ((tp->t_flags & TF_DELACK) == 0) &&                    \
4034          ((bbr->bbr_segs_rcvd + nsegs) < tp->t_delayed_ack) &&  \
4035          (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4036
4037 /*
4038  * Return the lowest RSM in the map of
4039  * packets still in flight that is not acked.
4040  * This should normally find on the first one
4041  * since we remove packets from the send
4042  * map after they are marked ACKED.
4043  */
4044 static struct bbr_sendmap *
4045 bbr_find_lowest_rsm(struct tcp_bbr *bbr)
4046 {
4047         struct bbr_sendmap *rsm;
4048
4049         /*
4050          * Walk the time-order transmitted list looking for an rsm that is
4051          * not acked. This will be the one that was sent the longest time
4052          * ago that is still outstanding.
4053          */
4054         TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_tmap, r_tnext) {
4055                 if (rsm->r_flags & BBR_ACKED) {
4056                         continue;
4057                 }
4058                 goto finish;
4059         }
4060 finish:
4061         return (rsm);
4062 }
4063
4064 static struct bbr_sendmap *
4065 bbr_find_high_nonack(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
4066 {
4067         struct bbr_sendmap *prsm;
4068
4069         /*
4070          * Walk the sequence order list backward until we hit and arrive at
4071          * the highest seq not acked. In theory when this is called it
4072          * should be the last segment (which it was not).
4073          */
4074         prsm = rsm;
4075         TAILQ_FOREACH_REVERSE_FROM(prsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4076                 if (prsm->r_flags & (BBR_ACKED | BBR_HAS_FIN)) {
4077                         continue;
4078                 }
4079                 return (prsm);
4080         }
4081         return (NULL);
4082 }
4083
4084 /*
4085  * Returns to the caller the number of microseconds that
4086  * the packet can be outstanding before we think we
4087  * should have had an ack returned.
4088  */
4089 static uint32_t
4090 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm)
4091 {
4092         /*
4093          * lro is the flag we use to determine if we have seen reordering.
4094          * If it gets set we have seen reordering. The reorder logic either
4095          * works in one of two ways:
4096          *
4097          * If reorder-fade is configured, then we track the last time we saw
4098          * re-ordering occur. If we reach the point where enough time as
4099          * passed we no longer consider reordering has occuring.
4100          *
4101          * Or if reorder-face is 0, then once we see reordering we consider
4102          * the connection to alway be subject to reordering and just set lro
4103          * to 1.
4104          *
4105          * In the end if lro is non-zero we add the extra time for
4106          * reordering in.
4107          */
4108         int32_t lro;
4109         uint32_t thresh, t_rxtcur;
4110
4111         if (srtt == 0)
4112                 srtt = 1;
4113         if (bbr->r_ctl.rc_reorder_ts) {
4114                 if (bbr->r_ctl.rc_reorder_fade) {
4115                         if (SEQ_GEQ(cts, bbr->r_ctl.rc_reorder_ts)) {
4116                                 lro = cts - bbr->r_ctl.rc_reorder_ts;
4117                                 if (lro == 0) {
4118                                         /*
4119                                          * No time as passed since the last
4120                                          * reorder, mark it as reordering.
4121                                          */
4122                                         lro = 1;
4123                                 }
4124                         } else {
4125                                 /* Negative time? */
4126                                 lro = 0;
4127                         }
4128                         if (lro > bbr->r_ctl.rc_reorder_fade) {
4129                                 /* Turn off reordering seen too */
4130                                 bbr->r_ctl.rc_reorder_ts = 0;
4131                                 lro = 0;
4132                         }
4133                 } else {
4134                         /* Reodering does not fade */
4135                         lro = 1;
4136                 }
4137         } else {
4138                 lro = 0;
4139         }
4140         thresh = srtt + bbr->r_ctl.rc_pkt_delay;
4141         if (lro) {
4142                 /* It must be set, if not you get 1/4 rtt */
4143                 if (bbr->r_ctl.rc_reorder_shift)
4144                         thresh += (srtt >> bbr->r_ctl.rc_reorder_shift);
4145                 else
4146                         thresh += (srtt >> 2);
4147         } else {
4148                 thresh += 1000;
4149         }
4150         /* We don't let the rack timeout be above a RTO */
4151         if ((bbr->rc_tp)->t_srtt == 0)
4152                 t_rxtcur = BBR_INITIAL_RTO;
4153         else
4154                 t_rxtcur = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
4155         if (thresh > t_rxtcur) {
4156                 thresh = t_rxtcur;
4157         }
4158         /* And we don't want it above the RTO max either */
4159         if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4160                 thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4161         }
4162         bbr_log_thresh_choice(bbr, cts, thresh, lro, srtt, rsm, BBR_TO_FRM_RACK);
4163         return (thresh);
4164 }
4165
4166 /*
4167  * Return to the caller the amount of time in mico-seconds
4168  * that should be used for the TLP timer from the last
4169  * send time of this packet.
4170  */
4171 static uint32_t
4172 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
4173     struct bbr_sendmap *rsm, uint32_t srtt,
4174     uint32_t cts)
4175 {
4176         uint32_t thresh, len, maxseg, t_rxtcur;
4177         struct bbr_sendmap *prsm;
4178
4179         if (srtt == 0)
4180                 srtt = 1;
4181         if (bbr->rc_tlp_threshold)
4182                 thresh = srtt + (srtt / bbr->rc_tlp_threshold);
4183         else
4184                 thresh = (srtt * 2);
4185         maxseg = tp->t_maxseg - bbr->rc_last_options;
4186         /* Get the previous sent packet, if any  */
4187         len = rsm->r_end - rsm->r_start;
4188
4189         /* 2.1 behavior */
4190         prsm = TAILQ_PREV(rsm, bbr_head, r_tnext);
4191         if (prsm && (len <= maxseg)) {
4192                 /*
4193                  * Two packets outstanding, thresh should be (2*srtt) +
4194                  * possible inter-packet delay (if any).
4195                  */
4196                 uint32_t inter_gap = 0;
4197                 int idx, nidx;
4198
4199                 idx = rsm->r_rtr_cnt - 1;
4200                 nidx = prsm->r_rtr_cnt - 1;
4201                 if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
4202                         /* Yes it was sent later (or at the same time) */
4203                         inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
4204                 }
4205                 thresh += inter_gap;
4206         } else if (len <= maxseg) {
4207                 /*
4208                  * Possibly compensate for delayed-ack.
4209                  */
4210                 uint32_t alt_thresh;
4211
4212                 alt_thresh = srtt + (srtt / 2) + bbr_delayed_ack_time;
4213                 if (alt_thresh > thresh)
4214                         thresh = alt_thresh;
4215         }
4216         /* Not above the current  RTO */
4217         if (tp->t_srtt == 0)
4218                 t_rxtcur = BBR_INITIAL_RTO;
4219         else
4220                 t_rxtcur = TICKS_2_USEC(tp->t_rxtcur);
4221
4222         bbr_log_thresh_choice(bbr, cts, thresh, t_rxtcur, srtt, rsm, BBR_TO_FRM_TLP);
4223         /* Not above an RTO */
4224         if (thresh > t_rxtcur) {
4225                 thresh = t_rxtcur;
4226         }
4227         /* Not above a RTO max */
4228         if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4229                 thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4230         }
4231         /* And now apply the user TLP min */
4232         if (thresh < bbr_tlp_min) {
4233                 thresh = bbr_tlp_min;
4234         }
4235         return (thresh);
4236 }
4237
4238 /*
4239  * Return one of three RTTs to use (in microseconds).
4240  */
4241 static __inline uint32_t
4242 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type)
4243 {
4244         uint32_t f_rtt;
4245         uint32_t srtt;
4246
4247         f_rtt = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
4248         if (get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) {
4249                 /* We have no rtt at all */
4250                 if (bbr->rc_tp->t_srtt == 0)
4251                         f_rtt = BBR_INITIAL_RTO;
4252                 else
4253                         f_rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4254                 /*
4255                  * Since we don't know how good the rtt is apply a
4256                  * delayed-ack min
4257                  */
4258                 if (f_rtt < bbr_delayed_ack_time) {
4259                         f_rtt = bbr_delayed_ack_time;
4260                 }
4261         }
4262         /* Take the filter version or last measured pkt-rtt */
4263         if (rtt_type == BBR_RTT_PROP) {
4264                 srtt = f_rtt;
4265         } else if (rtt_type == BBR_RTT_PKTRTT) {
4266                 if (bbr->r_ctl.rc_pkt_epoch_rtt) {
4267                         srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
4268                 } else {
4269                         /* No pkt rtt yet */
4270                         srtt = f_rtt;
4271                 }
4272         } else if (rtt_type == BBR_RTT_RACK) {
4273                 srtt = bbr->r_ctl.rc_last_rtt;
4274                 /* We need to add in any internal delay for our timer */
4275                 if (bbr->rc_ack_was_delayed)
4276                         srtt += bbr->r_ctl.rc_ack_hdwr_delay;
4277         } else if (rtt_type == BBR_SRTT) {
4278                 srtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4279         } else {
4280                 /* TSNH */
4281                 srtt = f_rtt;
4282 #ifdef BBR_INVARIANTS
4283                 panic("Unknown rtt request type %d", rtt_type);
4284 #endif
4285         }
4286         return (srtt);
4287 }
4288
4289 static int
4290 bbr_is_lost(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t cts)
4291 {
4292         uint32_t thresh;
4293
4294         thresh = bbr_calc_thresh_rack(bbr, bbr_get_rtt(bbr, BBR_RTT_RACK),
4295                                       cts, rsm);
4296         if ((cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)]) >= thresh) {
4297                 /* It is lost (past time) */
4298                 return (1);
4299         }
4300         return (0);
4301 }
4302
4303 /*
4304  * Return a sendmap if we need to retransmit something.
4305  */
4306 static struct bbr_sendmap *
4307 bbr_check_recovery_mode(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4308 {
4309         /*
4310          * Check to see that we don't need to fall into recovery. We will
4311          * need to do so if our oldest transmit is past the time we should
4312          * have had an ack.
4313          */
4314
4315         struct bbr_sendmap *rsm;
4316         int32_t idx;
4317
4318         if (TAILQ_EMPTY(&bbr->r_ctl.rc_map)) {
4319                 /* Nothing outstanding that we know of */
4320                 return (NULL);
4321         }
4322         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
4323         if (rsm == NULL) {
4324                 /* Nothing in the transmit map */
4325                 return (NULL);
4326         }
4327         if (tp->t_flags & TF_SENTFIN) {
4328                 /* Fin restricted, don't find anything once a fin is sent */
4329                 return (NULL);
4330         }
4331         if (rsm->r_flags & BBR_ACKED) {
4332                 /*
4333                  * Ok the first one is acked (this really should not happen
4334                  * since we remove the from the tmap once they are acked)
4335                  */
4336                 rsm = bbr_find_lowest_rsm(bbr);
4337                 if (rsm == NULL)
4338                         return (NULL);
4339         }
4340         idx = rsm->r_rtr_cnt - 1;
4341         if (SEQ_LEQ(cts, rsm->r_tim_lastsent[idx])) {
4342                 /* Send timestamp is the same or less? can't be ready */
4343                 return (NULL);
4344         }
4345         /* Get our RTT time */
4346         if (bbr_is_lost(bbr, rsm, cts) &&
4347             ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
4348              (rsm->r_flags & BBR_SACK_PASSED))) {
4349                 if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4350                         rsm->r_flags |= BBR_MARKED_LOST;
4351                         bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4352                         bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4353                 }
4354                 bbr_cong_signal(tp, NULL, CC_NDUPACK, rsm);
4355 #ifdef BBR_INVARIANTS
4356                 if ((rsm->r_end - rsm->r_start) == 0)
4357                         panic("tp:%p bbr:%p rsm:%p length is 0?", tp, bbr, rsm);
4358 #endif
4359                 return (rsm);
4360         }
4361         return (NULL);
4362 }
4363
4364 /*
4365  * RACK Timer, here we simply do logging and house keeping.
4366  * the normal bbr_output_wtime() function will call the
4367  * appropriate thing to check if we need to do a RACK retransmit.
4368  * We return 1, saying don't proceed with bbr_output_wtime only
4369  * when all timers have been stopped (destroyed PCB?).
4370  */
4371 static int
4372 bbr_timeout_rack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4373 {
4374         /*
4375          * This timer simply provides an internal trigger to send out data.
4376          * The check_recovery_mode call will see if there are needed
4377          * retransmissions, if so we will enter fast-recovery. The output
4378          * call may or may not do the same thing depending on sysctl
4379          * settings.
4380          */
4381         uint32_t lost;
4382
4383         if (bbr->rc_all_timers_stopped) {
4384                 return (1);
4385         }
4386         if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4387                 /* Its not time yet */
4388                 return (0);
4389         }
4390         BBR_STAT_INC(bbr_to_tot);
4391         lost = bbr->r_ctl.rc_lost;
4392         if (bbr->r_state && (bbr->r_state != tp->t_state))
4393                 bbr_set_state(tp, bbr, 0);
4394         bbr_log_to_event(bbr, cts, BBR_TO_FRM_RACK);
4395         if (bbr->r_ctl.rc_resend == NULL) {
4396                 /* Lets do the check here */
4397                 bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
4398         }
4399         if (bbr_policer_call_from_rack_to)
4400                 bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4401         bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
4402         return (0);
4403 }
4404
4405 static __inline void
4406 bbr_clone_rsm(struct tcp_bbr *bbr, struct bbr_sendmap *nrsm, struct bbr_sendmap *rsm, uint32_t start)
4407 {
4408         int idx;
4409
4410         nrsm->r_start = start;
4411         nrsm->r_end = rsm->r_end;
4412         nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4413         nrsm-> r_rtt_not_allowed = rsm->r_rtt_not_allowed;
4414         nrsm->r_flags = rsm->r_flags;
4415         /* We don't transfer forward the SYN flag */
4416         nrsm->r_flags &= ~BBR_HAS_SYN;
4417         /* We move forward the FIN flag, not that this should happen */
4418         rsm->r_flags &= ~BBR_HAS_FIN;
4419         nrsm->r_dupack = rsm->r_dupack;
4420         nrsm->r_rtr_bytes = 0;
4421         nrsm->r_is_gain = rsm->r_is_gain;
4422         nrsm->r_is_drain = rsm->r_is_drain;
4423         nrsm->r_delivered = rsm->r_delivered;
4424         nrsm->r_ts_valid = rsm->r_ts_valid;
4425         nrsm->r_del_ack_ts = rsm->r_del_ack_ts;
4426         nrsm->r_del_time = rsm->r_del_time;
4427         nrsm->r_app_limited = rsm->r_app_limited;
4428         nrsm->r_first_sent_time = rsm->r_first_sent_time;
4429         nrsm->r_flight_at_send = rsm->r_flight_at_send;
4430         /* We split a piece the lower section looses any just_ret flag. */
4431         nrsm->r_bbr_state = rsm->r_bbr_state;
4432         for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4433                 nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4434         }
4435         rsm->r_end = nrsm->r_start;
4436         idx = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
4437         idx /= 8;
4438         /* Check if we got too small */
4439         if ((rsm->r_is_smallmap == 0) &&
4440             ((rsm->r_end - rsm->r_start) <= idx)) {
4441                 bbr->r_ctl.rc_num_small_maps_alloced++;
4442                 rsm->r_is_smallmap = 1;
4443         }
4444         /* Check the new one as well */
4445         if ((nrsm->r_end - nrsm->r_start) <= idx) {
4446                 bbr->r_ctl.rc_num_small_maps_alloced++;
4447                 nrsm->r_is_smallmap = 1;
4448         }
4449 }
4450
4451 static int
4452 bbr_sack_mergable(struct bbr_sendmap *at,
4453                   uint32_t start, uint32_t end)
4454 {
4455         /*
4456          * Given a sack block defined by
4457          * start and end, and a current postion
4458          * at. Return 1 if either side of at
4459          * would show that the block is mergable
4460          * to that side. A block to be mergable
4461          * must have overlap with the start/end
4462          * and be in the SACK'd state.
4463          */
4464         struct bbr_sendmap *l_rsm;
4465         struct bbr_sendmap *r_rsm;
4466
4467         /* first get the either side blocks */
4468         l_rsm = TAILQ_PREV(at, bbr_head, r_next);
4469         r_rsm = TAILQ_NEXT(at, r_next);
4470         if (l_rsm && (l_rsm->r_flags & BBR_ACKED)) {
4471                 /* Potentially mergeable */
4472                 if ((l_rsm->r_end == start) ||
4473                     (SEQ_LT(start, l_rsm->r_end) &&
4474                      SEQ_GT(end, l_rsm->r_end))) {
4475                             /*
4476                              * map blk   |------|
4477                              * sack blk         |------|
4478                              * <or>
4479                              * map blk   |------|
4480                              * sack blk      |------|
4481                              */
4482                             return (1);
4483                     }
4484         }
4485         if (r_rsm && (r_rsm->r_flags & BBR_ACKED)) {
4486                 /* Potentially mergeable */
4487                 if ((r_rsm->r_start == end) ||
4488                     (SEQ_LT(start, r_rsm->r_start) &&
4489                      SEQ_GT(end, r_rsm->r_start))) {
4490                         /*
4491                          * map blk          |---------|
4492                          * sack blk    |----|
4493                          * <or>
4494                          * map blk          |---------|
4495                          * sack blk    |-------|
4496                          */
4497                         return (1);
4498                 }
4499         }
4500         return (0);
4501 }
4502
4503 static struct bbr_sendmap *
4504 bbr_merge_rsm(struct tcp_bbr *bbr,
4505               struct bbr_sendmap *l_rsm,
4506               struct bbr_sendmap *r_rsm)
4507 {
4508         /*
4509          * We are merging two ack'd RSM's,
4510          * the l_rsm is on the left (lower seq
4511          * values) and the r_rsm is on the right
4512          * (higher seq value). The simplest way
4513          * to merge these is to move the right
4514          * one into the left. I don't think there
4515          * is any reason we need to try to find
4516          * the oldest (or last oldest retransmitted).
4517          */
4518         l_rsm->r_end = r_rsm->r_end;
4519         if (l_rsm->r_dupack < r_rsm->r_dupack)
4520                 l_rsm->r_dupack = r_rsm->r_dupack;
4521         if (r_rsm->r_rtr_bytes)
4522                 l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
4523         if (r_rsm->r_in_tmap) {
4524                 /* This really should not happen */
4525                 TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, r_rsm, r_tnext);
4526         }
4527         if (r_rsm->r_app_limited)
4528                 l_rsm->r_app_limited = r_rsm->r_app_limited;
4529         /* Now the flags */
4530         if (r_rsm->r_flags & BBR_HAS_FIN)
4531                 l_rsm->r_flags |= BBR_HAS_FIN;
4532         if (r_rsm->r_flags & BBR_TLP)
4533                 l_rsm->r_flags |= BBR_TLP;
4534         if (r_rsm->r_flags & BBR_RWND_COLLAPSED)
4535                 l_rsm->r_flags |= BBR_RWND_COLLAPSED;
4536         if (r_rsm->r_flags & BBR_MARKED_LOST) {
4537                 /* This really should not happen */
4538                 bbr->r_ctl.rc_lost_bytes -= r_rsm->r_end - r_rsm->r_start;
4539         }
4540         TAILQ_REMOVE(&bbr->r_ctl.rc_map, r_rsm, r_next);
4541         if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
4542                 /* Transfer the split limit to the map we free */
4543                 r_rsm->r_limit_type = l_rsm->r_limit_type;
4544                 l_rsm->r_limit_type = 0;
4545         }
4546         bbr_free(bbr, r_rsm);
4547         return(l_rsm);
4548 }
4549
4550 /*
4551  * TLP Timer, here we simply setup what segment we want to
4552  * have the TLP expire on, the normal bbr_output_wtime() will then
4553  * send it out.
4554  *
4555  * We return 1, saying don't proceed with bbr_output_wtime only
4556  * when all timers have been stopped (destroyed PCB?).
4557  */
4558 static int
4559 bbr_timeout_tlp(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4560 {
4561         /*
4562          * Tail Loss Probe.
4563          */
4564         struct bbr_sendmap *rsm = NULL;
4565         struct socket *so;
4566         uint32_t amm;
4567         uint32_t out, avail;
4568         uint32_t maxseg;
4569         int collapsed_win = 0;
4570
4571         if (bbr->rc_all_timers_stopped) {
4572                 return (1);
4573         }
4574         if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4575                 /* Its not time yet */
4576                 return (0);
4577         }
4578         if (ctf_progress_timeout_check(tp, true)) {
4579                 bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4580                 tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4581                 return (1);
4582         }
4583         /* Did we somehow get into persists? */
4584         if (bbr->rc_in_persist) {
4585                 return (0);
4586         }
4587         if (bbr->r_state && (bbr->r_state != tp->t_state))
4588                 bbr_set_state(tp, bbr, 0);
4589         BBR_STAT_INC(bbr_tlp_tot);
4590         maxseg = tp->t_maxseg - bbr->rc_last_options;
4591         /*
4592          * A TLP timer has expired. We have been idle for 2 rtts. So we now
4593          * need to figure out how to force a full MSS segment out.
4594          */
4595         so = tp->t_inpcb->inp_socket;
4596         avail = sbavail(&so->so_snd);
4597         out = ctf_outstanding(tp);
4598         if (out > tp->snd_wnd) {
4599                 /* special case, we need a retransmission */
4600                 collapsed_win = 1;
4601                 goto need_retran;
4602         }
4603         if (avail > out) {
4604                 /* New data is available */
4605                 amm = avail - out;
4606                 if (amm > maxseg) {
4607                         amm = maxseg;
4608                 } else if ((amm < maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
4609                         /* not enough to fill a MTU and no-delay is off */
4610                         goto need_retran;
4611                 }
4612                 /* Set the send-new override */
4613                 if ((out + amm) <= tp->snd_wnd) {
4614                         bbr->rc_tlp_new_data = 1;
4615                 } else {
4616                         goto need_retran;
4617                 }
4618                 bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4619                 bbr->r_ctl.rc_last_tlp_seq = tp->snd_max;
4620                 bbr->r_ctl.rc_tlp_send = NULL;
4621                 /* cap any slots */
4622                 BBR_STAT_INC(bbr_tlp_newdata);
4623                 goto send;
4624         }
4625 need_retran:
4626         /*
4627          * Ok we need to arrange the last un-acked segment to be re-sent, or
4628          * optionally the first un-acked segment.
4629          */
4630         if (collapsed_win == 0) {
4631                 rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
4632                 if (rsm && (BBR_ACKED | BBR_HAS_FIN)) {
4633                         rsm = bbr_find_high_nonack(bbr, rsm);
4634                 }
4635                 if (rsm == NULL) {
4636                         goto restore;
4637                 }
4638         } else {
4639                 /*
4640                  * We must find the last segment
4641                  * that was acceptable by the client.
4642                  */
4643                 TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4644                         if ((rsm->r_flags & BBR_RWND_COLLAPSED) == 0) {
4645                                 /* Found one */
4646                                 break;
4647                         }
4648                 }
4649                 if (rsm == NULL) {
4650                         /* None? if so send the first */
4651                         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4652                         if (rsm == NULL)
4653                                 goto restore;
4654                 }
4655         }
4656         if ((rsm->r_end - rsm->r_start) > maxseg) {
4657                 /*
4658                  * We need to split this the last segment in two.
4659                  */
4660                 struct bbr_sendmap *nrsm;
4661
4662                 nrsm = bbr_alloc_full_limit(bbr);
4663                 if (nrsm == NULL) {
4664                         /*
4665                          * We can't get memory to split, we can either just
4666                          * not split it. Or retransmit the whole piece, lets
4667                          * do the large send (BTLP :-) ).
4668                          */
4669                         goto go_for_it;
4670                 }
4671                 bbr_clone_rsm(bbr, nrsm, rsm, (rsm->r_end - maxseg));
4672                 TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
4673                 if (rsm->r_in_tmap) {
4674                         TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4675                         nrsm->r_in_tmap = 1;
4676                 }
4677                 rsm->r_flags &= (~BBR_HAS_FIN);
4678                 rsm = nrsm;
4679         }
4680 go_for_it:
4681         bbr->r_ctl.rc_tlp_send = rsm;
4682         bbr->rc_tlp_rtx_out = 1;
4683         if (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) {
4684                 bbr->r_ctl.rc_tlp_seg_send_cnt++;
4685                 tp->t_rxtshift++;
4686         } else {
4687                 bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
4688                 bbr->r_ctl.rc_tlp_seg_send_cnt = 1;
4689         }
4690 send:
4691         if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
4692                 /*
4693                  * Can't [re]/transmit a segment we have retranmitted the
4694                  * max times. We need the retransmit timer to take over.
4695                  */
4696 restore:
4697                 bbr->rc_tlp_new_data = 0;
4698                 bbr->r_ctl.rc_tlp_send = NULL;
4699                 if (rsm)
4700                         rsm->r_flags &= ~BBR_TLP;
4701                 BBR_STAT_INC(bbr_tlp_retran_fail);
4702                 return (0);
4703         } else if (rsm) {
4704                 rsm->r_flags |= BBR_TLP;
4705         }
4706         if (rsm && (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) &&
4707             (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend)) {
4708                 /*
4709                  * We have retransmitted to many times for TLP. Switch to
4710                  * the regular RTO timer
4711                  */
4712                 goto restore;
4713         }
4714         bbr_log_to_event(bbr, cts, BBR_TO_FRM_TLP);
4715         bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
4716         return (0);
4717 }
4718
4719 /*
4720  * Delayed ack Timer, here we simply need to setup the
4721  * ACK_NOW flag and remove the DELACK flag. From there
4722  * the output routine will send the ack out.
4723  *
4724  * We only return 1, saying don't proceed, if all timers
4725  * are stopped (destroyed PCB?).
4726  */
4727 static int
4728 bbr_timeout_delack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4729 {
4730         if (bbr->rc_all_timers_stopped) {
4731                 return (1);
4732         }
4733         bbr_log_to_event(bbr, cts, BBR_TO_FRM_DELACK);
4734         tp->t_flags &= ~TF_DELACK;
4735         tp->t_flags |= TF_ACKNOW;
4736         KMOD_TCPSTAT_INC(tcps_delack);
4737         bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
4738         return (0);
4739 }
4740
4741 /*
4742  * Here we send a KEEP-ALIVE like probe to the
4743  * peer, we do not send data.
4744  *
4745  * We only return 1, saying don't proceed, if all timers
4746  * are stopped (destroyed PCB?).
4747  */
4748 static int
4749 bbr_timeout_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4750 {
4751         struct tcptemp *t_template;
4752         int32_t retval = 1;
4753
4754         if (bbr->rc_all_timers_stopped) {
4755                 return (1);
4756         }
4757         if (bbr->rc_in_persist == 0)
4758                 return (0);
4759         KASSERT(tp->t_inpcb != NULL,
4760             ("%s: tp %p tp->t_inpcb == NULL", __func__, tp));
4761         /*
4762          * Persistence timer into zero window. Force a byte to be output, if
4763          * possible.
4764          */
4765         bbr_log_to_event(bbr, cts, BBR_TO_FRM_PERSIST);
4766         bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
4767         KMOD_TCPSTAT_INC(tcps_persisttimeo);
4768         /*
4769          * Have we exceeded the user specified progress time?
4770          */
4771         if (ctf_progress_timeout_check(tp, true)) {
4772                 bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4773                 tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4774                 goto out;
4775         }
4776         /*
4777          * Hack: if the peer is dead/unreachable, we do not time out if the
4778          * window is closed.  After a full backoff, drop the connection if
4779          * the idle time (no responses to probes) reaches the maximum
4780          * backoff that we would use if retransmitting.
4781          */
4782         if (tp->t_rxtshift == TCP_MAXRXTSHIFT &&
4783             (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
4784             ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
4785                 KMOD_TCPSTAT_INC(tcps_persistdrop);
4786                 tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4787                 tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4788                 goto out;
4789         }
4790         if ((sbavail(&bbr->rc_inp->inp_socket->so_snd) == 0) &&
4791             tp->snd_una == tp->snd_max) {
4792                 bbr_exit_persist(tp, bbr, cts, __LINE__);
4793                 retval = 0;
4794                 goto out;
4795         }
4796         /*
4797          * If the user has closed the socket then drop a persisting
4798          * connection after a much reduced timeout.
4799          */
4800         if (tp->t_state > TCPS_CLOSE_WAIT &&
4801             (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
4802                 KMOD_TCPSTAT_INC(tcps_persistdrop);
4803                 tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4804                 tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4805                 goto out;
4806         }
4807         t_template = tcpip_maketemplate(bbr->rc_inp);
4808         if (t_template) {
4809                 tcp_respond(tp, t_template->tt_ipgen,
4810                             &t_template->tt_t, (struct mbuf *)NULL,
4811                             tp->rcv_nxt, tp->snd_una - 1, 0);
4812                 /* This sends an ack */
4813                 if (tp->t_flags & TF_DELACK)
4814                         tp->t_flags &= ~TF_DELACK;
4815                 free(t_template, M_TEMP);
4816         }
4817         if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
4818                 tp->t_rxtshift++;
4819         bbr_start_hpts_timer(bbr, tp, cts, 3, 0, 0);
4820 out:
4821         return (retval);
4822 }
4823
4824 /*
4825  * If a keepalive goes off, we had no other timers
4826  * happening. We always return 1 here since this
4827  * routine either drops the connection or sends
4828  * out a segment with respond.
4829  */
4830 static int
4831 bbr_timeout_keepalive(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4832 {
4833         struct tcptemp *t_template;
4834         struct inpcb *inp;
4835
4836         if (bbr->rc_all_timers_stopped) {
4837                 return (1);
4838         }
4839         bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
4840         inp = tp->t_inpcb;
4841         bbr_log_to_event(bbr, cts, BBR_TO_FRM_KEEP);
4842         /*
4843          * Keep-alive timer went off; send something or drop connection if
4844          * idle for too long.
4845          */
4846         KMOD_TCPSTAT_INC(tcps_keeptimeo);
4847         if (tp->t_state < TCPS_ESTABLISHED)
4848                 goto dropit;
4849         if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
4850             tp->t_state <= TCPS_CLOSING) {
4851                 if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
4852                         goto dropit;
4853                 /*
4854                  * Send a packet designed to force a response if the peer is
4855                  * up and reachable: either an ACK if the connection is
4856                  * still alive, or an RST if the peer has closed the
4857                  * connection due to timeout or reboot. Using sequence
4858                  * number tp->snd_una-1 causes the transmitted zero-length
4859                  * segment to lie outside the receive window; by the
4860                  * protocol spec, this requires the correspondent TCP to
4861                  * respond.
4862                  */
4863                 KMOD_TCPSTAT_INC(tcps_keepprobe);
4864                 t_template = tcpip_maketemplate(inp);
4865                 if (t_template) {
4866                         tcp_respond(tp, t_template->tt_ipgen,
4867                             &t_template->tt_t, (struct mbuf *)NULL,
4868                             tp->rcv_nxt, tp->snd_una - 1, 0);
4869                         free(t_template, M_TEMP);
4870                 }
4871         }
4872         bbr_start_hpts_timer(bbr, tp, cts, 4, 0, 0);
4873         return (1);
4874 dropit:
4875         KMOD_TCPSTAT_INC(tcps_keepdrops);
4876         tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
4877         tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4878         return (1);
4879 }
4880
4881 /*
4882  * Retransmit helper function, clear up all the ack
4883  * flags and take care of important book keeping.
4884  */
4885 static void
4886 bbr_remxt_tmr(struct tcpcb *tp)
4887 {
4888         /*
4889          * The retransmit timer went off, all sack'd blocks must be
4890          * un-acked.
4891          */
4892         struct bbr_sendmap *rsm, *trsm = NULL;
4893         struct tcp_bbr *bbr;
4894         uint32_t cts, lost;
4895
4896         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4897         cts = tcp_get_usecs(&bbr->rc_tv);
4898         lost = bbr->r_ctl.rc_lost;
4899         if (bbr->r_state && (bbr->r_state != tp->t_state))
4900                 bbr_set_state(tp, bbr, 0);
4901
4902         TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
4903                 if (rsm->r_flags & BBR_ACKED) {
4904                         uint32_t old_flags;
4905
4906                         rsm->r_dupack = 0;
4907                         if (rsm->r_in_tmap == 0) {
4908                                 /* We must re-add it back to the tlist */
4909                                 if (trsm == NULL) {
4910                                         TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
4911                                 } else {
4912                                         TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, trsm, rsm, r_tnext);
4913                                 }
4914                                 rsm->r_in_tmap = 1;
4915                         }
4916                         old_flags = rsm->r_flags;
4917                         rsm->r_flags |= BBR_RXT_CLEARED;
4918                         rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS);
4919                         bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
4920                 } else {
4921                         if ((tp->t_state < TCPS_ESTABLISHED) &&
4922                             (rsm->r_start == tp->snd_una)) {
4923                                 /*
4924                                  * Special case for TCP FO. Where
4925                                  * we sent more data beyond the snd_max.
4926                                  * We don't mark that as lost and stop here.
4927                                  */
4928                                 break;
4929                         }
4930                         if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4931                                 bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4932                                 bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4933                         }
4934                         if (bbr_marks_rxt_sack_passed) {
4935                                 /*
4936                                  * With this option, we will rack out
4937                                  * in 1ms increments the rest of the packets.
4938                                  */
4939                                 rsm->r_flags |= BBR_SACK_PASSED | BBR_MARKED_LOST;
4940                                 rsm->r_flags &= ~BBR_WAS_SACKPASS;
4941                         } else {
4942                                 /*
4943                                  * With this option we only mark them lost
4944                                  * and remove all sack'd markings. We will run
4945                                  * another RXT or a TLP. This will cause
4946                                  * us to eventually send more based on what
4947                                  * ack's come in.
4948                                  */
4949                                 rsm->r_flags |= BBR_MARKED_LOST;
4950                                 rsm->r_flags &= ~BBR_WAS_SACKPASS;
4951                                 rsm->r_flags &= ~BBR_SACK_PASSED;
4952                         }
4953                 }
4954                 trsm = rsm;
4955         }
4956         bbr->r_ctl.rc_resend = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4957         /* Clear the count (we just un-acked them) */
4958         bbr_log_to_event(bbr, cts, BBR_TO_FRM_TMR);
4959         bbr->rc_tlp_new_data = 0;
4960         bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4961         /* zap the behindness on a rxt */
4962         bbr->r_ctl.rc_hptsi_agg_delay = 0;
4963         bbr->r_agg_early_set = 0;
4964         bbr->r_ctl.rc_agg_early = 0;
4965         bbr->rc_tlp_rtx_out = 0;
4966         bbr->r_ctl.rc_sacked = 0;
4967         bbr->r_ctl.rc_sacklast = NULL;
4968         bbr->r_timer_override = 1;
4969         bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4970 }
4971
4972 /*
4973  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
4974  * we will setup to retransmit the lowest seq number outstanding.
4975  */
4976 static int
4977 bbr_timeout_rxt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4978 {
4979         int32_t rexmt;
4980         int32_t retval = 0;
4981         bool isipv6;
4982
4983         bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
4984         if (bbr->rc_all_timers_stopped) {
4985                 return (1);
4986         }
4987         if (TCPS_HAVEESTABLISHED(tp->t_state) &&
4988             (tp->snd_una == tp->snd_max)) {
4989                 /* Nothing outstanding .. nothing to do */
4990                 return (0);
4991         }
4992         /*
4993          * Retransmission timer went off.  Message has not been acked within
4994          * retransmit interval.  Back off to a longer retransmit interval
4995          * and retransmit one segment.
4996          */
4997         if (ctf_progress_timeout_check(tp, true)) {
4998                 retval = 1;
4999                 bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
5000                 tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
5001                 goto out;
5002         }
5003         bbr_remxt_tmr(tp);
5004         if ((bbr->r_ctl.rc_resend == NULL) ||
5005             ((bbr->r_ctl.rc_resend->r_flags & BBR_RWND_COLLAPSED) == 0)) {
5006                 /*
5007                  * If the rwnd collapsed on
5008                  * the one we are retransmitting
5009                  * it does not count against the
5010                  * rxt count.
5011                  */
5012                 tp->t_rxtshift++;
5013         }
5014         if (tp->t_rxtshift > TCP_MAXRXTSHIFT) {
5015                 tp->t_rxtshift = TCP_MAXRXTSHIFT;
5016                 KMOD_TCPSTAT_INC(tcps_timeoutdrop);
5017                 retval = 1;
5018                 tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
5019                 tcp_set_inp_to_drop(bbr->rc_inp,
5020                     (tp->t_softerror ? (uint16_t) tp->t_softerror : ETIMEDOUT));
5021                 goto out;
5022         }
5023         if (tp->t_state == TCPS_SYN_SENT) {
5024                 /*
5025                  * If the SYN was retransmitted, indicate CWND to be limited
5026                  * to 1 segment in cc_conn_init().
5027                  */
5028                 tp->snd_cwnd = 1;
5029         } else if (tp->t_rxtshift == 1) {
5030                 /*
5031                  * first retransmit; record ssthresh and cwnd so they can be
5032                  * recovered if this turns out to be a "bad" retransmit. A
5033                  * retransmit is considered "bad" if an ACK for this segment
5034                  * is received within RTT/2 interval; the assumption here is
5035                  * that the ACK was already in flight.  See "On Estimating
5036                  * End-to-End Network Path Properties" by Allman and Paxson
5037                  * for more details.
5038                  */
5039                 tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5040                 if (!IN_RECOVERY(tp->t_flags)) {
5041                         tp->snd_cwnd_prev = tp->snd_cwnd;
5042                         tp->snd_ssthresh_prev = tp->snd_ssthresh;
5043                         tp->snd_recover_prev = tp->snd_recover;
5044                         tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
5045                         tp->t_flags |= TF_PREVVALID;
5046                 } else {
5047                         tp->t_flags &= ~TF_PREVVALID;
5048                 }
5049                 tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5050         } else {
5051                 tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5052                 tp->t_flags &= ~TF_PREVVALID;
5053         }
5054         KMOD_TCPSTAT_INC(tcps_rexmttimeo);
5055         if ((tp->t_state == TCPS_SYN_SENT) ||
5056             (tp->t_state == TCPS_SYN_RECEIVED))
5057                 rexmt = USEC_2_TICKS(BBR_INITIAL_RTO) * tcp_backoff[tp->t_rxtshift];
5058         else
5059                 rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
5060         TCPT_RANGESET(tp->t_rxtcur, rexmt,
5061             MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms),
5062             MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
5063         /*
5064          * We enter the path for PLMTUD if connection is established or, if
5065          * connection is FIN_WAIT_1 status, reason for the last is that if
5066          * amount of data we send is very small, we could send it in couple
5067          * of packets and process straight to FIN. In that case we won't
5068          * catch ESTABLISHED state.
5069          */
5070 #ifdef INET6
5071         isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) ? true : false;
5072 #else
5073         isipv6 = false;
5074 #endif
5075         if (((V_tcp_pmtud_blackhole_detect == 1) ||
5076             (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
5077             (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
5078             ((tp->t_state == TCPS_ESTABLISHED) ||
5079             (tp->t_state == TCPS_FIN_WAIT_1))) {
5080                 /*
5081                  * Idea here is that at each stage of mtu probe (usually,
5082                  * 1448 -> 1188 -> 524) should be given 2 chances to recover
5083                  * before further clamping down. 'tp->t_rxtshift % 2 == 0'
5084                  * should take care of that.
5085                  */
5086                 if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
5087                     (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
5088                     (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
5089                     tp->t_rxtshift % 2 == 0)) {
5090                         /*
5091                          * Enter Path MTU Black-hole Detection mechanism: -
5092                          * Disable Path MTU Discovery (IP "DF" bit). -
5093                          * Reduce MTU to lower value than what we negotiated
5094                          * with peer.
5095                          */
5096                         if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
5097                                 /*
5098                                  * Record that we may have found a black
5099                                  * hole.
5100                                  */
5101                                 tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
5102                                 /* Keep track of previous MSS. */
5103                                 tp->t_pmtud_saved_maxseg = tp->t_maxseg;
5104                         }
5105                         /*
5106                          * Reduce the MSS to blackhole value or to the
5107                          * default in an attempt to retransmit.
5108                          */
5109 #ifdef INET6
5110                         isipv6 = bbr->r_is_v6;
5111                         if (isipv6 &&
5112                             tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
5113                                 /* Use the sysctl tuneable blackhole MSS. */
5114                                 tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
5115                                 KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5116                         } else if (isipv6) {
5117                                 /* Use the default MSS. */
5118                                 tp->t_maxseg = V_tcp_v6mssdflt;
5119                                 /*
5120                                  * Disable Path MTU Discovery when we switch
5121                                  * to minmss.
5122                                  */
5123                                 tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5124                                 KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5125                         }
5126 #endif
5127 #if defined(INET6) && defined(INET)
5128                         else
5129 #endif
5130 #ifdef INET
5131                         if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
5132                                 /* Use the sysctl tuneable blackhole MSS. */
5133                                 tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
5134                                 KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5135                         } else {
5136                                 /* Use the default MSS. */
5137                                 tp->t_maxseg = V_tcp_mssdflt;
5138                                 /*
5139                                  * Disable Path MTU Discovery when we switch
5140                                  * to minmss.
5141                                  */
5142                                 tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5143                                 KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5144                         }
5145 #endif
5146                 } else {
5147                         /*
5148                          * If further retransmissions are still unsuccessful
5149                          * with a lowered MTU, maybe this isn't a blackhole
5150                          * and we restore the previous MSS and blackhole
5151                          * detection flags. The limit '6' is determined by
5152                          * giving each probe stage (1448, 1188, 524) 2
5153                          * chances to recover.
5154                          */
5155                         if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
5156                             (tp->t_rxtshift >= 6)) {
5157                                 tp->t_flags2 |= TF2_PLPMTU_PMTUD;
5158                                 tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
5159                                 tp->t_maxseg = tp->t_pmtud_saved_maxseg;
5160                                 KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
5161                         }
5162                 }
5163         }
5164         /*
5165          * Disable RFC1323 and SACK if we haven't got any response to our
5166          * third SYN to work-around some broken terminal servers (most of
5167          * which have hopefully been retired) that have bad VJ header
5168          * compression code which trashes TCP segments containing
5169          * unknown-to-them TCP options.
5170          */
5171         if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
5172             (tp->t_rxtshift == 3))
5173                 tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
5174         /*
5175          * If we backed off this far, our srtt estimate is probably bogus.
5176          * Clobber it so we'll take the next rtt measurement as our srtt;
5177          * move the current srtt into rttvar to keep the current retransmit
5178          * times until then.
5179          */
5180         if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
5181 #ifdef INET6
5182                 if (bbr->r_is_v6)
5183                         in6_losing(tp->t_inpcb);
5184                 else
5185 #endif
5186                         in_losing(tp->t_inpcb);
5187                 tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
5188                 tp->t_srtt = 0;
5189         }
5190         sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
5191         tp->snd_recover = tp->snd_max;
5192         tp->t_flags |= TF_ACKNOW;
5193         tp->t_rtttime = 0;
5194 out:
5195         return (retval);
5196 }
5197
5198 static int
5199 bbr_process_timers(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, uint8_t hpts_calling)
5200 {
5201         int32_t ret = 0;
5202         int32_t timers = (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
5203
5204         if (timers == 0) {
5205                 return (0);
5206         }
5207         if (tp->t_state == TCPS_LISTEN) {
5208                 /* no timers on listen sockets */
5209                 if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
5210                         return (0);
5211                 return (1);
5212         }
5213         if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
5214                 uint32_t left;
5215
5216                 if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
5217                         ret = -1;
5218                         bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5219                         return (0);
5220                 }
5221                 if (hpts_calling == 0) {
5222                         ret = -2;
5223                         bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5224                         return (0);
5225                 }
5226                 /*
5227                  * Ok our timer went off early and we are not paced false
5228                  * alarm, go back to sleep.
5229                  */
5230                 left = bbr->r_ctl.rc_timer_exp - cts;
5231                 ret = -3;
5232                 bbr_log_to_processing(bbr, cts, ret, left, hpts_calling);
5233                 tcp_hpts_insert(tp->t_inpcb, HPTS_USEC_TO_SLOTS(left));
5234                 return (1);
5235         }
5236         bbr->rc_tmr_stopped = 0;
5237         bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
5238         if (timers & PACE_TMR_DELACK) {
5239                 ret = bbr_timeout_delack(tp, bbr, cts);
5240         } else if (timers & PACE_TMR_PERSIT) {
5241                 ret = bbr_timeout_persist(tp, bbr, cts);
5242         } else if (timers & PACE_TMR_RACK) {
5243                 bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5244                 ret = bbr_timeout_rack(tp, bbr, cts);
5245         } else if (timers & PACE_TMR_TLP) {
5246                 bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5247                 ret = bbr_timeout_tlp(tp, bbr, cts);
5248         } else if (timers & PACE_TMR_RXT) {
5249                 bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5250                 ret = bbr_timeout_rxt(tp, bbr, cts);
5251         } else if (timers & PACE_TMR_KEEP) {
5252                 ret = bbr_timeout_keepalive(tp, bbr, cts);
5253         }
5254         bbr_log_to_processing(bbr, cts, ret, timers, hpts_calling);
5255         return (ret);
5256 }
5257
5258 static void
5259 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts)
5260 {
5261         if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
5262                 uint8_t hpts_removed = 0;
5263
5264                 if (bbr->rc_inp->inp_in_hpts &&
5265                     (bbr->rc_timer_first == 1)) {
5266                         /*
5267                          * If we are canceling timer's when we have the
5268                          * timer ahead of the output being paced. We also
5269                          * must remove ourselves from the hpts.
5270                          */
5271                         hpts_removed = 1;
5272                         tcp_hpts_remove(bbr->rc_inp, HPTS_REMOVE_OUTPUT);
5273                         if (bbr->r_ctl.rc_last_delay_val) {
5274                                 /* Update the last hptsi delay too */
5275                                 uint32_t time_since_send;
5276
5277                                 if (TSTMP_GT(cts, bbr->rc_pacer_started))
5278                                         time_since_send = cts - bbr->rc_pacer_started;
5279                                 else
5280                                         time_since_send = 0;
5281                                 if (bbr->r_ctl.rc_last_delay_val > time_since_send) {
5282                                         /* Cut down our slot time */
5283                                         bbr->r_ctl.rc_last_delay_val -= time_since_send;
5284                                 } else {
5285                                         bbr->r_ctl.rc_last_delay_val = 0;
5286                                 }
5287                                 bbr->rc_pacer_started = cts;
5288                         }
5289                 }
5290                 bbr->rc_timer_first = 0;
5291                 bbr_log_to_cancel(bbr, line, cts, hpts_removed);
5292                 bbr->rc_tmr_stopped = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
5293                 bbr->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
5294         }
5295 }
5296
5297 static void
5298 bbr_timer_stop(struct tcpcb *tp, uint32_t timer_type)
5299 {
5300         struct tcp_bbr *bbr;
5301
5302         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
5303         bbr->rc_all_timers_stopped = 1;
5304         return;
5305 }
5306
5307 /*
5308  * stop all timers always returning 0.
5309  */
5310 static int
5311 bbr_stopall(struct tcpcb *tp)
5312 {
5313         return (0);
5314 }
5315
5316 static void
5317 bbr_timer_activate(struct tcpcb *tp, uint32_t timer_type, uint32_t delta)
5318 {
5319         return;
5320 }
5321
5322 /*
5323  * return true if a bbr timer (rack or tlp) is active.
5324  */
5325 static int
5326 bbr_timer_active(struct tcpcb *tp, uint32_t timer_type)
5327 {
5328         return (0);
5329 }
5330
5331 static uint32_t
5332 bbr_get_earliest_send_outstanding(struct tcp_bbr *bbr, struct bbr_sendmap *u_rsm, uint32_t cts)
5333 {
5334         struct bbr_sendmap *rsm;
5335
5336         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
5337         if ((rsm == NULL) || (u_rsm == rsm))
5338                 return (cts);
5339         return(rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
5340 }
5341
5342 static void
5343 bbr_update_rsm(struct tcpcb *tp, struct tcp_bbr *bbr,
5344      struct bbr_sendmap *rsm, uint32_t cts, uint32_t pacing_time)
5345 {
5346         int32_t idx;
5347
5348         rsm->r_rtr_cnt++;
5349         rsm->r_dupack = 0;
5350         if (rsm->r_rtr_cnt > BBR_NUM_OF_RETRANS) {
5351                 rsm->r_rtr_cnt = BBR_NUM_OF_RETRANS;
5352                 rsm->r_flags |= BBR_OVERMAX;
5353         }
5354         if (rsm->r_flags & BBR_RWND_COLLAPSED) {
5355                 /* Take off the collapsed flag at rxt */
5356                 rsm->r_flags &= ~BBR_RWND_COLLAPSED;
5357         }
5358         if (rsm->r_flags & BBR_MARKED_LOST) {
5359                 /* We have retransmitted, its no longer lost */
5360                 rsm->r_flags &= ~BBR_MARKED_LOST;
5361                 bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
5362         }
5363         if (rsm->r_flags & BBR_RXT_CLEARED) {
5364                 /*
5365                  * We hit a RXT timer on it and
5366                  * we cleared the "acked" flag.
5367                  * We now have it going back into
5368                  * flight, we can remove the cleared
5369                  * flag and possibly do accounting on
5370                  * this piece.
5371                  */
5372                 rsm->r_flags &= ~BBR_RXT_CLEARED;
5373         }
5374         if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & BBR_TLP) == 0)) {
5375                 bbr->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
5376                 rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
5377         }
5378         idx = rsm->r_rtr_cnt - 1;
5379         rsm->r_tim_lastsent[idx] = cts;
5380         rsm->r_pacing_delay = pacing_time;
5381         rsm->r_delivered = bbr->r_ctl.rc_delivered;
5382         rsm->r_ts_valid = bbr->rc_ts_valid;
5383         if (bbr->rc_ts_valid)
5384                 rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5385         if (bbr->r_ctl.r_app_limited_until)
5386                 rsm->r_app_limited = 1;
5387         else
5388                 rsm->r_app_limited = 0;
5389         if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5390                 rsm->r_bbr_state = bbr_state_val(bbr);
5391         else
5392                 rsm->r_bbr_state = 8;
5393         if (rsm->r_flags & BBR_ACKED) {
5394                 /* Problably MTU discovery messing with us */
5395                 uint32_t old_flags;
5396
5397                 old_flags = rsm->r_flags;
5398                 rsm->r_flags &= ~BBR_ACKED;
5399                 bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
5400                 bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
5401                 if (bbr->r_ctl.rc_sacked == 0)
5402                         bbr->r_ctl.rc_sacklast = NULL;
5403         }
5404         if (rsm->r_in_tmap) {
5405                 TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5406         }
5407         TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5408         rsm->r_in_tmap = 1;
5409         if (rsm->r_flags & BBR_SACK_PASSED) {
5410                 /* We have retransmitted due to the SACK pass */
5411                 rsm->r_flags &= ~BBR_SACK_PASSED;
5412                 rsm->r_flags |= BBR_WAS_SACKPASS;
5413         }
5414         rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5415         rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5416                                                 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5417         bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
5418         if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5419                 rsm->r_is_gain = 1;
5420                 rsm->r_is_drain = 0;
5421         } else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5422                 rsm->r_is_drain = 1;
5423                 rsm->r_is_gain = 0;
5424         } else {
5425                 rsm->r_is_drain = 0;
5426                 rsm->r_is_gain = 0;
5427         }
5428         rsm->r_del_time = bbr->r_ctl.rc_del_time; /* TEMP GOOGLE CODE */
5429 }
5430
5431 /*
5432  * Returns 0, or the sequence where we stopped
5433  * updating. We also update the lenp to be the amount
5434  * of data left.
5435  */
5436
5437 static uint32_t
5438 bbr_update_entry(struct tcpcb *tp, struct tcp_bbr *bbr,
5439     struct bbr_sendmap *rsm, uint32_t cts, int32_t *lenp, uint32_t pacing_time)
5440 {
5441         /*
5442          * We (re-)transmitted starting at rsm->r_start for some length
5443          * (possibly less than r_end.
5444          */
5445         struct bbr_sendmap *nrsm;
5446         uint32_t c_end;
5447         int32_t len;
5448
5449         len = *lenp;
5450         c_end = rsm->r_start + len;
5451         if (SEQ_GEQ(c_end, rsm->r_end)) {
5452                 /*
5453                  * We retransmitted the whole piece or more than the whole
5454                  * slopping into the next rsm.
5455                  */
5456                 bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5457                 if (c_end == rsm->r_end) {
5458                         *lenp = 0;
5459                         return (0);
5460                 } else {
5461                         int32_t act_len;
5462
5463                         /* Hangs over the end return whats left */
5464                         act_len = rsm->r_end - rsm->r_start;
5465                         *lenp = (len - act_len);
5466                         return (rsm->r_end);
5467                 }
5468                 /* We don't get out of this block. */
5469         }
5470         /*
5471          * Here we retransmitted less than the whole thing which means we
5472          * have to split this into what was transmitted and what was not.
5473          */
5474         nrsm = bbr_alloc_full_limit(bbr);
5475         if (nrsm == NULL) {
5476                 *lenp = 0;
5477                 return (0);
5478         }
5479         /*
5480          * So here we are going to take the original rsm and make it what we
5481          * retransmitted. nrsm will be the tail portion we did not
5482          * retransmit. For example say the chunk was 1, 11 (10 bytes). And
5483          * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
5484          * 1, 6 and the new piece will be 6, 11.
5485          */
5486         bbr_clone_rsm(bbr, nrsm, rsm, c_end);
5487         TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
5488         nrsm->r_dupack = 0;
5489         if (rsm->r_in_tmap) {
5490                 TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
5491                 nrsm->r_in_tmap = 1;
5492         }
5493         rsm->r_flags &= (~BBR_HAS_FIN);
5494         bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5495         *lenp = 0;
5496         return (0);
5497 }
5498
5499 static uint64_t
5500 bbr_get_hardware_rate(struct tcp_bbr *bbr)
5501 {
5502         uint64_t bw;
5503
5504         bw = bbr_get_bw(bbr);
5505         bw *= (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN];
5506         bw /= (uint64_t)BBR_UNIT;
5507         return(bw);
5508 }
5509
5510 static void
5511 bbr_setup_less_of_rate(struct tcp_bbr *bbr, uint32_t cts,
5512                        uint64_t act_rate, uint64_t rate_wanted)
5513 {
5514         /*
5515          * We could not get a full gains worth
5516          * of rate.
5517          */
5518         if (get_filter_value(&bbr->r_ctl.rc_delrate) >= act_rate) {
5519                 /* we can't even get the real rate */
5520                 uint64_t red;
5521
5522                 bbr->skip_gain = 1;
5523                 bbr->gain_is_limited = 0;
5524                 red = get_filter_value(&bbr->r_ctl.rc_delrate) - act_rate;
5525                 if (red)
5526                         filter_reduce_by(&bbr->r_ctl.rc_delrate, red, cts);
5527         } else {
5528                 /* We can use a lower gain */
5529                 bbr->skip_gain = 0;
5530                 bbr->gain_is_limited = 1;
5531         }
5532 }
5533
5534 static void
5535 bbr_update_hardware_pacing_rate(struct tcp_bbr *bbr, uint32_t cts)
5536 {
5537         const struct tcp_hwrate_limit_table *nrte;
5538         int error, rate = -1;
5539
5540         if (bbr->r_ctl.crte == NULL)
5541                 return;
5542         if ((bbr->rc_inp->inp_route.ro_nh == NULL) ||
5543             (bbr->rc_inp->inp_route.ro_nh->nh_ifp == NULL)) {
5544                 /* Lost our routes? */
5545                 /* Clear the way for a re-attempt */
5546                 bbr->bbr_attempt_hdwr_pace = 0;
5547 lost_rate:
5548                 bbr->gain_is_limited = 0;
5549                 bbr->skip_gain = 0;
5550                 bbr->bbr_hdrw_pacing = 0;
5551                 counter_u64_add(bbr_flows_whdwr_pacing, -1);
5552                 counter_u64_add(bbr_flows_nohdwr_pacing, 1);
5553                 tcp_bbr_tso_size_check(bbr, cts);
5554                 return;
5555         }
5556         rate = bbr_get_hardware_rate(bbr);
5557         nrte = tcp_chg_pacing_rate(bbr->r_ctl.crte,
5558                                    bbr->rc_tp,
5559                                    bbr->rc_inp->inp_route.ro_nh->nh_ifp,
5560                                    rate,
5561                                    (RS_PACING_GEQ|RS_PACING_SUB_OK),
5562                                    &error, NULL);
5563         if (nrte == NULL) {
5564                 goto lost_rate;
5565         }
5566         if (nrte != bbr->r_ctl.crte) {
5567                 bbr->r_ctl.crte = nrte;
5568                 if (error == 0)  {
5569                         BBR_STAT_INC(bbr_hdwr_rl_mod_ok);
5570                         if (bbr->r_ctl.crte->rate < rate) {
5571                                 /* We have a problem */
5572                                 bbr_setup_less_of_rate(bbr, cts,
5573                                                        bbr->r_ctl.crte->rate, rate);
5574                         } else {
5575                                 /* We are good */
5576                                 bbr->gain_is_limited = 0;
5577                                 bbr->skip_gain = 0;
5578                         }
5579                 } else {
5580                         /* A failure should release the tag */
5581                         BBR_STAT_INC(bbr_hdwr_rl_mod_fail);
5582                         bbr->gain_is_limited = 0;
5583                         bbr->skip_gain = 0;
5584                         bbr->bbr_hdrw_pacing = 0;
5585                 }
5586                 bbr_type_log_hdwr_pacing(bbr,
5587                                          bbr->r_ctl.crte->ptbl->rs_ifp,
5588                                          rate,
5589                                          ((bbr->r_ctl.crte == NULL) ? 0 : bbr->r_ctl.crte->rate),
5590                                          __LINE__,
5591                                          cts,
5592                                          error);
5593         }
5594 }
5595
5596 static void
5597 bbr_adjust_for_hw_pacing(struct tcp_bbr *bbr, uint32_t cts)
5598 {
5599         /*
5600          * If we have hardware pacing support
5601          * we need to factor that in for our
5602          * TSO size.
5603          */
5604         const struct tcp_hwrate_limit_table *rlp;
5605         uint32_t cur_delay, seg_sz, maxseg, new_tso, delta, hdwr_delay;
5606
5607         if ((bbr->bbr_hdrw_pacing == 0) ||
5608             (IN_RECOVERY(bbr->rc_tp->t_flags)) ||
5609             (bbr->r_ctl.crte == NULL))
5610                 return;
5611         if (bbr->hw_pacing_set == 0) {
5612                 /* Not yet by the hdwr pacing count delay */
5613                 return;
5614         }
5615         if (bbr_hdwr_pace_adjust == 0) {
5616                 /* No adjustment */
5617                 return;
5618         }
5619         rlp = bbr->r_ctl.crte;
5620         if (bbr->rc_tp->t_maxseg > bbr->rc_last_options)
5621                 maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5622         else
5623                 maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5624         /*
5625          * So lets first get the
5626          * time we will take between
5627          * TSO sized sends currently without
5628          * hardware help.
5629          */
5630         cur_delay = bbr_get_pacing_delay(bbr, BBR_UNIT,
5631                         bbr->r_ctl.rc_pace_max_segs, cts, 1);
5632         hdwr_delay = bbr->r_ctl.rc_pace_max_segs / maxseg;
5633         hdwr_delay *= rlp->time_between;
5634         if (cur_delay > hdwr_delay)
5635                 delta = cur_delay - hdwr_delay;
5636         else
5637                 delta = 0;
5638         bbr_log_type_tsosize(bbr, cts, delta, cur_delay, hdwr_delay,
5639                              (bbr->r_ctl.rc_pace_max_segs / maxseg),
5640                              1);
5641         if (delta &&
5642             (delta < (max(rlp->time_between,
5643                           bbr->r_ctl.bbr_hptsi_segments_delay_tar)))) {
5644                 /*
5645                  * Now lets divide by the pacing
5646                  * time between each segment the
5647                  * hardware sends rounding up and
5648                  * derive a bytes from that. We multiply
5649                  * that by bbr_hdwr_pace_adjust to get
5650                  * more bang for our buck.
5651                  *
5652                  * The goal is to have the software pacer
5653                  * waiting no more than an additional
5654                  * pacing delay if we can (without the
5655                  * compensation i.e. x bbr_hdwr_pace_adjust).
5656                  */
5657                 seg_sz = max(((cur_delay + rlp->time_between)/rlp->time_between),
5658                              (bbr->r_ctl.rc_pace_max_segs/maxseg));
5659                 seg_sz *= bbr_hdwr_pace_adjust;
5660                 if (bbr_hdwr_pace_floor &&
5661                     (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5662                         /* Currently hardware paces
5663                          * out rs_min_seg segments at a time.
5664                          * We need to make sure we always send at least
5665                          * a full burst of bbr_hdwr_pace_floor down.
5666                          */
5667                         seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5668                 }
5669                 seg_sz *= maxseg;
5670         } else if (delta == 0) {
5671                 /*
5672                  * The highest pacing rate is
5673                  * above our b/w gained. This means
5674                  * we probably are going quite fast at
5675                  * the hardware highest rate. Lets just multiply
5676                  * the calculated TSO size by the
5677                  * multiplier factor (its probably
5678                  * 4 segments in the default config for
5679                  * mlx).
5680                  */
5681                 seg_sz = bbr->r_ctl.rc_pace_max_segs * bbr_hdwr_pace_adjust;
5682                 if (bbr_hdwr_pace_floor &&
5683                     (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5684                         /* Currently hardware paces
5685                          * out rs_min_seg segments at a time.
5686                          * We need to make sure we always send at least
5687                          * a full burst of bbr_hdwr_pace_floor down.
5688                          */
5689                         seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5690                 }
5691         } else {
5692                 /*
5693                  * The pacing time difference is so
5694                  * big that the hardware will
5695                  * pace out more rapidly then we
5696                  * really want and then we
5697                  * will have a long delay. Lets just keep
5698                  * the same TSO size so its as if
5699                  * we were not using hdwr pacing (we
5700                  * just gain a bit of spacing from the
5701                  * hardware if seg_sz > 1).
5702                  */
5703                 seg_sz = bbr->r_ctl.rc_pace_max_segs;
5704         }
5705         if (seg_sz > bbr->r_ctl.rc_pace_max_segs)
5706                 new_tso = seg_sz;
5707         else
5708                 new_tso = bbr->r_ctl.rc_pace_max_segs;
5709         if (new_tso >= (PACE_MAX_IP_BYTES-maxseg))
5710                 new_tso = PACE_MAX_IP_BYTES - maxseg;
5711
5712         if (new_tso != bbr->r_ctl.rc_pace_max_segs) {
5713                 bbr_log_type_tsosize(bbr, cts, new_tso, 0, bbr->r_ctl.rc_pace_max_segs, maxseg, 0);
5714                 bbr->r_ctl.rc_pace_max_segs = new_tso;
5715         }
5716 }
5717
5718 static void
5719 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts)
5720 {
5721         uint64_t bw;
5722         uint32_t old_tso = 0, new_tso;
5723         uint32_t maxseg, bytes;
5724         uint32_t tls_seg=0;
5725         /*
5726          * Google/linux uses the following algorithm to determine
5727          * the TSO size based on the b/w of the link (from Neal Cardwell email 9/27/18):
5728          *
5729          *  bytes = bw_in_bytes_per_second / 1000
5730          *  bytes = min(bytes, 64k)
5731          *  tso_segs = bytes / MSS
5732          *  if (bw < 1.2Mbs)
5733          *      min_tso_segs = 1
5734          *  else
5735          *      min_tso_segs = 2
5736          * tso_segs = max(tso_segs, min_tso_segs)
5737          *
5738          * * Note apply a device specific limit (we apply this in the
5739          *   tcp_m_copym).
5740          * Note that before the initial measurement is made google bursts out
5741          * a full iwnd just like new-reno/cubic.
5742          *
5743          * We do not use this algorithm. Instead we
5744          * use a two phased approach:
5745          *
5746          *  if ( bw <= per-tcb-cross-over)
5747          *     goal_tso =  calculate how much with this bw we
5748          *                 can send in goal-time seconds.
5749          *     if (goal_tso > mss)
5750          *         seg = goal_tso / mss
5751          *         tso = seg * mss
5752          *     else
5753          *         tso = mss
5754          *     if (tso > per-tcb-max)
5755          *         tso = per-tcb-max
5756          *  else if ( bw > 512Mbps)
5757          *     tso = max-tso (64k/mss)
5758          *  else
5759          *     goal_tso = bw / per-tcb-divsor
5760          *     seg = (goal_tso + mss-1)/mss
5761          *     tso = seg * mss
5762          *
5763          * if (tso < per-tcb-floor)
5764          *    tso = per-tcb-floor
5765          * if (tso > per-tcb-utter_max)
5766          *    tso = per-tcb-utter_max
5767          *
5768          * Note the default per-tcb-divisor is 1000 (same as google).
5769          * the goal cross over is 30Mbps however. To recreate googles
5770          * algorithm you need to set:
5771          *
5772          * cross-over = 23,168,000 bps
5773          * goal-time = 18000
5774          * per-tcb-max = 2
5775          * per-tcb-divisor = 1000
5776          * per-tcb-floor = 1
5777          *
5778          * This will get you "google bbr" behavior with respect to tso size.
5779          *
5780          * Note we do set anything TSO size until we are past the initial
5781          * window. Before that we gnerally use either a single MSS
5782          * or we use the full IW size (so we burst a IW at a time)
5783          */
5784
5785         if (bbr->rc_tp->t_maxseg > bbr->rc_last_options) {
5786                 maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5787         } else {
5788                 maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5789         }
5790         old_tso = bbr->r_ctl.rc_pace_max_segs;
5791         if (bbr->rc_past_init_win == 0) {
5792                 /*
5793                  * Not enough data has been acknowledged to make a
5794                  * judgement. Set up the initial TSO based on if we
5795                  * are sending a full IW at once or not.
5796                  */
5797                 if (bbr->rc_use_google)
5798                         bbr->r_ctl.rc_pace_max_segs = ((bbr->rc_tp->t_maxseg - bbr->rc_last_options) * 2);
5799                 else if (bbr->bbr_init_win_cheat)
5800                         bbr->r_ctl.rc_pace_max_segs = bbr_initial_cwnd(bbr, bbr->rc_tp);
5801                 else
5802                         bbr->r_ctl.rc_pace_max_segs = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5803                 if (bbr->r_ctl.rc_pace_min_segs != bbr->rc_tp->t_maxseg)
5804                         bbr->r_ctl.rc_pace_min_segs = bbr->rc_tp->t_maxseg;
5805                 if (bbr->r_ctl.rc_pace_max_segs == 0) {
5806                         bbr->r_ctl.rc_pace_max_segs = maxseg;
5807                 }
5808                 bbr_log_type_tsosize(bbr, cts, bbr->r_ctl.rc_pace_max_segs, tls_seg, old_tso, maxseg, 0);
5809                         bbr_adjust_for_hw_pacing(bbr, cts);
5810                 return;
5811         }
5812         /**
5813          * Now lets set the TSO goal based on our delivery rate in
5814          * bytes per second. Note we only do this if
5815          * we have acked at least the initial cwnd worth of data.
5816          */
5817         bw = bbr_get_bw(bbr);
5818         if (IN_RECOVERY(bbr->rc_tp->t_flags) &&
5819              (bbr->rc_use_google == 0)) {
5820                 /* We clamp to one MSS in recovery */
5821                 new_tso = maxseg;
5822         } else if (bbr->rc_use_google) {
5823                 int min_tso_segs;
5824
5825                 /* Google considers the gain too */
5826                 if (bbr->r_ctl.rc_bbr_hptsi_gain != BBR_UNIT) {
5827                         bw *= bbr->r_ctl.rc_bbr_hptsi_gain;
5828                         bw /= BBR_UNIT;
5829                 }
5830                 bytes = bw / 1024;
5831                 if (bytes > (64 * 1024))
5832                         bytes = 64 * 1024;
5833                 new_tso = bytes / maxseg;
5834                 if (bw < ONE_POINT_TWO_MEG)
5835                         min_tso_segs = 1;
5836                 else
5837                         min_tso_segs = 2;
5838                 if (new_tso < min_tso_segs)
5839                         new_tso = min_tso_segs;
5840                 new_tso *= maxseg;
5841         } else if (bbr->rc_no_pacing) {
5842                 new_tso = (PACE_MAX_IP_BYTES / maxseg) * maxseg;
5843         } else if (bw <= bbr->r_ctl.bbr_cross_over) {
5844                 /*
5845                  * Calculate the worse case b/w TSO if we are inserting no
5846                  * more than a delay_target number of TSO's.
5847                  */
5848                 uint32_t tso_len, min_tso;
5849
5850                 tso_len = bbr_get_pacing_length(bbr, BBR_UNIT, bbr->r_ctl.bbr_hptsi_segments_delay_tar, bw);
5851                 if (tso_len > maxseg) {
5852                         new_tso = tso_len / maxseg;
5853                         if (new_tso > bbr->r_ctl.bbr_hptsi_segments_max)
5854                                 new_tso = bbr->r_ctl.bbr_hptsi_segments_max;
5855                         new_tso *= maxseg;
5856                 } else {
5857                         /*
5858                          * less than a full sized frame yikes.. long rtt or
5859                          * low bw?
5860                          */
5861                         min_tso = bbr_minseg(bbr);
5862                         if ((tso_len > min_tso) && (bbr_all_get_min == 0))
5863                                 new_tso = rounddown(tso_len, min_tso);
5864                         else
5865                                 new_tso = min_tso;
5866                 }
5867         } else if (bw > FIVETWELVE_MBPS) {
5868                 /*
5869                  * This guy is so fast b/w wise that we can TSO as large as
5870                  * possible of segments that the NIC will allow.
5871                  */
5872                 new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5873         } else {
5874                 /*
5875                  * This formula is based on attempting to send a segment or
5876                  * more every bbr_hptsi_per_second. The default is 1000
5877                  * which means you are targeting what you can send every 1ms
5878                  * based on the peers bw.
5879                  *
5880                  * If the number drops to say 500, then you are looking more
5881                  * at 2ms and you will raise how much we send in a single
5882                  * TSO thus saving CPU (less bbr_output_wtime() calls). The
5883                  * trade off of course is you will send more at once and
5884                  * thus tend to clump up the sends into larger "bursts"
5885                  * building a queue.
5886                  */
5887                 bw /= bbr->r_ctl.bbr_hptsi_per_second;
5888                 new_tso = roundup(bw, (uint64_t)maxseg);
5889                 /*
5890                  * Gate the floor to match what our lower than 48Mbps
5891                  * algorithm does. The ceiling (bbr_hptsi_segments_max) thus
5892                  * becomes the floor for this calculation.
5893                  */
5894                 if (new_tso < (bbr->r_ctl.bbr_hptsi_segments_max * maxseg))
5895                         new_tso = (bbr->r_ctl.bbr_hptsi_segments_max * maxseg);
5896         }
5897         if (bbr->r_ctl.bbr_hptsi_segments_floor && (new_tso < (maxseg * bbr->r_ctl.bbr_hptsi_segments_floor)))
5898                 new_tso = maxseg * bbr->r_ctl.bbr_hptsi_segments_floor;
5899         if (new_tso > PACE_MAX_IP_BYTES)
5900                 new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5901         /* Enforce an utter maximum. */
5902         if (bbr->r_ctl.bbr_utter_max && (new_tso > (bbr->r_ctl.bbr_utter_max * maxseg))) {
5903                 new_tso = bbr->r_ctl.bbr_utter_max * maxseg;
5904         }
5905         if (old_tso != new_tso) {
5906                 /* Only log changes */
5907                 bbr_log_type_tsosize(bbr, cts, new_tso, tls_seg, old_tso, maxseg, 0);
5908                 bbr->r_ctl.rc_pace_max_segs = new_tso;
5909         }
5910         /* We have hardware pacing! */
5911         bbr_adjust_for_hw_pacing(bbr, cts);
5912 }
5913
5914 static void
5915 bbr_log_output(struct tcp_bbr *bbr, struct tcpcb *tp, struct tcpopt *to, int32_t len,
5916     uint32_t seq_out, uint8_t th_flags, int32_t err, uint32_t cts,
5917     struct mbuf *mb, int32_t * abandon, struct bbr_sendmap *hintrsm, uint32_t delay_calc,
5918     struct sockbuf *sb)
5919 {
5920
5921         struct bbr_sendmap *rsm, *nrsm;
5922         register uint32_t snd_max, snd_una;
5923         uint32_t pacing_time;
5924         /*
5925          * Add to the RACK log of packets in flight or retransmitted. If
5926          * there is a TS option we will use the TS echoed, if not we will
5927          * grab a TS.
5928          *
5929          * Retransmissions will increment the count and move the ts to its
5930          * proper place. Note that if options do not include TS's then we
5931          * won't be able to effectively use the ACK for an RTT on a retran.
5932          *
5933          * Notes about r_start and r_end. Lets consider a send starting at
5934          * sequence 1 for 10 bytes. In such an example the r_start would be
5935          * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
5936          * This means that r_end is actually the first sequence for the next
5937          * slot (11).
5938          *
5939          */
5940         INP_WLOCK_ASSERT(tp->t_inpcb);
5941         if (err) {
5942                 /*
5943                  * We don't log errors -- we could but snd_max does not
5944                  * advance in this case either.
5945                  */
5946                 return;
5947         }
5948         if (th_flags & TH_RST) {
5949                 /*
5950                  * We don't log resets and we return immediately from
5951                  * sending
5952                  */
5953                 *abandon = 1;
5954                 return;
5955         }
5956         snd_una = tp->snd_una;
5957         if (th_flags & (TH_SYN | TH_FIN) && (hintrsm == NULL)) {
5958                 /*
5959                  * The call to bbr_log_output is made before bumping
5960                  * snd_max. This means we can record one extra byte on a SYN
5961                  * or FIN if seq_out is adding more on and a FIN is present
5962                  * (and we are not resending).
5963                  */
5964                 if ((th_flags & TH_SYN) && (tp->iss == seq_out))
5965                         len++;
5966                 if (th_flags & TH_FIN)
5967                         len++;
5968         }
5969         if (SEQ_LEQ((seq_out + len), snd_una)) {
5970                 /* Are sending an old segment to induce an ack (keep-alive)? */
5971                 return;
5972         }
5973         if (SEQ_LT(seq_out, snd_una)) {
5974                 /* huh? should we panic? */
5975                 uint32_t end;
5976
5977                 end = seq_out + len;
5978                 seq_out = snd_una;
5979                 len = end - seq_out;
5980         }
5981         snd_max = tp->snd_max;
5982         if (len == 0) {
5983                 /* We don't log zero window probes */
5984                 return;
5985         }
5986         pacing_time = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, len, cts, 1);
5987         /* First question is it a retransmission? */
5988         if (seq_out == snd_max) {
5989 again:
5990                 rsm = bbr_alloc(bbr);
5991                 if (rsm == NULL) {
5992                         return;
5993                 }
5994                 rsm->r_flags = 0;
5995                 if (th_flags & TH_SYN)
5996                         rsm->r_flags |= BBR_HAS_SYN;
5997                 if (th_flags & TH_FIN)
5998                         rsm->r_flags |= BBR_HAS_FIN;
5999                 rsm->r_tim_lastsent[0] = cts;
6000                 rsm->r_rtr_cnt = 1;
6001                 rsm->r_rtr_bytes = 0;
6002                 rsm->r_start = seq_out;
6003                 rsm->r_end = rsm->r_start + len;
6004                 rsm->r_dupack = 0;
6005                 rsm->r_delivered = bbr->r_ctl.rc_delivered;
6006                 rsm->r_pacing_delay = pacing_time;
6007                 rsm->r_ts_valid = bbr->rc_ts_valid;
6008                 if (bbr->rc_ts_valid)
6009                         rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
6010                 rsm->r_del_time = bbr->r_ctl.rc_del_time;
6011                 if (bbr->r_ctl.r_app_limited_until)
6012                         rsm->r_app_limited = 1;
6013                 else
6014                         rsm->r_app_limited = 0;
6015                 rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
6016                 rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
6017                                                 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
6018                 /*
6019                  * Here we must also add in this rsm since snd_max
6020                  * is updated after we return from a new send.
6021                  */
6022                 rsm->r_flight_at_send += len;
6023                 TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
6024                 TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
6025                 rsm->r_in_tmap = 1;
6026                 if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
6027                         rsm->r_bbr_state = bbr_state_val(bbr);
6028                 else
6029                         rsm->r_bbr_state = 8;
6030                 if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
6031                         rsm->r_is_gain = 1;
6032                         rsm->r_is_drain = 0;
6033                 } else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
6034                         rsm->r_is_drain = 1;
6035                         rsm->r_is_gain = 0;
6036                 } else {
6037                         rsm->r_is_drain = 0;
6038                         rsm->r_is_gain = 0;
6039                 }
6040                 return;
6041         }
6042         /*
6043          * If we reach here its a retransmission and we need to find it.
6044          */
6045 more:
6046         if (hintrsm && (hintrsm->r_start == seq_out)) {
6047                 rsm = hintrsm;
6048                 hintrsm = NULL;
6049         } else if (bbr->r_ctl.rc_next) {
6050                 /* We have a hint from a previous run */
6051                 rsm = bbr->r_ctl.rc_next;
6052         } else {
6053                 /* No hints sorry */
6054                 rsm = NULL;
6055         }
6056         if ((rsm) && (rsm->r_start == seq_out)) {
6057                 /*
6058                  * We used rc_next or hintrsm  to retransmit, hopefully the
6059                  * likely case.
6060                  */
6061                 seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6062                 if (len == 0) {
6063                         return;
6064                 } else {
6065                         goto more;
6066                 }
6067         }
6068         /* Ok it was not the last pointer go through it the hard way. */
6069         TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6070                 if (rsm->r_start == seq_out) {
6071                         seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6072                         bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
6073                         if (len == 0) {
6074                                 return;
6075                         } else {
6076                                 continue;
6077                         }
6078                 }
6079                 if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
6080                         /* Transmitted within this piece */
6081                         /*
6082                          * Ok we must split off the front and then let the
6083                          * update do the rest
6084                          */
6085                         nrsm = bbr_alloc_full_limit(bbr);
6086                         if (nrsm == NULL) {
6087                                 bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
6088                                 return;
6089                         }
6090                         /*
6091                          * copy rsm to nrsm and then trim the front of rsm
6092                          * to not include this part.
6093                          */
6094                         bbr_clone_rsm(bbr, nrsm, rsm, seq_out);
6095                         TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
6096                         if (rsm->r_in_tmap) {
6097                                 TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6098                                 nrsm->r_in_tmap = 1;
6099                         }
6100                         rsm->r_flags &= (~BBR_HAS_FIN);
6101                         seq_out = bbr_update_entry(tp, bbr, nrsm, cts, &len, pacing_time);
6102                         if (len == 0) {
6103                                 return;
6104                         }
6105                 }
6106         }
6107         /*
6108          * Hmm not found in map did they retransmit both old and on into the
6109          * new?
6110          */
6111         if (seq_out == tp->snd_max) {
6112                 goto again;
6113         } else if (SEQ_LT(seq_out, tp->snd_max)) {
6114 #ifdef BBR_INVARIANTS
6115                 printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
6116                     seq_out, len, tp->snd_una, tp->snd_max);
6117                 printf("Starting Dump of all rack entries\n");
6118                 TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6119                         printf("rsm:%p start:%u end:%u\n",
6120                             rsm, rsm->r_start, rsm->r_end);
6121                 }
6122                 printf("Dump complete\n");
6123                 panic("seq_out not found rack:%p tp:%p",
6124                     bbr, tp);
6125 #endif
6126         } else {
6127 #ifdef BBR_INVARIANTS
6128                 /*
6129                  * Hmm beyond sndmax? (only if we are using the new rtt-pack
6130                  * flag)
6131                  */
6132                 panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
6133                     seq_out, len, tp->snd_max, tp);
6134 #endif
6135         }
6136 }
6137
6138 static void
6139 bbr_collapse_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, int32_t rtt)
6140 {
6141         /*
6142          * Collapse timeout back the cum-ack moved.
6143          */
6144         tp->t_rxtshift = 0;
6145         tp->t_softerror = 0;
6146 }
6147
6148 static void
6149 tcp_bbr_xmit_timer(struct tcp_bbr *bbr, uint32_t rtt_usecs, uint32_t rsm_send_time, uint32_t r_start, uint32_t tsin)
6150 {
6151         bbr->rtt_valid = 1;
6152         bbr->r_ctl.cur_rtt = rtt_usecs;
6153         bbr->r_ctl.ts_in = tsin;
6154         if (rsm_send_time)
6155                 bbr->r_ctl.cur_rtt_send_time = rsm_send_time;
6156 }
6157
6158 static void
6159 bbr_make_timestamp_determination(struct tcp_bbr *bbr)
6160 {
6161         /**
6162          * We have in our bbr control:
6163          * 1) The timestamp we started observing cum-acks (bbr->r_ctl.bbr_ts_check_tstmp).
6164          * 2) Our timestamp indicating when we sent that packet (bbr->r_ctl.rsm->bbr_ts_check_our_cts).
6165          * 3) The current timestamp that just came in (bbr->r_ctl.last_inbound_ts)
6166          * 4) The time that the packet that generated that ack was sent (bbr->r_ctl.cur_rtt_send_time)
6167          *
6168          * Now we can calculate the time between the sends by doing:
6169          *
6170          * delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts
6171          *
6172          * And the peer's time between receiving them by doing:
6173          *
6174          * peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp
6175          *
6176          * We want to figure out if the timestamp values are in msec, 10msec or usec.
6177          * We also may find that we can't use the timestamps if say we see
6178          * that the peer_delta indicates that though we may have taken 10ms to
6179          * pace out the data, it only saw 1ms between the two packets. This would
6180          * indicate that somewhere on the path is a batching entity that is giving
6181          * out time-slices of the actual b/w. This would mean we could not use
6182          * reliably the peers timestamps.
6183          *
6184          * We expect delta > peer_delta initially. Until we figure out the
6185          * timestamp difference which we will store in bbr->r_ctl.bbr_peer_tsratio.
6186          * If we place 1000 there then its a ms vs our usec. If we place 10000 there
6187          * then its 10ms vs our usec. If the peer is running a usec clock we would
6188          * put a 1 there. If the value is faster then ours, we will disable the
6189          * use of timestamps (though we could revist this later if we find it to be not
6190          * just an isolated one or two flows)).
6191          *
6192          * To detect the batching middle boxes we will come up with our compensation and
6193          * if with it in place, we find the peer is drastically off (by some margin) in
6194          * the smaller direction, then we will assume the worst case and disable use of timestamps.
6195          *
6196          */
6197         uint64_t delta, peer_delta, delta_up;
6198
6199         delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts;
6200         if (delta < bbr_min_usec_delta) {
6201                 /*
6202                  * Have not seen a min amount of time
6203                  * between our send times so we can
6204                  * make a determination of the timestamp
6205                  * yet.
6206                  */
6207                 return;
6208         }
6209         peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp;
6210         if (peer_delta < bbr_min_peer_delta) {
6211                 /*
6212                  * We may have enough in the form of
6213                  * our delta but the peers number
6214                  * has not changed that much. It could
6215                  * be its clock ratio is such that
6216                  * we need more data (10ms tick) or
6217                  * there may be other compression scenarios
6218                  * going on. In any event we need the
6219                  * spread to be larger.
6220                  */
6221                 return;
6222         }
6223         /* Ok lets first see which way our delta is going */
6224         if (peer_delta > delta) {
6225                 /* Very unlikely, the peer without
6226                  * compensation shows that it saw
6227                  * the two sends arrive further apart
6228                  * then we saw then in micro-seconds.
6229                  */
6230                 if (peer_delta < (delta + ((delta * (uint64_t)1000)/ (uint64_t)bbr_delta_percent))) {
6231                         /* well it looks like the peer is a micro-second clock. */
6232                         bbr->rc_ts_clock_set = 1;
6233                         bbr->r_ctl.bbr_peer_tsratio = 1;
6234                 } else {
6235                         bbr->rc_ts_cant_be_used = 1;
6236                         bbr->rc_ts_clock_set = 1;
6237                 }
6238                 return;
6239         }
6240         /* Ok we know that the peer_delta is smaller than our send distance */
6241         bbr->rc_ts_clock_set = 1;
6242         /* First question is it within the percentage that they are using usec time? */
6243         delta_up = (peer_delta * 1000) / (uint64_t)bbr_delta_percent;
6244         if ((peer_delta + delta_up) >= delta) {
6245                 /* Its a usec clock */
6246                 bbr->r_ctl.bbr_peer_tsratio = 1;
6247                 bbr_log_tstmp_validation(bbr, peer_delta, delta);
6248                 return;
6249         }
6250         /* Ok if not usec, what about 10usec (though unlikely)? */
6251         delta_up = (peer_delta * 1000 * 10) / (uint64_t)bbr_delta_percent;
6252         if (((peer_delta * 10) + delta_up) >= delta) {
6253                 bbr->r_ctl.bbr_peer_tsratio = 10;
6254                 bbr_log_tstmp_validation(bbr, peer_delta, delta);
6255                 return;
6256         }
6257         /* And what about 100usec (though again unlikely)? */
6258         delta_up = (peer_delta * 1000 * 100) / (uint64_t)bbr_delta_percent;
6259         if (((peer_delta * 100) + delta_up) >= delta) {
6260                 bbr->r_ctl.bbr_peer_tsratio = 100;
6261                 bbr_log_tstmp_validation(bbr, peer_delta, delta);
6262                 return;
6263         }
6264         /* And how about 1 msec (the most likely one)? */
6265         delta_up = (peer_delta * 1000 * 1000) / (uint64_t)bbr_delta_percent;
6266         if (((peer_delta * 1000) + delta_up) >= delta) {
6267                 bbr->r_ctl.bbr_peer_tsratio = 1000;
6268                 bbr_log_tstmp_validation(bbr, peer_delta, delta);
6269                 return;
6270         }
6271         /* Ok if not msec could it be 10 msec? */
6272         delta_up = (peer_delta * 1000 * 10000) / (uint64_t)bbr_delta_percent;
6273         if (((peer_delta * 10000) + delta_up) >= delta) {
6274                 bbr->r_ctl.bbr_peer_tsratio = 10000;
6275                 return;
6276         }
6277         /* If we fall down here the clock tick so slowly we can't use it */
6278         bbr->rc_ts_cant_be_used = 1;
6279         bbr->r_ctl.bbr_peer_tsratio = 0;
6280         bbr_log_tstmp_validation(bbr, peer_delta, delta);
6281 }
6282
6283 /*
6284  * Collect new round-trip time estimate
6285  * and update averages and current timeout.
6286  */
6287 static void
6288 tcp_bbr_xmit_timer_commit(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts)
6289 {
6290         int32_t delta;
6291         uint32_t rtt, tsin;
6292         int32_t rtt_ticks;
6293
6294         if (bbr->rtt_valid == 0)
6295                 /* No valid sample */
6296                 return;
6297
6298         rtt = bbr->r_ctl.cur_rtt;
6299         tsin = bbr->r_ctl.ts_in;
6300         if (bbr->rc_prtt_set_ts) {
6301                 /*
6302                  * We are to force feed the rttProp filter due
6303                  * to an entry into PROBE_RTT. This assures
6304                  * that the times are sync'd between when we
6305                  * go into PROBE_RTT and the filter expiration.
6306                  *
6307                  * Google does not use a true filter, so they do
6308                  * this implicitly since they only keep one value
6309                  * and when they enter probe-rtt they update the
6310                  * value to the newest rtt.
6311                  */
6312                 uint32_t rtt_prop;
6313
6314                 bbr->rc_prtt_set_ts = 0;
6315                 rtt_prop = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
6316                 if (rtt > rtt_prop)
6317                         filter_increase_by_small(&bbr->r_ctl.rc_rttprop, (rtt - rtt_prop), cts);
6318                 else
6319                         apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6320         }
6321         if (bbr->rc_ack_was_delayed)
6322                 rtt += bbr->r_ctl.rc_ack_hdwr_delay;
6323
6324         if (rtt < bbr->r_ctl.rc_lowest_rtt)
6325                 bbr->r_ctl.rc_lowest_rtt = rtt;
6326         bbr_log_rtt_sample(bbr, rtt, tsin);
6327         if (bbr->r_init_rtt) {
6328                 /*
6329                  * The initial rtt is not-trusted, nuke it and lets get
6330                  * our first valid measurement in.
6331                  */
6332                 bbr->r_init_rtt = 0;
6333                 tp->t_srtt = 0;
6334         }
6335         if ((bbr->rc_ts_clock_set == 0) && bbr->rc_ts_valid) {
6336                 /*
6337                  * So we have not yet figured out
6338                  * what the peers TSTMP value is
6339                  * in (most likely ms). We need a
6340                  * series of cum-ack's to determine
6341                  * this reliably.
6342                  */
6343                 if (bbr->rc_ack_is_cumack) {
6344                         if (bbr->rc_ts_data_set) {
6345                                 /* Lets attempt to determine the timestamp granularity. */
6346                                 bbr_make_timestamp_determination(bbr);
6347                         } else {
6348                                 bbr->rc_ts_data_set = 1;
6349                                 bbr->r_ctl.bbr_ts_check_tstmp = bbr->r_ctl.last_inbound_ts;
6350                                 bbr->r_ctl.bbr_ts_check_our_cts = bbr->r_ctl.cur_rtt_send_time;
6351                         }
6352                 } else {
6353                         /*
6354                          * We have to have consecutive acks
6355                          * reset any "filled" state to none.
6356                          */
6357                         bbr->rc_ts_data_set = 0;
6358                 }
6359         }
6360         /* Round it up */
6361         rtt_ticks = USEC_2_TICKS((rtt + (USECS_IN_MSEC - 1)));
6362         if (rtt_ticks == 0)
6363                 rtt_ticks = 1;
6364         if (tp->t_srtt != 0) {
6365                 /*
6366                  * srtt is stored as fixed point with 5 bits after the
6367                  * binary point (i.e., scaled by 8).  The following magic is
6368                  * equivalent to the smoothing algorithm in rfc793 with an
6369                  * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6370                  * Adjust rtt to origin 0.
6371                  */
6372
6373                 delta = ((rtt_ticks - 1) << TCP_DELTA_SHIFT)
6374                     - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6375
6376                 tp->t_srtt += delta;
6377                 if (tp->t_srtt <= 0)
6378                         tp->t_srtt = 1;
6379
6380                 /*
6381                  * We accumulate a smoothed rtt variance (actually, a
6382                  * smoothed mean difference), then set the retransmit timer
6383                  * to smoothed rtt + 4 times the smoothed variance. rttvar
6384                  * is stored as fixed point with 4 bits after the binary
6385                  * point (scaled by 16).  The following is equivalent to
6386                  * rfc793 smoothing with an alpha of .75 (rttvar =
6387                  * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
6388                  * wired-in beta.
6389                  */
6390                 if (delta < 0)
6391                         delta = -delta;
6392                 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6393                 tp->t_rttvar += delta;
6394                 if (tp->t_rttvar <= 0)
6395                         tp->t_rttvar = 1;
6396                 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
6397                         tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6398         } else {
6399                 /*
6400                  * No rtt measurement yet - use the unsmoothed rtt. Set the
6401                  * variance to half the rtt (so our first retransmit happens
6402                  * at 3*rtt).
6403                  */
6404                 tp->t_srtt = rtt_ticks << TCP_RTT_SHIFT;
6405                 tp->t_rttvar = rtt_ticks << (TCP_RTTVAR_SHIFT - 1);
6406                 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6407         }
6408         KMOD_TCPSTAT_INC(tcps_rttupdated);
6409         tp->t_rttupdated++;
6410 #ifdef STATS
6411         stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt_ticks));
6412 #endif
6413         /*
6414          * the retransmit should happen at rtt + 4 * rttvar. Because of the
6415          * way we do the smoothing, srtt and rttvar will each average +1/2
6416          * tick of bias.  When we compute the retransmit timer, we want 1/2
6417          * tick of rounding and 1 extra tick because of +-1/2 tick
6418          * uncertainty in the firing of the timer.  The bias will give us
6419          * exactly the 1.5 tick we need.  But, because the bias is
6420          * statistical, we have to test that we don't drop below the minimum
6421          * feasible timer (which is 2 ticks).
6422          */
6423         TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6424             max(MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms), rtt_ticks + 2),
6425             MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
6426
6427         /*
6428          * We received an ack for a packet that wasn't retransmitted; it is
6429          * probably safe to discard any error indications we've received
6430          * recently.  This isn't quite right, but close enough for now (a
6431          * route might have failed after we sent a segment, and the return
6432          * path might not be symmetrical).
6433          */
6434         tp->t_softerror = 0;
6435         rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
6436         if (bbr->r_ctl.bbr_smallest_srtt_this_state > rtt)
6437                 bbr->r_ctl.bbr_smallest_srtt_this_state = rtt;
6438 }
6439
6440 static void
6441 bbr_set_reduced_rtt(struct tcp_bbr *bbr, uint32_t cts, uint32_t line)
6442 {
6443         bbr->r_ctl.rc_rtt_shrinks = cts;
6444         if (bbr_can_force_probertt &&
6445             (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
6446             ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
6447                 /*
6448                  * We should enter probe-rtt its been too long
6449                  * since we have been there.
6450                  */
6451                 bbr_enter_probe_rtt(bbr, cts, __LINE__);
6452         } else
6453                 bbr_check_probe_rtt_limits(bbr, cts);
6454 }
6455
6456 static void
6457 tcp_bbr_commit_bw(struct tcp_bbr *bbr, uint32_t cts)
6458 {
6459         uint64_t orig_bw;
6460
6461         if (bbr->r_ctl.rc_bbr_cur_del_rate == 0) {
6462                 /* We never apply a zero measurment */
6463                 bbr_log_type_bbrupd(bbr, 20, cts, 0, 0,
6464                                     0, 0, 0, 0, 0, 0);
6465                 return;
6466         }
6467         if (bbr->r_ctl.r_measurement_count < 0xffffffff)
6468                 bbr->r_ctl.r_measurement_count++;
6469         orig_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
6470         apply_filter_max(&bbr->r_ctl.rc_delrate, bbr->r_ctl.rc_bbr_cur_del_rate, bbr->r_ctl.rc_pkt_epoch);
6471         bbr_log_type_bbrupd(bbr, 21, cts, (uint32_t)orig_bw,
6472                             (uint32_t)get_filter_value(&bbr->r_ctl.rc_delrate),
6473                             0, 0, 0, 0, 0, 0);
6474         if (orig_bw &&
6475             (orig_bw != get_filter_value(&bbr->r_ctl.rc_delrate))) {
6476                 if (bbr->bbr_hdrw_pacing) {
6477                         /*
6478                          * Apply a new rate to the hardware
6479                          * possibly.
6480                          */
6481                         bbr_update_hardware_pacing_rate(bbr, cts);
6482                 }
6483                 bbr_set_state_target(bbr, __LINE__);
6484                 tcp_bbr_tso_size_check(bbr, cts);
6485                 if (bbr->r_recovery_bw)  {
6486                         bbr_setup_red_bw(bbr, cts);
6487                         bbr_log_type_bw_reduce(bbr, BBR_RED_BW_USELRBW);
6488                 }
6489         } else if ((orig_bw == 0) && get_filter_value(&bbr->r_ctl.rc_delrate))
6490                 tcp_bbr_tso_size_check(bbr, cts);
6491 }
6492
6493 static void
6494 bbr_nf_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6495 {
6496         if (bbr->rc_in_persist == 0) {
6497                 /* We log only when not in persist */
6498                 /* Translate to a Bytes Per Second */
6499                 uint64_t tim, bw, ts_diff, ts_bw;
6500                 uint32_t upper, lower, delivered;
6501
6502                 if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6503                         tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6504                 else
6505                         tim = 1;
6506                 /*
6507                  * Now that we have processed the tim (skipping the sample
6508                  * or possibly updating the time, go ahead and
6509                  * calculate the cdr.
6510                  */
6511                 delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6512                 bw = (uint64_t)delivered;
6513                 bw *= (uint64_t)USECS_IN_SECOND;
6514                 bw /= tim;
6515                 if (bw == 0) {
6516                         /* We must have a calculatable amount */
6517                         return;
6518                 }
6519                 upper = (bw >> 32) & 0x00000000ffffffff;
6520                 lower = bw & 0x00000000ffffffff;
6521                 /*
6522                  * If we are using this b/w shove it in now so we
6523                  * can see in the trace viewer if it gets over-ridden.
6524                  */
6525                 if (rsm->r_ts_valid &&
6526                     bbr->rc_ts_valid &&
6527                     bbr->rc_ts_clock_set &&
6528                     (bbr->rc_ts_cant_be_used == 0) &&
6529                     bbr->rc_use_ts_limit) {
6530                         ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6531                         ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6532                         if ((delivered == 0) ||
6533                             (rtt < 1000)) {
6534                                 /* Can't use the ts */
6535                                 bbr_log_type_bbrupd(bbr, 61, cts,
6536                                                     ts_diff,
6537                                                     bbr->r_ctl.last_inbound_ts,
6538                                                     rsm->r_del_ack_ts, 0,
6539                                                     0, 0, 0, delivered);
6540                         } else {
6541                                 ts_bw = (uint64_t)delivered;
6542                                 ts_bw *= (uint64_t)USECS_IN_SECOND;
6543                                 ts_bw /= ts_diff;
6544                                 bbr_log_type_bbrupd(bbr, 62, cts,
6545                                                     (ts_bw >> 32),
6546                                                     (ts_bw & 0xffffffff), 0, 0,
6547                                                     0, 0, ts_diff, delivered);
6548                                 if ((bbr->ts_can_raise) &&
6549                                     (ts_bw > bw)) {
6550                                         bbr_log_type_bbrupd(bbr, 8, cts,
6551                                                             delivered,
6552                                                             ts_diff,
6553                                                             (bw >> 32),
6554                                                             (bw & 0x00000000ffffffff),
6555                                                             0, 0, 0, 0);
6556                                         bw = ts_bw;
6557                                 } else if (ts_bw && (ts_bw < bw)) {
6558                                         bbr_log_type_bbrupd(bbr, 7, cts,
6559                                                             delivered,
6560                                                             ts_diff,
6561                                                             (bw >> 32),
6562                                                             (bw & 0x00000000ffffffff),
6563                                                             0, 0, 0, 0);
6564                                         bw = ts_bw;
6565                                 }
6566                         }
6567                 }
6568                 if (rsm->r_first_sent_time &&
6569                     TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6570                         uint64_t sbw, sti;
6571                         /*
6572                          * We use what was in flight at the time of our
6573                          * send  and the size of this send to figure
6574                          * out what we have been sending at (amount).
6575                          * For the time we take from the time of
6576                          * the send of the first send outstanding
6577                          * until this send plus this sends pacing
6578                          * time. This gives us a good calculation
6579                          * as to the rate we have been sending at.
6580                          */
6581
6582                         sbw = (uint64_t)(rsm->r_flight_at_send);
6583                         sbw *= (uint64_t)USECS_IN_SECOND;
6584                         sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6585                         sti += rsm->r_pacing_delay;
6586                         sbw /= sti;
6587                         if (sbw < bw) {
6588                                 bbr_log_type_bbrupd(bbr, 6, cts,
6589                                                     delivered,
6590                                                     (uint32_t)sti,
6591                                                     (bw >> 32),
6592                                                     (uint32_t)bw,
6593                                                     rsm->r_first_sent_time, 0, (sbw >> 32),
6594                                                     (uint32_t)sbw);
6595                                 bw = sbw;
6596                         }
6597                 }
6598                 /* Use the google algorithm for b/w measurements */
6599                 bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6600                 if ((rsm->r_app_limited == 0) ||
6601                     (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6602                         tcp_bbr_commit_bw(bbr, cts);
6603                         bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6604                                             0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6605                 }
6606         }
6607 }
6608
6609 static void
6610 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6611 {
6612         if (bbr->rc_in_persist == 0) {
6613                 /* We log only when not in persist */
6614                 /* Translate to a Bytes Per Second */
6615                 uint64_t tim, bw;
6616                 uint32_t upper, lower, delivered;
6617                 int no_apply = 0;
6618
6619                 if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6620                         tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6621                 else
6622                         tim = 1;
6623                 /*
6624                  * Now that we have processed the tim (skipping the sample
6625                  * or possibly updating the time, go ahead and
6626                  * calculate the cdr.
6627                  */
6628                 delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6629                 bw = (uint64_t)delivered;
6630                 bw *= (uint64_t)USECS_IN_SECOND;
6631                 bw /= tim;
6632                 if (tim < bbr->r_ctl.rc_lowest_rtt) {
6633                         bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6634                                             tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6635
6636                         no_apply = 1;
6637                 }
6638                 upper = (bw >> 32) & 0x00000000ffffffff;
6639                 lower = bw & 0x00000000ffffffff;
6640                 /*
6641                  * If we are using this b/w shove it in now so we
6642                  * can see in the trace viewer if it gets over-ridden.
6643                  */
6644                 bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6645                 /* Gate by the sending rate */
6646                 if (rsm->r_first_sent_time &&
6647                     TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6648                         uint64_t sbw, sti;
6649                         /*
6650                          * We use what was in flight at the time of our
6651                          * send  and the size of this send to figure
6652                          * out what we have been sending at (amount).
6653                          * For the time we take from the time of
6654                          * the send of the first send outstanding
6655                          * until this send plus this sends pacing
6656                          * time. This gives us a good calculation
6657                          * as to the rate we have been sending at.
6658                          */
6659
6660                         sbw = (uint64_t)(rsm->r_flight_at_send);
6661                         sbw *= (uint64_t)USECS_IN_SECOND;
6662                         sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6663                         sti += rsm->r_pacing_delay;
6664                         sbw /= sti;
6665                         if (sbw < bw) {
6666                                 bbr_log_type_bbrupd(bbr, 6, cts,
6667                                                     delivered,
6668                                                     (uint32_t)sti,
6669                                                     (bw >> 32),
6670                                                     (uint32_t)bw,
6671                                                     rsm->r_first_sent_time, 0, (sbw >> 32),
6672                                                     (uint32_t)sbw);
6673                                 bw = sbw;
6674                         }
6675                         if ((sti > tim) &&
6676                             (sti < bbr->r_ctl.rc_lowest_rtt)) {
6677                                 bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6678                                                     (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6679                                 no_apply = 1;
6680                         } else
6681                                 no_apply = 0;
6682                 }
6683                 bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6684                 if ((no_apply == 0) &&
6685                     ((rsm->r_app_limited == 0) ||
6686                      (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6687                         tcp_bbr_commit_bw(bbr, cts);
6688                         bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6689                                             0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6690                 }
6691         }
6692 }
6693
6694 static void
6695 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6696     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6697 {
6698         uint64_t old_rttprop;
6699
6700         /* Update our delivery time and amount */
6701         bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6702         bbr->r_ctl.rc_del_time = cts;
6703         if (rtt == 0) {
6704                 /*
6705                  * 0 means its a retransmit, for now we don't use these for
6706                  * the rest of BBR.
6707                  */
6708                 return;
6709         }
6710         if ((bbr->rc_use_google == 0) &&
6711             (match != BBR_RTT_BY_EXACTMATCH) &&
6712             (match != BBR_RTT_BY_TIMESTAMP)){
6713                 /*
6714                  * We get a lot of rtt updates, lets not pay attention to
6715                  * any that are not an exact match. That way we don't have
6716                  * to worry about timestamps and the whole nonsense of
6717                  * unsure if its a retransmission etc (if we ever had the
6718                  * timestamp fixed to always have the last thing sent this
6719                  * would not be a issue).
6720                  */
6721                 return;
6722         }
6723         if ((bbr_no_retran && bbr->rc_use_google) &&
6724             (match != BBR_RTT_BY_EXACTMATCH) &&
6725             (match != BBR_RTT_BY_TIMESTAMP)){
6726                 /*
6727                  * We only do measurements in google mode
6728                  * with bbr_no_retran on for sure things.
6729                  */
6730                 return;
6731         }
6732         /* Only update srtt if we know by exact match */
6733         tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6734         if (ack_type == BBR_CUM_ACKED)
6735                 bbr->rc_ack_is_cumack = 1;
6736         else
6737                 bbr->rc_ack_is_cumack = 0;
6738         old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6739         /*
6740          * Note the following code differs to the original
6741          * BBR spec. It calls for <= not <. However after a
6742          * long discussion in email with Neal, he acknowledged
6743          * that it should be < than so that we will have flows
6744          * going into probe-rtt (we were seeing cases where that
6745          * did not happen and caused ugly things to occur). We
6746          * have added this agreed upon fix to our code base.
6747          */
6748         if (rtt < old_rttprop) {
6749                 /* Update when we last saw a rtt drop */
6750                 bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6751                 bbr_set_reduced_rtt(bbr, cts, __LINE__);
6752         }
6753         bbr_log_type_bbrrttprop(bbr, rtt, (rsm ? rsm->r_end : 0), uts, cts,
6754             match, rsm->r_start, rsm->r_flags);
6755         apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6756         if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6757                 /*
6758                  * The RTT-prop moved, reset the target (may be a
6759                  * nop for some states).
6760                  */
6761                 bbr_set_state_target(bbr, __LINE__);
6762                 if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6763                         bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6764                                             __LINE__, BBR_RTTS_NEW_TARGET, 0);
6765                 else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6766                         /* It went up */
6767                         bbr_check_probe_rtt_limits(bbr, cts);
6768         }
6769         if ((bbr->rc_use_google == 0) &&
6770             (match == BBR_RTT_BY_TIMESTAMP)) {
6771                 /*
6772                  * We don't do b/w update with
6773                  * these since they are not really
6774                  * reliable.
6775                  */
6776                 return;
6777         }
6778         if (bbr->r_ctl.r_app_limited_until &&
6779             (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6780                 /* We are no longer app-limited */
6781                 bbr->r_ctl.r_app_limited_until = 0;
6782         }
6783         if (bbr->rc_use_google) {
6784                 bbr_google_measurement(bbr, rsm, rtt, cts);
6785         } else {
6786                 bbr_nf_measurement(bbr, rsm, rtt, cts);
6787         }
6788 }
6789
6790 /*
6791  * Convert a timestamp that the main stack
6792  * uses (milliseconds) into one that bbr uses
6793  * (microseconds). Return that converted timestamp.
6794  */
6795 static uint32_t
6796 bbr_ts_convert(uint32_t cts) {
6797         uint32_t sec, msec;
6798
6799         sec = cts / MS_IN_USEC;
6800         msec = cts - (MS_IN_USEC * sec);
6801         return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6802 }
6803
6804 /*
6805  * Return 0 if we did not update the RTT time, return
6806  * 1 if we did.
6807  */
6808 static int
6809 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6810     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6811 {
6812         int32_t i;
6813         uint32_t t, uts = 0;
6814
6815         if ((rsm->r_flags & BBR_ACKED) ||
6816             (rsm->r_flags & BBR_WAS_RENEGED) ||
6817             (rsm->r_flags & BBR_RXT_CLEARED)) {
6818                 /* Already done */
6819                 return (0);
6820         }
6821         if (rsm->r_rtt_not_allowed) {
6822                 /* Not allowed */
6823                 return (0);
6824         }
6825         if (rsm->r_rtr_cnt == 1) {
6826                 /*
6827                  * Only one transmit. Hopefully the normal case.
6828                  */
6829                 if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6830                         t = cts - rsm->r_tim_lastsent[0];
6831                 else
6832                         t = 1;
6833                 if ((int)t <= 0)
6834                         t = 1;
6835                 bbr->r_ctl.rc_last_rtt = t;
6836                 bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6837                                     BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6838                 return (1);
6839         }
6840         /* Convert to usecs */
6841         if ((bbr_can_use_ts_for_rtt == 1) &&
6842             (bbr->rc_use_google == 1) &&
6843             (ack_type == BBR_CUM_ACKED) &&
6844             (to->to_flags & TOF_TS) &&
6845             (to->to_tsecr != 0)) {
6846                 t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
6847                 if (t < 1)
6848                         t = 1;
6849                 t *= MS_IN_USEC;
6850                 bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6851                                     BBR_RTT_BY_TIMESTAMP,
6852                                     rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
6853                                     ack_type, to);
6854                 return (1);
6855         }
6856         uts = bbr_ts_convert(to->to_tsecr);
6857         if ((to->to_flags & TOF_TS) &&
6858             (to->to_tsecr != 0) &&
6859             (ack_type == BBR_CUM_ACKED) &&
6860             ((rsm->r_flags & BBR_OVERMAX) == 0)) {
6861                 /*
6862                  * Now which timestamp does it match? In this block the ACK
6863                  * may be coming from a previous transmission.
6864                  */
6865                 uint32_t fudge;
6866
6867                 fudge = BBR_TIMER_FUDGE;
6868                 for (i = 0; i < rsm->r_rtr_cnt; i++) {
6869                         if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
6870                             (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
6871                                 if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6872                                         t = cts - rsm->r_tim_lastsent[i];
6873                                 else
6874                                         t = 1;
6875                                 if ((int)t <= 0)
6876                                         t = 1;
6877                                 bbr->r_ctl.rc_last_rtt = t;
6878                                 bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
6879                                                     rsm->r_tim_lastsent[i], ack_type, to);
6880                                 if ((i + 1) < rsm->r_rtr_cnt) {
6881                                         /* Likely */
6882                                         return (0);
6883                                 } else if (rsm->r_flags & BBR_TLP) {
6884                                         bbr->rc_tlp_rtx_out = 0;
6885                                 }
6886                                 return (1);
6887                         }
6888                 }
6889                 /* Fall through if we can't find a matching timestamp */
6890         }
6891         /*
6892          * Ok its a SACK block that we retransmitted. or a windows
6893          * machine without timestamps. We can tell nothing from the
6894          * time-stamp since its not there or the time the peer last
6895          * recieved a segment that moved forward its cum-ack point.
6896          *
6897          * Lets look at the last retransmit and see what we can tell
6898          * (with BBR for space we only keep 2 note we have to keep
6899          * at least 2 so the map can not be condensed more).
6900          */
6901         i = rsm->r_rtr_cnt - 1;
6902         if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6903                 t = cts - rsm->r_tim_lastsent[i];
6904         else
6905                 goto not_sure;
6906         if (t < bbr->r_ctl.rc_lowest_rtt) {
6907                 /*
6908                  * We retransmitted and the ack came back in less
6909                  * than the smallest rtt we have observed in the
6910                  * windowed rtt. We most likey did an improper
6911                  * retransmit as outlined in 4.2 Step 3 point 2 in
6912                  * the rack-draft.
6913                  *
6914                  * Use the prior transmission to update all the
6915                  * information as long as there is only one prior
6916                  * transmission.
6917                  */
6918                 if ((rsm->r_flags & BBR_OVERMAX) == 0) {
6919 #ifdef BBR_INVARIANTS
6920                         if (rsm->r_rtr_cnt == 1)
6921                                 panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
6922 #endif
6923                         i = rsm->r_rtr_cnt - 2;
6924                         if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6925                                 t = cts - rsm->r_tim_lastsent[i];
6926                         else
6927                                 t = 1;
6928                         bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
6929                                             rsm->r_tim_lastsent[i], ack_type, to);
6930                         return (0);
6931                 } else {
6932                         /*
6933                          * Too many prior transmissions, just
6934                          * updated BBR delivered
6935                          */
6936 not_sure:
6937                         bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6938                                             BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6939                 }
6940         } else {
6941                 /*
6942                  * We retransmitted it and the retransmit did the
6943                  * job.
6944                  */
6945                 if (rsm->r_flags & BBR_TLP)
6946                         bbr->rc_tlp_rtx_out = 0;
6947                 if ((rsm->r_flags & BBR_OVERMAX) == 0)
6948                         bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
6949                                             BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
6950                 else
6951                         bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6952                                             BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6953                 return (1);
6954         }
6955         return (0);
6956 }
6957
6958 /*
6959  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
6960  */
6961 static void
6962 bbr_log_sack_passed(struct tcpcb *tp,
6963     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
6964 {
6965         struct bbr_sendmap *nrsm;
6966
6967         nrsm = rsm;
6968         TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
6969             bbr_head, r_tnext) {
6970                 if (nrsm == rsm) {
6971                         /* Skip orginal segment he is acked */
6972                         continue;
6973                 }
6974                 if (nrsm->r_flags & BBR_ACKED) {
6975                         /* Skip ack'd segments */
6976                         continue;
6977                 }
6978                 if (nrsm->r_flags & BBR_SACK_PASSED) {
6979                         /*
6980                          * We found one that is already marked
6981                          * passed, we have been here before and
6982                          * so all others below this are marked.
6983                          */
6984                         break;
6985                 }
6986                 BBR_STAT_INC(bbr_sack_passed);
6987                 nrsm->r_flags |= BBR_SACK_PASSED;
6988                 if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
6989                     bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
6990                         bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
6991                         bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
6992                         nrsm->r_flags |= BBR_MARKED_LOST;
6993                 }
6994                 nrsm->r_flags &= ~BBR_WAS_SACKPASS;
6995         }
6996 }
6997
6998 /*
6999  * Returns the number of bytes that were
7000  * newly ack'd by sack blocks.
7001  */
7002 static uint32_t
7003 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
7004     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
7005 {
7006         int32_t times = 0;
7007         uint32_t start, end, maxseg, changed = 0;
7008         struct bbr_sendmap *rsm, *nrsm;
7009         int32_t used_ref = 1;
7010         uint8_t went_back = 0, went_fwd = 0;
7011
7012         maxseg = tp->t_maxseg - bbr->rc_last_options;
7013         start = sack->start;
7014         end = sack->end;
7015         rsm = *prsm;
7016         if (rsm == NULL)
7017                 used_ref = 0;
7018
7019         /* Do we locate the block behind where we last were? */
7020         if (rsm && SEQ_LT(start, rsm->r_start)) {
7021                 went_back = 1;
7022                 TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
7023                         if (SEQ_GEQ(start, rsm->r_start) &&
7024                             SEQ_LT(start, rsm->r_end)) {
7025                                 goto do_rest_ofb;
7026                         }
7027                 }
7028         }
7029 start_at_beginning:
7030         went_fwd = 1;
7031         /*
7032          * Ok lets locate the block where this guy is fwd from rsm (if its
7033          * set)
7034          */
7035         TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
7036                 if (SEQ_GEQ(start, rsm->r_start) &&
7037                     SEQ_LT(start, rsm->r_end)) {
7038                         break;
7039                 }
7040         }
7041 do_rest_ofb:
7042         if (rsm == NULL) {
7043                 /*
7044                  * This happens when we get duplicate sack blocks with the
7045                  * same end. For example SACK 4: 100 SACK 3: 100 The sort
7046                  * will not change there location so we would just start at
7047                  * the end of the first one and get lost.
7048                  */
7049                 if (tp->t_flags & TF_SENTFIN) {
7050                         /*
7051                          * Check to see if we have not logged the FIN that
7052                          * went out.
7053                          */
7054                         nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7055                         if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
7056                                 /*
7057                                  * Ok we did not get the FIN logged.
7058                                  */
7059                                 nrsm->r_end++;
7060                                 rsm = nrsm;
7061                                 goto do_rest_ofb;
7062                         }
7063                 }
7064                 if (times == 1) {
7065 #ifdef BBR_INVARIANTS
7066                         panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7067                             tp, bbr, sack, to, prsm);
7068 #else
7069                         goto out;
7070 #endif
7071                 }
7072                 times++;
7073                 BBR_STAT_INC(bbr_sack_proc_restart);
7074                 rsm = NULL;
7075                 goto start_at_beginning;
7076         }
7077         /* Ok we have an ACK for some piece of rsm */
7078         if (rsm->r_start != start) {
7079                 /*
7080                  * Need to split this in two pieces the before and after.
7081                  */
7082                 if (bbr_sack_mergable(rsm, start, end))
7083                         nrsm = bbr_alloc_full_limit(bbr);
7084                 else
7085                         nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7086                 if (nrsm == NULL) {
7087                         /* We could not allocate ignore the sack */
7088                         struct sackblk blk;
7089
7090                         blk.start = start;
7091                         blk.end = end;
7092                         sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7093                         goto out;
7094                 }
7095                 bbr_clone_rsm(bbr, nrsm, rsm, start);
7096                 TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7097                 if (rsm->r_in_tmap) {
7098                         TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7099                         nrsm->r_in_tmap = 1;
7100                 }
7101                 rsm->r_flags &= (~BBR_HAS_FIN);
7102                 rsm = nrsm;
7103         }
7104         if (SEQ_GEQ(end, rsm->r_end)) {
7105                 /*
7106                  * The end of this block is either beyond this guy or right
7107                  * at this guy.
7108                  */
7109                 if ((rsm->r_flags & BBR_ACKED) == 0) {
7110                         bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7111                         changed += (rsm->r_end - rsm->r_start);
7112                         bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7113                         bbr_log_sack_passed(tp, bbr, rsm);
7114                         if (rsm->r_flags & BBR_MARKED_LOST) {
7115                                 bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7116                         }
7117                         /* Is Reordering occuring? */
7118                         if (rsm->r_flags & BBR_SACK_PASSED) {
7119                                 BBR_STAT_INC(bbr_reorder_seen);
7120                                 bbr->r_ctl.rc_reorder_ts = cts;
7121                                 if (rsm->r_flags & BBR_MARKED_LOST) {
7122                                         bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7123                                         if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7124                                                 /* LT sampling also needs adjustment */
7125                                                 bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7126                                 }
7127                         }
7128                         rsm->r_flags |= BBR_ACKED;
7129                         rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7130                         if (rsm->r_in_tmap) {
7131                                 TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7132                                 rsm->r_in_tmap = 0;
7133                         }
7134                 }
7135                 bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7136                 if (end == rsm->r_end) {
7137                         /* This block only - done */
7138                         goto out;
7139                 }
7140                 /* There is more not coverend by this rsm move on */
7141                 start = rsm->r_end;
7142                 nrsm = TAILQ_NEXT(rsm, r_next);
7143                 rsm = nrsm;
7144                 times = 0;
7145                 goto do_rest_ofb;
7146         }
7147         if (rsm->r_flags & BBR_ACKED) {
7148                 /* Been here done that */
7149                 goto out;
7150         }
7151         /* Ok we need to split off this one at the tail */
7152         if (bbr_sack_mergable(rsm, start, end))
7153                 nrsm = bbr_alloc_full_limit(bbr);
7154         else
7155                 nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7156         if (nrsm == NULL) {
7157                 /* failed XXXrrs what can we do but loose the sack info? */
7158                 struct sackblk blk;
7159
7160                 blk.start = start;
7161                 blk.end = end;
7162                 sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7163                 goto out;
7164         }
7165         /* Clone it */
7166         bbr_clone_rsm(bbr, nrsm, rsm, end);
7167         /* The sack block does not cover this guy fully */
7168         rsm->r_flags &= (~BBR_HAS_FIN);
7169         TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7170         if (rsm->r_in_tmap) {
7171                 TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7172                 nrsm->r_in_tmap = 1;
7173         }
7174         nrsm->r_dupack = 0;
7175         bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7176         bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7177         changed += (rsm->r_end - rsm->r_start);
7178         bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7179         bbr_log_sack_passed(tp, bbr, rsm);
7180         /* Is Reordering occuring? */
7181         if (rsm->r_flags & BBR_MARKED_LOST) {
7182                 bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7183         }
7184         if (rsm->r_flags & BBR_SACK_PASSED) {
7185                 BBR_STAT_INC(bbr_reorder_seen);
7186                 bbr->r_ctl.rc_reorder_ts = cts;
7187                 if (rsm->r_flags & BBR_MARKED_LOST) {
7188                         bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7189                         if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7190                                 /* LT sampling also needs adjustment */
7191                                 bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7192                 }
7193         }
7194         rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7195         rsm->r_flags |= BBR_ACKED;
7196         if (rsm->r_in_tmap) {
7197                 TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7198                 rsm->r_in_tmap = 0;
7199         }
7200 out:
7201         if (rsm && (rsm->r_flags & BBR_ACKED)) {
7202                 /*
7203                  * Now can we merge this newly acked
7204                  * block with either the previous or
7205                  * next block?
7206                  */
7207                 nrsm = TAILQ_NEXT(rsm, r_next);
7208                 if (nrsm &&
7209                     (nrsm->r_flags & BBR_ACKED)) {
7210                         /* yep this and next can be merged */
7211                         rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7212                 }
7213                 /* Now what about the previous? */
7214                 nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7215                 if (nrsm &&
7216                     (nrsm->r_flags & BBR_ACKED)) {
7217                         /* yep the previous and this can be merged */
7218                         rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7219                 }
7220         }
7221         if (used_ref == 0) {
7222                 BBR_STAT_INC(bbr_sack_proc_all);
7223         } else {
7224                 BBR_STAT_INC(bbr_sack_proc_short);
7225         }
7226         if (went_fwd && went_back) {
7227                 BBR_STAT_INC(bbr_sack_search_both);
7228         } else if (went_fwd) {
7229                 BBR_STAT_INC(bbr_sack_search_fwd);
7230         } else if (went_back) {
7231                 BBR_STAT_INC(bbr_sack_search_back);
7232         }
7233         /* Save off where the next seq is */
7234         if (rsm)
7235                 bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7236         else
7237                 bbr->r_ctl.rc_sacklast = NULL;
7238         *prsm = rsm;
7239         return (changed);
7240 }
7241
7242 static void inline
7243 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7244 {
7245         struct bbr_sendmap *tmap;
7246
7247         BBR_STAT_INC(bbr_reneges_seen);
7248         tmap = NULL;
7249         while (rsm && (rsm->r_flags & BBR_ACKED)) {
7250                 /* Its no longer sacked, mark it so */
7251                 uint32_t oflags;
7252                 bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7253 #ifdef BBR_INVARIANTS
7254                 if (rsm->r_in_tmap) {
7255                         panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7256                             bbr, rsm, rsm->r_flags);
7257                 }
7258 #endif
7259                 oflags = rsm->r_flags;
7260                 if (rsm->r_flags & BBR_MARKED_LOST) {
7261                         bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7262                         bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7263                         if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7264                                 /* LT sampling also needs adjustment */
7265                                 bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7266                 }
7267                 rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7268                 rsm->r_flags |= BBR_WAS_RENEGED;
7269                 rsm->r_flags |= BBR_RXT_CLEARED;
7270                 bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7271                 /* Rebuild it into our tmap */
7272                 if (tmap == NULL) {
7273                         TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7274                         tmap = rsm;
7275                 } else {
7276                         TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7277                         tmap = rsm;
7278                 }
7279                 tmap->r_in_tmap = 1;
7280                 /*
7281                  * XXXrrs Delivered? Should we do anything here?
7282                  *
7283                  * Of course we don't on a rxt timeout so maybe its ok that
7284                  * we don't?
7285                  *
7286                  * For now lets not.
7287                  */
7288                 rsm = TAILQ_NEXT(rsm, r_next);
7289         }
7290         /*
7291          * Now lets possibly clear the sack filter so we start recognizing
7292          * sacks that cover this area.
7293          */
7294         sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7295 }
7296
7297 static void
7298 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7299 {
7300         struct tcp_bbr *bbr;
7301         struct bbr_sendmap *rsm;
7302         uint32_t cts;
7303
7304         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7305         cts = bbr->r_ctl.rc_rcvtime;
7306         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7307         if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7308                 if ((rsm->r_end - rsm->r_start) <= 1) {
7309                         /* Log out the SYN completely */
7310                         bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7311                         rsm->r_rtr_bytes = 0;
7312                         TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7313                         if (rsm->r_in_tmap) {
7314                                 TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7315                                 rsm->r_in_tmap = 0;
7316                         }
7317                         if (bbr->r_ctl.rc_next == rsm) {
7318                                 /* scoot along the marker */
7319                                 bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7320                         }
7321                         if (to != NULL)
7322                                 bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7323                         bbr_free(bbr, rsm);
7324                 } else {
7325                         /* There is more (Fast open)? strip out SYN. */
7326                         rsm->r_flags &= ~BBR_HAS_SYN;
7327                         rsm->r_start++;
7328                 }
7329         }
7330 }
7331
7332 /*
7333  * Returns the number of bytes that were
7334  * acknowledged by SACK blocks.
7335  */
7336
7337 static uint32_t
7338 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7339     uint32_t *prev_acked)
7340 {
7341         uint32_t changed, last_seq, entered_recovery = 0;
7342         struct tcp_bbr *bbr;
7343         struct bbr_sendmap *rsm;
7344         struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7345         register uint32_t th_ack;
7346         int32_t i, j, k, new_sb, num_sack_blks = 0;
7347         uint32_t cts, acked, ack_point, sack_changed = 0;
7348         uint32_t p_maxseg, maxseg, p_acked = 0;
7349
7350         INP_WLOCK_ASSERT(tp->t_inpcb);
7351         if (th->th_flags & TH_RST) {
7352                 /* We don't log resets */
7353                 return (0);
7354         }
7355         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7356         cts = bbr->r_ctl.rc_rcvtime;
7357
7358         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7359         changed = 0;
7360         maxseg = tp->t_maxseg - bbr->rc_last_options;
7361         p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7362         th_ack = th->th_ack;
7363         if (SEQ_GT(th_ack, tp->snd_una)) {
7364                 acked = th_ack - tp->snd_una;
7365                 bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7366                 bbr->rc_tp->t_acktime = ticks;
7367         } else
7368                 acked = 0;
7369         if (SEQ_LEQ(th_ack, tp->snd_una)) {
7370                 /* Only sent here for sack processing */
7371                 goto proc_sack;
7372         }
7373         if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7374                 changed = th_ack - rsm->r_start;
7375         } else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7376                 /*
7377                  * For the SYN incoming case we will not have called
7378                  * tcp_output for the sending of the SYN, so there will be
7379                  * no map. All other cases should probably be a panic.
7380                  */
7381                 if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7382                         /*
7383                          * We have a timestamp that can be used to generate
7384                          * an initial RTT.
7385                          */
7386                         uint32_t ts, now, rtt;
7387
7388                         ts = bbr_ts_convert(to->to_tsecr);
7389                         now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7390                         rtt = now - ts;
7391                         if (rtt < 1)
7392                                 rtt = 1;
7393                         bbr_log_type_bbrrttprop(bbr, rtt,
7394                                                 tp->iss, 0, cts,
7395                                                 BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7396                         apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7397                         changed = 1;
7398                         bbr->r_wanted_output = 1;
7399                         goto out;
7400                 }
7401                 goto proc_sack;
7402         } else if (rsm == NULL) {
7403                 goto out;
7404         }
7405         if (changed) {
7406                 /*
7407                  * The ACK point is advancing to th_ack, we must drop off
7408                  * the packets in the rack log and calculate any eligble
7409                  * RTT's.
7410                  */
7411                 bbr->r_wanted_output = 1;
7412 more:
7413                 if (rsm == NULL) {
7414                         if (tp->t_flags & TF_SENTFIN) {
7415                                 /* if we send a FIN we will not hav a map */
7416                                 goto proc_sack;
7417                         }
7418 #ifdef BBR_INVARIANTS
7419                         panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7420                             tp,
7421                             th, tp->t_state, bbr,
7422                             tp->snd_una, tp->snd_max, changed);
7423 #endif
7424                         goto proc_sack;
7425                 }
7426         }
7427         if (SEQ_LT(th_ack, rsm->r_start)) {
7428                 /* Huh map is missing this */
7429 #ifdef BBR_INVARIANTS
7430                 printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7431                     rsm->r_start,
7432                     th_ack, tp->t_state,
7433                     bbr->r_state, bbr);
7434                 panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7435 #endif
7436                 goto proc_sack;
7437         } else if (th_ack == rsm->r_start) {
7438                 /* None here to ack */
7439                 goto proc_sack;
7440         }
7441         /*
7442          * Clear the dup ack counter, it will
7443          * either be freed or if there is some
7444          * remaining we need to start it at zero.
7445          */
7446         rsm->r_dupack = 0;
7447         /* Now do we consume the whole thing? */
7448         if (SEQ_GEQ(th_ack, rsm->r_end)) {
7449                 /* Its all consumed. */
7450                 uint32_t left;
7451
7452                 if (rsm->r_flags & BBR_ACKED) {
7453                         /*
7454                          * It was acked on the scoreboard -- remove it from
7455                          * total
7456                          */
7457                         p_acked += (rsm->r_end - rsm->r_start);
7458                         bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7459                         if (bbr->r_ctl.rc_sacked == 0)
7460                                 bbr->r_ctl.rc_sacklast = NULL;
7461                 } else {
7462                         bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7463                         if (rsm->r_flags & BBR_MARKED_LOST) {
7464                                 bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7465                         }
7466                         if (rsm->r_flags & BBR_SACK_PASSED) {
7467                                 /*
7468                                  * There are acked segments ACKED on the
7469                                  * scoreboard further up. We are seeing
7470                                  * reordering.
7471                                  */
7472                                 BBR_STAT_INC(bbr_reorder_seen);
7473                                 bbr->r_ctl.rc_reorder_ts = cts;
7474                                 if (rsm->r_flags & BBR_MARKED_LOST) {
7475                                         bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7476                                         if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7477                                                 /* LT sampling also needs adjustment */
7478                                                 bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7479                                 }
7480                         }
7481                         rsm->r_flags &= ~BBR_MARKED_LOST;
7482                 }
7483                 bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7484                 rsm->r_rtr_bytes = 0;
7485                 TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7486                 if (rsm->r_in_tmap) {
7487                         TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7488                         rsm->r_in_tmap = 0;
7489                 }
7490                 if (bbr->r_ctl.rc_next == rsm) {
7491                         /* scoot along the marker */
7492                         bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7493                 }
7494                 bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7495                 /* Adjust the packet counts */
7496                 left = th_ack - rsm->r_end;
7497                 /* Free back to zone */
7498                 bbr_free(bbr, rsm);
7499                 if (left) {
7500                         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7501                         goto more;
7502                 }
7503                 goto proc_sack;
7504         }
7505         if (rsm->r_flags & BBR_ACKED) {
7506                 /*
7507                  * It was acked on the scoreboard -- remove it from total
7508                  * for the part being cum-acked.
7509                  */
7510                 p_acked += (rsm->r_end - rsm->r_start);
7511                 bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7512                 if (bbr->r_ctl.rc_sacked == 0)
7513                         bbr->r_ctl.rc_sacklast = NULL;
7514         } else {
7515                 /*
7516                  * It was acked up to th_ack point for the first time
7517                  */
7518                 struct bbr_sendmap lrsm;
7519
7520                 memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7521                 lrsm.r_end = th_ack;
7522                 bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7523         }
7524         if ((rsm->r_flags & BBR_MARKED_LOST) &&
7525             ((rsm->r_flags & BBR_ACKED) == 0)) {
7526                 /*
7527                  * It was marked lost and partly ack'd now
7528                  * for the first time. We lower the rc_lost_bytes
7529                  * and still leave it MARKED.
7530                  */
7531                 bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7532         }
7533         bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7534         bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7535         rsm->r_rtr_bytes = 0;
7536         /* adjust packet count */
7537         rsm->r_start = th_ack;
7538 proc_sack:
7539         /* Check for reneging */
7540         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7541         if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7542                 /*
7543                  * The peer has moved snd_una up to the edge of this send,
7544                  * i.e. one that it had previously acked. The only way that
7545                  * can be true if the peer threw away data (space issues)
7546                  * that it had previously sacked (else it would have given
7547                  * us snd_una up to (rsm->r_end). We need to undo the acked
7548                  * markings here.
7549                  *
7550                  * Note we have to look to make sure th_ack is our
7551                  * rsm->r_start in case we get an old ack where th_ack is
7552                  * behind snd_una.
7553                  */
7554                 bbr_peer_reneges(bbr, rsm, th->th_ack);
7555         }
7556         if ((to->to_flags & TOF_SACK) == 0) {
7557                 /* We are done nothing left to log */
7558                 goto out;
7559         }
7560         rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7561         if (rsm) {
7562                 last_seq = rsm->r_end;
7563         } else {
7564                 last_seq = tp->snd_max;
7565         }
7566         /* Sack block processing */
7567         if (SEQ_GT(th_ack, tp->snd_una))
7568                 ack_point = th_ack;
7569         else
7570                 ack_point = tp->snd_una;
7571         for (i = 0; i < to->to_nsacks; i++) {
7572                 bcopy((to->to_sacks + i * TCPOLEN_SACK),
7573                     &sack, sizeof(sack));
7574                 sack.start = ntohl(sack.start);
7575                 sack.end = ntohl(sack.end);
7576                 if (SEQ_GT(sack.end, sack.start) &&
7577                     SEQ_GT(sack.start, ack_point) &&
7578                     SEQ_LT(sack.start, tp->snd_max) &&
7579                     SEQ_GT(sack.end, ack_point) &&
7580                     SEQ_LEQ(sack.end, tp->snd_max)) {
7581                         if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7582                             (SEQ_LT(sack.end, last_seq)) &&
7583                             ((sack.end - sack.start) < (p_maxseg / 8))) {
7584                                 /*
7585                                  * Not the last piece and its smaller than
7586                                  * 1/8th of a p_maxseg. We ignore this.
7587                                  */
7588                                 BBR_STAT_INC(bbr_runt_sacks);
7589                                 continue;
7590                         }
7591                         sack_blocks[num_sack_blks] = sack;
7592                         num_sack_blks++;
7593 #ifdef NETFLIX_STATS
7594                 } else if (SEQ_LEQ(sack.start, th_ack) &&
7595                     SEQ_LEQ(sack.end, th_ack)) {
7596                         /*
7597                          * Its a D-SACK block.
7598                          */
7599                         tcp_record_dsack(sack.start, sack.end);
7600 #endif
7601                 }
7602         }
7603         if (num_sack_blks == 0)
7604                 goto out;
7605         /*
7606          * Sort the SACK blocks so we can update the rack scoreboard with
7607          * just one pass.
7608          */
7609         new_sb = sack_filter_blks(&bbr->r_ctl.bbr_sf, sack_blocks,
7610                                   num_sack_blks, th->th_ack);
7611         ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7612         BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7613         BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7614         num_sack_blks = new_sb;
7615         if (num_sack_blks < 2) {
7616                 goto do_sack_work;
7617         }
7618         /* Sort the sacks */
7619         for (i = 0; i < num_sack_blks; i++) {
7620                 for (j = i + 1; j < num_sack_blks; j++) {
7621                         if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7622                                 sack = sack_blocks[i];
7623                                 sack_blocks[i] = sack_blocks[j];
7624                                 sack_blocks[j] = sack;
7625                         }
7626                 }
7627         }
7628         /*
7629          * Now are any of the sack block ends the same (yes some
7630          * implememtations send these)?
7631          */
7632 again:
7633         if (num_sack_blks > 1) {
7634                 for (i = 0; i < num_sack_blks; i++) {
7635                         for (j = i + 1; j < num_sack_blks; j++) {
7636                                 if (sack_blocks[i].end == sack_blocks[j].end) {
7637                                         /*
7638                                          * Ok these two have the same end we
7639                                          * want the smallest end and then
7640                                          * throw away the larger and start
7641                                          * again.
7642                                          */
7643                                         if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7644                                                 /*
7645                                                  * The second block covers
7646                                                  * more area use that
7647                                                  */
7648                                                 sack_blocks[i].start = sack_blocks[j].start;
7649                                         }
7650                                         /*
7651                                          * Now collapse out the dup-sack and
7652                                          * lower the count
7653                                          */
7654                                         for (k = (j + 1); k < num_sack_blks; k++) {
7655                                                 sack_blocks[j].start = sack_blocks[k].start;
7656                                                 sack_blocks[j].end = sack_blocks[k].end;
7657                                                 j++;
7658                                         }
7659                                         num_sack_blks--;
7660                                         goto again;
7661                                 }
7662                         }
7663                 }
7664         }
7665 do_sack_work:
7666         rsm = bbr->r_ctl.rc_sacklast;
7667         for (i = 0; i < num_sack_blks; i++) {
7668                 acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7669                 if (acked) {
7670                         bbr->r_wanted_output = 1;
7671                         changed += acked;
7672                         sack_changed += acked;
7673                 }
7674         }
7675 out:
7676         *prev_acked = p_acked;
7677         if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7678                 /*
7679                  * Ok we have a high probability that we need to go in to
7680                  * recovery since we have data sack'd
7681                  */
7682                 struct bbr_sendmap *rsm;
7683
7684                 rsm = bbr_check_recovery_mode(tp, bbr, cts);
7685                 if (rsm) {
7686                         /* Enter recovery */
7687                         entered_recovery = 1;
7688                         bbr->r_wanted_output = 1;
7689                         /*
7690                          * When we enter recovery we need to assure we send
7691                          * one packet.
7692                          */
7693                         if (bbr->r_ctl.rc_resend == NULL) {
7694                                 bbr->r_ctl.rc_resend = rsm;
7695                         }
7696                 }
7697         }
7698         if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7699                 /*
7700                  * See if we need to rack-retransmit anything if so set it
7701                  * up as the thing to resend assuming something else is not
7702                  * already in that position.
7703                  */
7704                 if (bbr->r_ctl.rc_resend == NULL) {
7705                         bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7706                 }
7707         }
7708         /*
7709          * We return the amount that changed via sack, this is used by the
7710          * ack-received code to augment what was changed between th_ack <->
7711          * snd_una.
7712          */
7713         return (sack_changed);
7714 }
7715
7716 static void
7717 bbr_strike_dupack(struct tcp_bbr *bbr)
7718 {
7719         struct bbr_sendmap *rsm;
7720
7721         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7722         if (rsm && (rsm->r_dupack < 0xff)) {
7723                 rsm->r_dupack++;
7724                 if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7725                         bbr->r_wanted_output = 1;
7726         }
7727 }
7728
7729 /*
7730  * Return value of 1, we do not need to call bbr_process_data().
7731  * return value of 0, bbr_process_data can be called.
7732  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7733  * its unlocked and probably unsafe to touch the TCB.
7734  */
7735 static int
7736 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7737     struct tcpcb *tp, struct tcpopt *to,
7738     uint32_t tiwin, int32_t tlen,
7739     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7740 {
7741         int32_t ourfinisacked = 0;
7742         int32_t acked_amount;
7743         uint16_t nsegs;
7744         int32_t acked;
7745         uint32_t lost, sack_changed = 0;
7746         struct mbuf *mfree;
7747         struct tcp_bbr *bbr;
7748         uint32_t prev_acked = 0;
7749
7750         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7751         lost = bbr->r_ctl.rc_lost;
7752         nsegs = max(1, m->m_pkthdr.lro_nsegs);
7753         if (SEQ_GT(th->th_ack, tp->snd_max)) {
7754                 ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7755                 bbr->r_wanted_output = 1;
7756                 return (1);
7757         }
7758         if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7759                 /* Process the ack */
7760                 if (bbr->rc_in_persist)
7761                         tp->t_rxtshift = 0;
7762                 if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7763                         bbr_strike_dupack(bbr);
7764                 sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7765         }
7766         bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7767         if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7768                 /*
7769                  * Old ack, behind the last one rcv'd or a duplicate ack
7770                  * with SACK info.
7771                  */
7772                 if (th->th_ack == tp->snd_una) {
7773                         bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7774                         if (bbr->r_state == TCPS_SYN_SENT) {
7775                                 /*
7776                                  * Special case on where we sent SYN. When
7777                                  * the SYN-ACK is processed in syn_sent
7778                                  * state it bumps the snd_una. This causes
7779                                  * us to hit here even though we did ack 1
7780                                  * byte.
7781                                  *
7782                                  * Go through the nothing left case so we
7783                                  * send data.
7784                                  */
7785                                 goto nothing_left;
7786                         }
7787                 }
7788                 return (0);
7789         }
7790         /*
7791          * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7792          * something we sent.
7793          */
7794         if (tp->t_flags & TF_NEEDSYN) {
7795                 /*
7796                  * T/TCP: Connection was half-synchronized, and our SYN has
7797                  * been ACK'd (so connection is now fully synchronized).  Go
7798                  * to non-starred state, increment snd_una for ACK of SYN,
7799                  * and check if we can do window scaling.
7800                  */
7801                 tp->t_flags &= ~TF_NEEDSYN;
7802                 tp->snd_una++;
7803                 /* Do window scaling? */
7804                 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7805                     (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7806                         tp->rcv_scale = tp->request_r_scale;
7807                         /* Send window already scaled. */
7808                 }
7809         }
7810         INP_WLOCK_ASSERT(tp->t_inpcb);
7811
7812         acked = BYTES_THIS_ACK(tp, th);
7813         KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7814         KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
7815
7816         /*
7817          * If we just performed our first retransmit, and the ACK arrives
7818          * within our recovery window, then it was a mistake to do the
7819          * retransmit in the first place.  Recover our original cwnd and
7820          * ssthresh, and proceed to transmit where we left off.
7821          */
7822         if (tp->t_flags & TF_PREVVALID) {
7823                 tp->t_flags &= ~TF_PREVVALID;
7824                 if (tp->t_rxtshift == 1 &&
7825                     (int)(ticks - tp->t_badrxtwin) < 0)
7826                         bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7827         }
7828         SOCKBUF_LOCK(&so->so_snd);
7829         acked_amount = min(acked, (int)sbavail(&so->so_snd));
7830         tp->snd_wnd -= acked_amount;
7831         mfree = sbcut_locked(&so->so_snd, acked_amount);
7832         /* NB: sowwakeup_locked() does an implicit unlock. */
7833         sowwakeup_locked(so);
7834         m_freem(mfree);
7835         if (SEQ_GT(th->th_ack, tp->snd_una)) {
7836                 bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
7837         }
7838         tp->snd_una = th->th_ack;
7839         bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
7840         if (IN_RECOVERY(tp->t_flags)) {
7841                 if (SEQ_LT(th->th_ack, tp->snd_recover) &&
7842                     (SEQ_LT(th->th_ack, tp->snd_max))) {
7843                         tcp_bbr_partialack(tp);
7844                 } else {
7845                         bbr_post_recovery(tp);
7846                 }
7847         }
7848         if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
7849                 tp->snd_recover = tp->snd_una;
7850         }
7851         if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
7852                 tp->snd_nxt = tp->snd_max;
7853         }
7854         if (tp->snd_una == tp->snd_max) {
7855                 /* Nothing left outstanding */
7856 nothing_left:
7857                 bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
7858                 if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
7859                         bbr->rc_tp->t_acktime = 0;
7860                 if ((sbused(&so->so_snd) == 0) &&
7861                     (tp->t_flags & TF_SENTFIN)) {
7862                         ourfinisacked = 1;
7863                 }
7864                 bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
7865                 if (bbr->rc_in_persist == 0) {
7866                         bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
7867                 }
7868                 sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
7869                 bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
7870                 /*
7871                  * We invalidate the last ack here since we
7872                  * don't want to transfer forward the time
7873                  * for our sum's calculations.
7874                  */
7875                 if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
7876                     (sbavail(&so->so_snd) == 0) &&
7877                     (tp->t_flags2 & TF2_DROP_AF_DATA)) {
7878                         /*
7879                          * The socket was gone and the peer sent data, time
7880                          * to reset him.
7881                          */
7882                         *ret_val = 1;
7883                         tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
7884                         /* tcp_close will kill the inp pre-log the Reset */
7885                         tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
7886                         tp = tcp_close(tp);
7887                         ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
7888                         BBR_STAT_INC(bbr_dropped_af_data);
7889                         return (1);
7890                 }
7891                 /* Set need output so persist might get set */
7892                 bbr->r_wanted_output = 1;
7893         }
7894         if (ofia)
7895                 *ofia = ourfinisacked;
7896         return (0);
7897 }
7898
7899 static void
7900 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7901 {
7902         if (bbr->rc_in_persist == 0) {
7903                 bbr_timer_cancel(bbr, __LINE__, cts);
7904                 bbr->r_ctl.rc_last_delay_val = 0;
7905                 tp->t_rxtshift = 0;
7906                 bbr->rc_in_persist = 1;
7907                 bbr->r_ctl.rc_went_idle_time = cts;
7908                 /* We should be capped when rw went to 0 but just in case */
7909                 bbr_log_type_pesist(bbr, cts, 0, line, 1);
7910                 /* Time freezes for the state, so do the accounting now */
7911                 if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
7912                         uint32_t time_in;
7913
7914                         time_in = cts - bbr->r_ctl.rc_bbr_state_time;
7915                         if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7916                                 int32_t idx;
7917
7918                                 idx = bbr_state_val(bbr);
7919                                 counter_u64_add(bbr_state_time[(idx + 5)], time_in);
7920                         } else {
7921                                 counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
7922                         }
7923                 }
7924                 bbr->r_ctl.rc_bbr_state_time = cts;
7925         }
7926 }
7927
7928 static void
7929 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
7930 {
7931         /*
7932          * Note that if idle time does not exceed our
7933          * threshold, we do nothing continuing the state
7934          * transitions we were last walking through.
7935          */
7936         if (idle_time >= bbr_idle_restart_threshold) {
7937                 if (bbr->rc_use_idle_restart) {
7938                         bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
7939                         /*
7940                          * Set our target using BBR_UNIT, so
7941                          * we increase at a dramatic rate but
7942                          * we stop when we get the pipe
7943                          * full again for our current b/w estimate.
7944                          */
7945                         bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
7946                         bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
7947                         bbr_set_state_target(bbr, __LINE__);
7948                         /* Now setup our gains to ramp up */
7949                         bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
7950                         bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
7951                         bbr_log_type_statechange(bbr, cts, __LINE__);
7952                 } else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7953                         bbr_substate_change(bbr, cts, __LINE__, 1);
7954                 }
7955         }
7956 }
7957
7958 static void
7959 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7960 {
7961         uint32_t idle_time;
7962
7963         if (bbr->rc_in_persist == 0)
7964                 return;
7965         idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
7966         bbr->rc_in_persist = 0;
7967         bbr->rc_hit_state_1 = 0;
7968         bbr->r_ctl.rc_del_time = cts;
7969         /*
7970          * We invalidate the last ack here since we
7971          * don't want to transfer forward the time
7972          * for our sum's calculations.
7973          */
7974         if (bbr->rc_inp->inp_in_hpts) {
7975                 tcp_hpts_remove(bbr->rc_inp, HPTS_REMOVE_OUTPUT);
7976                 bbr->rc_timer_first = 0;
7977                 bbr->r_ctl.rc_hpts_flags = 0;
7978                 bbr->r_ctl.rc_last_delay_val = 0;
7979                 bbr->r_ctl.rc_hptsi_agg_delay = 0;
7980                 bbr->r_agg_early_set = 0;
7981                 bbr->r_ctl.rc_agg_early = 0;
7982         }
7983         bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
7984         if (idle_time >= bbr_rtt_probe_time) {
7985                 /*
7986                  * This qualifies as a RTT_PROBE session since we drop the
7987                  * data outstanding to nothing and waited more than
7988                  * bbr_rtt_probe_time.
7989                  */
7990                 bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
7991                 bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
7992         }
7993         tp->t_rxtshift = 0;
7994         /*
7995          * If in probeBW and we have persisted more than an RTT lets do
7996          * special handling.
7997          */
7998         /* Force a time based epoch */
7999         bbr_set_epoch(bbr, cts, __LINE__);
8000         /*
8001          * Setup the lost so we don't count anything against the guy
8002          * we have been stuck with during persists.
8003          */
8004         bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
8005         /* Time un-freezes for the state */
8006         bbr->r_ctl.rc_bbr_state_time = cts;
8007         if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
8008             (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
8009                 /*
8010                  * If we are going back to probe-bw
8011                  * or probe_rtt, we may need to possibly
8012                  * do a fast restart.
8013                  */
8014                 bbr_restart_after_idle(bbr, cts, idle_time);
8015         }
8016 }
8017
8018 static void
8019 bbr_collapsed_window(struct tcp_bbr *bbr)
8020 {
8021         /*
8022          * Now we must walk the
8023          * send map and divide the
8024          * ones left stranded. These
8025          * guys can't cause us to abort
8026          * the connection and are really
8027          * "unsent". However if a buggy
8028          * client actually did keep some
8029          * of the data i.e. collapsed the win
8030          * and refused to ack and then opened
8031          * the win and acked that data. We would
8032          * get into an ack war, the simplier
8033          * method then of just pretending we
8034          * did not send those segments something
8035          * won't work.
8036          */
8037         struct bbr_sendmap *rsm, *nrsm;
8038         tcp_seq max_seq;
8039         uint32_t maxseg;
8040         int can_split = 0;
8041         int fnd = 0;
8042
8043         maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
8044         max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
8045         bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
8046         TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
8047                 /* Find the first seq past or at maxseq */
8048                 if (rsm->r_flags & BBR_RWND_COLLAPSED)
8049                         rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8050                 if (SEQ_GEQ(max_seq, rsm->r_start) &&
8051                     SEQ_GEQ(rsm->r_end, max_seq)) {
8052                         fnd = 1;
8053                         break;
8054                 }
8055         }
8056         bbr->rc_has_collapsed = 0;
8057         if (!fnd) {
8058                 /* Nothing to do strange */
8059                 return;
8060         }
8061         /*
8062          * Now can we split?
8063          *
8064          * We don't want to split if splitting
8065          * would generate too many small segments
8066          * less we let an attacker fragment our
8067          * send_map and leave us out of memory.
8068          */
8069         if ((max_seq != rsm->r_start) &&
8070             (max_seq != rsm->r_end)){
8071                 /* can we split? */
8072                 int res1, res2;
8073
8074                 res1 = max_seq - rsm->r_start;
8075                 res2 = rsm->r_end - max_seq;
8076                 if ((res1 >= (maxseg/8)) &&
8077                     (res2 >= (maxseg/8))) {
8078                         /* No small pieces here */
8079                         can_split = 1;
8080                 } else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8081                         /* We are under the limit */
8082                         can_split = 1;
8083                 }
8084         }
8085         /* Ok do we need to split this rsm? */
8086         if (max_seq == rsm->r_start) {
8087                 /* It's this guy no split required */
8088                 nrsm = rsm;
8089         } else if (max_seq == rsm->r_end) {
8090                 /* It's the next one no split required. */
8091                 nrsm = TAILQ_NEXT(rsm, r_next);
8092                 if (nrsm == NULL) {
8093                         /* Huh? */
8094                         return;
8095                 }
8096         } else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8097                 /* yep we need to split it */
8098                 nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8099                 if (nrsm == NULL) {
8100                         /* failed XXXrrs what can we do mark the whole? */
8101                         nrsm = rsm;
8102                         goto no_split;
8103                 }
8104                 /* Clone it */
8105                 bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8106                 bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8107                 TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8108                 if (rsm->r_in_tmap) {
8109                         TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8110                         nrsm->r_in_tmap = 1;
8111                 }
8112         } else {
8113                 /*
8114                  * Split not allowed just start here just
8115                  * use this guy.
8116                  */
8117                 nrsm = rsm;
8118         }
8119 no_split:
8120         BBR_STAT_INC(bbr_collapsed_win);
8121         /* reuse fnd as a count */
8122         fnd = 0;
8123         TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8124                 nrsm->r_flags |= BBR_RWND_COLLAPSED;
8125                 fnd++;
8126                 bbr->rc_has_collapsed = 1;
8127         }
8128         bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8129 }
8130
8131 static void
8132 bbr_un_collapse_window(struct tcp_bbr *bbr)
8133 {
8134         struct bbr_sendmap *rsm;
8135         int cleared = 0;
8136
8137         TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8138                 if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8139                         /* Clear the flag */
8140                         rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8141                         cleared++;
8142                 } else
8143                         break;
8144         }
8145         bbr_log_type_rwnd_collapse(bbr,
8146                                    (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8147         bbr->rc_has_collapsed = 0;
8148 }
8149
8150 /*
8151  * Return value of 1, the TCB is unlocked and most
8152  * likely gone, return value of 0, the TCB is still
8153  * locked.
8154  */
8155 static int
8156 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8157     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8158     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8159 {
8160         /*
8161          * Update window information. Don't look at window if no ACK: TAC's
8162          * send garbage on first SYN.
8163          */
8164         uint16_t nsegs;
8165         int32_t tfo_syn;
8166         struct tcp_bbr *bbr;
8167
8168         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8169         INP_WLOCK_ASSERT(tp->t_inpcb);
8170         nsegs = max(1, m->m_pkthdr.lro_nsegs);
8171         if ((thflags & TH_ACK) &&
8172             (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8173             (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8174             (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8175                 /* keep track of pure window updates */
8176                 if (tlen == 0 &&
8177                     tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8178                         KMOD_TCPSTAT_INC(tcps_rcvwinupd);
8179                 tp->snd_wnd = tiwin;
8180                 tp->snd_wl1 = th->th_seq;
8181                 tp->snd_wl2 = th->th_ack;
8182                 if (tp->snd_wnd > tp->max_sndwnd)
8183                         tp->max_sndwnd = tp->snd_wnd;
8184                 bbr->r_wanted_output = 1;
8185         } else if (thflags & TH_ACK) {
8186                 if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8187                         tp->snd_wnd = tiwin;
8188                         tp->snd_wl1 = th->th_seq;
8189                         tp->snd_wl2 = th->th_ack;
8190                 }
8191         }
8192         if (tp->snd_wnd < ctf_outstanding(tp))
8193                 /* The peer collapsed its window on us */
8194                 bbr_collapsed_window(bbr);
8195         else if (bbr->rc_has_collapsed)
8196                 bbr_un_collapse_window(bbr);
8197         /* Was persist timer active and now we have window space? */
8198         if ((bbr->rc_in_persist != 0) &&
8199             (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8200                                 bbr_minseg(bbr)))) {
8201                 /*
8202                  * Make the rate persist at end of persist mode if idle long
8203                  * enough
8204                  */
8205                 bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8206
8207                 /* Make sure we output to start the timer */
8208                 bbr->r_wanted_output = 1;
8209         }
8210         /* Do we need to enter persist? */
8211         if ((bbr->rc_in_persist == 0) &&
8212             (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8213             TCPS_HAVEESTABLISHED(tp->t_state) &&
8214             (tp->snd_max == tp->snd_una) &&
8215             sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
8216             (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
8217                 /* No send window.. we must enter persist */
8218                 bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8219         }
8220         if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8221                 m_freem(m);
8222                 return (0);
8223         }
8224         /*
8225          * We don't support urgent data but
8226          * drag along the up just to make sure
8227          * if there is a stack switch no one
8228          * is surprised.
8229          */
8230         tp->rcv_up = tp->rcv_nxt;
8231         INP_WLOCK_ASSERT(tp->t_inpcb);
8232
8233         /*
8234          * Process the segment text, merging it into the TCP sequencing
8235          * queue, and arranging for acknowledgment of receipt if necessary.
8236          * This process logically involves adjusting tp->rcv_wnd as data is
8237          * presented to the user (this happens in tcp_usrreq.c, case
8238          * PRU_RCVD).  If a FIN has already been received on this connection
8239          * then we just ignore the text.
8240          */
8241         tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8242                    IS_FASTOPEN(tp->t_flags));
8243         if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
8244             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8245                 tcp_seq save_start = th->th_seq;
8246                 tcp_seq save_rnxt  = tp->rcv_nxt;
8247                 int     save_tlen  = tlen;
8248
8249                 m_adj(m, drop_hdrlen);  /* delayed header drop */
8250                 /*
8251                  * Insert segment which includes th into TCP reassembly
8252                  * queue with control block tp.  Set thflags to whether
8253                  * reassembly now includes a segment with FIN.  This handles
8254                  * the common case inline (segment is the next to be
8255                  * received on an established connection, and the queue is
8256                  * empty), avoiding linkage into and removal from the queue
8257                  * and repetition of various conversions. Set DELACK for
8258                  * segments received in order, but ack immediately when
8259                  * segments are out of order (so fast retransmit can work).
8260                  */
8261                 if (th->th_seq == tp->rcv_nxt &&
8262                     SEGQ_EMPTY(tp) &&
8263                     (TCPS_HAVEESTABLISHED(tp->t_state) ||
8264                     tfo_syn)) {
8265 #ifdef NETFLIX_SB_LIMITS
8266                         u_int mcnt, appended;
8267
8268                         if (so->so_rcv.sb_shlim) {
8269                                 mcnt = m_memcnt(m);
8270                                 appended = 0;
8271                                 if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8272                                     CFO_NOSLEEP, NULL) == false) {
8273                                         counter_u64_add(tcp_sb_shlim_fails, 1);
8274                                         m_freem(m);
8275                                         return (0);
8276                                 }
8277                         }
8278
8279 #endif
8280                         if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8281                                 bbr->bbr_segs_rcvd += max(1, nsegs);
8282                                 tp->t_flags |= TF_DELACK;
8283                                 bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8284                         } else {
8285                                 bbr->r_wanted_output = 1;
8286                                 tp->t_flags |= TF_ACKNOW;
8287                         }
8288                         tp->rcv_nxt += tlen;
8289                         if (tlen &&
8290                             ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8291                             (tp->t_fbyte_in == 0)) {
8292                                 tp->t_fbyte_in = ticks;
8293                                 if (tp->t_fbyte_in == 0)
8294                                         tp->t_fbyte_in = 1;
8295                                 if (tp->t_fbyte_out && tp->t_fbyte_in)
8296                                         tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8297                         }
8298                         thflags = th->th_flags & TH_FIN;
8299                         KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8300                         KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8301                         SOCKBUF_LOCK(&so->so_rcv);
8302                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8303                                 m_freem(m);
8304                         else
8305 #ifdef NETFLIX_SB_LIMITS
8306                                 appended =
8307 #endif
8308                                         sbappendstream_locked(&so->so_rcv, m, 0);
8309                         /* NB: sorwakeup_locked() does an implicit unlock. */
8310                         sorwakeup_locked(so);
8311 #ifdef NETFLIX_SB_LIMITS
8312                         if (so->so_rcv.sb_shlim && appended != mcnt)
8313                                 counter_fo_release(so->so_rcv.sb_shlim,
8314                                     mcnt - appended);
8315 #endif
8316
8317                 } else {
8318                         /*
8319                          * XXX: Due to the header drop above "th" is
8320                          * theoretically invalid by now.  Fortunately
8321                          * m_adj() doesn't actually frees any mbufs when
8322                          * trimming from the head.
8323                          */
8324                         tcp_seq temp = save_start;
8325
8326                         thflags = tcp_reass(tp, th, &temp, &tlen, m);
8327                         tp->t_flags |= TF_ACKNOW;
8328                         if (tp->t_flags & TF_WAKESOR) {
8329                                 tp->t_flags &= ~TF_WAKESOR;
8330                                 /* NB: sorwakeup_locked() does an implicit unlock. */
8331                                 sorwakeup_locked(so);
8332                         }
8333                 }
8334                 if ((tp->t_flags & TF_SACK_PERMIT) &&
8335                     (save_tlen > 0) &&
8336                     TCPS_HAVEESTABLISHED(tp->t_state)) {
8337                         if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8338                                 /*
8339                                  * DSACK actually handled in the fastpath
8340                                  * above.
8341                                  */
8342                                 tcp_update_sack_list(tp, save_start,
8343                                     save_start + save_tlen);
8344                         } else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8345                                 if ((tp->rcv_numsacks >= 1) &&
8346                                     (tp->sackblks[0].end == save_start)) {
8347                                         /*
8348                                          * Partial overlap, recorded at todrop
8349                                          * above.
8350                                          */
8351                                         tcp_update_sack_list(tp,
8352                                             tp->sackblks[0].start,
8353                                             tp->sackblks[0].end);
8354                                 } else {
8355                                         tcp_update_dsack_list(tp, save_start,
8356                                             save_start + save_tlen);
8357                                 }
8358                         } else if (tlen >= save_tlen) {
8359                                 /* Update of sackblks. */
8360                                 tcp_update_dsack_list(tp, save_start,
8361                                     save_start + save_tlen);
8362                         } else if (tlen > 0) {
8363                                 tcp_update_dsack_list(tp, save_start,
8364                                     save_start + tlen);
8365                         }
8366                 }
8367         } else {
8368                 m_freem(m);
8369                 thflags &= ~TH_FIN;
8370         }
8371
8372         /*
8373          * If FIN is received ACK the FIN and let the user know that the
8374          * connection is closing.
8375          */
8376         if (thflags & TH_FIN) {
8377                 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8378                         /* The socket upcall is handled by socantrcvmore. */
8379                         socantrcvmore(so);
8380                         /*
8381                          * If connection is half-synchronized (ie NEEDSYN
8382                          * flag on) then delay ACK, so it may be piggybacked
8383                          * when SYN is sent. Otherwise, since we received a
8384                          * FIN then no more input can be expected, send ACK
8385                          * now.
8386                          */
8387                         if (tp->t_flags & TF_NEEDSYN) {
8388                                 tp->t_flags |= TF_DELACK;
8389                                 bbr_timer_cancel(bbr,
8390                                     __LINE__, bbr->r_ctl.rc_rcvtime);
8391                         } else {
8392                                 tp->t_flags |= TF_ACKNOW;
8393                         }
8394                         tp->rcv_nxt++;
8395                 }
8396                 switch (tp->t_state) {
8397                         /*
8398                          * In SYN_RECEIVED and ESTABLISHED STATES enter the
8399                          * CLOSE_WAIT state.
8400                          */
8401                 case TCPS_SYN_RECEIVED:
8402                         tp->t_starttime = ticks;
8403                         /* FALLTHROUGH */
8404                 case TCPS_ESTABLISHED:
8405                         tcp_state_change(tp, TCPS_CLOSE_WAIT);
8406                         break;
8407
8408                         /*
8409                          * If still in FIN_WAIT_1 STATE FIN has not been
8410                          * acked so enter the CLOSING state.
8411                          */
8412                 case TCPS_FIN_WAIT_1:
8413                         tcp_state_change(tp, TCPS_CLOSING);
8414                         break;
8415
8416                         /*
8417                          * In FIN_WAIT_2 state enter the TIME_WAIT state,
8418                          * starting the time-wait timer, turning off the
8419                          * other standard timers.
8420                          */
8421                 case TCPS_FIN_WAIT_2:
8422                         bbr->rc_timer_first = 1;
8423                         bbr_timer_cancel(bbr,
8424                             __LINE__, bbr->r_ctl.rc_rcvtime);
8425                         INP_WLOCK_ASSERT(tp->t_inpcb);
8426                         tcp_twstart(tp);
8427                         return (1);
8428                 }
8429         }
8430         /*
8431          * Return any desired output.
8432          */
8433         if ((tp->t_flags & TF_ACKNOW) ||
8434             (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8435                 bbr->r_wanted_output = 1;
8436         }
8437         INP_WLOCK_ASSERT(tp->t_inpcb);
8438         return (0);
8439 }
8440
8441 /*
8442  * Here nothing is really faster, its just that we
8443  * have broken out the fast-data path also just like
8444  * the fast-ack. Return 1 if we processed the packet
8445  * return 0 if you need to take the "slow-path".
8446  */
8447 static int
8448 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8449     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8450     uint32_t tiwin, int32_t nxt_pkt)
8451 {
8452         uint16_t nsegs;
8453         int32_t newsize = 0;    /* automatic sockbuf scaling */
8454         struct tcp_bbr *bbr;
8455 #ifdef NETFLIX_SB_LIMITS
8456         u_int mcnt, appended;
8457 #endif
8458 #ifdef TCPDEBUG
8459         /*
8460          * The size of tcp_saveipgen must be the size of the max ip header,
8461          * now IPv6.
8462          */
8463         u_char tcp_saveipgen[IP6_HDR_LEN];
8464         struct tcphdr tcp_savetcp;
8465         short ostate = 0;
8466
8467 #endif
8468         /* On the hpts and we would have called output */
8469         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8470
8471         /*
8472          * If last ACK falls within this segment's sequence numbers, record
8473          * the timestamp. NOTE that the test is modified according to the
8474          * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8475          */
8476         if (bbr->r_ctl.rc_resend != NULL) {
8477                 return (0);
8478         }
8479         if (tiwin && tiwin != tp->snd_wnd) {
8480                 return (0);
8481         }
8482         if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8483                 return (0);
8484         }
8485         if (__predict_false((to->to_flags & TOF_TS) &&
8486             (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8487                 return (0);
8488         }
8489         if (__predict_false((th->th_ack != tp->snd_una))) {
8490                 return (0);
8491         }
8492         if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8493                 return (0);
8494         }
8495         if ((to->to_flags & TOF_TS) != 0 &&
8496             SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8497                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8498                 tp->ts_recent = to->to_tsval;
8499         }
8500         /*
8501          * This is a pure, in-sequence data packet with nothing on the
8502          * reassembly queue and we have enough buffer space to take it.
8503          */
8504         nsegs = max(1, m->m_pkthdr.lro_nsegs);
8505
8506 #ifdef NETFLIX_SB_LIMITS
8507         if (so->so_rcv.sb_shlim) {
8508                 mcnt = m_memcnt(m);
8509                 appended = 0;
8510                 if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8511                     CFO_NOSLEEP, NULL) == false) {
8512                         counter_u64_add(tcp_sb_shlim_fails, 1);
8513                         m_freem(m);
8514                         return (1);
8515                 }
8516         }
8517 #endif
8518         /* Clean receiver SACK report if present */
8519         if (tp->rcv_numsacks)
8520                 tcp_clean_sackreport(tp);
8521         KMOD_TCPSTAT_INC(tcps_preddat);
8522         tp->rcv_nxt += tlen;
8523         if (tlen &&
8524             ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8525             (tp->t_fbyte_in == 0)) {
8526                 tp->t_fbyte_in = ticks;
8527                 if (tp->t_fbyte_in == 0)
8528                         tp->t_fbyte_in = 1;
8529                 if (tp->t_fbyte_out && tp->t_fbyte_in)
8530                         tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8531         }
8532         /*
8533          * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8534          */
8535         tp->snd_wl1 = th->th_seq;
8536         /*
8537          * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8538          */
8539         tp->rcv_up = tp->rcv_nxt;
8540         KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8541         KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8542 #ifdef TCPDEBUG
8543         if (so->so_options & SO_DEBUG)
8544                 tcp_trace(TA_INPUT, ostate, tp,
8545                     (void *)tcp_saveipgen, &tcp_savetcp, 0);
8546 #endif
8547         newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8548
8549         /* Add data to socket buffer. */
8550         SOCKBUF_LOCK(&so->so_rcv);
8551         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8552                 m_freem(m);
8553         } else {
8554                 /*
8555                  * Set new socket buffer size. Give up when limit is
8556                  * reached.
8557                  */
8558                 if (newsize)
8559                         if (!sbreserve_locked(&so->so_rcv,
8560                             newsize, so, NULL))
8561                                 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8562                 m_adj(m, drop_hdrlen);  /* delayed header drop */
8563
8564 #ifdef NETFLIX_SB_LIMITS
8565                 appended =
8566 #endif
8567                         sbappendstream_locked(&so->so_rcv, m, 0);
8568                 ctf_calc_rwin(so, tp);
8569         }
8570         /* NB: sorwakeup_locked() does an implicit unlock. */
8571         sorwakeup_locked(so);
8572 #ifdef NETFLIX_SB_LIMITS
8573         if (so->so_rcv.sb_shlim && mcnt != appended)
8574                 counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8575 #endif
8576         if (DELAY_ACK(tp, bbr, nsegs)) {
8577                 bbr->bbr_segs_rcvd += max(1, nsegs);
8578                 tp->t_flags |= TF_DELACK;
8579                 bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8580         } else {
8581                 bbr->r_wanted_output = 1;
8582                 tp->t_flags |= TF_ACKNOW;
8583         }
8584         return (1);
8585 }
8586
8587 /*
8588  * This subfunction is used to try to highly optimize the
8589  * fast path. We again allow window updates that are
8590  * in sequence to remain in the fast-path. We also add
8591  * in the __predict's to attempt to help the compiler.
8592  * Note that if we return a 0, then we can *not* process
8593  * it and the caller should push the packet into the
8594  * slow-path. If we return 1, then all is well and
8595  * the packet is fully processed.
8596  */
8597 static int
8598 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8599     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8600     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
8601 {
8602         int32_t acked;
8603         uint16_t nsegs;
8604         uint32_t sack_changed;
8605 #ifdef TCPDEBUG
8606         /*
8607          * The size of tcp_saveipgen must be the size of the max ip header,
8608          * now IPv6.
8609          */
8610         u_char tcp_saveipgen[IP6_HDR_LEN];
8611         struct tcphdr tcp_savetcp;
8612         short ostate = 0;
8613
8614 #endif
8615         uint32_t prev_acked = 0;
8616         struct tcp_bbr *bbr;
8617
8618         if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8619                 /* Old ack, behind (or duplicate to) the last one rcv'd */
8620                 return (0);
8621         }
8622         if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8623                 /* Above what we have sent? */
8624                 return (0);
8625         }
8626         if (__predict_false(tiwin == 0)) {
8627                 /* zero window */
8628                 return (0);
8629         }
8630         if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8631                 /* We need a SYN or a FIN, unlikely.. */
8632                 return (0);
8633         }
8634         if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8635                 /* Timestamp is behind .. old ack with seq wrap? */
8636                 return (0);
8637         }
8638         if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8639                 /* Still recovering */
8640                 return (0);
8641         }
8642         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8643         if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8644                 /* We are retransmitting */
8645                 return (0);
8646         }
8647         if (__predict_false(bbr->rc_in_persist != 0)) {
8648                 /* In persist mode */
8649                 return (0);
8650         }
8651         if (bbr->r_ctl.rc_sacked) {
8652                 /* We have sack holes on our scoreboard */
8653                 return (0);
8654         }
8655         /* Ok if we reach here, we can process a fast-ack */
8656         nsegs = max(1, m->m_pkthdr.lro_nsegs);
8657         sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8658         /*
8659          * We never detect loss in fast ack [we can't
8660          * have a sack and can't be in recovery so
8661          * we always pass 0 (nothing detected)].
8662          */
8663         bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8664         /* Did the window get updated? */
8665         if (tiwin != tp->snd_wnd) {
8666                 tp->snd_wnd = tiwin;
8667                 tp->snd_wl1 = th->th_seq;
8668                 if (tp->snd_wnd > tp->max_sndwnd)
8669                         tp->max_sndwnd = tp->snd_wnd;
8670         }
8671         /* Do we need to exit persists? */
8672         if ((bbr->rc_in_persist != 0) &&
8673             (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8674                                bbr_minseg(bbr)))) {
8675                 bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8676                 bbr->r_wanted_output = 1;
8677         }
8678         /* Do we need to enter persists? */
8679         if ((bbr->rc_in_persist == 0) &&
8680             (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8681             TCPS_HAVEESTABLISHED(tp->t_state) &&
8682             (tp->snd_max == tp->snd_una) &&
8683             sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
8684             (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
8685                 /* No send window.. we must enter persist */
8686                 bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8687         }
8688         /*
8689          * If last ACK falls within this segment's sequence numbers, record
8690          * the timestamp. NOTE that the test is modified according to the
8691          * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8692          */
8693         if ((to->to_flags & TOF_TS) != 0 &&
8694             SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8695                 tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8696                 tp->ts_recent = to->to_tsval;
8697         }
8698         /*
8699          * This is a pure ack for outstanding data.
8700          */
8701         KMOD_TCPSTAT_INC(tcps_predack);
8702
8703         /*
8704          * "bad retransmit" recovery.
8705          */
8706         if (tp->t_flags & TF_PREVVALID) {
8707                 tp->t_flags &= ~TF_PREVVALID;
8708                 if (tp->t_rxtshift == 1 &&
8709                     (int)(ticks - tp->t_badrxtwin) < 0)
8710                         bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8711         }
8712         /*
8713          * Recalculate the transmit timer / rtt.
8714          *
8715          * Some boxes send broken timestamp replies during the SYN+ACK
8716          * phase, ignore timestamps of 0 or we could calculate a huge RTT
8717          * and blow up the retransmit timer.
8718          */
8719         acked = BYTES_THIS_ACK(tp, th);
8720
8721 #ifdef TCP_HHOOK
8722         /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8723         hhook_run_tcp_est_in(tp, th, to);
8724 #endif
8725
8726         KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8727         KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
8728         sbdrop(&so->so_snd, acked);
8729
8730         if (SEQ_GT(th->th_ack, tp->snd_una))
8731                 bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8732         tp->snd_una = th->th_ack;
8733         if (tp->snd_wnd < ctf_outstanding(tp))
8734                 /* The peer collapsed its window on us */
8735                 bbr_collapsed_window(bbr);
8736         else if (bbr->rc_has_collapsed)
8737                 bbr_un_collapse_window(bbr);
8738
8739         if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8740                 tp->snd_recover = tp->snd_una;
8741         }
8742         bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8743         /*
8744          * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8745          */
8746         tp->snd_wl2 = th->th_ack;
8747         m_freem(m);
8748         /*
8749          * If all outstanding data are acked, stop retransmit timer,
8750          * otherwise restart timer using current (possibly backed-off)
8751          * value. If process is waiting for space, wakeup/selwakeup/signal.
8752          * If data are ready to send, let tcp_output decide between more
8753          * output or persist.
8754          */
8755 #ifdef TCPDEBUG
8756         if (so->so_options & SO_DEBUG)
8757                 tcp_trace(TA_INPUT, ostate, tp,
8758                     (void *)tcp_saveipgen,
8759                     &tcp_savetcp, 0);
8760 #endif
8761         /* Wake up the socket if we have room to write more */
8762         sowwakeup(so);
8763         if (tp->snd_una == tp->snd_max) {
8764                 /* Nothing left outstanding */
8765                 bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8766                 if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
8767                         bbr->rc_tp->t_acktime = 0;
8768                 bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8769                 if (bbr->rc_in_persist == 0) {
8770                         bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8771                 }
8772                 sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8773                 bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8774                 /*
8775                  * We invalidate the last ack here since we
8776                  * don't want to transfer forward the time
8777                  * for our sum's calculations.
8778                  */
8779                 bbr->r_wanted_output = 1;
8780         }
8781         if (sbavail(&so->so_snd)) {
8782                 bbr->r_wanted_output = 1;
8783         }
8784         return (1);
8785 }
8786
8787 /*
8788  * Return value of 1, the TCB is unlocked and most
8789  * likely gone, return value of 0, the TCB is still
8790  * locked.
8791  */
8792 static int
8793 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8794     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8795     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8796 {
8797         int32_t todrop;
8798         int32_t ourfinisacked = 0;
8799         struct tcp_bbr *bbr;
8800         int32_t ret_val = 0;
8801
8802         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8803         ctf_calc_rwin(so, tp);
8804         /*
8805          * If the state is SYN_SENT: if seg contains an ACK, but not for our
8806          * SYN, drop the input. if seg contains a RST, then drop the
8807          * connection. if seg does not contain SYN, then drop it. Otherwise
8808          * this is an acceptable SYN segment initialize tp->rcv_nxt and
8809          * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8810          * not support ECN so we will not say we are capable. if SYN has
8811          * been acked change to ESTABLISHED else SYN_RCVD state arrange for
8812          * segment to be acked (eventually) continue processing rest of
8813          * data/controls, beginning with URG
8814          */
8815         if ((thflags & TH_ACK) &&
8816             (SEQ_LEQ(th->th_ack, tp->iss) ||
8817             SEQ_GT(th->th_ack, tp->snd_max))) {
8818                 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8819                 ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8820                 return (1);
8821         }
8822         if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
8823                 TCP_PROBE5(connect__refused, NULL, tp,
8824                     mtod(m, const char *), tp, th);
8825                 tp = tcp_drop(tp, ECONNREFUSED);
8826                 ctf_do_drop(m, tp);
8827                 return (1);
8828         }
8829         if (thflags & TH_RST) {
8830                 ctf_do_drop(m, tp);
8831                 return (1);
8832         }
8833         if (!(thflags & TH_SYN)) {
8834                 ctf_do_drop(m, tp);
8835                 return (1);
8836         }
8837         tp->irs = th->th_seq;
8838         tcp_rcvseqinit(tp);
8839         if (thflags & TH_ACK) {
8840                 int tfo_partial = 0;
8841
8842                 KMOD_TCPSTAT_INC(tcps_connects);
8843                 soisconnected(so);
8844 #ifdef MAC
8845                 mac_socketpeer_set_from_mbuf(m, so);
8846 #endif
8847                 /* Do window scaling on this connection? */
8848                 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
8849                     (TF_RCVD_SCALE | TF_REQ_SCALE)) {
8850                         tp->rcv_scale = tp->request_r_scale;
8851                 }
8852                 tp->rcv_adv += min(tp->rcv_wnd,
8853                     TCP_MAXWIN << tp->rcv_scale);
8854                 /*
8855                  * If not all the data that was sent in the TFO SYN
8856                  * has been acked, resend the remainder right away.
8857                  */
8858                 if (IS_FASTOPEN(tp->t_flags) &&
8859                     (tp->snd_una != tp->snd_max)) {
8860                         tp->snd_nxt = th->th_ack;
8861                         tfo_partial = 1;
8862                 }
8863                 /*
8864                  * If there's data, delay ACK; if there's also a FIN ACKNOW
8865                  * will be turned on later.
8866                  */
8867                 if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && !tfo_partial) {
8868                         bbr->bbr_segs_rcvd += 1;
8869                         tp->t_flags |= TF_DELACK;
8870                         bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8871                 } else {
8872                         bbr->r_wanted_output = 1;
8873                         tp->t_flags |= TF_ACKNOW;
8874                 }
8875                 if (SEQ_GT(th->th_ack, tp->iss)) {
8876                         /*
8877                          * The SYN is acked
8878                          * handle it specially.
8879                          */
8880                         bbr_log_syn(tp, to);
8881                 }
8882                 if (SEQ_GT(th->th_ack, tp->snd_una)) {
8883                         /*
8884                          * We advance snd_una for the
8885                          * fast open case. If th_ack is
8886                          * acknowledging data beyond
8887                          * snd_una we can't just call
8888                          * ack-processing since the
8889                          * data stream in our send-map
8890                          * will start at snd_una + 1 (one
8891                          * beyond the SYN). If its just
8892                          * equal we don't need to do that
8893                          * and there is no send_map.
8894                          */
8895                         tp->snd_una++;
8896                 }
8897                 /*
8898                  * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
8899                  * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
8900                  */
8901                 tp->t_starttime = ticks;
8902                 if (tp->t_flags & TF_NEEDFIN) {
8903                         tcp_state_change(tp, TCPS_FIN_WAIT_1);
8904                         tp->t_flags &= ~TF_NEEDFIN;
8905                         thflags &= ~TH_SYN;
8906                 } else {
8907                         tcp_state_change(tp, TCPS_ESTABLISHED);
8908                         TCP_PROBE5(connect__established, NULL, tp,
8909                             mtod(m, const char *), tp, th);
8910                         cc_conn_init(tp);
8911                 }
8912         } else {
8913                 /*
8914                  * Received initial SYN in SYN-SENT[*] state => simultaneous
8915                  * open.  If segment contains CC option and there is a
8916                  * cached CC, apply TAO test. If it succeeds, connection is *
8917                  * half-synchronized. Otherwise, do 3-way handshake:
8918                  * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
8919                  * there was no CC option, clear cached CC value.
8920                  */
8921                 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
8922                 tcp_state_change(tp, TCPS_SYN_RECEIVED);
8923         }
8924         INP_WLOCK_ASSERT(tp->t_inpcb);
8925         /*
8926          * Advance th->th_seq to correspond to first data byte. If data,
8927          * trim to stay within window, dropping FIN if necessary.
8928          */
8929         th->th_seq++;
8930         if (tlen > tp->rcv_wnd) {
8931                 todrop = tlen - tp->rcv_wnd;
8932                 m_adj(m, -todrop);
8933                 tlen = tp->rcv_wnd;
8934                 thflags &= ~TH_FIN;
8935                 KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
8936                 KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
8937         }
8938         tp->snd_wl1 = th->th_seq - 1;
8939         tp->rcv_up = th->th_seq;
8940         /*
8941          * Client side of transaction: already sent SYN and data. If the
8942          * remote host used T/TCP to validate the SYN, our data will be
8943          * ACK'd; if so, enter normal data segment processing in the middle
8944          * of step 5, ack processing. Otherwise, goto step 6.
8945          */
8946         if (thflags & TH_ACK) {
8947                 if ((to->to_flags & TOF_TS) != 0) {
8948                         uint32_t t, rtt;
8949
8950                         t = tcp_tv_to_mssectick(&bbr->rc_tv);
8951                         if (TSTMP_GEQ(t, to->to_tsecr)) {
8952                                 rtt = t - to->to_tsecr;
8953                                 if (rtt == 0) {
8954                                         rtt = 1;
8955                                 }
8956                                 rtt *= MS_IN_USEC;
8957                                 tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
8958                                 apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
8959                                                        rtt, bbr->r_ctl.rc_rcvtime);
8960                         }
8961                 }
8962                 if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
8963                         return (ret_val);
8964                 /* We may have changed to FIN_WAIT_1 above */
8965                 if (tp->t_state == TCPS_FIN_WAIT_1) {
8966                         /*
8967                          * In FIN_WAIT_1 STATE in addition to the processing
8968                          * for the ESTABLISHED state if our FIN is now
8969                          * acknowledged then enter FIN_WAIT_2.
8970                          */
8971                         if (ourfinisacked) {
8972                                 /*
8973                                  * If we can't receive any more data, then
8974                                  * closing user can proceed. Starting the
8975                                  * timer is contrary to the specification,
8976                                  * but if we don't get a FIN we'll hang
8977                                  * forever.
8978                                  *
8979                                  * XXXjl: we should release the tp also, and
8980                                  * use a compressed state.
8981                                  */
8982                                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8983                                         soisdisconnected(so);
8984                                         tcp_timer_activate(tp, TT_2MSL,
8985                                             (tcp_fast_finwait2_recycle ?
8986                                             tcp_finwait2_timeout :
8987                                             TP_MAXIDLE(tp)));
8988                                 }
8989                                 tcp_state_change(tp, TCPS_FIN_WAIT_2);
8990                         }
8991                 }
8992         }
8993         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
8994             tiwin, thflags, nxt_pkt));
8995 }
8996
8997 /*
8998  * Return value of 1, the TCB is unlocked and most
8999  * likely gone, return value of 0, the TCB is still
9000  * locked.
9001  */
9002 static int
9003 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
9004                 struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9005                 uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9006 {
9007         int32_t ourfinisacked = 0;
9008         int32_t ret_val;
9009         struct tcp_bbr *bbr;
9010
9011         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9012         ctf_calc_rwin(so, tp);
9013         if ((thflags & TH_ACK) &&
9014             (SEQ_LEQ(th->th_ack, tp->snd_una) ||
9015              SEQ_GT(th->th_ack, tp->snd_max))) {
9016                 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9017                 ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9018                 return (1);
9019         }
9020         if (IS_FASTOPEN(tp->t_flags)) {
9021                 /*
9022                  * When a TFO connection is in SYN_RECEIVED, the only valid
9023                  * packets are the initial SYN, a retransmit/copy of the
9024                  * initial SYN (possibly with a subset of the original
9025                  * data), a valid ACK, a FIN, or a RST.
9026                  */
9027                 if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
9028                         tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9029                         ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9030                         return (1);
9031                 } else if (thflags & TH_SYN) {
9032                         /* non-initial SYN is ignored */
9033                         if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
9034                             (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
9035                             (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
9036                                 ctf_do_drop(m, NULL);
9037                                 return (0);
9038                         }
9039                 } else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
9040                         ctf_do_drop(m, NULL);
9041                         return (0);
9042                 }
9043         }
9044         if ((thflags & TH_RST) ||
9045             (tp->t_fin_is_rst && (thflags & TH_FIN)))
9046                 return (ctf_process_rst(m, th, so, tp));
9047         /*
9048          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9049          * it's less than ts_recent, drop it.
9050          */
9051         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9052             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9053                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9054                         return (ret_val);
9055         }
9056         /*
9057          * In the SYN-RECEIVED state, validate that the packet belongs to
9058          * this connection before trimming the data to fit the receive
9059          * window.  Check the sequence number versus IRS since we know the
9060          * sequence numbers haven't wrapped.  This is a partial fix for the
9061          * "LAND" DoS attack.
9062          */
9063         if (SEQ_LT(th->th_seq, tp->irs)) {
9064                 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9065                 ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9066                 return (1);
9067         }
9068         INP_WLOCK_ASSERT(tp->t_inpcb);
9069         if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9070                 return (ret_val);
9071         }
9072         /*
9073          * If last ACK falls within this segment's sequence numbers, record
9074          * its timestamp. NOTE: 1) That the test incorporates suggestions
9075          * from the latest proposal of the tcplw@cray.com list (Braden
9076          * 1993/04/26). 2) That updating only on newer timestamps interferes
9077          * with our earlier PAWS tests, so this check should be solely
9078          * predicated on the sequence space of this segment. 3) That we
9079          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9080          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9081          * SEG.Len, This modified check allows us to overcome RFC1323's
9082          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9083          * p.869. In such cases, we can still calculate the RTT correctly
9084          * when RCV.NXT == Last.ACK.Sent.
9085          */
9086         if ((to->to_flags & TOF_TS) != 0 &&
9087             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9088             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9089                     ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9090                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9091                 tp->ts_recent = to->to_tsval;
9092         }
9093         tp->snd_wnd = tiwin;
9094         /*
9095          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9096          * is on (half-synchronized state), then queue data for later
9097          * processing; else drop segment and return.
9098          */
9099         if ((thflags & TH_ACK) == 0) {
9100                 if (IS_FASTOPEN(tp->t_flags)) {
9101                         cc_conn_init(tp);
9102                 }
9103                 return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9104                                          tiwin, thflags, nxt_pkt));
9105         }
9106         KMOD_TCPSTAT_INC(tcps_connects);
9107         soisconnected(so);
9108         /* Do window scaling? */
9109         if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9110             (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9111                 tp->rcv_scale = tp->request_r_scale;
9112         }
9113         /*
9114          * ok for the first time in lets see if we can use the ts to figure
9115          * out what the initial RTT was.
9116          */
9117         if ((to->to_flags & TOF_TS) != 0) {
9118                 uint32_t t, rtt;
9119
9120                 t = tcp_tv_to_mssectick(&bbr->rc_tv);
9121                 if (TSTMP_GEQ(t, to->to_tsecr)) {
9122                         rtt = t - to->to_tsecr;
9123                         if (rtt == 0) {
9124                                 rtt = 1;
9125                         }
9126                         rtt *= MS_IN_USEC;
9127                         tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9128                         apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9129                 }
9130         }
9131         /* Drop off any SYN in the send map (probably not there)  */
9132         if (thflags & TH_ACK)
9133                 bbr_log_syn(tp, to);
9134         if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
9135                 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9136                 tp->t_tfo_pending = NULL;
9137         }
9138         /*
9139          * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9140          * FIN-WAIT-1
9141          */
9142         tp->t_starttime = ticks;
9143         if (tp->t_flags & TF_NEEDFIN) {
9144                 tcp_state_change(tp, TCPS_FIN_WAIT_1);
9145                 tp->t_flags &= ~TF_NEEDFIN;
9146         } else {
9147                 tcp_state_change(tp, TCPS_ESTABLISHED);
9148                 TCP_PROBE5(accept__established, NULL, tp,
9149                            mtod(m, const char *), tp, th);
9150                 /*
9151                  * TFO connections call cc_conn_init() during SYN
9152                  * processing.  Calling it again here for such connections
9153                  * is not harmless as it would undo the snd_cwnd reduction
9154                  * that occurs when a TFO SYN|ACK is retransmitted.
9155                  */
9156                 if (!IS_FASTOPEN(tp->t_flags))
9157                         cc_conn_init(tp);
9158         }
9159         /*
9160          * Account for the ACK of our SYN prior to
9161          * regular ACK processing below, except for
9162          * simultaneous SYN, which is handled later.
9163          */
9164         if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
9165                 tp->snd_una++;
9166         /*
9167          * If segment contains data or ACK, will call tcp_reass() later; if
9168          * not, do so now to pass queued data to user.
9169          */
9170         if (tlen == 0 && (thflags & TH_FIN) == 0) {
9171                 (void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9172                         (struct mbuf *)0);
9173                 if (tp->t_flags & TF_WAKESOR) {
9174                         tp->t_flags &= ~TF_WAKESOR;
9175                         /* NB: sorwakeup_locked() does an implicit unlock. */
9176                         sorwakeup_locked(so);
9177                 }
9178         }
9179         tp->snd_wl1 = th->th_seq - 1;
9180         if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9181                 return (ret_val);
9182         }
9183         if (tp->t_state == TCPS_FIN_WAIT_1) {
9184                 /* We could have went to FIN_WAIT_1 (or EST) above */
9185                 /*
9186                  * In FIN_WAIT_1 STATE in addition to the processing for the
9187                  * ESTABLISHED state if our FIN is now acknowledged then
9188                  * enter FIN_WAIT_2.
9189                  */
9190                 if (ourfinisacked) {
9191                         /*
9192                          * If we can't receive any more data, then closing
9193                          * user can proceed. Starting the timer is contrary
9194                          * to the specification, but if we don't get a FIN
9195                          * we'll hang forever.
9196                          *
9197                          * XXXjl: we should release the tp also, and use a
9198                          * compressed state.
9199                          */
9200                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9201                                 soisdisconnected(so);
9202                                 tcp_timer_activate(tp, TT_2MSL,
9203                                                    (tcp_fast_finwait2_recycle ?
9204                                                     tcp_finwait2_timeout :
9205                                                     TP_MAXIDLE(tp)));
9206                         }
9207                         tcp_state_change(tp, TCPS_FIN_WAIT_2);
9208                 }
9209         }
9210         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9211                                  tiwin, thflags, nxt_pkt));
9212 }
9213
9214 /*
9215  * Return value of 1, the TCB is unlocked and most
9216  * likely gone, return value of 0, the TCB is still
9217  * locked.
9218  */
9219 static int
9220 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9221     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9222     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9223 {
9224         struct tcp_bbr *bbr;
9225         int32_t ret_val;
9226
9227         /*
9228          * Header prediction: check for the two common cases of a
9229          * uni-directional data xfer.  If the packet has no control flags,
9230          * is in-sequence, the window didn't change and we're not
9231          * retransmitting, it's a candidate.  If the length is zero and the
9232          * ack moved forward, we're the sender side of the xfer.  Just free
9233          * the data acked & wake any higher level process that was blocked
9234          * waiting for space.  If the length is non-zero and the ack didn't
9235          * move, we're the receiver side.  If we're getting packets in-order
9236          * (the reassembly queue is empty), add the data toc The socket
9237          * buffer and note that we need a delayed ack. Make sure that the
9238          * hidden state-flags are also off. Since we check for
9239          * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9240          */
9241         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9242         if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9243                 /*
9244                  * If we have delived under 4 segments increase the initial
9245                  * window if raised by the peer. We use this to determine
9246                  * dynamic and static rwnd's at the end of a connection.
9247                  */
9248                 bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9249         }
9250         if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9251             __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9252             __predict_true(SEGQ_EMPTY(tp)) &&
9253             __predict_true(th->th_seq == tp->rcv_nxt)) {
9254                 if (tlen == 0) {
9255                         if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9256                             tiwin, nxt_pkt, iptos)) {
9257                                 return (0);
9258                         }
9259                 } else {
9260                         if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9261                             tiwin, nxt_pkt)) {
9262                                 return (0);
9263                         }
9264                 }
9265         }
9266         ctf_calc_rwin(so, tp);
9267
9268         if ((thflags & TH_RST) ||
9269             (tp->t_fin_is_rst && (thflags & TH_FIN)))
9270                 return (ctf_process_rst(m, th, so, tp));
9271         /*
9272          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9273          * synchronized state.
9274          */
9275         if (thflags & TH_SYN) {
9276                 ctf_challenge_ack(m, th, tp, &ret_val);
9277                 return (ret_val);
9278         }
9279         /*
9280          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9281          * it's less than ts_recent, drop it.
9282          */
9283         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9284             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9285                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9286                         return (ret_val);
9287         }
9288         INP_WLOCK_ASSERT(tp->t_inpcb);
9289         if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9290                 return (ret_val);
9291         }
9292         /*
9293          * If last ACK falls within this segment's sequence numbers, record
9294          * its timestamp. NOTE: 1) That the test incorporates suggestions
9295          * from the latest proposal of the tcplw@cray.com list (Braden
9296          * 1993/04/26). 2) That updating only on newer timestamps interferes
9297          * with our earlier PAWS tests, so this check should be solely
9298          * predicated on the sequence space of this segment. 3) That we
9299          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9300          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9301          * SEG.Len, This modified check allows us to overcome RFC1323's
9302          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9303          * p.869. In such cases, we can still calculate the RTT correctly
9304          * when RCV.NXT == Last.ACK.Sent.
9305          */
9306         if ((to->to_flags & TOF_TS) != 0 &&
9307             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9308             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9309             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9310                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9311                 tp->ts_recent = to->to_tsval;
9312         }
9313         /*
9314          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9315          * is on (half-synchronized state), then queue data for later
9316          * processing; else drop segment and return.
9317          */
9318         if ((thflags & TH_ACK) == 0) {
9319                 if (tp->t_flags & TF_NEEDSYN) {
9320                         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9321                             tiwin, thflags, nxt_pkt));
9322                 } else if (tp->t_flags & TF_ACKNOW) {
9323                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9324                         bbr->r_wanted_output = 1;
9325                         return (ret_val);
9326                 } else {
9327                         ctf_do_drop(m, NULL);
9328                         return (0);
9329                 }
9330         }
9331         /*
9332          * Ack processing.
9333          */
9334         if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9335                 return (ret_val);
9336         }
9337         if (sbavail(&so->so_snd)) {
9338                 if (ctf_progress_timeout_check(tp, true)) {
9339                         bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9340                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9341                         return (1);
9342                 }
9343         }
9344         /* State changes only happen in bbr_process_data() */
9345         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9346             tiwin, thflags, nxt_pkt));
9347 }
9348
9349 /*
9350  * Return value of 1, the TCB is unlocked and most
9351  * likely gone, return value of 0, the TCB is still
9352  * locked.
9353  */
9354 static int
9355 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9356     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9357     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9358 {
9359         struct tcp_bbr *bbr;
9360         int32_t ret_val;
9361
9362         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9363         ctf_calc_rwin(so, tp);
9364         if ((thflags & TH_RST) ||
9365             (tp->t_fin_is_rst && (thflags & TH_FIN)))
9366                 return (ctf_process_rst(m, th, so, tp));
9367         /*
9368          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9369          * synchronized state.
9370          */
9371         if (thflags & TH_SYN) {
9372                 ctf_challenge_ack(m, th, tp, &ret_val);
9373                 return (ret_val);
9374         }
9375         /*
9376          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9377          * it's less than ts_recent, drop it.
9378          */
9379         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9380             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9381                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9382                         return (ret_val);
9383         }
9384         INP_WLOCK_ASSERT(tp->t_inpcb);
9385         if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9386                 return (ret_val);
9387         }
9388         /*
9389          * If last ACK falls within this segment's sequence numbers, record
9390          * its timestamp. NOTE: 1) That the test incorporates suggestions
9391          * from the latest proposal of the tcplw@cray.com list (Braden
9392          * 1993/04/26). 2) That updating only on newer timestamps interferes
9393          * with our earlier PAWS tests, so this check should be solely
9394          * predicated on the sequence space of this segment. 3) That we
9395          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9396          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9397          * SEG.Len, This modified check allows us to overcome RFC1323's
9398          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9399          * p.869. In such cases, we can still calculate the RTT correctly
9400          * when RCV.NXT == Last.ACK.Sent.
9401          */
9402         if ((to->to_flags & TOF_TS) != 0 &&
9403             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9404             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9405             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9406                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9407                 tp->ts_recent = to->to_tsval;
9408         }
9409         /*
9410          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9411          * is on (half-synchronized state), then queue data for later
9412          * processing; else drop segment and return.
9413          */
9414         if ((thflags & TH_ACK) == 0) {
9415                 if (tp->t_flags & TF_NEEDSYN) {
9416                         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9417                             tiwin, thflags, nxt_pkt));
9418                 } else if (tp->t_flags & TF_ACKNOW) {
9419                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9420                         bbr->r_wanted_output = 1;
9421                         return (ret_val);
9422                 } else {
9423                         ctf_do_drop(m, NULL);
9424                         return (0);
9425                 }
9426         }
9427         /*
9428          * Ack processing.
9429          */
9430         if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9431                 return (ret_val);
9432         }
9433         if (sbavail(&so->so_snd)) {
9434                 if (ctf_progress_timeout_check(tp, true)) {
9435                         bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9436                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9437                         return (1);
9438                 }
9439         }
9440         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9441             tiwin, thflags, nxt_pkt));
9442 }
9443
9444 static int
9445 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9446     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9447 {
9448
9449         if (bbr->rc_allow_data_af_clo == 0) {
9450 close_now:
9451                 tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
9452                 /* tcp_close will kill the inp pre-log the Reset */
9453                 tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
9454                 tp = tcp_close(tp);
9455                 KMOD_TCPSTAT_INC(tcps_rcvafterclose);
9456                 ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9457                 return (1);
9458         }
9459         if (sbavail(&so->so_snd) == 0)
9460                 goto close_now;
9461         /* Ok we allow data that is ignored and a followup reset */
9462         tp->rcv_nxt = th->th_seq + *tlen;
9463         tp->t_flags2 |= TF2_DROP_AF_DATA;
9464         bbr->r_wanted_output = 1;
9465         *tlen = 0;
9466         return (0);
9467 }
9468
9469 /*
9470  * Return value of 1, the TCB is unlocked and most
9471  * likely gone, return value of 0, the TCB is still
9472  * locked.
9473  */
9474 static int
9475 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9476     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9477     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9478 {
9479         int32_t ourfinisacked = 0;
9480         int32_t ret_val;
9481         struct tcp_bbr *bbr;
9482
9483         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9484         ctf_calc_rwin(so, tp);
9485         if ((thflags & TH_RST) ||
9486             (tp->t_fin_is_rst && (thflags & TH_FIN)))
9487                 return (ctf_process_rst(m, th, so, tp));
9488         /*
9489          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9490          * synchronized state.
9491          */
9492         if (thflags & TH_SYN) {
9493                 ctf_challenge_ack(m, th, tp, &ret_val);
9494                 return (ret_val);
9495         }
9496         /*
9497          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9498          * it's less than ts_recent, drop it.
9499          */
9500         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9501             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9502                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9503                         return (ret_val);
9504         }
9505         INP_WLOCK_ASSERT(tp->t_inpcb);
9506         if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9507                 return (ret_val);
9508         }
9509         /*
9510          * If new data are received on a connection after the user processes
9511          * are gone, then RST the other end.
9512          */
9513         if ((so->so_state & SS_NOFDREF) && tlen) {
9514                 /*
9515                  * We call a new function now so we might continue and setup
9516                  * to reset at all data being ack'd.
9517                  */
9518                 if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9519                         return (1);
9520         }
9521         /*
9522          * If last ACK falls within this segment's sequence numbers, record
9523          * its timestamp. NOTE: 1) That the test incorporates suggestions
9524          * from the latest proposal of the tcplw@cray.com list (Braden
9525          * 1993/04/26). 2) That updating only on newer timestamps interferes
9526          * with our earlier PAWS tests, so this check should be solely
9527          * predicated on the sequence space of this segment. 3) That we
9528          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9529          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9530          * SEG.Len, This modified check allows us to overcome RFC1323's
9531          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9532          * p.869. In such cases, we can still calculate the RTT correctly
9533          * when RCV.NXT == Last.ACK.Sent.
9534          */
9535         if ((to->to_flags & TOF_TS) != 0 &&
9536             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9537             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9538             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9539                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9540                 tp->ts_recent = to->to_tsval;
9541         }
9542         /*
9543          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9544          * is on (half-synchronized state), then queue data for later
9545          * processing; else drop segment and return.
9546          */
9547         if ((thflags & TH_ACK) == 0) {
9548                 if (tp->t_flags & TF_NEEDSYN) {
9549                         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9550                             tiwin, thflags, nxt_pkt));
9551                 } else if (tp->t_flags & TF_ACKNOW) {
9552                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9553                         bbr->r_wanted_output = 1;
9554                         return (ret_val);
9555                 } else {
9556                         ctf_do_drop(m, NULL);
9557                         return (0);
9558                 }
9559         }
9560         /*
9561          * Ack processing.
9562          */
9563         if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9564                 return (ret_val);
9565         }
9566         if (ourfinisacked) {
9567                 /*
9568                  * If we can't receive any more data, then closing user can
9569                  * proceed. Starting the timer is contrary to the
9570                  * specification, but if we don't get a FIN we'll hang
9571                  * forever.
9572                  *
9573                  * XXXjl: we should release the tp also, and use a
9574                  * compressed state.
9575                  */
9576                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9577                         soisdisconnected(so);
9578                         tcp_timer_activate(tp, TT_2MSL,
9579                             (tcp_fast_finwait2_recycle ?
9580                             tcp_finwait2_timeout :
9581                             TP_MAXIDLE(tp)));
9582                 }
9583                 tcp_state_change(tp, TCPS_FIN_WAIT_2);
9584         }
9585         if (sbavail(&so->so_snd)) {
9586                 if (ctf_progress_timeout_check(tp, true)) {
9587                         bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9588                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9589                         return (1);
9590                 }
9591         }
9592         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9593             tiwin, thflags, nxt_pkt));
9594 }
9595
9596 /*
9597  * Return value of 1, the TCB is unlocked and most
9598  * likely gone, return value of 0, the TCB is still
9599  * locked.
9600  */
9601 static int
9602 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9603     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9604     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9605 {
9606         int32_t ourfinisacked = 0;
9607         int32_t ret_val;
9608         struct tcp_bbr *bbr;
9609
9610         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9611         ctf_calc_rwin(so, tp);
9612         if ((thflags & TH_RST) ||
9613             (tp->t_fin_is_rst && (thflags & TH_FIN)))
9614                 return (ctf_process_rst(m, th, so, tp));
9615         /*
9616          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9617          * synchronized state.
9618          */
9619         if (thflags & TH_SYN) {
9620                 ctf_challenge_ack(m, th, tp, &ret_val);
9621                 return (ret_val);
9622         }
9623         /*
9624          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9625          * it's less than ts_recent, drop it.
9626          */
9627         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9628             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9629                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9630                         return (ret_val);
9631         }
9632         INP_WLOCK_ASSERT(tp->t_inpcb);
9633         if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9634                 return (ret_val);
9635         }
9636         /*
9637          * If new data are received on a connection after the user processes
9638          * are gone, then RST the other end.
9639          */
9640         if ((so->so_state & SS_NOFDREF) && tlen) {
9641                 /*
9642                  * We call a new function now so we might continue and setup
9643                  * to reset at all data being ack'd.
9644                  */
9645                 if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9646                         return (1);
9647         }
9648         /*
9649          * If last ACK falls within this segment's sequence numbers, record
9650          * its timestamp. NOTE: 1) That the test incorporates suggestions
9651          * from the latest proposal of the tcplw@cray.com list (Braden
9652          * 1993/04/26). 2) That updating only on newer timestamps interferes
9653          * with our earlier PAWS tests, so this check should be solely
9654          * predicated on the sequence space of this segment. 3) That we
9655          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9656          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9657          * SEG.Len, This modified check allows us to overcome RFC1323's
9658          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9659          * p.869. In such cases, we can still calculate the RTT correctly
9660          * when RCV.NXT == Last.ACK.Sent.
9661          */
9662         if ((to->to_flags & TOF_TS) != 0 &&
9663             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9664             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9665             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9666                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9667                 tp->ts_recent = to->to_tsval;
9668         }
9669         /*
9670          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9671          * is on (half-synchronized state), then queue data for later
9672          * processing; else drop segment and return.
9673          */
9674         if ((thflags & TH_ACK) == 0) {
9675                 if (tp->t_flags & TF_NEEDSYN) {
9676                         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9677                             tiwin, thflags, nxt_pkt));
9678                 } else if (tp->t_flags & TF_ACKNOW) {
9679                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9680                         bbr->r_wanted_output = 1;
9681                         return (ret_val);
9682                 } else {
9683                         ctf_do_drop(m, NULL);
9684                         return (0);
9685                 }
9686         }
9687         /*
9688          * Ack processing.
9689          */
9690         if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9691                 return (ret_val);
9692         }
9693         if (ourfinisacked) {
9694                 tcp_twstart(tp);
9695                 m_freem(m);
9696                 return (1);
9697         }
9698         if (sbavail(&so->so_snd)) {
9699                 if (ctf_progress_timeout_check(tp, true)) {
9700                         bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9701                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9702                         return (1);
9703                 }
9704         }
9705         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9706             tiwin, thflags, nxt_pkt));
9707 }
9708
9709 /*
9710  * Return value of 1, the TCB is unlocked and most
9711  * likely gone, return value of 0, the TCB is still
9712  * locked.
9713  */
9714 static int
9715 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9716     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9717     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9718 {
9719         int32_t ourfinisacked = 0;
9720         int32_t ret_val;
9721         struct tcp_bbr *bbr;
9722
9723         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9724         ctf_calc_rwin(so, tp);
9725         if ((thflags & TH_RST) ||
9726             (tp->t_fin_is_rst && (thflags & TH_FIN)))
9727                 return (ctf_process_rst(m, th, so, tp));
9728         /*
9729          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9730          * synchronized state.
9731          */
9732         if (thflags & TH_SYN) {
9733                 ctf_challenge_ack(m, th, tp, &ret_val);
9734                 return (ret_val);
9735         }
9736         /*
9737          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9738          * it's less than ts_recent, drop it.
9739          */
9740         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9741             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9742                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9743                         return (ret_val);
9744         }
9745         INP_WLOCK_ASSERT(tp->t_inpcb);
9746         if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9747                 return (ret_val);
9748         }
9749         /*
9750          * If new data are received on a connection after the user processes
9751          * are gone, then RST the other end.
9752          */
9753         if ((so->so_state & SS_NOFDREF) && tlen) {
9754                 /*
9755                  * We call a new function now so we might continue and setup
9756                  * to reset at all data being ack'd.
9757                  */
9758                 if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9759                         return (1);
9760         }
9761         /*
9762          * If last ACK falls within this segment's sequence numbers, record
9763          * its timestamp. NOTE: 1) That the test incorporates suggestions
9764          * from the latest proposal of the tcplw@cray.com list (Braden
9765          * 1993/04/26). 2) That updating only on newer timestamps interferes
9766          * with our earlier PAWS tests, so this check should be solely
9767          * predicated on the sequence space of this segment. 3) That we
9768          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9769          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9770          * SEG.Len, This modified check allows us to overcome RFC1323's
9771          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9772          * p.869. In such cases, we can still calculate the RTT correctly
9773          * when RCV.NXT == Last.ACK.Sent.
9774          */
9775         if ((to->to_flags & TOF_TS) != 0 &&
9776             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9777             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9778             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9779                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9780                 tp->ts_recent = to->to_tsval;
9781         }
9782         /*
9783          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9784          * is on (half-synchronized state), then queue data for later
9785          * processing; else drop segment and return.
9786          */
9787         if ((thflags & TH_ACK) == 0) {
9788                 if (tp->t_flags & TF_NEEDSYN) {
9789                         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9790                             tiwin, thflags, nxt_pkt));
9791                 } else if (tp->t_flags & TF_ACKNOW) {
9792                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9793                         bbr->r_wanted_output = 1;
9794                         return (ret_val);
9795                 } else {
9796                         ctf_do_drop(m, NULL);
9797                         return (0);
9798                 }
9799         }
9800         /*
9801          * case TCPS_LAST_ACK: Ack processing.
9802          */
9803         if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9804                 return (ret_val);
9805         }
9806         if (ourfinisacked) {
9807                 tp = tcp_close(tp);
9808                 ctf_do_drop(m, tp);
9809                 return (1);
9810         }
9811         if (sbavail(&so->so_snd)) {
9812                 if (ctf_progress_timeout_check(tp, true)) {
9813                         bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9814                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9815                         return (1);
9816                 }
9817         }
9818         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9819             tiwin, thflags, nxt_pkt));
9820 }
9821
9822 /*
9823  * Return value of 1, the TCB is unlocked and most
9824  * likely gone, return value of 0, the TCB is still
9825  * locked.
9826  */
9827 static int
9828 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9829     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9830     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9831 {
9832         int32_t ourfinisacked = 0;
9833         int32_t ret_val;
9834         struct tcp_bbr *bbr;
9835
9836         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9837         ctf_calc_rwin(so, tp);
9838         /* Reset receive buffer auto scaling when not in bulk receive mode. */
9839         if ((thflags & TH_RST) ||
9840             (tp->t_fin_is_rst && (thflags & TH_FIN)))
9841                 return (ctf_process_rst(m, th, so, tp));
9842
9843         /*
9844          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9845          * synchronized state.
9846          */
9847         if (thflags & TH_SYN) {
9848                 ctf_challenge_ack(m, th, tp, &ret_val);
9849                 return (ret_val);
9850         }
9851         INP_WLOCK_ASSERT(tp->t_inpcb);
9852         /*
9853          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9854          * it's less than ts_recent, drop it.
9855          */
9856         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9857             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9858                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9859                         return (ret_val);
9860         }
9861         INP_WLOCK_ASSERT(tp->t_inpcb);
9862         if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9863                 return (ret_val);
9864         }
9865         /*
9866          * If new data are received on a connection after the user processes
9867          * are gone, then we may RST the other end depending on the outcome
9868          * of bbr_check_data_after_close.
9869          */
9870         if ((so->so_state & SS_NOFDREF) &&
9871             tlen) {
9872                 /*
9873                  * We call a new function now so we might continue and setup
9874                  * to reset at all data being ack'd.
9875                  */
9876                 if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9877                         return (1);
9878         }
9879         INP_WLOCK_ASSERT(tp->t_inpcb);
9880         /*
9881          * If last ACK falls within this segment's sequence numbers, record
9882          * its timestamp. NOTE: 1) That the test incorporates suggestions
9883          * from the latest proposal of the tcplw@cray.com list (Braden
9884          * 1993/04/26). 2) That updating only on newer timestamps interferes
9885          * with our earlier PAWS tests, so this check should be solely
9886          * predicated on the sequence space of this segment. 3) That we
9887          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9888          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9889          * SEG.Len, This modified check allows us to overcome RFC1323's
9890          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9891          * p.869. In such cases, we can still calculate the RTT correctly
9892          * when RCV.NXT == Last.ACK.Sent.
9893          */
9894         INP_WLOCK_ASSERT(tp->t_inpcb);
9895         if ((to->to_flags & TOF_TS) != 0 &&
9896             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9897             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9898             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9899                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9900                 tp->ts_recent = to->to_tsval;
9901         }
9902         /*
9903          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9904          * is on (half-synchronized state), then queue data for later
9905          * processing; else drop segment and return.
9906          */
9907         if ((thflags & TH_ACK) == 0) {
9908                 if (tp->t_flags & TF_NEEDSYN) {
9909                         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9910                             tiwin, thflags, nxt_pkt));
9911                 } else if (tp->t_flags & TF_ACKNOW) {
9912                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9913                         bbr->r_wanted_output = 1;
9914                         return (ret_val);
9915                 } else {
9916                         ctf_do_drop(m, NULL);
9917                         return (0);
9918                 }
9919         }
9920         /*
9921          * Ack processing.
9922          */
9923         INP_WLOCK_ASSERT(tp->t_inpcb);
9924         if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9925                 return (ret_val);
9926         }
9927         if (sbavail(&so->so_snd)) {
9928                 if (ctf_progress_timeout_check(tp, true)) {
9929                         bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9930                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9931                         return (1);
9932                 }
9933         }
9934         INP_WLOCK_ASSERT(tp->t_inpcb);
9935         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9936             tiwin, thflags, nxt_pkt));
9937 }
9938
9939 static void
9940 bbr_stop_all_timers(struct tcpcb *tp)
9941 {
9942         struct tcp_bbr *bbr;
9943
9944         /*
9945          * Assure no timers are running.
9946          */
9947         if (tcp_timer_active(tp, TT_PERSIST)) {
9948                 /* We enter in persists, set the flag appropriately */
9949                 bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9950                 bbr->rc_in_persist = 1;
9951         }
9952         tcp_timer_suspend(tp, TT_PERSIST);
9953         tcp_timer_suspend(tp, TT_REXMT);
9954         tcp_timer_suspend(tp, TT_KEEP);
9955         tcp_timer_suspend(tp, TT_DELACK);
9956 }
9957
9958 static void
9959 bbr_google_mode_on(struct tcp_bbr *bbr)
9960 {
9961         bbr->rc_use_google = 1;
9962         bbr->rc_no_pacing = 0;
9963         bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9964         bbr->r_use_policer = bbr_policer_detection_enabled;
9965         bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
9966         bbr->bbr_use_rack_cheat = 0;
9967         bbr->r_ctl.rc_incr_tmrs = 0;
9968         bbr->r_ctl.rc_inc_tcp_oh = 0;
9969         bbr->r_ctl.rc_inc_ip_oh = 0;
9970         bbr->r_ctl.rc_inc_enet_oh = 0;
9971         reset_time(&bbr->r_ctl.rc_delrate,
9972                    BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
9973         reset_time_small(&bbr->r_ctl.rc_rttprop,
9974                          (11 * USECS_IN_SECOND));
9975         tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9976 }
9977
9978 static void
9979 bbr_google_mode_off(struct tcp_bbr *bbr)
9980 {
9981         bbr->rc_use_google = 0;
9982         bbr->r_ctl.bbr_google_discount = 0;
9983         bbr->no_pacing_until = bbr_no_pacing_until;
9984         bbr->r_use_policer = 0;
9985         if (bbr->no_pacing_until)
9986                 bbr->rc_no_pacing = 1;
9987         else
9988                 bbr->rc_no_pacing = 0;
9989         if (bbr_use_rack_resend_cheat)
9990                 bbr->bbr_use_rack_cheat = 1;
9991         else
9992                 bbr->bbr_use_rack_cheat = 0;
9993         if (bbr_incr_timers)
9994                 bbr->r_ctl.rc_incr_tmrs = 1;
9995         else
9996                 bbr->r_ctl.rc_incr_tmrs = 0;
9997         if (bbr_include_tcp_oh)
9998                 bbr->r_ctl.rc_inc_tcp_oh = 1;
9999         else
10000                 bbr->r_ctl.rc_inc_tcp_oh = 0;
10001         if (bbr_include_ip_oh)
10002                 bbr->r_ctl.rc_inc_ip_oh = 1;
10003         else
10004                 bbr->r_ctl.rc_inc_ip_oh = 0;
10005         if (bbr_include_enet_oh)
10006                 bbr->r_ctl.rc_inc_enet_oh = 1;
10007         else
10008                 bbr->r_ctl.rc_inc_enet_oh = 0;
10009         bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10010         reset_time(&bbr->r_ctl.rc_delrate,
10011                    bbr_num_pktepo_for_del_limit);
10012         reset_time_small(&bbr->r_ctl.rc_rttprop,
10013                          (bbr_filter_len_sec * USECS_IN_SECOND));
10014         tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
10015 }
10016 /*
10017  * Return 0 on success, non-zero on failure
10018  * which indicates the error (usually no memory).
10019  */
10020 static int
10021 bbr_init(struct tcpcb *tp)
10022 {
10023         struct tcp_bbr *bbr = NULL;
10024         struct inpcb *inp;
10025         uint32_t cts;
10026
10027         tp->t_fb_ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
10028         if (tp->t_fb_ptr == NULL) {
10029                 /*
10030                  * We need to allocate memory but cant. The INP and INP_INFO
10031                  * locks and they are recusive (happens during setup. So a
10032                  * scheme to drop the locks fails :(
10033                  *
10034                  */
10035                 return (ENOMEM);
10036         }
10037         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10038         bbr->rtt_valid = 0;
10039         inp = tp->t_inpcb;
10040         inp->inp_flags2 |= INP_CANNOT_DO_ECN;
10041         inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
10042         TAILQ_INIT(&bbr->r_ctl.rc_map);
10043         TAILQ_INIT(&bbr->r_ctl.rc_free);
10044         TAILQ_INIT(&bbr->r_ctl.rc_tmap);
10045         bbr->rc_tp = tp;
10046         if (tp->t_inpcb) {
10047                 bbr->rc_inp = tp->t_inpcb;
10048         }
10049         cts = tcp_get_usecs(&bbr->rc_tv);
10050         tp->t_acktime = 0;
10051         bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
10052         bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
10053         bbr->rc_tlp_threshold = bbr_tlp_thresh;
10054         bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
10055         bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
10056         bbr->r_ctl.rc_min_to = bbr_min_to;
10057         bbr->rc_bbr_state = BBR_STATE_STARTUP;
10058         bbr->r_ctl.bbr_lost_at_state = 0;
10059         bbr->r_ctl.rc_lost_at_startup = 0;
10060         bbr->rc_all_timers_stopped = 0;
10061         bbr->r_ctl.rc_bbr_lastbtlbw = 0;
10062         bbr->r_ctl.rc_pkt_epoch_del = 0;
10063         bbr->r_ctl.rc_pkt_epoch = 0;
10064         bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
10065         bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
10066         bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
10067         bbr->r_ctl.rc_went_idle_time = cts;
10068         bbr->rc_pacer_started = cts;
10069         bbr->r_ctl.rc_pkt_epoch_time = cts;
10070         bbr->r_ctl.rc_rcvtime = cts;
10071         bbr->r_ctl.rc_bbr_state_time = cts;
10072         bbr->r_ctl.rc_del_time = cts;
10073         bbr->r_ctl.rc_tlp_rxt_last_time = cts;
10074         bbr->r_ctl.last_in_probertt = cts;
10075         bbr->skip_gain = 0;
10076         bbr->gain_is_limited = 0;
10077         bbr->no_pacing_until = bbr_no_pacing_until;
10078         if (bbr->no_pacing_until)
10079                 bbr->rc_no_pacing = 1;
10080         if (bbr_use_google_algo) {
10081                 bbr->rc_no_pacing = 0;
10082                 bbr->rc_use_google = 1;
10083                 bbr->r_ctl.bbr_google_discount = bbr_google_discount;
10084                 bbr->r_use_policer = bbr_policer_detection_enabled;
10085         } else {
10086                 bbr->rc_use_google = 0;
10087                 bbr->r_ctl.bbr_google_discount = 0;
10088                 bbr->r_use_policer = 0;
10089         }
10090         if (bbr_ts_limiting)
10091                 bbr->rc_use_ts_limit = 1;
10092         else
10093                 bbr->rc_use_ts_limit = 0;
10094         if (bbr_ts_can_raise)
10095                 bbr->ts_can_raise = 1;
10096         else
10097                 bbr->ts_can_raise = 0;
10098         if (V_tcp_delack_enabled == 1)
10099                 tp->t_delayed_ack = 2;
10100         else if (V_tcp_delack_enabled == 0)
10101                 tp->t_delayed_ack = 0;
10102         else if (V_tcp_delack_enabled < 100)
10103                 tp->t_delayed_ack = V_tcp_delack_enabled;
10104         else
10105                 tp->t_delayed_ack = 2;
10106         if (bbr->rc_use_google == 0)
10107                 bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10108         else
10109                 bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10110         bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10111         bbr->rc_max_rto_sec = bbr_rto_max_sec;
10112         bbr->rc_init_win = bbr_def_init_win;
10113         if (tp->t_flags & TF_REQ_TSTMP)
10114                 bbr->rc_last_options = TCP_TS_OVERHEAD;
10115         bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10116         bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10117         bbr->r_init_rtt = 1;
10118
10119         counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10120         if (bbr_allow_hdwr_pacing)
10121                 bbr->bbr_hdw_pace_ena = 1;
10122         else
10123                 bbr->bbr_hdw_pace_ena = 0;
10124         if (bbr_sends_full_iwnd)
10125                 bbr->bbr_init_win_cheat = 1;
10126         else
10127                 bbr->bbr_init_win_cheat = 0;
10128         bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10129         bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10130         bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10131         bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10132         bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10133         bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10134         bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10135         bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10136         bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10137         bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10138         bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10139         bbr->r_ctl.rc_rtt_shrinks = cts;
10140         if (bbr->rc_use_google) {
10141                 setup_time_filter(&bbr->r_ctl.rc_delrate,
10142                                   FILTER_TYPE_MAX,
10143                                   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10144                 setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10145                                         FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10146         } else {
10147                 setup_time_filter(&bbr->r_ctl.rc_delrate,
10148                                   FILTER_TYPE_MAX,
10149                                   bbr_num_pktepo_for_del_limit);
10150                 setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10151                                         FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10152         }
10153         bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10154         if (bbr_uses_idle_restart)
10155                 bbr->rc_use_idle_restart = 1;
10156         else
10157                 bbr->rc_use_idle_restart = 0;
10158         bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10159         bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10160         if (bbr_resends_use_tso)
10161                 bbr->rc_resends_use_tso = 1;
10162 #ifdef NETFLIX_PEAKRATE
10163         tp->t_peakrate_thr = tp->t_maxpeakrate;
10164 #endif
10165         if (tp->snd_una != tp->snd_max) {
10166                 /* Create a send map for the current outstanding data */
10167                 struct bbr_sendmap *rsm;
10168
10169                 rsm = bbr_alloc(bbr);
10170                 if (rsm == NULL) {
10171                         uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10172                         tp->t_fb_ptr = NULL;
10173                         return (ENOMEM);
10174                 }
10175                 rsm->r_rtt_not_allowed = 1;
10176                 rsm->r_tim_lastsent[0] = cts;
10177                 rsm->r_rtr_cnt = 1;
10178                 rsm->r_rtr_bytes = 0;
10179                 rsm->r_start = tp->snd_una;
10180                 rsm->r_end = tp->snd_max;
10181                 rsm->r_dupack = 0;
10182                 rsm->r_delivered = bbr->r_ctl.rc_delivered;
10183                 rsm->r_ts_valid = 0;
10184                 rsm->r_del_ack_ts = tp->ts_recent;
10185                 rsm->r_del_time = cts;
10186                 if (bbr->r_ctl.r_app_limited_until)
10187                         rsm->r_app_limited = 1;
10188                 else
10189                         rsm->r_app_limited = 0;
10190                 TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10191                 TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10192                 rsm->r_in_tmap = 1;
10193                 if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10194                         rsm->r_bbr_state = bbr_state_val(bbr);
10195                 else
10196                         rsm->r_bbr_state = 8;
10197         }
10198         if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10199                 bbr->bbr_use_rack_cheat = 1;
10200         if (bbr_incr_timers && (bbr->rc_use_google == 0))
10201                 bbr->r_ctl.rc_incr_tmrs = 1;
10202         if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10203                 bbr->r_ctl.rc_inc_tcp_oh = 1;
10204         if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10205                 bbr->r_ctl.rc_inc_ip_oh = 1;
10206         if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10207                 bbr->r_ctl.rc_inc_enet_oh = 1;
10208
10209         bbr_log_type_statechange(bbr, cts, __LINE__);
10210         if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10211             (tp->t_srtt)) {
10212                 uint32_t rtt;
10213
10214                 rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10215                 apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10216         }
10217         /* announce the settings and state */
10218         bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10219         tcp_bbr_tso_size_check(bbr, cts);
10220         /*
10221          * Now call the generic function to start a timer. This will place
10222          * the TCB on the hptsi wheel if a timer is needed with appropriate
10223          * flags.
10224          */
10225         bbr_stop_all_timers(tp);
10226         bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10227         return (0);
10228 }
10229
10230 /*
10231  * Return 0 if we can accept the connection. Return
10232  * non-zero if we can't handle the connection. A EAGAIN
10233  * means you need to wait until the connection is up.
10234  * a EADDRNOTAVAIL means we can never handle the connection
10235  * (no SACK).
10236  */
10237 static int
10238 bbr_handoff_ok(struct tcpcb *tp)
10239 {
10240         if ((tp->t_state == TCPS_CLOSED) ||
10241             (tp->t_state == TCPS_LISTEN)) {
10242                 /* Sure no problem though it may not stick */
10243                 return (0);
10244         }
10245         if ((tp->t_state == TCPS_SYN_SENT) ||
10246             (tp->t_state == TCPS_SYN_RECEIVED)) {
10247                 /*
10248                  * We really don't know you have to get to ESTAB or beyond
10249                  * to tell.
10250                  */
10251                 return (EAGAIN);
10252         }
10253         if (tp->t_flags & TF_SENTFIN)
10254                 return (EINVAL);
10255         if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10256                 return (0);
10257         }
10258         /*
10259          * If we reach here we don't do SACK on this connection so we can
10260          * never do rack.
10261          */
10262         return (EINVAL);
10263 }
10264
10265 static void
10266 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10267 {
10268         if (tp->t_fb_ptr) {
10269                 uint32_t calc;
10270                 struct tcp_bbr *bbr;
10271                 struct bbr_sendmap *rsm;
10272
10273                 bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10274                 if (bbr->r_ctl.crte)
10275                         tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10276                 bbr_log_flowend(bbr);
10277                 bbr->rc_tp = NULL;
10278                 if (tp->t_inpcb) {
10279                         /* Backout any flags2 we applied */
10280                         tp->t_inpcb->inp_flags2 &= ~INP_CANNOT_DO_ECN;
10281                         tp->t_inpcb->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
10282                         tp->t_inpcb->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
10283                 }
10284                 if (bbr->bbr_hdrw_pacing)
10285                         counter_u64_add(bbr_flows_whdwr_pacing, -1);
10286                 else
10287                         counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10288                 if (bbr->r_ctl.crte != NULL) {
10289                         tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
10290                         bbr->r_ctl.crte = NULL;
10291                 }
10292                 rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10293                 while (rsm) {
10294                         TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10295                         uma_zfree(bbr_zone, rsm);
10296                         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10297                 }
10298                 rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10299                 while (rsm) {
10300                         TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10301                         uma_zfree(bbr_zone, rsm);
10302                         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10303                 }
10304                 calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10305                 if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10306                         BBR_STAT_INC(bbr_dynamic_rwnd);
10307                 else
10308                         BBR_STAT_INC(bbr_static_rwnd);
10309                 bbr->r_ctl.rc_free_cnt = 0;
10310                 uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10311                 tp->t_fb_ptr = NULL;
10312         }
10313         /* Make sure snd_nxt is correctly set */
10314         tp->snd_nxt = tp->snd_max;
10315 }
10316
10317 static void
10318 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10319 {
10320         switch (tp->t_state) {
10321         case TCPS_SYN_SENT:
10322                 bbr->r_state = TCPS_SYN_SENT;
10323                 bbr->r_substate = bbr_do_syn_sent;
10324                 break;
10325         case TCPS_SYN_RECEIVED:
10326                 bbr->r_state = TCPS_SYN_RECEIVED;
10327                 bbr->r_substate = bbr_do_syn_recv;
10328                 break;
10329         case TCPS_ESTABLISHED:
10330                 bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10331                 bbr->r_state = TCPS_ESTABLISHED;
10332                 bbr->r_substate = bbr_do_established;
10333                 break;
10334         case TCPS_CLOSE_WAIT:
10335                 bbr->r_state = TCPS_CLOSE_WAIT;
10336                 bbr->r_substate = bbr_do_close_wait;
10337                 break;
10338         case TCPS_FIN_WAIT_1:
10339                 bbr->r_state = TCPS_FIN_WAIT_1;
10340                 bbr->r_substate = bbr_do_fin_wait_1;
10341                 break;
10342         case TCPS_CLOSING:
10343                 bbr->r_state = TCPS_CLOSING;
10344                 bbr->r_substate = bbr_do_closing;
10345                 break;
10346         case TCPS_LAST_ACK:
10347                 bbr->r_state = TCPS_LAST_ACK;
10348                 bbr->r_substate = bbr_do_lastack;
10349                 break;
10350         case TCPS_FIN_WAIT_2:
10351                 bbr->r_state = TCPS_FIN_WAIT_2;
10352                 bbr->r_substate = bbr_do_fin_wait_2;
10353                 break;
10354         case TCPS_LISTEN:
10355         case TCPS_CLOSED:
10356         case TCPS_TIME_WAIT:
10357         default:
10358                 break;
10359         };
10360 }
10361
10362 static void
10363 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10364 {
10365         /*
10366          * Now what state are we going into now? Is there adjustments
10367          * needed?
10368          */
10369         int32_t old_state, old_gain;
10370
10371         old_state = bbr_state_val(bbr);
10372         old_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
10373         if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10374                 /* Save the lowest srtt we saw in our end of the sub-state */
10375                 bbr->rc_hit_state_1 = 0;
10376                 if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10377                         bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10378         }
10379         bbr->rc_bbr_substate++;
10380         if (bbr->rc_bbr_substate >= BBR_SUBSTATE_COUNT) {
10381                 /* Cycle back to first state-> gain */
10382                 bbr->rc_bbr_substate = 0;
10383         }
10384         if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10385                 /*
10386                  * We enter the gain(5/4) cycle (possibly less if
10387                  * shallow buffer detection is enabled)
10388                  */
10389                 if (bbr->skip_gain) {
10390                         /*
10391                          * Hardware pacing has set our rate to
10392                          * the max and limited our b/w just
10393                          * do level i.e. no gain.
10394                          */
10395                         bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10396                 } else if (bbr->gain_is_limited &&
10397                            bbr->bbr_hdrw_pacing &&
10398                            bbr->r_ctl.crte) {
10399                         /*
10400                          * We can't gain above the hardware pacing
10401                          * rate which is less than our rate + the gain
10402                          * calculate the gain needed to reach the hardware
10403                          * pacing rate..
10404                          */
10405                         uint64_t bw, rate, gain_calc;
10406
10407                         bw = bbr_get_bw(bbr);
10408                         rate = bbr->r_ctl.crte->rate;
10409                         if ((rate > bw) &&
10410                             (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10411                                 gain_calc = (rate * BBR_UNIT) / bw;
10412                                 if (gain_calc < BBR_UNIT)
10413                                         gain_calc = BBR_UNIT;
10414                                 bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10415                         } else {
10416                                 bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10417                         }
10418                 } else
10419                         bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10420                 if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10421                         bbr->r_ctl.rc_bbr_state_atflight = cts;
10422                 } else
10423                         bbr->r_ctl.rc_bbr_state_atflight = 0;
10424         } else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10425                 bbr->rc_hit_state_1 = 1;
10426                 bbr->r_ctl.rc_exta_time_gd = 0;
10427                 bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10428                                                      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10429                 if (bbr_state_drain_2_tar) {
10430                         bbr->r_ctl.rc_bbr_state_atflight = 0;
10431                 } else
10432                         bbr->r_ctl.rc_bbr_state_atflight = cts;
10433                 bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10434         } else {
10435                 /* All other cycles hit here 2-7 */
10436                 if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10437                         if (bbr_sub_drain_slam_cwnd &&
10438                             (bbr->rc_use_google == 0) &&
10439                             (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10440                                 bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10441                                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10442                         }
10443                         if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10444                                 bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10445                                                                bbr_get_rtt(bbr, BBR_RTT_PROP));
10446                         else
10447                                 bbr->r_ctl.rc_exta_time_gd = 0;
10448                         if (bbr->r_ctl.rc_exta_time_gd) {
10449                                 bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10450                                 /* Now chop up the time for each state (div by 7) */
10451                                 bbr->r_ctl.rc_level_state_extra /= 7;
10452                                 if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10453                                         /* Add a randomization */
10454                                         bbr_randomize_extra_state_time(bbr);
10455                                 }
10456                         }
10457                 }
10458                 bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10459                 bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10460         }
10461         if (bbr->rc_use_google) {
10462                 bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10463         }
10464         bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10465         bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10466         if (dolog)
10467                 bbr_log_type_statechange(bbr, cts, line);
10468
10469         if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10470                 uint32_t time_in;
10471
10472                 time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10473                 if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10474                         counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10475                 } else {
10476                         counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10477                 }
10478         }
10479         bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10480         bbr_set_state_target(bbr, __LINE__);
10481         if (bbr_sub_drain_slam_cwnd &&
10482             (bbr->rc_use_google == 0) &&
10483             (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10484                 /* Slam down the cwnd */
10485                 bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10486                 bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10487                 if (bbr_sub_drain_app_limit) {
10488                         /* Go app limited if we are on a long drain */
10489                         bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10490                                                           ctf_flight_size(bbr->rc_tp,
10491                                                               (bbr->r_ctl.rc_sacked +
10492                                                                bbr->r_ctl.rc_lost_bytes)));
10493                 }
10494                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10495         }
10496         if (bbr->rc_lt_use_bw) {
10497                 /* In policed mode we clamp pacing_gain to BBR_UNIT */
10498                 bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10499         }
10500         /* Google changes TSO size every cycle */
10501         if (bbr->rc_use_google)
10502                 tcp_bbr_tso_size_check(bbr, cts);
10503         bbr->r_ctl.gain_epoch = cts;
10504         bbr->r_ctl.rc_bbr_state_time = cts;
10505         bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10506 }
10507
10508 static void
10509 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10510 {
10511         if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10512             (google_allow_early_out == 1) &&
10513             (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10514                 /* We have reached out target flight size possibly early */
10515                 goto change_state;
10516         }
10517         if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10518                 return;
10519         }
10520         if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10521                 /*
10522                  * Must be a rttProp movement forward before
10523                  * we can change states.
10524                  */
10525                 return;
10526         }
10527         if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10528                 /*
10529                  * The needed time has passed but for
10530                  * the gain cycle extra rules apply:
10531                  * 1) If we have seen loss, we exit
10532                  * 2) If we have not reached the target
10533                  *    we stay in GAIN (gain-to-target).
10534                  */
10535                 if (google_consider_lost && losses)
10536                         goto change_state;
10537                 if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10538                         return;
10539                 }
10540         }
10541 change_state:
10542         /* For gain we must reach our target, all others last 1 rttProp */
10543         bbr_substate_change(bbr, cts, __LINE__, 1);
10544 }
10545
10546 static void
10547 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10548 {
10549         uint32_t flight, bbr_cur_cycle_time;
10550
10551         if (bbr->rc_use_google) {
10552                 bbr_set_probebw_google_gains(bbr, cts, losses);
10553                 return;
10554         }
10555         if (cts == 0) {
10556                 /*
10557                  * Never alow cts to be 0 we
10558                  * do this so we can judge if
10559                  * we have set a timestamp.
10560                  */
10561                 cts = 1;
10562         }
10563         if (bbr_state_is_pkt_epoch)
10564                 bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10565         else
10566                 bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10567
10568         if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10569                 if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10570                         flight = ctf_flight_size(bbr->rc_tp,
10571                                      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10572                         if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10573                                 /* Keep it slam down */
10574                                 if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10575                                         bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10576                                         bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10577                                 }
10578                                 if (bbr_sub_drain_app_limit) {
10579                                         /* Go app limited if we are on a long drain */
10580                                         bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10581                                 }
10582                         }
10583                         if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10584                             (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10585                              (flight >= bbr->r_ctl.flightsize_at_drain))) {
10586                                 /*
10587                                  * Still here after the same time as
10588                                  * the gain. We need to drain harder
10589                                  * for the next srtt. Reduce by a set amount
10590                                  * the gain drop is capped at DRAIN states
10591                                  * value (88).
10592                                  */
10593                                 bbr->r_ctl.flightsize_at_drain = flight;
10594                                 if (bbr_drain_drop_mul &&
10595                                     bbr_drain_drop_div &&
10596                                     (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10597                                         /* Use your specific drop value (def 4/5 = 20%) */
10598                                         bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10599                                         bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10600                                 } else {
10601                                         /* You get drop of 20% */
10602                                         bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10603                                         bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10604                                 }
10605                                 if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10606                                         /* Reduce our gain again to the bottom  */
10607                                         bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10608                                 }
10609                                 bbr_log_exit_gain(bbr, cts, 4);
10610                                 /*
10611                                  * Extend out so we wait another
10612                                  * epoch before dropping again.
10613                                  */
10614                                 bbr->r_ctl.gain_epoch = cts;
10615                         }
10616                         if (flight <= bbr->r_ctl.rc_target_at_state) {
10617                                 if (bbr_sub_drain_slam_cwnd &&
10618                                     (bbr->rc_use_google == 0) &&
10619                                     (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10620                                         bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10621                                         bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10622                                 }
10623                                 bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10624                                 bbr_log_exit_gain(bbr, cts, 3);
10625                         }
10626                 } else {
10627                         /* Its a gain  */
10628                         if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10629                                 bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10630                                 goto change_state;
10631                         }
10632                         if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10633                             ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10634                              bbr->rc_tp->snd_wnd)) {
10635                                 bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10636                                 bbr_log_exit_gain(bbr, cts, 2);
10637                         }
10638                 }
10639                 /**
10640                  * We fall through and return always one of two things has
10641                  * occurred.
10642                  * 1) We are still not at target
10643                  *    <or>
10644                  * 2) We reached the target and set rc_bbr_state_atflight
10645                  *    which means we no longer hit this block
10646                  *    next time we are called.
10647                  */
10648                 return;
10649         }
10650 change_state:
10651         if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10652                 return;
10653         if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10654                 /* Less than a full time-period has passed */
10655                 return;
10656         }
10657         if (bbr->r_ctl.rc_level_state_extra &&
10658             (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10659             ((cts - bbr->r_ctl.rc_bbr_state_time) <
10660              (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10661                 /* Less than a full time-period + extra has passed */
10662                 return;
10663         }
10664         if (bbr_gain_gets_extra_too &&
10665             bbr->r_ctl.rc_level_state_extra &&
10666             (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10667             ((cts - bbr->r_ctl.rc_bbr_state_time) <
10668              (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10669                 /* Less than a full time-period + extra has passed */
10670                 return;
10671         }
10672         bbr_substate_change(bbr, cts, __LINE__, 1);
10673 }
10674
10675 static uint32_t
10676 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10677 {
10678         uint32_t mss, tar;
10679
10680         if (bbr->rc_use_google) {
10681                 /* Google just uses the cwnd target */
10682                 tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10683         } else {
10684                 mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10685                           bbr->r_ctl.rc_pace_max_segs);
10686                 /* Get the base cwnd with gain rounded to a mss */
10687                 tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10688                                                       gain), mss);
10689                 /* Make sure it is within our min */
10690                 if (tar < get_min_cwnd(bbr))
10691                         return (get_min_cwnd(bbr));
10692         }
10693         return (tar);
10694 }
10695
10696 static void
10697 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10698 {
10699         uint32_t tar, meth;
10700
10701         if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10702             ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10703                 /* Special case using old probe-rtt method */
10704                 tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10705                 meth = 1;
10706         } else {
10707                 /* Non-probe-rtt case and reduced probe-rtt  */
10708                 if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10709                     (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10710                         /* For gain cycle we use the hptsi gain */
10711                         tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10712                         meth = 2;
10713                 } else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10714                         /*
10715                          * If configured, or for google all other states
10716                          * get BBR_UNIT.
10717                          */
10718                         tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10719                         meth = 3;
10720                 } else {
10721                         /*
10722                          * Or we set a target based on the pacing gain
10723                          * for non-google mode and default (non-configured).
10724                          * Note we don't set a target goal below drain (192).
10725                          */
10726                         if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10727                                 tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10728                                 meth = 4;
10729                         } else {
10730                                 tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10731                                 meth = 5;
10732                         }
10733                 }
10734         }
10735         bbr_log_set_of_state_target(bbr, tar, line, meth);
10736         bbr->r_ctl.rc_target_at_state = tar;
10737 }
10738
10739 static void
10740 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10741 {
10742         /* Change to probe_rtt */
10743         uint32_t time_in;
10744
10745         bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10746         bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10747                                              (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10748         bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10749                                           + bbr->r_ctl.rc_delivered);
10750         /* Setup so we force feed the filter */
10751         if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10752                 bbr->rc_prtt_set_ts = 1;
10753         if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10754                 time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10755                 counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10756         }
10757         bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10758         bbr->r_ctl.rc_rtt_shrinks = cts;
10759         bbr->r_ctl.last_in_probertt = cts;
10760         bbr->r_ctl.rc_probertt_srttchktim = cts;
10761         bbr->r_ctl.rc_bbr_state_time = cts;
10762         bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10763         /* We need to force the filter to update */
10764
10765         if ((bbr_sub_drain_slam_cwnd) &&
10766             bbr->rc_hit_state_1 &&
10767             (bbr->rc_use_google == 0) &&
10768             (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10769                 if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10770                         bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10771         } else
10772                 bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10773         /* Update the lost */
10774         bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10775         if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10776                 /* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10777                 bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10778                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10779                 bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10780                 bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10781                 bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10782                 bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10783         } else {
10784                 /*
10785                  * We bring it down slowly by using a hptsi gain that is
10786                  * probably 75%. This will slowly float down our outstanding
10787                  * without tampering with the cwnd.
10788                  */
10789                 bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10790                 bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10791                 bbr_set_state_target(bbr, __LINE__);
10792                 if (bbr_prtt_slam_cwnd &&
10793                     (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10794                         bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10795                         bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10796                 }
10797         }
10798         if (ctf_flight_size(bbr->rc_tp,
10799                 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10800             bbr->r_ctl.rc_target_at_state) {
10801                 /* We are at target */
10802                 bbr->r_ctl.rc_bbr_enters_probertt = cts;
10803         } else {
10804                 /* We need to come down to reach target before our time begins */
10805                 bbr->r_ctl.rc_bbr_enters_probertt = 0;
10806         }
10807         bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10808         BBR_STAT_INC(bbr_enter_probertt);
10809         bbr_log_exit_gain(bbr, cts, 0);
10810         bbr_log_type_statechange(bbr, cts, line);
10811 }
10812
10813 static void
10814 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10815 {
10816         /*
10817          * Sanity check on probe-rtt intervals.
10818          * In crazy situations where we are competing
10819          * against new-reno flows with huge buffers
10820          * our rtt-prop interval could come to dominate
10821          * things if we can't get through a full set
10822          * of cycles, we need to adjust it.
10823          */
10824         if (bbr_can_adjust_probertt &&
10825             (bbr->rc_use_google == 0)) {
10826                 uint16_t val = 0;
10827                 uint32_t cur_rttp, fval, newval, baseval;
10828
10829                 /* Are we to small and go into probe-rtt to often? */
10830                 baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10831                 cur_rttp = roundup(baseval, USECS_IN_SECOND);
10832                 fval = bbr_filter_len_sec * USECS_IN_SECOND;
10833                 if (bbr_is_ratio == 0) {
10834                         if (fval > bbr_rtt_probe_limit)
10835                                 newval = cur_rttp + (fval - bbr_rtt_probe_limit);
10836                         else
10837                                 newval = cur_rttp;
10838                 } else {
10839                         int mul;
10840
10841                         mul = fval / bbr_rtt_probe_limit;
10842                         newval = cur_rttp * mul;
10843                 }
10844                 if (cur_rttp >  bbr->r_ctl.rc_probertt_int) {
10845                         bbr->r_ctl.rc_probertt_int = cur_rttp;
10846                         reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10847                         val = 1;
10848                 } else {
10849                         /*
10850                          * No adjustments were made
10851                          * do we need to shrink it?
10852                          */
10853                         if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
10854                                 if (cur_rttp <= bbr_rtt_probe_limit) {
10855                                         /*
10856                                          * Things have calmed down lets
10857                                          * shrink all the way to default
10858                                          */
10859                                         bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10860                                         reset_time_small(&bbr->r_ctl.rc_rttprop,
10861                                                          (bbr_filter_len_sec * USECS_IN_SECOND));
10862                                         cur_rttp = bbr_rtt_probe_limit;
10863                                         newval = (bbr_filter_len_sec * USECS_IN_SECOND);
10864                                         val = 2;
10865                                 } else {
10866                                         /*
10867                                          * Well does some adjustment make sense?
10868                                          */
10869                                         if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
10870                                                 /* We can reduce interval time some */
10871                                                 bbr->r_ctl.rc_probertt_int = cur_rttp;
10872                                                 reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10873                                                 val = 3;
10874                                         }
10875                                 }
10876                         }
10877                 }
10878                 if (val)
10879                         bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
10880         }
10881 }
10882
10883 static void
10884 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
10885 {
10886         /* Exit probe-rtt */
10887
10888         if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
10889                 tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10890                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10891         }
10892         bbr_log_exit_gain(bbr, cts, 1);
10893         bbr->rc_hit_state_1 = 0;
10894         bbr->r_ctl.rc_rtt_shrinks = cts;
10895         bbr->r_ctl.last_in_probertt = cts;
10896         bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
10897         bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10898         bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
10899                                               (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
10900                                           bbr->r_ctl.rc_delivered);
10901         if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10902                 uint32_t time_in;
10903
10904                 time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10905                 counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10906         }
10907         if (bbr->rc_filled_pipe) {
10908                 /* Switch to probe_bw */
10909                 bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
10910                 bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
10911                 bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10912                 bbr_substate_change(bbr, cts, __LINE__, 0);
10913                 bbr_log_type_statechange(bbr, cts, __LINE__);
10914         } else {
10915                 /* Back to startup */
10916                 bbr->rc_bbr_state = BBR_STATE_STARTUP;
10917                 bbr->r_ctl.rc_bbr_state_time = cts;
10918                 /*
10919                  * We don't want to give a complete free 3
10920                  * measurements until we exit, so we use
10921                  * the number of pe's we were in probe-rtt
10922                  * to add to the startup_epoch. That way
10923                  * we will still retain the old state.
10924                  */
10925                 bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
10926                 bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10927                 /* Make sure to use the lower pg when shifting back in */
10928                 if (bbr->r_ctl.rc_lost &&
10929                     bbr_use_lower_gain_in_startup &&
10930                     (bbr->rc_use_google == 0))
10931                         bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10932                 else
10933                         bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
10934                 bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
10935                 /* Probably not needed but set it anyway */
10936                 bbr_set_state_target(bbr, __LINE__);
10937                 bbr_log_type_statechange(bbr, cts, __LINE__);
10938                 bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10939                     bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 0);
10940         }
10941         bbr_check_probe_rtt_limits(bbr, cts);
10942 }
10943
10944 static int32_t inline
10945 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
10946 {
10947         if ((bbr->rc_past_init_win == 1) &&
10948             (bbr->rc_in_persist == 0) &&
10949             (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
10950                 return (1);
10951         }
10952         if (bbr_can_force_probertt &&
10953             (bbr->rc_in_persist == 0) &&
10954             (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
10955             ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
10956                 return (1);
10957         }
10958         return (0);
10959 }
10960
10961 static int32_t
10962 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
10963 {
10964         uint64_t btlbw, gain;
10965         if (pkt_epoch == 0) {
10966                 /*
10967                  * Need to be on a pkt-epoch to continue.
10968                  */
10969                 return (0);
10970         }
10971         btlbw = bbr_get_full_bw(bbr);
10972         gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10973                  (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10974         if (btlbw >= gain) {
10975                 bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10976                 bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10977                                       bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10978                 bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10979         }
10980         if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
10981                 return (1);
10982         bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10983                               bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
10984         return(0);
10985 }
10986
10987 static int32_t inline
10988 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
10989 {
10990         /* Have we gained 25% in the last 3 packet based epoch's? */
10991         uint64_t btlbw, gain;
10992         int do_exit;
10993         int delta, rtt_gain;
10994
10995         if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
10996             (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
10997                 /*
10998                  * This qualifies as a RTT_PROBE session since we drop the
10999                  * data outstanding to nothing and waited more than
11000                  * bbr_rtt_probe_time.
11001                  */
11002                 bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11003                 bbr_set_reduced_rtt(bbr, cts, __LINE__);
11004         }
11005         if (bbr_should_enter_probe_rtt(bbr, cts)) {
11006                 bbr_enter_probe_rtt(bbr, cts, __LINE__);
11007                 return (0);
11008         }
11009         if (bbr->rc_use_google)
11010                 return (bbr_google_startup(bbr, cts,  pkt_epoch));
11011
11012         if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11013             (bbr_use_lower_gain_in_startup)) {
11014                 /* Drop to a lower gain 1.5 x since we saw loss */
11015                 bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
11016         }
11017         if (pkt_epoch == 0) {
11018                 /*
11019                  * Need to be on a pkt-epoch to continue.
11020                  */
11021                 return (0);
11022         }
11023         if (bbr_rtt_gain_thresh) {
11024                 /*
11025                  * Do we allow a flow to stay
11026                  * in startup with no loss and no
11027                  * gain in rtt over a set threshold?
11028                  */
11029                 if (bbr->r_ctl.rc_pkt_epoch_rtt &&
11030                     bbr->r_ctl.startup_last_srtt &&
11031                     (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
11032                         delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
11033                         rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
11034                 } else
11035                         rtt_gain = 0;
11036                 if ((bbr->r_ctl.startup_last_srtt == 0)  ||
11037                     (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
11038                         /* First time or new lower value */
11039                         bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
11040
11041                 if ((bbr->r_ctl.rc_lost == 0) &&
11042                     (rtt_gain < bbr_rtt_gain_thresh)) {
11043                         /*
11044                          * No loss, and we are under
11045                          * our gain threhold for
11046                          * increasing RTT.
11047                          */
11048                         if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11049                                 bbr->r_ctl.rc_bbr_last_startup_epoch++;
11050                         bbr_log_startup_event(bbr, cts, rtt_gain,
11051                                               delta, bbr->r_ctl.startup_last_srtt, 10);
11052                         return (0);
11053                 }
11054         }
11055         if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
11056             (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
11057             (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
11058                 /*
11059                  * We only assess if we have a new measurment when
11060                  * we have no loss and are not in recovery.
11061                  * Drag up by one our last_startup epoch so we will hold
11062                  * the number of non-gain we have already accumulated.
11063                  */
11064                 if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11065                         bbr->r_ctl.rc_bbr_last_startup_epoch++;
11066                 bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11067                                       bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 9);
11068                 return (0);
11069         }
11070         /* Case where we reduced the lost (bad retransmit) */
11071         if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
11072                 bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11073         bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
11074         btlbw = bbr_get_full_bw(bbr);
11075         if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
11076                 gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11077                          (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11078         else
11079                 gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11080                          (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11081         do_exit = 0;
11082         if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
11083                 bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
11084         if (btlbw >= gain) {
11085                 bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
11086                 /* Update the lost so we won't exit in next set of tests */
11087                 bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11088                 bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11089                                       bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
11090         }
11091         if ((bbr->rc_loss_exit &&
11092              (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11093              (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
11094             ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
11095                 /*
11096                  * If we had no gain,  we had loss and that loss was above
11097                  * our threshould, the rwnd is not constrained, and we have
11098                  * had at least 3 packet epochs exit. Note that this is
11099                  * switched off by sysctl. Google does not do this by the
11100                  * way.
11101                  */
11102                 if ((ctf_flight_size(bbr->rc_tp,
11103                          (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11104                      (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11105                         do_exit = 1;
11106                         bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11107                                               bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11108                 } else {
11109                         /* Just record an updated loss value */
11110                         bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11111                         bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11112                                               bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11113                 }
11114         } else
11115                 bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11116         if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11117             do_exit) {
11118                 /* Return 1 to exit the startup state. */
11119                 return (1);
11120         }
11121         /* Stay in startup */
11122         bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11123                               bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11124         return (0);
11125 }
11126
11127 static void
11128 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11129 {
11130         /*
11131          * A tick occurred in the rtt epoch do we need to do anything?
11132          */
11133 #ifdef BBR_INVARIANTS
11134         if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11135             (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11136             (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11137             (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11138             (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11139                 /* Debug code? */
11140                 panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11141         }
11142 #endif
11143         if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11144                 /* Do we exit the startup state? */
11145                 if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11146                         uint32_t time_in;
11147
11148                         bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11149                                               bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11150                         bbr->rc_filled_pipe = 1;
11151                         bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11152                         if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11153                                 time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11154                                 counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11155                         } else
11156                                 time_in = 0;
11157                         if (bbr->rc_no_pacing)
11158                                 bbr->rc_no_pacing = 0;
11159                         bbr->r_ctl.rc_bbr_state_time = cts;
11160                         bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11161                         bbr->rc_bbr_state = BBR_STATE_DRAIN;
11162                         bbr_set_state_target(bbr, __LINE__);
11163                         if ((bbr->rc_use_google == 0) &&
11164                             bbr_slam_cwnd_in_main_drain) {
11165                                 /* Here we don't have to worry about probe-rtt */
11166                                 bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
11167                                 bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11168                                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11169                         }
11170                         bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11171                         bbr_log_type_statechange(bbr, cts, __LINE__);
11172                         if (ctf_flight_size(bbr->rc_tp,
11173                                 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11174                             bbr->r_ctl.rc_target_at_state) {
11175                                 /*
11176                                  * Switch to probe_bw if we are already
11177                                  * there
11178                                  */
11179                                 bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11180                                 bbr_substate_change(bbr, cts, __LINE__, 0);
11181                                 bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11182                                 bbr_log_type_statechange(bbr, cts, __LINE__);
11183                         }
11184                 }
11185         } else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11186                 uint32_t inflight;
11187                 struct tcpcb *tp;
11188
11189                 tp = bbr->rc_tp;
11190                 inflight = ctf_flight_size(tp,
11191                               (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11192                 if (inflight >= bbr->r_ctl.rc_target_at_state) {
11193                         /* We have reached a flight of the cwnd target */
11194                         bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11195                         bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11196                         bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11197                         bbr_set_state_target(bbr, __LINE__);
11198                         /*
11199                          * Rig it so we don't do anything crazy and
11200                          * start fresh with a new randomization.
11201                          */
11202                         bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11203                         bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11204                         bbr_substate_change(bbr, cts, __LINE__, 1);
11205                 }
11206         } else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11207                 /* Has in-flight reached the bdp (or less)? */
11208                 uint32_t inflight;
11209                 struct tcpcb *tp;
11210
11211                 tp = bbr->rc_tp;
11212                 inflight = ctf_flight_size(tp,
11213                               (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11214                 if ((bbr->rc_use_google == 0) &&
11215                     bbr_slam_cwnd_in_main_drain &&
11216                     (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11217                         /*
11218                          * Here we don't have to worry about probe-rtt
11219                          * re-slam it, but keep it slammed down.
11220                          */
11221                         bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11222                         bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11223                 }
11224                 if (inflight <= bbr->r_ctl.rc_target_at_state) {
11225                         /* We have drained */
11226                         bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11227                         bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11228                         if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11229                                 uint32_t time_in;
11230
11231                                 time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11232                                 counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11233                         }
11234                         if ((bbr->rc_use_google == 0) &&
11235                             bbr_slam_cwnd_in_main_drain &&
11236                             (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11237                                 /* Restore the cwnd */
11238                                 tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11239                                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11240                         }
11241                         /* Setup probe-rtt has being done now RRS-HERE */
11242                         bbr->r_ctl.rc_rtt_shrinks = cts;
11243                         bbr->r_ctl.last_in_probertt = cts;
11244                         bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11245                         /* Randomly pick a sub-state */
11246                         bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11247                         bbr_substate_change(bbr, cts, __LINE__, 0);
11248                         bbr_log_type_statechange(bbr, cts, __LINE__);
11249                 }
11250         } else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11251                 uint32_t flight;
11252
11253                 flight = ctf_flight_size(bbr->rc_tp,
11254                              (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11255                 bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11256                 if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11257                     (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11258                         /*
11259                          * We must keep cwnd at the desired MSS.
11260                          */
11261                         bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11262                         bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11263                 } else if ((bbr_prtt_slam_cwnd) &&
11264                            (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11265                         /* Re-slam it */
11266                         bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11267                         bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11268                 }
11269                 if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11270                         /* Has outstanding reached our target? */
11271                         if (flight <= bbr->r_ctl.rc_target_at_state) {
11272                                 bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11273                                 bbr->r_ctl.rc_bbr_enters_probertt = cts;
11274                                 /* If time is exactly 0, be 1usec off */
11275                                 if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11276                                         bbr->r_ctl.rc_bbr_enters_probertt = 1;
11277                                 if (bbr->rc_use_google == 0) {
11278                                         /*
11279                                          * Restore any lowering that as occurred to
11280                                          * reach here
11281                                          */
11282                                         if (bbr->r_ctl.bbr_rttprobe_gain_val)
11283                                                 bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11284                                         else
11285                                                 bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11286                                 }
11287                         }
11288                         if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11289                             (bbr->rc_use_google == 0) &&
11290                             bbr->r_ctl.bbr_rttprobe_gain_val &&
11291                             (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11292                              (flight >= bbr->r_ctl.flightsize_at_drain))) {
11293                                 /*
11294                                  * We have doddled with our current hptsi
11295                                  * gain an srtt and have still not made it
11296                                  * to target, or we have increased our flight.
11297                                  * Lets reduce the gain by xx%
11298                                  * flooring the reduce at DRAIN (based on
11299                                  * mul/div)
11300                                  */
11301                                 int red;
11302
11303                                 bbr->r_ctl.flightsize_at_drain = flight;
11304                                 bbr->r_ctl.rc_probertt_srttchktim = cts;
11305                                 red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11306                                 if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11307                                         /* Reduce our gain again */
11308                                         bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11309                                         bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11310                                 } else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11311                                         /* one more chance before we give up */
11312                                         bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11313                                         bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11314                                 } else {
11315                                         /* At the very bottom */
11316                                         bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11317                                 }
11318                         }
11319                 }
11320                 if (bbr->r_ctl.rc_bbr_enters_probertt &&
11321                     (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11322                     ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11323                         /* Time to exit probe RTT normally */
11324                         bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11325                 }
11326         } else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11327                 if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11328                     (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11329                         /*
11330                          * This qualifies as a RTT_PROBE session since we
11331                          * drop the data outstanding to nothing and waited
11332                          * more than bbr_rtt_probe_time.
11333                          */
11334                         bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11335                         bbr_set_reduced_rtt(bbr, cts, __LINE__);
11336                 }
11337                 if (bbr_should_enter_probe_rtt(bbr, cts)) {
11338                         bbr_enter_probe_rtt(bbr, cts, __LINE__);
11339                 } else {
11340                         bbr_set_probebw_gains(bbr, cts, losses);
11341                 }
11342         }
11343 }
11344
11345 static void
11346 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11347 {
11348         int32_t epoch = 0;
11349
11350         if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11351                 bbr_set_epoch(bbr, cts, line);
11352                 /* At each epoch doe lt bw sampling */
11353                 epoch = 1;
11354         }
11355         bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11356 }
11357
11358 static int
11359 bbr_do_segment_nounlock(struct mbuf *m, struct tcphdr *th, struct socket *so,
11360     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos,
11361     int32_t nxt_pkt, struct timeval *tv)
11362 {
11363         int32_t thflags, retval;
11364         uint32_t cts, lcts;
11365         uint32_t tiwin;
11366         struct tcpopt to;
11367         struct tcp_bbr *bbr;
11368         struct bbr_sendmap *rsm;
11369         struct timeval ltv;
11370         int32_t did_out = 0;
11371         int32_t in_recovery;
11372         uint16_t nsegs;
11373         int32_t prev_state;
11374         uint32_t lost;
11375
11376         nsegs = max(1, m->m_pkthdr.lro_nsegs);
11377         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11378         /* add in our stats */
11379         kern_prefetch(bbr, &prev_state);
11380         prev_state = 0;
11381         thflags = th->th_flags;
11382         /*
11383          * If this is either a state-changing packet or current state isn't
11384          * established, we require a write lock on tcbinfo.  Otherwise, we
11385          * allow the tcbinfo to be in either alocked or unlocked, as the
11386          * caller may have unnecessarily acquired a write lock due to a
11387          * race.
11388          */
11389         INP_WLOCK_ASSERT(tp->t_inpcb);
11390         KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11391             __func__));
11392         KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11393             __func__));
11394
11395         tp->t_rcvtime = ticks;
11396         /*
11397          * Unscale the window into a 32-bit value. For the SYN_SENT state
11398          * the scale is zero.
11399          */
11400         tiwin = th->th_win << tp->snd_scale;
11401 #ifdef STATS
11402         stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11403 #endif
11404
11405         if (m->m_flags & M_TSTMP) {
11406                 /* Prefer the hardware timestamp if present */
11407                 struct timespec ts;
11408
11409                 mbuf_tstmp2timespec(m, &ts);
11410                 bbr->rc_tv.tv_sec = ts.tv_sec;
11411                 bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11412                 bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11413         } else if (m->m_flags & M_TSTMP_LRO) {
11414                 /* Next the arrival timestamp */
11415                 struct timespec ts;
11416
11417                 mbuf_tstmp2timespec(m, &ts);
11418                 bbr->rc_tv.tv_sec = ts.tv_sec;
11419                 bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11420                 bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11421         } else {
11422                 /*
11423                  * Ok just get the current time.
11424                  */
11425                 bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11426         }
11427         /*
11428          * Parse options on any incoming segment.
11429          */
11430         tcp_dooptions(&to, (u_char *)(th + 1),
11431             (th->th_off << 2) - sizeof(struct tcphdr),
11432             (thflags & TH_SYN) ? TO_SYN : 0);
11433
11434         /*
11435          * If timestamps were negotiated during SYN/ACK and a
11436          * segment without a timestamp is received, silently drop
11437          * the segment, unless it is a RST segment or missing timestamps are
11438          * tolerated.
11439          * See section 3.2 of RFC 7323.
11440          */
11441         if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
11442             ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
11443                 retval = 0;
11444                 m_freem(m);
11445                 goto done_with_input;
11446         }
11447         /*
11448          * If echoed timestamp is later than the current time, fall back to
11449          * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
11450          * were used when this connection was established.
11451          */
11452         if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
11453                 to.to_tsecr -= tp->ts_offset;
11454                 if (TSTMP_GT(to.to_tsecr, tcp_tv_to_mssectick(&bbr->rc_tv)))
11455                         to.to_tsecr = 0;
11456         }
11457         /*
11458          * If its the first time in we need to take care of options and
11459          * verify we can do SACK for rack!
11460          */
11461         if (bbr->r_state == 0) {
11462                 /*
11463                  * Process options only when we get SYN/ACK back. The SYN
11464                  * case for incoming connections is handled in tcp_syncache.
11465                  * According to RFC1323 the window field in a SYN (i.e., a
11466                  * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
11467                  * this is traditional behavior, may need to be cleaned up.
11468                  */
11469                 if (bbr->rc_inp == NULL) {
11470                         bbr->rc_inp = tp->t_inpcb;
11471                 }
11472                 /*
11473                  * We need to init rc_inp here since its not init'd when
11474                  * bbr_init is called
11475                  */
11476                 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
11477                         if ((to.to_flags & TOF_SCALE) &&
11478                             (tp->t_flags & TF_REQ_SCALE)) {
11479                                 tp->t_flags |= TF_RCVD_SCALE;
11480                                 tp->snd_scale = to.to_wscale;
11481                         } else
11482                                 tp->t_flags &= ~TF_REQ_SCALE;
11483                         /*
11484                          * Initial send window.  It will be updated with the
11485                          * next incoming segment to the scaled value.
11486                          */
11487                         tp->snd_wnd = th->th_win;
11488                         if ((to.to_flags & TOF_TS) &&
11489                             (tp->t_flags & TF_REQ_TSTMP)) {
11490                                 tp->t_flags |= TF_RCVD_TSTMP;
11491                                 tp->ts_recent = to.to_tsval;
11492                                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
11493                         } else
11494                             tp->t_flags &= ~TF_REQ_TSTMP;
11495                         if (to.to_flags & TOF_MSS)
11496                                 tcp_mss(tp, to.to_mss);
11497                         if ((tp->t_flags & TF_SACK_PERMIT) &&
11498                             (to.to_flags & TOF_SACKPERM) == 0)
11499                                 tp->t_flags &= ~TF_SACK_PERMIT;
11500                         if (IS_FASTOPEN(tp->t_flags)) {
11501                                 if (to.to_flags & TOF_FASTOPEN) {
11502                                         uint16_t mss;
11503
11504                                         if (to.to_flags & TOF_MSS)
11505                                                 mss = to.to_mss;
11506                                         else
11507                                                 if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
11508                                                         mss = TCP6_MSS;
11509                                                 else
11510                                                         mss = TCP_MSS;
11511                                         tcp_fastopen_update_cache(tp, mss,
11512                                             to.to_tfo_len, to.to_tfo_cookie);
11513                                 } else
11514                                         tcp_fastopen_disable_path(tp);
11515                         }
11516                 }
11517                 /*
11518                  * At this point we are at the initial call. Here we decide
11519                  * if we are doing RACK or not. We do this by seeing if
11520                  * TF_SACK_PERMIT is set, if not rack is *not* possible and
11521                  * we switch to the default code.
11522                  */
11523                 if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
11524                         /* Bail */
11525                         tcp_switch_back_to_default(tp);
11526                         (*tp->t_fb->tfb_tcp_do_segment) (m, th, so, tp, drop_hdrlen,
11527                             tlen, iptos);
11528                         return (1);
11529                 }
11530                 /* Set the flag */
11531                 bbr->r_is_v6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
11532                 tcp_set_hpts(tp->t_inpcb);
11533                 sack_filter_clear(&bbr->r_ctl.bbr_sf, th->th_ack);
11534         }
11535         if (thflags & TH_ACK) {
11536                 /* Track ack types */
11537                 if (to.to_flags & TOF_SACK)
11538                         BBR_STAT_INC(bbr_acks_with_sacks);
11539                 else
11540                         BBR_STAT_INC(bbr_plain_acks);
11541         }
11542         /*
11543          * This is the one exception case where we set the rack state
11544          * always. All other times (timers etc) we must have a rack-state
11545          * set (so we assure we have done the checks above for SACK).
11546          */
11547         if (thflags & TH_FIN)
11548                 tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
11549         if (bbr->r_state != tp->t_state)
11550                 bbr_set_state(tp, bbr, tiwin);
11551
11552         if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map)) != NULL)
11553                 kern_prefetch(rsm, &prev_state);
11554         prev_state = bbr->r_state;
11555         bbr->rc_ack_was_delayed = 0;
11556         lost = bbr->r_ctl.rc_lost;
11557         bbr->rc_is_pkt_epoch_now = 0;
11558         if (m->m_flags & (M_TSTMP|M_TSTMP_LRO)) {
11559                 /* Get the real time into lcts and figure the real delay */
11560                 lcts = tcp_get_usecs(&ltv);
11561                 if (TSTMP_GT(lcts, cts)) {
11562                         bbr->r_ctl.rc_ack_hdwr_delay = lcts - cts;
11563                         bbr->rc_ack_was_delayed = 1;
11564                         if (TSTMP_GT(bbr->r_ctl.rc_ack_hdwr_delay,
11565                                      bbr->r_ctl.highest_hdwr_delay))
11566                                 bbr->r_ctl.highest_hdwr_delay = bbr->r_ctl.rc_ack_hdwr_delay;
11567                 } else {
11568                         bbr->r_ctl.rc_ack_hdwr_delay = 0;
11569                         bbr->rc_ack_was_delayed = 0;
11570                 }
11571         } else {
11572                 bbr->r_ctl.rc_ack_hdwr_delay = 0;
11573                 bbr->rc_ack_was_delayed = 0;
11574         }
11575         bbr_log_ack_event(bbr, th, &to, tlen, nsegs, cts, nxt_pkt, m);
11576         if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
11577                 retval = 0;
11578                 m_freem(m);
11579                 goto done_with_input;
11580         }
11581         /*
11582          * If a segment with the ACK-bit set arrives in the SYN-SENT state
11583          * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
11584          */
11585         if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
11586             (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
11587                 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11588                 ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11589                 return (1);
11590         }
11591         in_recovery = IN_RECOVERY(tp->t_flags);
11592         if (tiwin > bbr->r_ctl.rc_high_rwnd)
11593                 bbr->r_ctl.rc_high_rwnd = tiwin;
11594 #ifdef BBR_INVARIANTS
11595         if ((tp->t_inpcb->inp_flags & INP_DROPPED) ||
11596             (tp->t_inpcb->inp_flags2 & INP_FREED)) {
11597                 panic("tp:%p bbr:%p given a dropped inp:%p",
11598                     tp, bbr, tp->t_inpcb);
11599         }
11600 #endif
11601         bbr->r_ctl.rc_flight_at_input = ctf_flight_size(tp,
11602                                             (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11603         bbr->rtt_valid = 0;
11604         if (to.to_flags & TOF_TS) {
11605                 bbr->rc_ts_valid = 1;
11606                 bbr->r_ctl.last_inbound_ts = to.to_tsval;
11607         } else {
11608                 bbr->rc_ts_valid = 0;
11609                 bbr->r_ctl.last_inbound_ts = 0;
11610         }
11611         retval = (*bbr->r_substate) (m, th, so,
11612             tp, &to, drop_hdrlen,
11613             tlen, tiwin, thflags, nxt_pkt, iptos);
11614 #ifdef BBR_INVARIANTS
11615         if ((retval == 0) &&
11616             (tp->t_inpcb == NULL)) {
11617                 panic("retval:%d tp:%p t_inpcb:NULL state:%d",
11618                     retval, tp, prev_state);
11619         }
11620 #endif
11621         if (nxt_pkt == 0)
11622                 BBR_STAT_INC(bbr_rlock_left_ret0);
11623         else
11624                 BBR_STAT_INC(bbr_rlock_left_ret1);
11625         if (retval == 0) {
11626                 /*
11627                  * If retval is 1 the tcb is unlocked and most likely the tp
11628                  * is gone.
11629                  */
11630                 INP_WLOCK_ASSERT(tp->t_inpcb);
11631                 tcp_bbr_xmit_timer_commit(bbr, tp, cts);
11632                 if (bbr->rc_is_pkt_epoch_now)
11633                         bbr_set_pktepoch(bbr, cts, __LINE__);
11634                 bbr_check_bbr_for_state(bbr, cts, __LINE__, (bbr->r_ctl.rc_lost - lost));
11635                 if (nxt_pkt == 0) {
11636                         if (bbr->r_wanted_output != 0) {
11637                                 bbr->rc_output_starts_timer = 0;
11638                                 did_out = 1;
11639                                 (void)tp->t_fb->tfb_tcp_output(tp);
11640                         } else
11641                                 bbr_start_hpts_timer(bbr, tp, cts, 6, 0, 0);
11642                 }
11643                 if ((nxt_pkt == 0) &&
11644                     ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
11645                     (SEQ_GT(tp->snd_max, tp->snd_una) ||
11646                      (tp->t_flags & TF_DELACK) ||
11647                      ((V_tcp_always_keepalive || bbr->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
11648                       (tp->t_state <= TCPS_CLOSING)))) {
11649                         /*
11650                          * We could not send (probably in the hpts but
11651                          * stopped the timer)?
11652                          */
11653                         if ((tp->snd_max == tp->snd_una) &&
11654                             ((tp->t_flags & TF_DELACK) == 0) &&
11655                             (bbr->rc_inp->inp_in_hpts) &&
11656                             (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11657                                 /*
11658                                  * keep alive not needed if we are hptsi
11659                                  * output yet
11660                                  */
11661                                 ;
11662                         } else {
11663                                 if (bbr->rc_inp->inp_in_hpts) {
11664                                         tcp_hpts_remove(bbr->rc_inp, HPTS_REMOVE_OUTPUT);
11665                                         if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11666                                             (TSTMP_GT(lcts, bbr->rc_pacer_started))) {
11667                                                 uint32_t del;
11668
11669                                                 del = lcts - bbr->rc_pacer_started;
11670                                                 if (bbr->r_ctl.rc_last_delay_val > del) {
11671                                                         BBR_STAT_INC(bbr_force_timer_start);
11672                                                         bbr->r_ctl.rc_last_delay_val -= del;
11673                                                         bbr->rc_pacer_started = lcts;
11674                                                 } else {
11675                                                         /* We are late */
11676                                                         bbr->r_ctl.rc_last_delay_val = 0;
11677                                                         BBR_STAT_INC(bbr_force_output);
11678                                                         (void)tp->t_fb->tfb_tcp_output(tp);
11679                                                 }
11680                                         }
11681                                 }
11682                                 bbr_start_hpts_timer(bbr, tp, cts, 8, bbr->r_ctl.rc_last_delay_val,
11683                                     0);
11684                         }
11685                 } else if ((bbr->rc_output_starts_timer == 0) && (nxt_pkt == 0)) {
11686                         /* Do we have the correct timer running? */
11687                         bbr_timer_audit(tp, bbr, lcts, &so->so_snd);
11688                 }
11689                 /* Do we have a new state */
11690                 if (bbr->r_state != tp->t_state)
11691                         bbr_set_state(tp, bbr, tiwin);
11692 done_with_input:
11693                 bbr_log_doseg_done(bbr, cts, nxt_pkt, did_out);
11694                 if (did_out)
11695                         bbr->r_wanted_output = 0;
11696 #ifdef BBR_INVARIANTS
11697                 if (tp->t_inpcb == NULL) {
11698                         panic("OP:%d retval:%d tp:%p t_inpcb:NULL state:%d",
11699                             did_out,
11700                             retval, tp, prev_state);
11701                 }
11702 #endif
11703         }
11704         return (retval);
11705 }
11706
11707 static void
11708 bbr_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
11709     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
11710 {
11711         struct timeval tv;
11712         int retval;
11713
11714         /* First lets see if we have old packets */
11715         if (tp->t_in_pkt) {
11716                 if (ctf_do_queued_segments(so, tp, 1)) {
11717                         m_freem(m);
11718                         return;
11719                 }
11720         }
11721         if (m->m_flags & M_TSTMP_LRO) {
11722                 tv.tv_sec = m->m_pkthdr.rcv_tstmp /1000000000;
11723                 tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000)/1000;
11724         } else {
11725                 /* Should not be should we kassert instead? */
11726                 tcp_get_usecs(&tv);
11727         }
11728         retval = bbr_do_segment_nounlock(m, th, so, tp,
11729                                          drop_hdrlen, tlen, iptos, 0, &tv);
11730         if (retval == 0) {
11731                 INP_WUNLOCK(tp->t_inpcb);
11732         }
11733 }
11734
11735 /*
11736  * Return how much data can be sent without violating the
11737  * cwnd or rwnd.
11738  */
11739
11740 static inline uint32_t
11741 bbr_what_can_we_send(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t sendwin,
11742     uint32_t avail, int32_t sb_offset, uint32_t cts)
11743 {
11744         uint32_t len;
11745
11746         if (ctf_outstanding(tp) >= tp->snd_wnd) {
11747                 /* We never want to go over our peers rcv-window */
11748                 len = 0;
11749         } else {
11750                 uint32_t flight;
11751
11752                 flight = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11753                 if (flight >= sendwin) {
11754                         /*
11755                          * We have in flight what we are allowed by cwnd (if
11756                          * it was rwnd blocking it would have hit above out
11757                          * >= tp->snd_wnd).
11758                          */
11759                         return (0);
11760                 }
11761                 len = sendwin - flight;
11762                 if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
11763                         /* We would send too much (beyond the rwnd) */
11764                         len = tp->snd_wnd - ctf_outstanding(tp);
11765                 }
11766                 if ((len + sb_offset) > avail) {
11767                         /*
11768                          * We don't have that much in the SB, how much is
11769                          * there?
11770                          */
11771                         len = avail - sb_offset;
11772                 }
11773         }
11774         return (len);
11775 }
11776
11777 static inline void
11778 bbr_do_error_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11779 {
11780 #ifdef NETFLIX_STATS
11781         KMOD_TCPSTAT_INC(tcps_sndpack_error);
11782         KMOD_TCPSTAT_ADD(tcps_sndbyte_error, len);
11783 #endif
11784 }
11785
11786 static inline void
11787 bbr_do_send_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11788 {
11789         if (error) {
11790                 bbr_do_error_accounting(tp, bbr, rsm, len, error);
11791                 return;
11792         }
11793         if (rsm) {
11794                 if (rsm->r_flags & BBR_TLP) {
11795                         /*
11796                          * TLP should not count in retran count, but in its
11797                          * own bin
11798                          */
11799 #ifdef NETFLIX_STATS
11800                         KMOD_TCPSTAT_INC(tcps_tlpresends);
11801                         KMOD_TCPSTAT_ADD(tcps_tlpresend_bytes, len);
11802 #endif
11803                 } else {
11804                         /* Retransmit */
11805                         tp->t_sndrexmitpack++;
11806                         KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
11807                         KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
11808 #ifdef STATS
11809                         stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
11810                             len);
11811 #endif
11812                 }
11813                 /*
11814                  * Logs in 0 - 8, 8 is all non probe_bw states 0-7 is
11815                  * sub-state
11816                  */
11817                 counter_u64_add(bbr_state_lost[rsm->r_bbr_state], len);
11818                 if (bbr->rc_bbr_state != BBR_STATE_PROBE_BW) {
11819                         /* Non probe_bw log in 1, 2, or 4. */
11820                         counter_u64_add(bbr_state_resend[bbr->rc_bbr_state], len);
11821                 } else {
11822                         /*
11823                          * Log our probe state 3, and log also 5-13 to show
11824                          * us the recovery sub-state for the send. This
11825                          * means that 3 == (5+6+7+8+9+10+11+12+13)
11826                          */
11827                         counter_u64_add(bbr_state_resend[BBR_STATE_PROBE_BW], len);
11828                         counter_u64_add(bbr_state_resend[(bbr_state_val(bbr) + 5)], len);
11829                 }
11830                 /* Place in both 16's the totals of retransmitted */
11831                 counter_u64_add(bbr_state_lost[16], len);
11832                 counter_u64_add(bbr_state_resend[16], len);
11833                 /* Place in 17's the total sent */
11834                 counter_u64_add(bbr_state_resend[17], len);
11835                 counter_u64_add(bbr_state_lost[17], len);
11836
11837         } else {
11838                 /* New sends */
11839                 KMOD_TCPSTAT_INC(tcps_sndpack);
11840                 KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
11841                 /* Place in 17's the total sent */
11842                 counter_u64_add(bbr_state_resend[17], len);
11843                 counter_u64_add(bbr_state_lost[17], len);
11844 #ifdef STATS
11845                 stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
11846                     len);
11847 #endif
11848         }
11849 }
11850
11851 static void
11852 bbr_cwnd_limiting(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t in_level)
11853 {
11854         if (bbr->rc_filled_pipe && bbr_target_cwnd_mult_limit && (bbr->rc_use_google == 0)) {
11855                 /*
11856                  * Limit the cwnd to not be above N x the target plus whats
11857                  * is outstanding. The target is based on the current b/w
11858                  * estimate.
11859                  */
11860                 uint32_t target;
11861
11862                 target = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), BBR_UNIT);
11863                 target += ctf_outstanding(tp);
11864                 target *= bbr_target_cwnd_mult_limit;
11865                 if (tp->snd_cwnd > target)
11866                         tp->snd_cwnd = target;
11867                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 10, 0, 0, __LINE__);
11868         }
11869 }
11870
11871 static int
11872 bbr_window_update_needed(struct tcpcb *tp, struct socket *so, uint32_t recwin, int32_t maxseg)
11873 {
11874         /*
11875          * "adv" is the amount we could increase the window, taking into
11876          * account that we are limited by TCP_MAXWIN << tp->rcv_scale.
11877          */
11878         int32_t adv;
11879         int32_t oldwin;
11880
11881         adv = recwin;
11882         if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
11883                 oldwin = (tp->rcv_adv - tp->rcv_nxt);
11884                 if (adv > oldwin)
11885                         adv -= oldwin;
11886                 else {
11887                         /* We can't increase the window */
11888                         adv = 0;
11889                 }
11890         } else
11891                 oldwin = 0;
11892
11893         /*
11894          * If the new window size ends up being the same as or less
11895          * than the old size when it is scaled, then don't force
11896          * a window update.
11897          */
11898         if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
11899                 return (0);
11900
11901         if (adv >= (2 * maxseg) &&
11902             (adv >= (so->so_rcv.sb_hiwat / 4) ||
11903             recwin <= (so->so_rcv.sb_hiwat / 8) ||
11904             so->so_rcv.sb_hiwat <= 8 * maxseg)) {
11905                 return (1);
11906         }
11907         if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
11908                 return (1);
11909         return (0);
11910 }
11911
11912 /*
11913  * Return 0 on success and a errno on failure to send.
11914  * Note that a 0 return may not mean we sent anything
11915  * if the TCB was on the hpts. A non-zero return
11916  * does indicate the error we got from ip[6]_output.
11917  */
11918 static int
11919 bbr_output_wtime(struct tcpcb *tp, const struct timeval *tv)
11920 {
11921         struct socket *so;
11922         int32_t len;
11923         uint32_t cts;
11924         uint32_t recwin, sendwin;
11925         int32_t sb_offset;
11926         int32_t flags, abandon, error = 0;
11927         struct tcp_log_buffer *lgb = NULL;
11928         struct mbuf *m;
11929         struct mbuf *mb;
11930         uint32_t if_hw_tsomaxsegcount = 0;
11931         uint32_t if_hw_tsomaxsegsize = 0;
11932         uint32_t if_hw_tsomax = 0;
11933         struct ip *ip = NULL;
11934 #ifdef TCPDEBUG
11935         struct ipovly *ipov = NULL;
11936 #endif
11937         struct tcp_bbr *bbr;
11938         struct tcphdr *th;
11939         struct udphdr *udp = NULL;
11940         u_char opt[TCP_MAXOLEN];
11941         unsigned ipoptlen, optlen, hdrlen;
11942         unsigned ulen;
11943         uint32_t bbr_seq;
11944         uint32_t delay_calc=0;
11945         uint8_t doing_tlp = 0;
11946         uint8_t local_options;
11947 #ifdef BBR_INVARIANTS
11948         uint8_t doing_retran_from = 0;
11949         uint8_t picked_up_retran = 0;
11950 #endif
11951         uint8_t wanted_cookie = 0;
11952         uint8_t more_to_rxt=0;
11953         int32_t prefetch_so_done = 0;
11954         int32_t prefetch_rsm = 0;
11955         uint32_t what_we_can = 0;
11956         uint32_t tot_len = 0;
11957         uint32_t rtr_cnt = 0;
11958         uint32_t maxseg, pace_max_segs, p_maxseg;
11959         int32_t csum_flags;
11960         int32_t hw_tls;
11961 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
11962         unsigned ipsec_optlen = 0;
11963
11964 #endif
11965         volatile int32_t sack_rxmit;
11966         struct bbr_sendmap *rsm = NULL;
11967         int32_t tso, mtu;
11968         struct tcpopt to;
11969         int32_t slot = 0;
11970         struct inpcb *inp;
11971         struct sockbuf *sb;
11972         uint32_t hpts_calling;
11973 #ifdef INET6
11974         struct ip6_hdr *ip6 = NULL;
11975         int32_t isipv6;
11976 #endif
11977         uint8_t app_limited = BBR_JR_SENT_DATA;
11978         uint8_t filled_all = 0;
11979         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11980         /* We take a cache hit here */
11981         memcpy(&bbr->rc_tv, tv, sizeof(struct timeval));
11982         cts = tcp_tv_to_usectick(&bbr->rc_tv);
11983         inp = bbr->rc_inp;
11984         so = inp->inp_socket;
11985         sb = &so->so_snd;
11986         if (sb->sb_flags & SB_TLS_IFNET)
11987                 hw_tls = 1;
11988         else
11989                 hw_tls = 0;
11990         kern_prefetch(sb, &maxseg);
11991         maxseg = tp->t_maxseg - bbr->rc_last_options;
11992         if (bbr_minseg(bbr) < maxseg) {
11993                 tcp_bbr_tso_size_check(bbr, cts);
11994         }
11995         /* Remove any flags that indicate we are pacing on the inp  */
11996         pace_max_segs = bbr->r_ctl.rc_pace_max_segs;
11997         p_maxseg = min(maxseg, pace_max_segs);
11998         INP_WLOCK_ASSERT(inp);
11999 #ifdef TCP_OFFLOAD
12000         if (tp->t_flags & TF_TOE)
12001                 return (tcp_offload_output(tp));
12002 #endif
12003
12004 #ifdef INET6
12005         if (bbr->r_state) {
12006                 /* Use the cache line loaded if possible */
12007                 isipv6 = bbr->r_is_v6;
12008         } else {
12009                 isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
12010         }
12011 #endif
12012         if (((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
12013             inp->inp_in_hpts) {
12014                 /*
12015                  * We are on the hpts for some timer but not hptsi output.
12016                  * Possibly remove from the hpts so we can send/recv etc.
12017                  */
12018                 if ((tp->t_flags & TF_ACKNOW) == 0) {
12019                         /*
12020                          * No immediate demand right now to send an ack, but
12021                          * the user may have read, making room for new data
12022                          * (a window update). If so we may want to cancel
12023                          * whatever timer is running (KEEP/DEL-ACK?) and
12024                          * continue to send out a window update. Or we may
12025                          * have gotten more data into the socket buffer to
12026                          * send.
12027                          */
12028                         recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12029                                       (long)TCP_MAXWIN << tp->rcv_scale);
12030                         if ((bbr_window_update_needed(tp, so, recwin, maxseg) == 0) &&
12031                             ((tcp_outflags[tp->t_state] & TH_RST) == 0) &&
12032                             ((sbavail(sb) + ((tcp_outflags[tp->t_state] & TH_FIN) ? 1 : 0)) <=
12033                             (tp->snd_max - tp->snd_una))) {
12034                                 /*
12035                                  * Nothing new to send and no window update
12036                                  * is needed to send. Lets just return and
12037                                  * let the timer-run off.
12038                                  */
12039                                 return (0);
12040                         }
12041                 }
12042                 tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12043                 bbr_timer_cancel(bbr, __LINE__, cts);
12044         }
12045         if (bbr->r_ctl.rc_last_delay_val) {
12046                 /* Calculate a rough delay for early escape to sending  */
12047                 if (SEQ_GT(cts, bbr->rc_pacer_started))
12048                         delay_calc = cts - bbr->rc_pacer_started;
12049                 if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12050                         delay_calc -= bbr->r_ctl.rc_last_delay_val;
12051                 else
12052                         delay_calc = 0;
12053         }
12054         /* Mark that we have called bbr_output(). */
12055         if ((bbr->r_timer_override) ||
12056             (tp->t_state < TCPS_ESTABLISHED)) {
12057                 /* Timeouts or early states are exempt */
12058                 if (inp->inp_in_hpts)
12059                         tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12060         } else if (inp->inp_in_hpts) {
12061                 if ((bbr->r_ctl.rc_last_delay_val) &&
12062                     (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
12063                     delay_calc) {
12064                         /*
12065                          * We were being paced for output and the delay has
12066                          * already exceeded when we were supposed to be
12067                          * called, lets go ahead and pull out of the hpts
12068                          * and call output.
12069                          */
12070                         counter_u64_add(bbr_out_size[TCP_MSS_ACCT_LATE], 1);
12071                         bbr->r_ctl.rc_last_delay_val = 0;
12072                         tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12073                 } else if (tp->t_state == TCPS_CLOSED) {
12074                         bbr->r_ctl.rc_last_delay_val = 0;
12075                         tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12076                 } else {
12077                         /*
12078                          * On the hpts, you shall not pass! even if ACKNOW
12079                          * is on, we will when the hpts fires, unless of
12080                          * course we are overdue.
12081                          */
12082                         counter_u64_add(bbr_out_size[TCP_MSS_ACCT_INPACE], 1);
12083                         return (0);
12084                 }
12085         }
12086         bbr->rc_cwnd_limited = 0;
12087         if (bbr->r_ctl.rc_last_delay_val) {
12088                 /* recalculate the real delay and deal with over/under  */
12089                 if (SEQ_GT(cts, bbr->rc_pacer_started))
12090                         delay_calc = cts - bbr->rc_pacer_started;
12091                 else
12092                         delay_calc = 0;
12093                 if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12094                         /* Setup the delay which will be added in */
12095                         delay_calc -= bbr->r_ctl.rc_last_delay_val;
12096                 else {
12097                         /*
12098                          * We are early setup to adjust
12099                          * our slot time.
12100                          */
12101                         uint64_t merged_val;
12102
12103                         bbr->r_ctl.rc_agg_early += (bbr->r_ctl.rc_last_delay_val - delay_calc);
12104                         bbr->r_agg_early_set = 1;
12105                         if (bbr->r_ctl.rc_hptsi_agg_delay) {
12106                                 if (bbr->r_ctl.rc_hptsi_agg_delay >= bbr->r_ctl.rc_agg_early) {
12107                                         /* Nope our previous late cancels out the early */
12108                                         bbr->r_ctl.rc_hptsi_agg_delay -= bbr->r_ctl.rc_agg_early;
12109                                         bbr->r_agg_early_set = 0;
12110                                         bbr->r_ctl.rc_agg_early = 0;
12111                                 } else {
12112                                         bbr->r_ctl.rc_agg_early -= bbr->r_ctl.rc_hptsi_agg_delay;
12113                                         bbr->r_ctl.rc_hptsi_agg_delay = 0;
12114                                 }
12115                         }
12116                         merged_val = bbr->rc_pacer_started;
12117                         merged_val <<= 32;
12118                         merged_val |= bbr->r_ctl.rc_last_delay_val;
12119                         bbr_log_pacing_delay_calc(bbr, inp->inp_hpts_calls,
12120                                                  bbr->r_ctl.rc_agg_early, cts, delay_calc, merged_val,
12121                                                  bbr->r_agg_early_set, 3);
12122                         bbr->r_ctl.rc_last_delay_val = 0;
12123                         BBR_STAT_INC(bbr_early);
12124                         delay_calc = 0;
12125                 }
12126         } else {
12127                 /* We were not delayed due to hptsi */
12128                 if (bbr->r_agg_early_set)
12129                         bbr->r_ctl.rc_agg_early = 0;
12130                 bbr->r_agg_early_set = 0;
12131                 delay_calc = 0;
12132         }
12133         if (delay_calc) {
12134                 /*
12135                  * We had a hptsi delay which means we are falling behind on
12136                  * sending at the expected rate. Calculate an extra amount
12137                  * of data we can send, if any, to put us back on track.
12138                  */
12139                 if ((bbr->r_ctl.rc_hptsi_agg_delay + delay_calc) < bbr->r_ctl.rc_hptsi_agg_delay)
12140                         bbr->r_ctl.rc_hptsi_agg_delay = 0xffffffff;
12141                 else
12142                         bbr->r_ctl.rc_hptsi_agg_delay += delay_calc;
12143         }
12144         sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12145         if ((tp->snd_una == tp->snd_max) &&
12146             (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
12147             (sbavail(sb))) {
12148                 /*
12149                  * Ok we have been idle with nothing outstanding
12150                  * we possibly need to start fresh with either a new
12151                  * suite of states or a fast-ramp up.
12152                  */
12153                 bbr_restart_after_idle(bbr,
12154                                        cts, bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time));
12155         }
12156         /*
12157          * Now was there a hptsi delay where we are behind? We only count
12158          * being behind if: a) We are not in recovery. b) There was a delay.
12159          * <and> c) We had room to send something.
12160          *
12161          */
12162         hpts_calling = inp->inp_hpts_calls;
12163         inp->inp_hpts_calls = 0;
12164         if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
12165                 if (bbr_process_timers(tp, bbr, cts, hpts_calling)) {
12166                         counter_u64_add(bbr_out_size[TCP_MSS_ACCT_ATIMER], 1);
12167                         return (0);
12168                 }
12169         }
12170         bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
12171         if (hpts_calling &&
12172             (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
12173                 bbr->r_ctl.rc_last_delay_val = 0;
12174         }
12175         bbr->r_timer_override = 0;
12176         bbr->r_wanted_output = 0;
12177         /*
12178          * For TFO connections in SYN_RECEIVED, only allow the initial
12179          * SYN|ACK and those sent by the retransmit timer.
12180          */
12181         if (IS_FASTOPEN(tp->t_flags) &&
12182             ((tp->t_state == TCPS_SYN_RECEIVED) ||
12183              (tp->t_state == TCPS_SYN_SENT)) &&
12184             SEQ_GT(tp->snd_max, tp->snd_una) && /* initial SYN or SYN|ACK sent */
12185             (tp->t_rxtshift == 0)) {    /* not a retransmit */
12186                 len = 0;
12187                 goto just_return_nolock;
12188         }
12189         /*
12190          * Before sending anything check for a state update. For hpts
12191          * calling without input this is important. If its input calling
12192          * then this was already done.
12193          */
12194         if (bbr->rc_use_google == 0)
12195                 bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12196 again:
12197         /*
12198          * If we've recently taken a timeout, snd_max will be greater than
12199          * snd_max. BBR in general does not pay much attention to snd_nxt
12200          * for historic reasons the persist timer still uses it. This means
12201          * we have to look at it. All retransmissions that are not persits
12202          * use the rsm that needs to be sent so snd_nxt is ignored. At the
12203          * end of this routine we pull snd_nxt always up to snd_max.
12204          */
12205         doing_tlp = 0;
12206 #ifdef BBR_INVARIANTS
12207         doing_retran_from = picked_up_retran = 0;
12208 #endif
12209         error = 0;
12210         tso = 0;
12211         slot = 0;
12212         mtu = 0;
12213         sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12214         sb_offset = tp->snd_max - tp->snd_una;
12215         flags = tcp_outflags[tp->t_state];
12216         sack_rxmit = 0;
12217         len = 0;
12218         rsm = NULL;
12219         if (flags & TH_RST) {
12220                 SOCKBUF_LOCK(sb);
12221                 goto send;
12222         }
12223 recheck_resend:
12224         while (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
12225                 /* We need to always have one in reserve */
12226                 rsm = bbr_alloc(bbr);
12227                 if (rsm == NULL) {
12228                         error = ENOMEM;
12229                         /* Lie to get on the hpts */
12230                         tot_len = tp->t_maxseg;
12231                         if (hpts_calling)
12232                                 /* Retry in a ms */
12233                                 slot = 1001;
12234                         goto just_return_nolock;
12235                 }
12236                 TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
12237                 bbr->r_ctl.rc_free_cnt++;
12238                 rsm = NULL;
12239         }
12240         /* What do we send, a resend? */
12241         if (bbr->r_ctl.rc_resend == NULL) {
12242                 /* Check for rack timeout */
12243                 bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
12244                 if (bbr->r_ctl.rc_resend) {
12245 #ifdef BBR_INVARIANTS
12246                         picked_up_retran = 1;
12247 #endif
12248                         bbr_cong_signal(tp, NULL, CC_NDUPACK, bbr->r_ctl.rc_resend);
12249                 }
12250         }
12251         if (bbr->r_ctl.rc_resend) {
12252                 rsm = bbr->r_ctl.rc_resend;
12253 #ifdef BBR_INVARIANTS
12254                 doing_retran_from = 1;
12255 #endif
12256                 /* Remove any TLP flags its a RACK or T-O */
12257                 rsm->r_flags &= ~BBR_TLP;
12258                 bbr->r_ctl.rc_resend = NULL;
12259                 if (SEQ_LT(rsm->r_start, tp->snd_una)) {
12260 #ifdef BBR_INVARIANTS
12261                         panic("Huh, tp:%p bbr:%p rsm:%p start:%u < snd_una:%u\n",
12262                             tp, bbr, rsm, rsm->r_start, tp->snd_una);
12263                         goto recheck_resend;
12264 #else
12265                         /* TSNH */
12266                         rsm = NULL;
12267                         goto recheck_resend;
12268 #endif
12269                 }
12270                 rtr_cnt++;
12271                 if (rsm->r_flags & BBR_HAS_SYN) {
12272                         /* Only retransmit a SYN by itself */
12273                         len = 0;
12274                         if ((flags & TH_SYN) == 0) {
12275                                 /* Huh something is wrong */
12276                                 rsm->r_start++;
12277                                 if (rsm->r_start == rsm->r_end) {
12278                                         /* Clean it up, somehow we missed the ack? */
12279                                         bbr_log_syn(tp, NULL);
12280                                 } else {
12281                                         /* TFO with data? */
12282                                         rsm->r_flags &= ~BBR_HAS_SYN;
12283                                         len = rsm->r_end - rsm->r_start;
12284                                 }
12285                         } else {
12286                                 /* Retransmitting SYN */
12287                                 rsm = NULL;
12288                                 SOCKBUF_LOCK(sb);
12289                                 goto send;
12290                         }
12291                 } else
12292                         len = rsm->r_end - rsm->r_start;
12293                 if ((bbr->rc_resends_use_tso == 0) &&
12294                     (len > maxseg)) {
12295                         len = maxseg;
12296                         more_to_rxt = 1;
12297                 }
12298                 sb_offset = rsm->r_start - tp->snd_una;
12299                 if (len > 0) {
12300                         sack_rxmit = 1;
12301                         KMOD_TCPSTAT_INC(tcps_sack_rexmits);
12302                         KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
12303                             min(len, maxseg));
12304                 } else {
12305                         /* I dont think this can happen */
12306                         rsm = NULL;
12307                         goto recheck_resend;
12308                 }
12309                 BBR_STAT_INC(bbr_resends_set);
12310         } else if (bbr->r_ctl.rc_tlp_send) {
12311                 /*
12312                  * Tail loss probe
12313                  */
12314                 doing_tlp = 1;
12315                 rsm = bbr->r_ctl.rc_tlp_send;
12316                 bbr->r_ctl.rc_tlp_send = NULL;
12317                 sack_rxmit = 1;
12318                 len = rsm->r_end - rsm->r_start;
12319                 rtr_cnt++;
12320                 if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12321                         len = maxseg;
12322
12323                 if (SEQ_GT(tp->snd_una, rsm->r_start)) {
12324 #ifdef BBR_INVARIANTS
12325                         panic("tp:%p bbc:%p snd_una:%u rsm:%p r_start:%u",
12326                             tp, bbr, tp->snd_una, rsm, rsm->r_start);
12327 #else
12328                         /* TSNH */
12329                         rsm = NULL;
12330                         goto recheck_resend;
12331 #endif
12332                 }
12333                 sb_offset = rsm->r_start - tp->snd_una;
12334                 BBR_STAT_INC(bbr_tlp_set);
12335         }
12336         /*
12337          * Enforce a connection sendmap count limit if set
12338          * as long as we are not retransmiting.
12339          */
12340         if ((rsm == NULL) &&
12341             (V_tcp_map_entries_limit > 0) &&
12342             (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
12343                 BBR_STAT_INC(bbr_alloc_limited);
12344                 if (!bbr->alloc_limit_reported) {
12345                         bbr->alloc_limit_reported = 1;
12346                         BBR_STAT_INC(bbr_alloc_limited_conns);
12347                 }
12348                 goto just_return_nolock;
12349         }
12350 #ifdef BBR_INVARIANTS
12351         if (rsm && SEQ_LT(rsm->r_start, tp->snd_una)) {
12352                 panic("tp:%p bbr:%p rsm:%p sb_offset:%u len:%u",
12353                     tp, bbr, rsm, sb_offset, len);
12354         }
12355 #endif
12356         /*
12357          * Get standard flags, and add SYN or FIN if requested by 'hidden'
12358          * state flags.
12359          */
12360         if (tp->t_flags & TF_NEEDFIN && (rsm == NULL))
12361                 flags |= TH_FIN;
12362         if (tp->t_flags & TF_NEEDSYN)
12363                 flags |= TH_SYN;
12364
12365         if (rsm && (rsm->r_flags & BBR_HAS_FIN)) {
12366                 /* we are retransmitting the fin */
12367                 len--;
12368                 if (len) {
12369                         /*
12370                          * When retransmitting data do *not* include the
12371                          * FIN. This could happen from a TLP probe if we
12372                          * allowed data with a FIN.
12373                          */
12374                         flags &= ~TH_FIN;
12375                 }
12376         } else if (rsm) {
12377                 if (flags & TH_FIN)
12378                         flags &= ~TH_FIN;
12379         }
12380         if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
12381                 void *end_rsm;
12382
12383                 end_rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
12384                 if (end_rsm)
12385                         kern_prefetch(end_rsm, &prefetch_rsm);
12386                 prefetch_rsm = 1;
12387         }
12388         SOCKBUF_LOCK(sb);
12389         /*
12390          * If snd_nxt == snd_max and we have transmitted a FIN, the
12391          * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
12392          * negative length.  This can also occur when TCP opens up its
12393          * congestion window while receiving additional duplicate acks after
12394          * fast-retransmit because TCP will reset snd_nxt to snd_max after
12395          * the fast-retransmit.
12396          *
12397          * In the normal retransmit-FIN-only case, however, snd_nxt will be
12398          * set to snd_una, the sb_offset will be 0, and the length may wind
12399          * up 0.
12400          *
12401          * If sack_rxmit is true we are retransmitting from the scoreboard
12402          * in which case len is already set.
12403          */
12404         if (sack_rxmit == 0) {
12405                 uint32_t avail;
12406
12407                 avail = sbavail(sb);
12408                 if (SEQ_GT(tp->snd_max, tp->snd_una))
12409                         sb_offset = tp->snd_max - tp->snd_una;
12410                 else
12411                         sb_offset = 0;
12412                 if (bbr->rc_tlp_new_data) {
12413                         /* TLP is forcing out new data */
12414                         uint32_t tlplen;
12415
12416                         doing_tlp = 1;
12417                         tlplen = maxseg;
12418
12419                         if (tlplen > (uint32_t)(avail - sb_offset)) {
12420                                 tlplen = (uint32_t)(avail - sb_offset);
12421                         }
12422                         if (tlplen > tp->snd_wnd) {
12423                                 len = tp->snd_wnd;
12424                         } else {
12425                                 len = tlplen;
12426                         }
12427                         bbr->rc_tlp_new_data = 0;
12428                 } else {
12429                         what_we_can = len = bbr_what_can_we_send(tp, bbr, sendwin, avail, sb_offset, cts);
12430                         if ((len < p_maxseg) &&
12431                             (bbr->rc_in_persist == 0) &&
12432                             (ctf_outstanding(tp) >= (2 * p_maxseg)) &&
12433                             ((avail - sb_offset) >= p_maxseg)) {
12434                                 /*
12435                                  * We are not completing whats in the socket
12436                                  * buffer (i.e. there is at least a segment
12437                                  * waiting to send) and we have 2 or more
12438                                  * segments outstanding. There is no sense
12439                                  * of sending a little piece. Lets defer and
12440                                  * and wait until we can send a whole
12441                                  * segment.
12442                                  */
12443                                 len = 0;
12444                         }
12445                         if (bbr->rc_in_persist) {
12446                                 /*
12447                                  * We are in persists, figure out if
12448                                  * a retransmit is available (maybe the previous
12449                                  * persists we sent) or if we have to send new
12450                                  * data.
12451                                  */
12452                                 rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
12453                                 if (rsm) {
12454                                         len = rsm->r_end - rsm->r_start;
12455                                         if (rsm->r_flags & BBR_HAS_FIN)
12456                                                 len--;
12457                                         if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12458                                                 len = maxseg;
12459                                         if (len > 1)
12460                                                 BBR_STAT_INC(bbr_persist_reneg);
12461                                         /*
12462                                          * XXXrrs we could force the len to
12463                                          * 1 byte here to cause the chunk to
12464                                          * split apart.. but that would then
12465                                          * mean we always retransmit it as
12466                                          * one byte even after the window
12467                                          * opens.
12468                                          */
12469                                         sack_rxmit = 1;
12470                                         sb_offset = rsm->r_start - tp->snd_una;
12471                                 } else {
12472                                         /*
12473                                          * First time through in persists or peer
12474                                          * acked our one byte. Though we do have
12475                                          * to have something in the sb.
12476                                          */
12477                                         len = 1;
12478                                         sb_offset = 0;
12479                                         if (avail == 0)
12480                                             len = 0;
12481                                 }
12482                         }
12483                 }
12484         }
12485         if (prefetch_so_done == 0) {
12486                 kern_prefetch(so, &prefetch_so_done);
12487                 prefetch_so_done = 1;
12488         }
12489         /*
12490          * Lop off SYN bit if it has already been sent.  However, if this is
12491          * SYN-SENT state and if segment contains data and if we don't know
12492          * that foreign host supports TAO, suppress sending segment.
12493          */
12494         if ((flags & TH_SYN) && (rsm == NULL) &&
12495             SEQ_GT(tp->snd_max, tp->snd_una)) {
12496                 if (tp->t_state != TCPS_SYN_RECEIVED)
12497                         flags &= ~TH_SYN;
12498                 /*
12499                  * When sending additional segments following a TFO SYN|ACK,
12500                  * do not include the SYN bit.
12501                  */
12502                 if (IS_FASTOPEN(tp->t_flags) &&
12503                     (tp->t_state == TCPS_SYN_RECEIVED))
12504                         flags &= ~TH_SYN;
12505                 sb_offset--, len++;
12506                 if (sbavail(sb) == 0)
12507                         len = 0;
12508         } else if ((flags & TH_SYN) && rsm) {
12509                 /*
12510                  * Subtract one from the len for the SYN being
12511                  * retransmitted.
12512                  */
12513                 len--;
12514         }
12515         /*
12516          * Be careful not to send data and/or FIN on SYN segments. This
12517          * measure is needed to prevent interoperability problems with not
12518          * fully conformant TCP implementations.
12519          */
12520         if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
12521                 len = 0;
12522                 flags &= ~TH_FIN;
12523         }
12524         /*
12525          * On TFO sockets, ensure no data is sent in the following cases:
12526          *
12527          *  - When retransmitting SYN|ACK on a passively-created socket
12528          *  - When retransmitting SYN on an actively created socket
12529          *  - When sending a zero-length cookie (cookie request) on an
12530          *    actively created socket
12531          *  - When the socket is in the CLOSED state (RST is being sent)
12532          */
12533         if (IS_FASTOPEN(tp->t_flags) &&
12534             (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
12535              ((tp->t_state == TCPS_SYN_SENT) &&
12536               (tp->t_tfo_client_cookie_len == 0)) ||
12537              (flags & TH_RST))) {
12538                 len = 0;
12539                 sack_rxmit = 0;
12540                 rsm = NULL;
12541         }
12542         /* Without fast-open there should never be data sent on a SYN */
12543         if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags)))
12544                 len = 0;
12545         if (len <= 0) {
12546                 /*
12547                  * If FIN has been sent but not acked, but we haven't been
12548                  * called to retransmit, len will be < 0.  Otherwise, window
12549                  * shrank after we sent into it.  If window shrank to 0,
12550                  * cancel pending retransmit, pull snd_nxt back to (closed)
12551                  * window, and set the persist timer if it isn't already
12552                  * going.  If the window didn't close completely, just wait
12553                  * for an ACK.
12554                  *
12555                  * We also do a general check here to ensure that we will
12556                  * set the persist timer when we have data to send, but a
12557                  * 0-byte window. This makes sure the persist timer is set
12558                  * even if the packet hits one of the "goto send" lines
12559                  * below.
12560                  */
12561                 len = 0;
12562                 if ((tp->snd_wnd == 0) &&
12563                     (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12564                     (tp->snd_una == tp->snd_max) &&
12565                     (sb_offset < (int)sbavail(sb))) {
12566                         /*
12567                          * Not enough room in the rwnd to send
12568                          * a paced segment out.
12569                          */
12570                         bbr_enter_persist(tp, bbr, cts, __LINE__);
12571                 }
12572         } else if ((rsm == NULL) &&
12573                    (doing_tlp == 0) &&
12574                    (len < bbr->r_ctl.rc_pace_max_segs)) {
12575                 /*
12576                  * We are not sending a full segment for
12577                  * some reason. Should we not send anything (think
12578                  * sws or persists)?
12579                  */
12580                 if ((tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12581                     (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12582                     (len < (int)(sbavail(sb) - sb_offset))) {
12583                         /*
12584                          * Here the rwnd is less than
12585                          * the pacing size, this is not a retransmit,
12586                          * we are established and
12587                          * the send is not the last in the socket buffer
12588                          * lets not send, and possibly enter persists.
12589                          */
12590                         len = 0;
12591                         if (tp->snd_max == tp->snd_una)
12592                                 bbr_enter_persist(tp, bbr, cts, __LINE__);
12593                 } else if ((tp->snd_cwnd >= bbr->r_ctl.rc_pace_max_segs) &&
12594                            (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12595                                                  bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12596                            (len < (int)(sbavail(sb) - sb_offset)) &&
12597                            (len < bbr_minseg(bbr))) {
12598                         /*
12599                          * Here we are not retransmitting, and
12600                          * the cwnd is not so small that we could
12601                          * not send at least a min size (rxt timer
12602                          * not having gone off), We have 2 segments or
12603                          * more already in flight, its not the tail end
12604                          * of the socket buffer  and the cwnd is blocking
12605                          * us from sending out minimum pacing segment size.
12606                          * Lets not send anything.
12607                          */
12608                         bbr->rc_cwnd_limited = 1;
12609                         len = 0;
12610                 } else if (((tp->snd_wnd - ctf_outstanding(tp)) <
12611                             min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12612                            (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12613                                                  bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12614                            (len < (int)(sbavail(sb) - sb_offset)) &&
12615                            (TCPS_HAVEESTABLISHED(tp->t_state))) {
12616                         /*
12617                          * Here we have a send window but we have
12618                          * filled it up and we can't send another pacing segment.
12619                          * We also have in flight more than 2 segments
12620                          * and we are not completing the sb i.e. we allow
12621                          * the last bytes of the sb to go out even if
12622                          * its not a full pacing segment.
12623                          */
12624                         len = 0;
12625                 }
12626         }
12627         /* len will be >= 0 after this point. */
12628         KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
12629         tcp_sndbuf_autoscale(tp, so, sendwin);
12630         /*
12631          *
12632          */
12633         if (bbr->rc_in_persist &&
12634             len &&
12635             (rsm == NULL) &&
12636             (len < min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs))) {
12637                 /*
12638                  * We are in persist, not doing a retransmit and don't have enough space
12639                  * yet to send a full TSO. So is it at the end of the sb
12640                  * if so we need to send else nuke to 0 and don't send.
12641                  */
12642                 int sbleft;
12643                 if (sbavail(sb) > sb_offset)
12644                         sbleft = sbavail(sb) - sb_offset;
12645                 else
12646                         sbleft = 0;
12647                 if (sbleft >= min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs)) {
12648                         /* not at end of sb lets not send */
12649                         len = 0;
12650                 }
12651         }
12652         /*
12653          * Decide if we can use TCP Segmentation Offloading (if supported by
12654          * hardware).
12655          *
12656          * TSO may only be used if we are in a pure bulk sending state.  The
12657          * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
12658          * options prevent using TSO.  With TSO the TCP header is the same
12659          * (except for the sequence number) for all generated packets.  This
12660          * makes it impossible to transmit any options which vary per
12661          * generated segment or packet.
12662          *
12663          * IPv4 handling has a clear separation of ip options and ip header
12664          * flags while IPv6 combines both in in6p_outputopts. ip6_optlen()
12665          * does the right thing below to provide length of just ip options
12666          * and thus checking for ipoptlen is enough to decide if ip options
12667          * are present.
12668          */
12669 #ifdef INET6
12670         if (isipv6)
12671                 ipoptlen = ip6_optlen(inp);
12672         else
12673 #endif
12674         if (inp->inp_options)
12675                 ipoptlen = inp->inp_options->m_len -
12676                     offsetof(struct ipoption, ipopt_list);
12677         else
12678                 ipoptlen = 0;
12679 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12680         /*
12681          * Pre-calculate here as we save another lookup into the darknesses
12682          * of IPsec that way and can actually decide if TSO is ok.
12683          */
12684 #ifdef INET6
12685         if (isipv6 && IPSEC_ENABLED(ipv6))
12686                 ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
12687 #ifdef INET
12688         else
12689 #endif
12690 #endif                          /* INET6 */
12691 #ifdef INET
12692         if (IPSEC_ENABLED(ipv4))
12693                 ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
12694 #endif                          /* INET */
12695 #endif                          /* IPSEC */
12696 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12697         ipoptlen += ipsec_optlen;
12698 #endif
12699         if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
12700             (len > maxseg) &&
12701             (tp->t_port == 0) &&
12702             ((tp->t_flags & TF_SIGNATURE) == 0) &&
12703             tp->rcv_numsacks == 0 &&
12704             ipoptlen == 0)
12705                 tso = 1;
12706
12707         recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12708             (long)TCP_MAXWIN << tp->rcv_scale);
12709         /*
12710          * Sender silly window avoidance.   We transmit under the following
12711          * conditions when len is non-zero:
12712          *
12713          * - We have a full segment (or more with TSO) - This is the last
12714          * buffer in a write()/send() and we are either idle or running
12715          * NODELAY - we've timed out (e.g. persist timer) - we have more
12716          * then 1/2 the maximum send window's worth of data (receiver may be
12717          * limited the window size) - we need to retransmit
12718          */
12719         if (rsm)
12720                 goto send;
12721         if (len) {
12722                 if (sack_rxmit)
12723                         goto send;
12724                 if (len >= p_maxseg)
12725                         goto send;
12726                 /*
12727                  * NOTE! on localhost connections an 'ack' from the remote
12728                  * end may occur synchronously with the output and cause us
12729                  * to flush a buffer queued with moretocome.  XXX
12730                  *
12731                  */
12732                 if (((tp->t_flags & TF_MORETOCOME) == 0) &&     /* normal case */
12733                     ((tp->t_flags & TF_NODELAY) ||
12734                     ((uint32_t)len + (uint32_t)sb_offset) >= sbavail(&so->so_snd)) &&
12735                     (tp->t_flags & TF_NOPUSH) == 0) {
12736                         goto send;
12737                 }
12738                 if ((tp->snd_una == tp->snd_max) && len) {      /* Nothing outstanding */
12739                         goto send;
12740                 }
12741                 if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
12742                         goto send;
12743                 }
12744         }
12745         /*
12746          * Sending of standalone window updates.
12747          *
12748          * Window updates are important when we close our window due to a
12749          * full socket buffer and are opening it again after the application
12750          * reads data from it.  Once the window has opened again and the
12751          * remote end starts to send again the ACK clock takes over and
12752          * provides the most current window information.
12753          *
12754          * We must avoid the silly window syndrome whereas every read from
12755          * the receive buffer, no matter how small, causes a window update
12756          * to be sent.  We also should avoid sending a flurry of window
12757          * updates when the socket buffer had queued a lot of data and the
12758          * application is doing small reads.
12759          *
12760          * Prevent a flurry of pointless window updates by only sending an
12761          * update when we can increase the advertized window by more than
12762          * 1/4th of the socket buffer capacity.  When the buffer is getting
12763          * full or is very small be more aggressive and send an update
12764          * whenever we can increase by two mss sized segments. In all other
12765          * situations the ACK's to new incoming data will carry further
12766          * window increases.
12767          *
12768          * Don't send an independent window update if a delayed ACK is
12769          * pending (it will get piggy-backed on it) or the remote side
12770          * already has done a half-close and won't send more data.  Skip
12771          * this if the connection is in T/TCP half-open state.
12772          */
12773         if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
12774             !(tp->t_flags & TF_DELACK) &&
12775             !TCPS_HAVERCVDFIN(tp->t_state)) {
12776                 /* Check to see if we should do a window update */
12777                 if (bbr_window_update_needed(tp, so, recwin, maxseg))
12778                         goto send;
12779         }
12780         /*
12781          * Send if we owe the peer an ACK, RST, SYN.  ACKNOW
12782          * is also a catch-all for the retransmit timer timeout case.
12783          */
12784         if (tp->t_flags & TF_ACKNOW) {
12785                 goto send;
12786         }
12787         if (flags & TH_RST) {
12788                 /* Always send a RST if one is due */
12789                 goto send;
12790         }
12791         if ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0) {
12792                 goto send;
12793         }
12794         /*
12795          * If our state indicates that FIN should be sent and we have not
12796          * yet done so, then we need to send.
12797          */
12798         if (flags & TH_FIN &&
12799             ((tp->t_flags & TF_SENTFIN) == 0)) {
12800                 goto send;
12801         }
12802         /*
12803          * No reason to send a segment, just return.
12804          */
12805 just_return:
12806         SOCKBUF_UNLOCK(sb);
12807 just_return_nolock:
12808         if (tot_len)
12809                 slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
12810         if (bbr->rc_no_pacing)
12811                 slot = 0;
12812         if (tot_len == 0) {
12813                 if ((ctf_outstanding(tp) + min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) >=
12814                     tp->snd_wnd) {
12815                         BBR_STAT_INC(bbr_rwnd_limited);
12816                         app_limited = BBR_JR_RWND_LIMITED;
12817                         bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12818                         if ((bbr->rc_in_persist == 0) &&
12819                             TCPS_HAVEESTABLISHED(tp->t_state) &&
12820                             (tp->snd_max == tp->snd_una) &&
12821                             sbavail(&tp->t_inpcb->inp_socket->so_snd)) {
12822                                 /* No send window.. we must enter persist */
12823                                 bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
12824                         }
12825                 } else if (ctf_outstanding(tp) >= sbavail(sb)) {
12826                         BBR_STAT_INC(bbr_app_limited);
12827                         app_limited = BBR_JR_APP_LIMITED;
12828                         bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12829                 } else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12830                                                  bbr->r_ctl.rc_lost_bytes)) + p_maxseg) >= tp->snd_cwnd) {
12831                         BBR_STAT_INC(bbr_cwnd_limited);
12832                         app_limited = BBR_JR_CWND_LIMITED;
12833                         bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12834                                                                         bbr->r_ctl.rc_lost_bytes)));
12835                         bbr->rc_cwnd_limited = 1;
12836                 } else {
12837                         BBR_STAT_INC(bbr_app_limited);
12838                         app_limited = BBR_JR_APP_LIMITED;
12839                         bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12840                 }
12841                 bbr->r_ctl.rc_hptsi_agg_delay = 0;
12842                 bbr->r_agg_early_set = 0;
12843                 bbr->r_ctl.rc_agg_early = 0;
12844                 bbr->r_ctl.rc_last_delay_val = 0;
12845         } else if (bbr->rc_use_google == 0)
12846                 bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12847         /* Are we app limited? */
12848         if ((app_limited == BBR_JR_APP_LIMITED) ||
12849             (app_limited == BBR_JR_RWND_LIMITED)) {
12850                 /**
12851                  * We are application limited.
12852                  */
12853                 bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12854                                                                        bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_delivered);
12855         }
12856         if (tot_len == 0)
12857                 counter_u64_add(bbr_out_size[TCP_MSS_ACCT_JUSTRET], 1);
12858         /* Dont update the time if we did not send */
12859         bbr->r_ctl.rc_last_delay_val = 0;
12860         bbr->rc_output_starts_timer = 1;
12861         bbr_start_hpts_timer(bbr, tp, cts, 9, slot, tot_len);
12862         bbr_log_type_just_return(bbr, cts, tot_len, hpts_calling, app_limited, p_maxseg, len);
12863         if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
12864                 /* Make sure snd_nxt is drug up */
12865                 tp->snd_nxt = tp->snd_max;
12866         }
12867         return (error);
12868
12869 send:
12870         if (doing_tlp == 0) {
12871                 /*
12872                  * Data not a TLP, and its not the rxt firing. If it is the
12873                  * rxt firing, we want to leave the tlp_in_progress flag on
12874                  * so we don't send another TLP. It has to be a rack timer
12875                  * or normal send (response to acked data) to clear the tlp
12876                  * in progress flag.
12877                  */
12878                 bbr->rc_tlp_in_progress = 0;
12879                 bbr->rc_tlp_rtx_out = 0;
12880         } else {
12881                 /*
12882                  * Its a TLP.
12883                  */
12884                 bbr->rc_tlp_in_progress = 1;
12885         }
12886         bbr_timer_cancel(bbr, __LINE__, cts);
12887         if (rsm == NULL) {
12888                 if (sbused(sb) > 0) {
12889                         /*
12890                          * This is sub-optimal. We only send a stand alone
12891                          * FIN on its own segment.
12892                          */
12893                         if (flags & TH_FIN) {
12894                                 flags &= ~TH_FIN;
12895                                 if ((len == 0) && ((tp->t_flags & TF_ACKNOW) == 0)) {
12896                                         /* Lets not send this */
12897                                         slot = 0;
12898                                         goto just_return;
12899                                 }
12900                         }
12901                 }
12902         } else {
12903                 /*
12904                  * We do *not* send a FIN on a retransmit if it has data.
12905                  * The if clause here where len > 1 should never come true.
12906                  */
12907                 if ((len > 0) &&
12908                     (((rsm->r_flags & BBR_HAS_FIN) == 0) &&
12909                     (flags & TH_FIN))) {
12910                         flags &= ~TH_FIN;
12911                         len--;
12912                 }
12913         }
12914         SOCKBUF_LOCK_ASSERT(sb);
12915         if (len > 0) {
12916                 if ((tp->snd_una == tp->snd_max) &&
12917                     (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
12918                         /*
12919                          * This qualifies as a RTT_PROBE session since we
12920                          * drop the data outstanding to nothing and waited
12921                          * more than bbr_rtt_probe_time.
12922                          */
12923                         bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
12924                         bbr_set_reduced_rtt(bbr, cts, __LINE__);
12925                 }
12926                 if (len >= maxseg)
12927                         tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
12928                 else
12929                         tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
12930         }
12931         /*
12932          * Before ESTABLISHED, force sending of initial options unless TCP
12933          * set not to do any options. NOTE: we assume that the IP/TCP header
12934          * plus TCP options always fit in a single mbuf, leaving room for a
12935          * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
12936          * + optlen <= MCLBYTES
12937          */
12938         optlen = 0;
12939 #ifdef INET6
12940         if (isipv6)
12941                 hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
12942         else
12943 #endif
12944                 hdrlen = sizeof(struct tcpiphdr);
12945
12946         /*
12947          * Compute options for segment. We only have to care about SYN and
12948          * established connection segments.  Options for SYN-ACK segments
12949          * are handled in TCP syncache.
12950          */
12951         to.to_flags = 0;
12952         local_options = 0;
12953         if ((tp->t_flags & TF_NOOPT) == 0) {
12954                 /* Maximum segment size. */
12955                 if (flags & TH_SYN) {
12956                         to.to_mss = tcp_mssopt(&inp->inp_inc);
12957                         if (tp->t_port)
12958                                 to.to_mss -= V_tcp_udp_tunneling_overhead;
12959                         to.to_flags |= TOF_MSS;
12960                         /*
12961                          * On SYN or SYN|ACK transmits on TFO connections,
12962                          * only include the TFO option if it is not a
12963                          * retransmit, as the presence of the TFO option may
12964                          * have caused the original SYN or SYN|ACK to have
12965                          * been dropped by a middlebox.
12966                          */
12967                         if (IS_FASTOPEN(tp->t_flags) &&
12968                             (tp->t_rxtshift == 0)) {
12969                                 if (tp->t_state == TCPS_SYN_RECEIVED) {
12970                                         to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
12971                                         to.to_tfo_cookie =
12972                                             (u_int8_t *)&tp->t_tfo_cookie.server;
12973                                         to.to_flags |= TOF_FASTOPEN;
12974                                         wanted_cookie = 1;
12975                                 } else if (tp->t_state == TCPS_SYN_SENT) {
12976                                         to.to_tfo_len =
12977                                             tp->t_tfo_client_cookie_len;
12978                                         to.to_tfo_cookie =
12979                                             tp->t_tfo_cookie.client;
12980                                         to.to_flags |= TOF_FASTOPEN;
12981                                         wanted_cookie = 1;
12982                                 }
12983                         }
12984                 }
12985                 /* Window scaling. */
12986                 if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
12987                         to.to_wscale = tp->request_r_scale;
12988                         to.to_flags |= TOF_SCALE;
12989                 }
12990                 /* Timestamps. */
12991                 if ((tp->t_flags & TF_RCVD_TSTMP) ||
12992                     ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
12993                         to.to_tsval =   tcp_tv_to_mssectick(&bbr->rc_tv) + tp->ts_offset;
12994                         to.to_tsecr = tp->ts_recent;
12995                         to.to_flags |= TOF_TS;
12996                         local_options += TCPOLEN_TIMESTAMP + 2;
12997                 }
12998                 /* Set receive buffer autosizing timestamp. */
12999                 if (tp->rfbuf_ts == 0 &&
13000                     (so->so_rcv.sb_flags & SB_AUTOSIZE))
13001                         tp->rfbuf_ts =  tcp_tv_to_mssectick(&bbr->rc_tv);
13002                 /* Selective ACK's. */
13003                 if (flags & TH_SYN)
13004                         to.to_flags |= TOF_SACKPERM;
13005                 else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13006                     tp->rcv_numsacks > 0) {
13007                         to.to_flags |= TOF_SACK;
13008                         to.to_nsacks = tp->rcv_numsacks;
13009                         to.to_sacks = (u_char *)tp->sackblks;
13010                 }
13011 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13012                 /* TCP-MD5 (RFC2385). */
13013                 if (tp->t_flags & TF_SIGNATURE)
13014                         to.to_flags |= TOF_SIGNATURE;
13015 #endif                          /* TCP_SIGNATURE */
13016
13017                 /* Processing the options. */
13018                 hdrlen += (optlen = tcp_addoptions(&to, opt));
13019                 /*
13020                  * If we wanted a TFO option to be added, but it was unable
13021                  * to fit, ensure no data is sent.
13022                  */
13023                 if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
13024                     !(to.to_flags & TOF_FASTOPEN))
13025                         len = 0;
13026         }
13027         if (tp->t_port) {
13028                 if (V_tcp_udp_tunneling_port == 0) {
13029                         /* The port was removed?? */
13030                         SOCKBUF_UNLOCK(&so->so_snd);
13031                         return (EHOSTUNREACH);
13032                 }
13033                 hdrlen += sizeof(struct udphdr);
13034         }
13035 #ifdef INET6
13036         if (isipv6)
13037                 ipoptlen = ip6_optlen(tp->t_inpcb);
13038         else
13039 #endif
13040         if (tp->t_inpcb->inp_options)
13041                 ipoptlen = tp->t_inpcb->inp_options->m_len -
13042                     offsetof(struct ipoption, ipopt_list);
13043         else
13044                 ipoptlen = 0;
13045         ipoptlen = 0;
13046 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
13047         ipoptlen += ipsec_optlen;
13048 #endif
13049         if (bbr->rc_last_options != local_options) {
13050                 /*
13051                  * Cache the options length this generally does not change
13052                  * on a connection. We use this to calculate TSO.
13053                  */
13054                 bbr->rc_last_options = local_options;
13055         }
13056         maxseg = tp->t_maxseg - (ipoptlen + optlen);
13057         p_maxseg = min(maxseg, pace_max_segs);
13058         /*
13059          * Adjust data length if insertion of options will bump the packet
13060          * length beyond the t_maxseg length. Clear the FIN bit because we
13061          * cut off the tail of the segment.
13062          */
13063         if (len > maxseg) {
13064                 if (len != 0 && (flags & TH_FIN)) {
13065                         flags &= ~TH_FIN;
13066                 }
13067                 if (tso) {
13068                         uint32_t moff;
13069                         int32_t max_len;
13070
13071                         /* extract TSO information */
13072                         if_hw_tsomax = tp->t_tsomax;
13073                         if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
13074                         if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
13075                         KASSERT(ipoptlen == 0,
13076                             ("%s: TSO can't do IP options", __func__));
13077
13078                         /*
13079                          * Check if we should limit by maximum payload
13080                          * length:
13081                          */
13082                         if (if_hw_tsomax != 0) {
13083                                 /* compute maximum TSO length */
13084                                 max_len = (if_hw_tsomax - hdrlen -
13085                                     max_linkhdr);
13086                                 if (max_len <= 0) {
13087                                         len = 0;
13088                                 } else if (len > max_len) {
13089                                         len = max_len;
13090                                 }
13091                         }
13092                         /*
13093                          * Prevent the last segment from being fractional
13094                          * unless the send sockbuf can be emptied:
13095                          */
13096                         if ((sb_offset + len) < sbavail(sb)) {
13097                                 moff = len % (uint32_t)maxseg;
13098                                 if (moff != 0) {
13099                                         len -= moff;
13100                                 }
13101                         }
13102                         /*
13103                          * In case there are too many small fragments don't
13104                          * use TSO:
13105                          */
13106                         if (len <= maxseg) {
13107                                 len = maxseg;
13108                                 tso = 0;
13109                         }
13110                 } else {
13111                         /* Not doing TSO */
13112                         if (optlen + ipoptlen >= tp->t_maxseg) {
13113                                 /*
13114                                  * Since we don't have enough space to put
13115                                  * the IP header chain and the TCP header in
13116                                  * one packet as required by RFC 7112, don't
13117                                  * send it. Also ensure that at least one
13118                                  * byte of the payload can be put into the
13119                                  * TCP segment.
13120                                  */
13121                                 SOCKBUF_UNLOCK(&so->so_snd);
13122                                 error = EMSGSIZE;
13123                                 sack_rxmit = 0;
13124                                 goto out;
13125                         }
13126                         len = maxseg;
13127                 }
13128         } else {
13129                 /* Not doing TSO */
13130                 if_hw_tsomaxsegcount = 0;
13131                 tso = 0;
13132         }
13133         KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
13134             ("%s: len > IP_MAXPACKET", __func__));
13135 #ifdef DIAGNOSTIC
13136 #ifdef INET6
13137         if (max_linkhdr + hdrlen > MCLBYTES)
13138 #else
13139         if (max_linkhdr + hdrlen > MHLEN)
13140 #endif
13141                 panic("tcphdr too big");
13142 #endif
13143         /*
13144          * This KASSERT is here to catch edge cases at a well defined place.
13145          * Before, those had triggered (random) panic conditions further
13146          * down.
13147          */
13148 #ifdef BBR_INVARIANTS
13149         if (sack_rxmit) {
13150                 if (SEQ_LT(rsm->r_start, tp->snd_una)) {
13151                         panic("RSM:%p TP:%p bbr:%p start:%u is < snd_una:%u",
13152                             rsm, tp, bbr, rsm->r_start, tp->snd_una);
13153                 }
13154         }
13155 #endif
13156         KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
13157         if ((len == 0) &&
13158             (flags & TH_FIN) &&
13159             (sbused(sb))) {
13160                 /*
13161                  * We have outstanding data, don't send a fin by itself!.
13162                  */
13163                 slot = 0;
13164                 goto just_return;
13165         }
13166         /*
13167          * Grab a header mbuf, attaching a copy of data to be transmitted,
13168          * and initialize the header from the template for sends on this
13169          * connection.
13170          */
13171         if (len) {
13172                 uint32_t moff;
13173                 uint32_t orig_len;
13174
13175                 /*
13176                  * We place a limit on sending with hptsi.
13177                  */
13178                 if ((rsm == NULL) && len > pace_max_segs)
13179                         len = pace_max_segs;
13180                 if (len <= maxseg)
13181                         tso = 0;
13182 #ifdef INET6
13183                 if (MHLEN < hdrlen + max_linkhdr)
13184                         m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
13185                 else
13186 #endif
13187                         m = m_gethdr(M_NOWAIT, MT_DATA);
13188
13189                 if (m == NULL) {
13190                         BBR_STAT_INC(bbr_failed_mbuf_aloc);
13191                         bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13192                         SOCKBUF_UNLOCK(sb);
13193                         error = ENOBUFS;
13194                         sack_rxmit = 0;
13195                         goto out;
13196                 }
13197                 m->m_data += max_linkhdr;
13198                 m->m_len = hdrlen;
13199                 /*
13200                  * Start the m_copy functions from the closest mbuf to the
13201                  * sb_offset in the socket buffer chain.
13202                  */
13203                 if ((sb_offset > sbavail(sb)) || ((len + sb_offset) > sbavail(sb))) {
13204 #ifdef BBR_INVARIANTS
13205                         if ((len + sb_offset) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0)))
13206                                 panic("tp:%p bbr:%p len:%u sb_offset:%u sbavail:%u rsm:%p %u:%u:%u",
13207                                     tp, bbr, len, sb_offset, sbavail(sb), rsm,
13208                                     doing_retran_from,
13209                                     picked_up_retran,
13210                                     doing_tlp);
13211
13212 #endif
13213                         /*
13214                          * In this messed up situation we have two choices,
13215                          * a) pretend the send worked, and just start timers
13216                          * and what not (not good since that may lead us
13217                          * back here a lot). <or> b) Send the lowest segment
13218                          * in the map. <or> c) Drop the connection. Lets do
13219                          * <b> which if it continues to happen will lead to
13220                          * <c> via timeouts.
13221                          */
13222                         BBR_STAT_INC(bbr_offset_recovery);
13223                         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
13224                         sb_offset = 0;
13225                         if (rsm == NULL) {
13226                                 sack_rxmit = 0;
13227                                 len = sbavail(sb);
13228                         } else {
13229                                 sack_rxmit = 1;
13230                                 if (rsm->r_start != tp->snd_una) {
13231                                         /*
13232                                          * Things are really messed up, <c>
13233                                          * is the only thing to do.
13234                                          */
13235                                         BBR_STAT_INC(bbr_offset_drop);
13236                                         tcp_set_inp_to_drop(inp, EFAULT);
13237                                         SOCKBUF_UNLOCK(sb);
13238                                         (void)m_free(m);
13239                                         return (0);
13240                                 }
13241                                 len = rsm->r_end - rsm->r_start;
13242                         }
13243                         if (len > sbavail(sb))
13244                                 len = sbavail(sb);
13245                         if (len > maxseg)
13246                                 len = maxseg;
13247                 }
13248                 mb = sbsndptr_noadv(sb, sb_offset, &moff);
13249                 if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
13250                         m_copydata(mb, moff, (int)len,
13251                             mtod(m, caddr_t)+hdrlen);
13252                         if (rsm == NULL)
13253                                 sbsndptr_adv(sb, mb, len);
13254                         m->m_len += len;
13255                 } else {
13256                         struct sockbuf *msb;
13257
13258                         if (rsm)
13259                                 msb = NULL;
13260                         else
13261                                 msb = sb;
13262 #ifdef BBR_INVARIANTS
13263                         if ((len + moff) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0))) {
13264                                 if (rsm) {
13265                                         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 ",
13266                                             tp, bbr, len, moff,
13267                                             sbavail(sb), rsm,
13268                                             tp->snd_una, rsm->r_flags, rsm->r_start,
13269                                             doing_retran_from,
13270                                             picked_up_retran,
13271                                             doing_tlp, sack_rxmit);
13272                                 } else {
13273                                         panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u sb_offset:%u snd_una:%u",
13274                                             tp, bbr, len, moff, sbavail(sb), sb_offset, tp->snd_una);
13275                                 }
13276                         }
13277 #endif
13278                         orig_len = len;
13279                         m->m_next = tcp_m_copym(
13280                                 mb, moff, &len,
13281                                 if_hw_tsomaxsegcount,
13282                                 if_hw_tsomaxsegsize, msb,
13283                                 ((rsm == NULL) ? hw_tls : 0)
13284 #ifdef NETFLIX_COPY_ARGS
13285                                 , &filled_all
13286 #endif
13287                                 );
13288                         if (len <= maxseg) {
13289                                 /*
13290                                  * Must have ran out of mbufs for the copy
13291                                  * shorten it to no longer need tso. Lets
13292                                  * not put on sendalot since we are low on
13293                                  * mbufs.
13294                                  */
13295                                 tso = 0;
13296                         }
13297                         if (m->m_next == NULL) {
13298                                 SOCKBUF_UNLOCK(sb);
13299                                 (void)m_free(m);
13300                                 error = ENOBUFS;
13301                                 sack_rxmit = 0;
13302                                 goto out;
13303                         }
13304                 }
13305 #ifdef BBR_INVARIANTS
13306                 if (tso && len < maxseg) {
13307                         panic("tp:%p tso on, but len:%d < maxseg:%d",
13308                             tp, len, maxseg);
13309                 }
13310                 if (tso && if_hw_tsomaxsegcount) {
13311                         int32_t seg_cnt = 0;
13312                         struct mbuf *foo;
13313
13314                         foo = m;
13315                         while (foo) {
13316                                 seg_cnt++;
13317                                 foo = foo->m_next;
13318                         }
13319                         if (seg_cnt > if_hw_tsomaxsegcount) {
13320                                 panic("seg_cnt:%d > max:%d", seg_cnt, if_hw_tsomaxsegcount);
13321                         }
13322                 }
13323 #endif
13324                 /*
13325                  * If we're sending everything we've got, set PUSH. (This
13326                  * will keep happy those implementations which only give
13327                  * data to the user when a buffer fills or a PUSH comes in.)
13328                  */
13329                 if (sb_offset + len == sbused(sb) &&
13330                     sbused(sb) &&
13331                     !(flags & TH_SYN)) {
13332                         flags |= TH_PUSH;
13333                 }
13334                 SOCKBUF_UNLOCK(sb);
13335         } else {
13336                 SOCKBUF_UNLOCK(sb);
13337                 if (tp->t_flags & TF_ACKNOW)
13338                         KMOD_TCPSTAT_INC(tcps_sndacks);
13339                 else if (flags & (TH_SYN | TH_FIN | TH_RST))
13340                         KMOD_TCPSTAT_INC(tcps_sndctrl);
13341                 else
13342                         KMOD_TCPSTAT_INC(tcps_sndwinup);
13343
13344                 m = m_gethdr(M_NOWAIT, MT_DATA);
13345                 if (m == NULL) {
13346                         BBR_STAT_INC(bbr_failed_mbuf_aloc);
13347                         bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13348                         error = ENOBUFS;
13349                         /* Fudge the send time since we could not send */
13350                         sack_rxmit = 0;
13351                         goto out;
13352                 }
13353 #ifdef INET6
13354                 if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
13355                     MHLEN >= hdrlen) {
13356                         M_ALIGN(m, hdrlen);
13357                 } else
13358 #endif
13359                         m->m_data += max_linkhdr;
13360                 m->m_len = hdrlen;
13361         }
13362         SOCKBUF_UNLOCK_ASSERT(sb);
13363         m->m_pkthdr.rcvif = (struct ifnet *)0;
13364 #ifdef MAC
13365         mac_inpcb_create_mbuf(inp, m);
13366 #endif
13367 #ifdef INET6
13368         if (isipv6) {
13369                 ip6 = mtod(m, struct ip6_hdr *);
13370                 if (tp->t_port) {
13371                         udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
13372                         udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13373                         udp->uh_dport = tp->t_port;
13374                         ulen = hdrlen + len - sizeof(struct ip6_hdr);
13375                         udp->uh_ulen = htons(ulen);
13376                         th = (struct tcphdr *)(udp + 1);
13377                 } else {
13378                         th = (struct tcphdr *)(ip6 + 1);
13379                 }
13380                 tcpip_fillheaders(inp, tp->t_port, ip6, th);
13381         } else
13382 #endif                          /* INET6 */
13383         {
13384                 ip = mtod(m, struct ip *);
13385 #ifdef TCPDEBUG
13386                 ipov = (struct ipovly *)ip;
13387 #endif
13388                 if (tp->t_port) {
13389                         udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
13390                         udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13391                         udp->uh_dport = tp->t_port;
13392                         ulen = hdrlen + len - sizeof(struct ip);
13393                         udp->uh_ulen = htons(ulen);
13394                         th = (struct tcphdr *)(udp + 1);
13395                 } else {
13396                         th = (struct tcphdr *)(ip + 1);
13397                 }
13398                 tcpip_fillheaders(inp, tp->t_port, ip, th);
13399         }
13400         /*
13401          * If we are doing retransmissions, then snd_nxt will not reflect
13402          * the first unsent octet.  For ACK only packets, we do not want the
13403          * sequence number of the retransmitted packet, we want the sequence
13404          * number of the next unsent octet.  So, if there is no data (and no
13405          * SYN or FIN), use snd_max instead of snd_nxt when filling in
13406          * ti_seq.  But if we are in persist state, snd_max might reflect
13407          * one byte beyond the right edge of the window, so use snd_nxt in
13408          * that case, since we know we aren't doing a retransmission.
13409          * (retransmit and persist are mutually exclusive...)
13410          */
13411         if (sack_rxmit == 0) {
13412                 if (len && ((flags & (TH_FIN | TH_SYN | TH_RST)) == 0)) {
13413                         /* New data (including new persists) */
13414                         th->th_seq = htonl(tp->snd_max);
13415                         bbr_seq = tp->snd_max;
13416                 } else if (flags & TH_SYN) {
13417                         /* Syn's always send from iss */
13418                         th->th_seq = htonl(tp->iss);
13419                         bbr_seq = tp->iss;
13420                 } else if (flags & TH_FIN) {
13421                         if (flags & TH_FIN && tp->t_flags & TF_SENTFIN) {
13422                                 /*
13423                                  * If we sent the fin already its 1 minus
13424                                  * snd_max
13425                                  */
13426                                 th->th_seq = (htonl(tp->snd_max - 1));
13427                                 bbr_seq = (tp->snd_max - 1);
13428                         } else {
13429                                 /* First time FIN use snd_max */
13430                                 th->th_seq = htonl(tp->snd_max);
13431                                 bbr_seq = tp->snd_max;
13432                         }
13433                 } else {
13434                         /*
13435                          * len == 0 and not persist we use snd_max, sending
13436                          * an ack unless we have sent the fin then its 1
13437                          * minus.
13438                          */
13439                         /*
13440                          * XXXRRS Question if we are in persists and we have
13441                          * nothing outstanding to send and we have not sent
13442                          * a FIN, we will send an ACK. In such a case it
13443                          * might be better to send (tp->snd_una - 1) which
13444                          * would force the peer to ack.
13445                          */
13446                         if (tp->t_flags & TF_SENTFIN) {
13447                                 th->th_seq = htonl(tp->snd_max - 1);
13448                                 bbr_seq = (tp->snd_max - 1);
13449                         } else {
13450                                 th->th_seq = htonl(tp->snd_max);
13451                                 bbr_seq = tp->snd_max;
13452                         }
13453                 }
13454         } else {
13455                 /* All retransmits use the rsm to guide the send */
13456                 th->th_seq = htonl(rsm->r_start);
13457                 bbr_seq = rsm->r_start;
13458         }
13459         th->th_ack = htonl(tp->rcv_nxt);
13460         if (optlen) {
13461                 bcopy(opt, th + 1, optlen);
13462                 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
13463         }
13464         th->th_flags = flags;
13465         /*
13466          * Calculate receive window.  Don't shrink window, but avoid silly
13467          * window syndrome.
13468          */
13469         if ((flags & TH_RST) || ((recwin < (so->so_rcv.sb_hiwat / 4) &&
13470                                   recwin < maxseg)))
13471                 recwin = 0;
13472         if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
13473             recwin < (tp->rcv_adv - tp->rcv_nxt))
13474                 recwin = (tp->rcv_adv - tp->rcv_nxt);
13475         if (recwin > TCP_MAXWIN << tp->rcv_scale)
13476                 recwin = TCP_MAXWIN << tp->rcv_scale;
13477
13478         /*
13479          * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
13480          * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
13481          * handled in syncache.
13482          */
13483         if (flags & TH_SYN)
13484                 th->th_win = htons((u_short)
13485                     (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
13486         else {
13487                 /* Avoid shrinking window with window scaling. */
13488                 recwin = roundup2(recwin, 1 << tp->rcv_scale);
13489                 th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
13490         }
13491         /*
13492          * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
13493          * window.  This may cause the remote transmitter to stall.  This
13494          * flag tells soreceive() to disable delayed acknowledgements when
13495          * draining the buffer.  This can occur if the receiver is
13496          * attempting to read more data than can be buffered prior to
13497          * transmitting on the connection.
13498          */
13499         if (th->th_win == 0) {
13500                 tp->t_sndzerowin++;
13501                 tp->t_flags |= TF_RXWIN0SENT;
13502         } else
13503                 tp->t_flags &= ~TF_RXWIN0SENT;
13504         /*
13505          * We don't support urgent data, but drag along
13506          * the pointer in case of a stack switch.
13507          */
13508         tp->snd_up = tp->snd_una;
13509
13510 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13511         if (to.to_flags & TOF_SIGNATURE) {
13512                 /*
13513                  * Calculate MD5 signature and put it into the place
13514                  * determined before. NOTE: since TCP options buffer doesn't
13515                  * point into mbuf's data, calculate offset and use it.
13516                  */
13517                 if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
13518                     (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
13519                         /*
13520                          * Do not send segment if the calculation of MD5
13521                          * digest has failed.
13522                          */
13523                         goto out;
13524                 }
13525         }
13526 #endif
13527
13528         /*
13529          * Put TCP length in extended header, and then checksum extended
13530          * header and data.
13531          */
13532         m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
13533 #ifdef INET6
13534         if (isipv6) {
13535                 /*
13536                  * ip6_plen is not need to be filled now, and will be filled
13537                  * in ip6_output.
13538                  */
13539                 if (tp->t_port) {
13540                         m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
13541                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13542                         udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
13543                         th->th_sum = htons(0);
13544                         UDPSTAT_INC(udps_opackets);
13545                 } else {
13546                         csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
13547                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13548                         th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
13549                             optlen + len, IPPROTO_TCP, 0);
13550                 }
13551         }
13552 #endif
13553 #if defined(INET6) && defined(INET)
13554         else
13555 #endif
13556 #ifdef INET
13557         {
13558                 if (tp->t_port) {
13559                         m->m_pkthdr.csum_flags = CSUM_UDP;
13560                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13561                         udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
13562                             ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
13563                         th->th_sum = htons(0);
13564                         UDPSTAT_INC(udps_opackets);
13565                 } else {
13566                         csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP;
13567                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13568                         th->th_sum = in_pseudo(ip->ip_src.s_addr,
13569                             ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
13570                             IPPROTO_TCP + len + optlen));
13571                 }
13572                 /* IP version must be set here for ipv4/ipv6 checking later */
13573                 KASSERT(ip->ip_v == IPVERSION,
13574                     ("%s: IP version incorrect: %d", __func__, ip->ip_v));
13575         }
13576 #endif
13577
13578         /*
13579          * Enable TSO and specify the size of the segments. The TCP pseudo
13580          * header checksum is always provided. XXX: Fixme: This is currently
13581          * not the case for IPv6.
13582          */
13583         if (tso) {
13584                 KASSERT(len > maxseg,
13585                     ("%s: len:%d <= tso_segsz:%d", __func__, len, maxseg));
13586                 m->m_pkthdr.csum_flags |= CSUM_TSO;
13587                 csum_flags |= CSUM_TSO;
13588                 m->m_pkthdr.tso_segsz = maxseg;
13589         }
13590         KASSERT(len + hdrlen == m_length(m, NULL),
13591             ("%s: mbuf chain different than expected: %d + %u != %u",
13592             __func__, len, hdrlen, m_length(m, NULL)));
13593
13594 #ifdef TCP_HHOOK
13595         /* Run HHOOK_TC_ESTABLISHED_OUT helper hooks. */
13596         hhook_run_tcp_est_out(tp, th, &to, len, tso);
13597 #endif
13598 #ifdef TCPDEBUG
13599         /*
13600          * Trace.
13601          */
13602         if (so->so_options & SO_DEBUG) {
13603                 u_short save = 0;
13604
13605 #ifdef INET6
13606                 if (!isipv6)
13607 #endif
13608                 {
13609                         save = ipov->ih_len;
13610                         ipov->ih_len = htons(m->m_pkthdr.len    /* - hdrlen +
13611                               * (th->th_off << 2) */ );
13612                 }
13613                 tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
13614 #ifdef INET6
13615                 if (!isipv6)
13616 #endif
13617                         ipov->ih_len = save;
13618         }
13619 #endif                          /* TCPDEBUG */
13620
13621         /* Log to the black box */
13622         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
13623                 union tcp_log_stackspecific log;
13624
13625                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
13626                 /* Record info on type of transmission */
13627                 log.u_bbr.flex1 = bbr->r_ctl.rc_hptsi_agg_delay;
13628                 log.u_bbr.flex2 = (bbr->r_recovery_bw << 3);
13629                 log.u_bbr.flex3 = maxseg;
13630                 log.u_bbr.flex4 = delay_calc;
13631                 /* Encode filled_all into the upper flex5 bit */
13632                 log.u_bbr.flex5 = bbr->rc_past_init_win;
13633                 log.u_bbr.flex5 <<= 1;
13634                 log.u_bbr.flex5 |= bbr->rc_no_pacing;
13635                 log.u_bbr.flex5 <<= 29;
13636                 if (filled_all)
13637                         log.u_bbr.flex5 |= 0x80000000;
13638                 log.u_bbr.flex5 |= tp->t_maxseg;
13639                 log.u_bbr.flex6 = bbr->r_ctl.rc_pace_max_segs;
13640                 log.u_bbr.flex7 = (bbr->rc_bbr_state << 8) | bbr_state_val(bbr);
13641                 /* lets poke in the low and the high here for debugging */
13642                 log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
13643                 if (rsm || sack_rxmit) {
13644                         if (doing_tlp)
13645                                 log.u_bbr.flex8 = 2;
13646                         else
13647                                 log.u_bbr.flex8 = 1;
13648                 } else {
13649                         log.u_bbr.flex8 = 0;
13650                 }
13651                 lgb = tcp_log_event_(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
13652                     len, &log, false, NULL, NULL, 0, tv);
13653         } else {
13654                 lgb = NULL;
13655         }
13656         /*
13657          * Fill in IP length and desired time to live and send to IP level.
13658          * There should be a better way to handle ttl and tos; we could keep
13659          * them in the template, but need a way to checksum without them.
13660          */
13661         /*
13662          * m->m_pkthdr.len should have been set before cksum calcuration,
13663          * because in6_cksum() need it.
13664          */
13665 #ifdef INET6
13666         if (isipv6) {
13667                 /*
13668                  * we separately set hoplimit for every segment, since the
13669                  * user might want to change the value via setsockopt. Also,
13670                  * desired default hop limit might be changed via Neighbor
13671                  * Discovery.
13672                  */
13673                 ip6->ip6_hlim = in6_selecthlim(inp, NULL);
13674
13675                 /*
13676                  * Set the packet size here for the benefit of DTrace
13677                  * probes. ip6_output() will set it properly; it's supposed
13678                  * to include the option header lengths as well.
13679                  */
13680                 ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
13681
13682                 if (V_path_mtu_discovery && maxseg > V_tcp_minmss)
13683                         tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13684                 else
13685                         tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13686
13687                 if (tp->t_state == TCPS_SYN_SENT)
13688                         TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
13689
13690                 TCP_PROBE5(send, NULL, tp, ip6, tp, th);
13691                 /* TODO: IPv6 IP6TOS_ECT bit on */
13692                 error = ip6_output(m, inp->in6p_outputopts,
13693                     &inp->inp_route6,
13694                     ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
13695                     NULL, NULL, inp);
13696
13697                 if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
13698                         mtu = inp->inp_route6.ro_nh->nh_mtu;
13699         }
13700 #endif                          /* INET6 */
13701 #if defined(INET) && defined(INET6)
13702         else
13703 #endif
13704 #ifdef INET
13705         {
13706                 ip->ip_len = htons(m->m_pkthdr.len);
13707 #ifdef INET6
13708                 if (isipv6)
13709                         ip->ip_ttl = in6_selecthlim(inp, NULL);
13710 #endif                          /* INET6 */
13711                 /*
13712                  * If we do path MTU discovery, then we set DF on every
13713                  * packet. This might not be the best thing to do according
13714                  * to RFC3390 Section 2. However the tcp hostcache migitates
13715                  * the problem so it affects only the first tcp connection
13716                  * with a host.
13717                  *
13718                  * NB: Don't set DF on small MTU/MSS to have a safe
13719                  * fallback.
13720                  */
13721                 if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
13722                         tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13723                         if (tp->t_port == 0 || len < V_tcp_minmss) {
13724                                 ip->ip_off |= htons(IP_DF);
13725                         }
13726                 } else {
13727                         tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13728                 }
13729
13730                 if (tp->t_state == TCPS_SYN_SENT)
13731                         TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
13732
13733                 TCP_PROBE5(send, NULL, tp, ip, tp, th);
13734
13735                 error = ip_output(m, inp->inp_options, &inp->inp_route,
13736                     ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
13737                     inp);
13738                 if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
13739                         mtu = inp->inp_route.ro_nh->nh_mtu;
13740         }
13741 #endif                          /* INET */
13742 out:
13743
13744         if (lgb) {
13745                 lgb->tlb_errno = error;
13746                 lgb = NULL;
13747         }
13748         /*
13749          * In transmit state, time the transmission and arrange for the
13750          * retransmit.  In persist state, just set snd_max.
13751          */
13752         if (error == 0) {
13753                 tcp_account_for_send(tp, len, (rsm != NULL), doing_tlp);
13754                 if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13755                     (tp->t_flags & TF_SACK_PERMIT) &&
13756                     tp->rcv_numsacks > 0)
13757                         tcp_clean_dsack_blocks(tp);
13758                 /* We sent an ack clear the bbr_segs_rcvd count */
13759                 bbr->output_error_seen = 0;
13760                 bbr->oerror_cnt = 0;
13761                 bbr->bbr_segs_rcvd = 0;
13762                 if (len == 0)
13763                         counter_u64_add(bbr_out_size[TCP_MSS_ACCT_SNDACK], 1);
13764                 /* Do accounting for new sends */
13765                 if ((len > 0) && (rsm == NULL)) {
13766                         int idx;
13767                         if (tp->snd_una == tp->snd_max) {
13768                                 /*
13769                                  * Special case to match google, when
13770                                  * nothing is in flight the delivered
13771                                  * time does get updated to the current
13772                                  * time (see tcp_rate_bsd.c).
13773                                  */
13774                                 bbr->r_ctl.rc_del_time = cts;
13775                         }
13776                         if (len >= maxseg) {
13777                                 idx = (len / maxseg) + 3;
13778                                 if (idx >= TCP_MSS_ACCT_ATIMER)
13779                                         counter_u64_add(bbr_out_size[(TCP_MSS_ACCT_ATIMER - 1)], 1);
13780                                 else
13781                                         counter_u64_add(bbr_out_size[idx], 1);
13782                         } else {
13783                                 /* smaller than a MSS */
13784                                 idx = len / (bbr_hptsi_bytes_min - bbr->rc_last_options);
13785                                 if (idx >= TCP_MSS_SMALL_MAX_SIZE_DIV)
13786                                         idx = (TCP_MSS_SMALL_MAX_SIZE_DIV - 1);
13787                                 counter_u64_add(bbr_out_size[(idx + TCP_MSS_SMALL_SIZE_OFF)], 1);
13788                         }
13789                 }
13790         }
13791         abandon = 0;
13792         /*
13793          * We must do the send accounting before we log the output,
13794          * otherwise the state of the rsm could change and we account to the
13795          * wrong bucket.
13796          */
13797         if (len > 0) {
13798                 bbr_do_send_accounting(tp, bbr, rsm, len, error);
13799                 if (error == 0) {
13800                         if (tp->snd_una == tp->snd_max)
13801                                 bbr->r_ctl.rc_tlp_rxt_last_time = cts;
13802                 }
13803         }
13804         bbr_log_output(bbr, tp, &to, len, bbr_seq, (uint8_t) flags, error,
13805             cts, mb, &abandon, rsm, 0, sb);
13806         if (abandon) {
13807                 /*
13808                  * If bbr_log_output destroys the TCB or sees a TH_RST being
13809                  * sent we should hit this condition.
13810                  */
13811                 return (0);
13812         }
13813         if (bbr->rc_in_persist == 0) {
13814                 /*
13815                  * Advance snd_nxt over sequence space of this segment.
13816                  */
13817                 if (error)
13818                         /* We don't log or do anything with errors */
13819                         goto skip_upd;
13820
13821                 if (tp->snd_una == tp->snd_max &&
13822                     (len || (flags & (TH_SYN | TH_FIN)))) {
13823                         /*
13824                          * Update the time we just added data since none was
13825                          * outstanding.
13826                          */
13827                         bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13828                         bbr->rc_tp->t_acktime  = ticks;
13829                 }
13830                 if (flags & (TH_SYN | TH_FIN) && (rsm == NULL)) {
13831                         if (flags & TH_SYN) {
13832                                 /*
13833                                  * Smack the snd_max to iss + 1
13834                                  * if its a FO we will add len below.
13835                                  */
13836                                 tp->snd_max = tp->iss + 1;
13837                         }
13838                         if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13839                                 tp->snd_max++;
13840                                 tp->t_flags |= TF_SENTFIN;
13841                         }
13842                 }
13843                 if (sack_rxmit == 0)
13844                         tp->snd_max += len;
13845 skip_upd:
13846                 if ((error == 0) && len)
13847                         tot_len += len;
13848         } else {
13849                 /* Persists case */
13850                 int32_t xlen = len;
13851
13852                 if (error)
13853                         goto nomore;
13854
13855                 if (flags & TH_SYN)
13856                         ++xlen;
13857                 if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13858                         ++xlen;
13859                         tp->t_flags |= TF_SENTFIN;
13860                 }
13861                 if (xlen && (tp->snd_una == tp->snd_max)) {
13862                         /*
13863                          * Update the time we just added data since none was
13864                          * outstanding.
13865                          */
13866                         bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13867                         bbr->rc_tp->t_acktime = ticks;
13868                 }
13869                 if (sack_rxmit == 0)
13870                         tp->snd_max += xlen;
13871                 tot_len += (len + optlen + ipoptlen);
13872         }
13873 nomore:
13874         if (error) {
13875                 /*
13876                  * Failures do not advance the seq counter above. For the
13877                  * case of ENOBUFS we will fall out and become ack-clocked.
13878                  * capping the cwnd at the current flight.
13879                  * Everything else will just have to retransmit with the timer
13880                  * (no pacer).
13881                  */
13882                 SOCKBUF_UNLOCK_ASSERT(sb);
13883                 BBR_STAT_INC(bbr_saw_oerr);
13884                 /* Clear all delay/early tracks */
13885                 bbr->r_ctl.rc_hptsi_agg_delay = 0;
13886                 bbr->r_ctl.rc_agg_early = 0;
13887                 bbr->r_agg_early_set = 0;
13888                 bbr->output_error_seen = 1;
13889                 if (bbr->oerror_cnt < 0xf)
13890                         bbr->oerror_cnt++;
13891                 if (bbr_max_net_error_cnt && (bbr->oerror_cnt >= bbr_max_net_error_cnt)) {
13892                         /* drop the session */
13893                         tcp_set_inp_to_drop(inp, ENETDOWN);
13894                 }
13895                 switch (error) {
13896                 case ENOBUFS:
13897                         /*
13898                          * Make this guy have to get ack's to send
13899                          * more but lets make sure we don't
13900                          * slam him below a T-O (1MSS).
13901                          */
13902                         if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
13903                                 tp->snd_cwnd = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13904                                                                     bbr->r_ctl.rc_lost_bytes)) - maxseg;
13905                                 if (tp->snd_cwnd < maxseg)
13906                                         tp->snd_cwnd = maxseg;
13907                         }
13908                         slot = (bbr_error_base_paceout + 1) << bbr->oerror_cnt;
13909                         BBR_STAT_INC(bbr_saw_enobuf);
13910                         if (bbr->bbr_hdrw_pacing)
13911                                 counter_u64_add(bbr_hdwr_pacing_enobuf, 1);
13912                         else
13913                                 counter_u64_add(bbr_nohdwr_pacing_enobuf, 1);
13914                         /*
13915                          * Here even in the enobuf's case we want to do our
13916                          * state update. The reason being we may have been
13917                          * called by the input function. If so we have had
13918                          * things change.
13919                          */
13920                         error = 0;
13921                         goto enobufs;
13922                 case EMSGSIZE:
13923                         /*
13924                          * For some reason the interface we used initially
13925                          * to send segments changed to another or lowered
13926                          * its MTU. If TSO was active we either got an
13927                          * interface without TSO capabilits or TSO was
13928                          * turned off. If we obtained mtu from ip_output()
13929                          * then update it and try again.
13930                          */
13931                         /* Turn on tracing (or try to) */
13932                         {
13933                                 int old_maxseg;
13934
13935                                 old_maxseg = tp->t_maxseg;
13936                                 BBR_STAT_INC(bbr_saw_emsgsiz);
13937                                 bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, csum_flags, tso, cts);
13938                                 if (mtu != 0)
13939                                         tcp_mss_update(tp, -1, mtu, NULL, NULL);
13940                                 if (old_maxseg <= tp->t_maxseg) {
13941                                         /* Huh it did not shrink? */
13942                                         tp->t_maxseg = old_maxseg - 40;
13943                                         bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
13944                                 }
13945                                 /*
13946                                  * Nuke all other things that can interfere
13947                                  * with slot
13948                                  */
13949                                 if ((tot_len + len) && (len >= tp->t_maxseg)) {
13950                                         slot = bbr_get_pacing_delay(bbr,
13951                                             bbr->r_ctl.rc_bbr_hptsi_gain,
13952                                             (tot_len + len), cts, 0);
13953                                         if (slot < bbr_error_base_paceout)
13954                                                 slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13955                                 } else
13956                                         slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13957                                 bbr->rc_output_starts_timer = 1;
13958                                 bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
13959                                     tot_len);
13960                                 return (error);
13961                         }
13962                 case EPERM:
13963                         tp->t_softerror = error;
13964                         /* Fall through */
13965                 case EHOSTDOWN:
13966                 case EHOSTUNREACH:
13967                 case ENETDOWN:
13968                 case ENETUNREACH:
13969                         if (TCPS_HAVERCVDSYN(tp->t_state)) {
13970                                 tp->t_softerror = error;
13971                         }
13972                         /* FALLTHROUGH */
13973                 default:
13974                         slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
13975                         bbr->rc_output_starts_timer = 1;
13976                         bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
13977                         return (error);
13978                 }
13979 #ifdef STATS
13980         } else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
13981                     len &&
13982                     (rsm == NULL) &&
13983             (bbr->rc_in_persist == 0)) {
13984                 tp->gput_seq = bbr_seq;
13985                 tp->gput_ack = bbr_seq +
13986                     min(sbavail(&so->so_snd) - sb_offset, sendwin);
13987                 tp->gput_ts = cts;
13988                 tp->t_flags |= TF_GPUTINPROG;
13989 #endif
13990         }
13991         KMOD_TCPSTAT_INC(tcps_sndtotal);
13992         if ((bbr->bbr_hdw_pace_ena) &&
13993             (bbr->bbr_attempt_hdwr_pace == 0) &&
13994             (bbr->rc_past_init_win) &&
13995             (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
13996             (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
13997             (inp->inp_route.ro_nh &&
13998              inp->inp_route.ro_nh->nh_ifp)) {
13999                 /*
14000                  * We are past the initial window and
14001                  * have at least one measurement so we
14002                  * could use hardware pacing if its available.
14003                  * We have an interface and we have not attempted
14004                  * to setup hardware pacing, lets try to now.
14005                  */
14006                 uint64_t rate_wanted;
14007                 int err = 0;
14008
14009                 rate_wanted = bbr_get_hardware_rate(bbr);
14010                 bbr->bbr_attempt_hdwr_pace = 1;
14011                 bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp,
14012                                                       inp->inp_route.ro_nh->nh_ifp,
14013                                                       rate_wanted,
14014                                                       (RS_PACING_GEQ|RS_PACING_SUB_OK),
14015                                                       &err, NULL);
14016                 if (bbr->r_ctl.crte) {
14017                         bbr_type_log_hdwr_pacing(bbr,
14018                                                  bbr->r_ctl.crte->ptbl->rs_ifp,
14019                                                  rate_wanted,
14020                                                  bbr->r_ctl.crte->rate,
14021                                                  __LINE__, cts, err);
14022                         BBR_STAT_INC(bbr_hdwr_rl_add_ok);
14023                         counter_u64_add(bbr_flows_nohdwr_pacing, -1);
14024                         counter_u64_add(bbr_flows_whdwr_pacing, 1);
14025                         bbr->bbr_hdrw_pacing = 1;
14026                         /* Now what is our gain status? */
14027                         if (bbr->r_ctl.crte->rate < rate_wanted) {
14028                                 /* We have a problem */
14029                                 bbr_setup_less_of_rate(bbr, cts,
14030                                                        bbr->r_ctl.crte->rate, rate_wanted);
14031                         } else {
14032                                 /* We are good */
14033                                 bbr->gain_is_limited = 0;
14034                                 bbr->skip_gain = 0;
14035                         }
14036                         tcp_bbr_tso_size_check(bbr, cts);
14037                 } else {
14038                         bbr_type_log_hdwr_pacing(bbr,
14039                                                  inp->inp_route.ro_nh->nh_ifp,
14040                                                  rate_wanted,
14041                                                  0,
14042                                                  __LINE__, cts, err);
14043                         BBR_STAT_INC(bbr_hdwr_rl_add_fail);
14044                 }
14045         }
14046         if (bbr->bbr_hdrw_pacing) {
14047                 /*
14048                  * Worry about cases where the route
14049                  * changes or something happened that we
14050                  * lost our hardware pacing possibly during
14051                  * the last ip_output call.
14052                  */
14053                 if (inp->inp_snd_tag == NULL) {
14054                         /* A change during ip output disabled hw pacing? */
14055                         bbr->bbr_hdrw_pacing = 0;
14056                 } else if ((inp->inp_route.ro_nh == NULL) ||
14057                     (inp->inp_route.ro_nh->nh_ifp != inp->inp_snd_tag->ifp)) {
14058                         /*
14059                          * We had an interface or route change,
14060                          * detach from the current hdwr pacing
14061                          * and setup to re-attempt next go
14062                          * round.
14063                          */
14064                         bbr->bbr_hdrw_pacing = 0;
14065                         bbr->bbr_attempt_hdwr_pace = 0;
14066                         tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
14067                         tcp_bbr_tso_size_check(bbr, cts);
14068                 }
14069         }
14070         /*
14071          * Data sent (as far as we can tell). If this advertises a larger
14072          * window than any other segment, then remember the size of the
14073          * advertised window. Any pending ACK has now been sent.
14074          */
14075         if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
14076                 tp->rcv_adv = tp->rcv_nxt + recwin;
14077
14078         tp->last_ack_sent = tp->rcv_nxt;
14079         if ((error == 0) &&
14080             (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
14081             (doing_tlp == 0) &&
14082             (tso == 0) &&
14083             (len > 0) &&
14084             ((flags & TH_RST) == 0) &&
14085             ((flags & TH_SYN) == 0) &&
14086             (IN_RECOVERY(tp->t_flags) == 0) &&
14087             (bbr->rc_in_persist == 0) &&
14088             (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
14089                 /*
14090                  * For non-tso we need to goto again until we have sent out
14091                  * enough data to match what we are hptsi out every hptsi
14092                  * interval.
14093                  */
14094                 if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14095                         /* Make sure snd_nxt is drug up */
14096                         tp->snd_nxt = tp->snd_max;
14097                 }
14098                 if (rsm != NULL) {
14099                         rsm = NULL;
14100                         goto skip_again;
14101                 }
14102                 rsm = NULL;
14103                 sack_rxmit = 0;
14104                 tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
14105                 goto again;
14106         }
14107 skip_again:
14108         if ((error == 0) && (flags & TH_FIN))
14109                 tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
14110         if ((error == 0) && (flags & TH_RST))
14111                 tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
14112         if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
14113                 /*
14114                  * Calculate/Re-Calculate the hptsi slot in usecs based on
14115                  * what we have sent so far
14116                  */
14117                 slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
14118                 if (bbr->rc_no_pacing)
14119                         slot = 0;
14120         }
14121         tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
14122 enobufs:
14123         if (bbr->rc_use_google == 0)
14124                 bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
14125         bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
14126                                                         bbr->r_ctl.rc_lost_bytes)));
14127         bbr->rc_output_starts_timer = 1;
14128         if (bbr->bbr_use_rack_cheat &&
14129             (more_to_rxt ||
14130              ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
14131                 /* Rack cheats and shotguns out all rxt's 1ms apart */
14132                 if (slot > 1000)
14133                         slot = 1000;
14134         }
14135         if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
14136                 /*
14137                  * We don't change the tso size until some number of sends
14138                  * to give the hardware commands time to get down
14139                  * to the interface.
14140                  */
14141                 bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
14142                 if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
14143                         bbr->hw_pacing_set = 1;
14144                         tcp_bbr_tso_size_check(bbr, cts);
14145                 }
14146         }
14147         bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
14148         if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14149                 /* Make sure snd_nxt is drug up */
14150                 tp->snd_nxt = tp->snd_max;
14151         }
14152         return (error);
14153
14154 }
14155
14156 /*
14157  * See bbr_output_wtime() for return values.
14158  */
14159 static int
14160 bbr_output(struct tcpcb *tp)
14161 {
14162         int32_t ret;
14163         struct timeval tv;
14164         struct tcp_bbr *bbr;
14165
14166         NET_EPOCH_ASSERT();
14167
14168         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14169         INP_WLOCK_ASSERT(tp->t_inpcb);
14170         (void)tcp_get_usecs(&tv);
14171         ret = bbr_output_wtime(tp, &tv);
14172         return (ret);
14173 }
14174
14175 static void
14176 bbr_mtu_chg(struct tcpcb *tp)
14177 {
14178         struct tcp_bbr *bbr;
14179         struct bbr_sendmap *rsm, *frsm = NULL;
14180         uint32_t maxseg;
14181
14182         /*
14183          * The MTU has changed. a) Clear the sack filter. b) Mark everything
14184          * over the current size as SACK_PASS so a retransmit will occur.
14185          */
14186
14187         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14188         maxseg = tp->t_maxseg - bbr->rc_last_options;
14189         sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14190         TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14191                 /* Don't mess with ones acked (by sack?) */
14192                 if (rsm->r_flags & BBR_ACKED)
14193                         continue;
14194                 if ((rsm->r_end - rsm->r_start) > maxseg) {
14195                         /*
14196                          * We mark sack-passed on all the previous large
14197                          * sends we did. This will force them to retransmit.
14198                          */
14199                         rsm->r_flags |= BBR_SACK_PASSED;
14200                         if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14201                             bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14202                                 bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14203                                 bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14204                                 rsm->r_flags |= BBR_MARKED_LOST;
14205                         }
14206                         if (frsm == NULL)
14207                                 frsm = rsm;
14208                 }
14209         }
14210         if (frsm) {
14211                 bbr->r_ctl.rc_resend = frsm;
14212         }
14213 }
14214
14215 static int
14216 bbr_pru_options(struct tcpcb *tp, int flags)
14217 {
14218         if (flags & PRUS_OOB)
14219                 return (EOPNOTSUPP);
14220         return (0);
14221 }
14222
14223 struct tcp_function_block __tcp_bbr = {
14224         .tfb_tcp_block_name = __XSTRING(STACKNAME),
14225         .tfb_tcp_output = bbr_output,
14226         .tfb_do_queued_segments = ctf_do_queued_segments,
14227         .tfb_do_segment_nounlock = bbr_do_segment_nounlock,
14228         .tfb_tcp_do_segment = bbr_do_segment,
14229         .tfb_tcp_ctloutput = bbr_ctloutput,
14230         .tfb_tcp_fb_init = bbr_init,
14231         .tfb_tcp_fb_fini = bbr_fini,
14232         .tfb_tcp_timer_stop_all = bbr_stopall,
14233         .tfb_tcp_timer_activate = bbr_timer_activate,
14234         .tfb_tcp_timer_active = bbr_timer_active,
14235         .tfb_tcp_timer_stop = bbr_timer_stop,
14236         .tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
14237         .tfb_tcp_handoff_ok = bbr_handoff_ok,
14238         .tfb_tcp_mtu_chg = bbr_mtu_chg,
14239         .tfb_pru_options = bbr_pru_options,
14240 };
14241
14242 /*
14243  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14244  * socket option arguments.  When it re-acquires the lock after the copy, it
14245  * has to revalidate that the connection is still valid for the socket
14246  * option.
14247  */
14248 static int
14249 bbr_set_sockopt(struct socket *so, struct sockopt *sopt,
14250                 struct inpcb *inp, struct tcpcb *tp, struct tcp_bbr *bbr)
14251 {
14252         struct epoch_tracker et;
14253         int32_t error = 0, optval;
14254
14255         switch (sopt->sopt_name) {
14256         case TCP_RACK_PACE_MAX_SEG:
14257         case TCP_RACK_MIN_TO:
14258         case TCP_RACK_REORD_THRESH:
14259         case TCP_RACK_REORD_FADE:
14260         case TCP_RACK_TLP_THRESH:
14261         case TCP_RACK_PKT_DELAY:
14262         case TCP_BBR_ALGORITHM:
14263         case TCP_BBR_TSLIMITS:
14264         case TCP_BBR_IWINTSO:
14265         case TCP_BBR_RECFORCE:
14266         case TCP_BBR_STARTUP_PG:
14267         case TCP_BBR_DRAIN_PG:
14268         case TCP_BBR_RWND_IS_APP:
14269         case TCP_BBR_PROBE_RTT_INT:
14270         case TCP_BBR_PROBE_RTT_GAIN:
14271         case TCP_BBR_PROBE_RTT_LEN:
14272         case TCP_BBR_STARTUP_LOSS_EXIT:
14273         case TCP_BBR_USEDEL_RATE:
14274         case TCP_BBR_MIN_RTO:
14275         case TCP_BBR_MAX_RTO:
14276         case TCP_BBR_PACE_PER_SEC:
14277         case TCP_DELACK:
14278         case TCP_BBR_PACE_DEL_TAR:
14279         case TCP_BBR_SEND_IWND_IN_TSO:
14280         case TCP_BBR_EXTRA_STATE:
14281         case TCP_BBR_UTTER_MAX_TSO:
14282         case TCP_BBR_MIN_TOPACEOUT:
14283         case TCP_BBR_FLOOR_MIN_TSO:
14284         case TCP_BBR_TSTMP_RAISES:
14285         case TCP_BBR_POLICER_DETECT:
14286         case TCP_BBR_USE_RACK_CHEAT:
14287         case TCP_DATA_AFTER_CLOSE:
14288         case TCP_BBR_HDWR_PACE:
14289         case TCP_BBR_PACE_SEG_MAX:
14290         case TCP_BBR_PACE_SEG_MIN:
14291         case TCP_BBR_PACE_CROSS:
14292         case TCP_BBR_PACE_OH:
14293 #ifdef NETFLIX_PEAKRATE
14294         case TCP_MAXPEAKRATE:
14295 #endif
14296         case TCP_BBR_TMR_PACE_OH:
14297         case TCP_BBR_RACK_RTT_USE:
14298         case TCP_BBR_RETRAN_WTSO:
14299                 break;
14300         default:
14301                 return (tcp_default_ctloutput(so, sopt, inp, tp));
14302                 break;
14303         }
14304         INP_WUNLOCK(inp);
14305         error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14306         if (error)
14307                 return (error);
14308         INP_WLOCK(inp);
14309         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
14310                 INP_WUNLOCK(inp);
14311                 return (ECONNRESET);
14312         }
14313         tp = intotcpcb(inp);
14314         if (tp->t_fb != &__tcp_bbr) {
14315                 INP_WUNLOCK(inp);
14316                 return (ENOPROTOOPT);
14317         }
14318         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14319         switch (sopt->sopt_name) {
14320         case TCP_BBR_PACE_PER_SEC:
14321                 BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14322                 bbr->r_ctl.bbr_hptsi_per_second = optval;
14323                 break;
14324         case TCP_BBR_PACE_DEL_TAR:
14325                 BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14326                 bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14327                 break;
14328         case TCP_BBR_PACE_SEG_MAX:
14329                 BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14330                 bbr->r_ctl.bbr_hptsi_segments_max = optval;
14331                 break;
14332         case TCP_BBR_PACE_SEG_MIN:
14333                 BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14334                 bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14335                 break;
14336         case TCP_BBR_PACE_CROSS:
14337                 BBR_OPTS_INC(tcp_bbr_pace_cross);
14338                 bbr->r_ctl.bbr_cross_over = optval;
14339                 break;
14340         case TCP_BBR_ALGORITHM:
14341                 BBR_OPTS_INC(tcp_bbr_algorithm);
14342                 if (optval && (bbr->rc_use_google == 0)) {
14343                         /* Turn on the google mode */
14344                         bbr_google_mode_on(bbr);
14345                         if ((optval > 3) && (optval < 500)) {
14346                                 /*
14347                                  * Must be at least greater than .3%
14348                                  * and must be less than 50.0%.
14349                                  */
14350                                 bbr->r_ctl.bbr_google_discount = optval;
14351                         }
14352                 } else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14353                         /* Turn off the google mode */
14354                         bbr_google_mode_off(bbr);
14355                 }
14356                 break;
14357         case TCP_BBR_TSLIMITS:
14358                 BBR_OPTS_INC(tcp_bbr_tslimits);
14359                 if (optval == 1)
14360                         bbr->rc_use_ts_limit = 1;
14361                 else if (optval == 0)
14362                         bbr->rc_use_ts_limit = 0;
14363                 else
14364                         error = EINVAL;
14365                 break;
14366
14367         case TCP_BBR_IWINTSO:
14368                 BBR_OPTS_INC(tcp_bbr_iwintso);
14369                 if ((optval >= 0) && (optval < 128)) {
14370                         uint32_t twin;
14371
14372                         bbr->rc_init_win = optval;
14373                         twin = bbr_initial_cwnd(bbr, tp);
14374                         if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14375                                 tp->snd_cwnd = twin;
14376                         else
14377                                 error = EBUSY;
14378                 } else
14379                         error = EINVAL;
14380                 break;
14381         case TCP_BBR_STARTUP_PG:
14382                 BBR_OPTS_INC(tcp_bbr_startup_pg);
14383                 if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14384                         bbr->r_ctl.rc_startup_pg = optval;
14385                         if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14386                                 bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14387                         }
14388                 } else
14389                         error = EINVAL;
14390                 break;
14391         case TCP_BBR_DRAIN_PG:
14392                 BBR_OPTS_INC(tcp_bbr_drain_pg);
14393                 if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14394                         bbr->r_ctl.rc_drain_pg = optval;
14395                 else
14396                         error = EINVAL;
14397                 break;
14398         case TCP_BBR_PROBE_RTT_LEN:
14399                 BBR_OPTS_INC(tcp_bbr_probertt_len);
14400                 if (optval <= 1)
14401                         reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14402                 else
14403                         error = EINVAL;
14404                 break;
14405         case TCP_BBR_PROBE_RTT_GAIN:
14406                 BBR_OPTS_INC(tcp_bbr_probertt_gain);
14407                 if (optval <= BBR_UNIT)
14408                         bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14409                 else
14410                         error = EINVAL;
14411                 break;
14412         case TCP_BBR_PROBE_RTT_INT:
14413                 BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14414                 if (optval > 1000)
14415                         bbr->r_ctl.rc_probertt_int = optval;
14416                 else
14417                         error = EINVAL;
14418                 break;
14419         case TCP_BBR_MIN_TOPACEOUT:
14420                 BBR_OPTS_INC(tcp_bbr_topaceout);
14421                 if (optval == 0) {
14422                         bbr->no_pacing_until = 0;
14423                         bbr->rc_no_pacing = 0;
14424                 } else if (optval <= 0x00ff) {
14425                         bbr->no_pacing_until = optval;
14426                         if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14427                             (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14428                                 /* Turn on no pacing */
14429                                 bbr->rc_no_pacing = 1;
14430                         }
14431                 } else
14432                         error = EINVAL;
14433                 break;
14434         case TCP_BBR_STARTUP_LOSS_EXIT:
14435                 BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14436                 bbr->rc_loss_exit = optval;
14437                 break;
14438         case TCP_BBR_USEDEL_RATE:
14439                 error = EINVAL;
14440                 break;
14441         case TCP_BBR_MIN_RTO:
14442                 BBR_OPTS_INC(tcp_bbr_min_rto);
14443                 bbr->r_ctl.rc_min_rto_ms = optval;
14444                 break;
14445         case TCP_BBR_MAX_RTO:
14446                 BBR_OPTS_INC(tcp_bbr_max_rto);
14447                 bbr->rc_max_rto_sec = optval;
14448                 break;
14449         case TCP_RACK_MIN_TO:
14450                 /* Minimum time between rack t-o's in ms */
14451                 BBR_OPTS_INC(tcp_rack_min_to);
14452                 bbr->r_ctl.rc_min_to = optval;
14453                 break;
14454         case TCP_RACK_REORD_THRESH:
14455                 /* RACK reorder threshold (shift amount) */
14456                 BBR_OPTS_INC(tcp_rack_reord_thresh);
14457                 if ((optval > 0) && (optval < 31))
14458                         bbr->r_ctl.rc_reorder_shift = optval;
14459                 else
14460                         error = EINVAL;
14461                 break;
14462         case TCP_RACK_REORD_FADE:
14463                 /* Does reordering fade after ms time */
14464                 BBR_OPTS_INC(tcp_rack_reord_fade);
14465                 bbr->r_ctl.rc_reorder_fade = optval;
14466                 break;
14467         case TCP_RACK_TLP_THRESH:
14468                 /* RACK TLP theshold i.e. srtt+(srtt/N) */
14469                 BBR_OPTS_INC(tcp_rack_tlp_thresh);
14470                 if (optval)
14471                         bbr->rc_tlp_threshold = optval;
14472                 else
14473                         error = EINVAL;
14474                 break;
14475         case TCP_BBR_USE_RACK_CHEAT:
14476                 BBR_OPTS_INC(tcp_use_rackcheat);
14477                 if (bbr->rc_use_google) {
14478                         error = EINVAL;
14479                         break;
14480                 }
14481                 BBR_OPTS_INC(tcp_rack_cheat);
14482                 if (optval)
14483                         bbr->bbr_use_rack_cheat = 1;
14484                 else
14485                         bbr->bbr_use_rack_cheat = 0;
14486                 break;
14487         case TCP_BBR_FLOOR_MIN_TSO:
14488                 BBR_OPTS_INC(tcp_utter_max_tso);
14489                 if ((optval >= 0) && (optval < 40))
14490                         bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14491                 else
14492                         error = EINVAL;
14493                 break;
14494         case TCP_BBR_UTTER_MAX_TSO:
14495                 BBR_OPTS_INC(tcp_utter_max_tso);
14496                 if ((optval >= 0) && (optval < 0xffff))
14497                         bbr->r_ctl.bbr_utter_max = optval;
14498                 else
14499                         error = EINVAL;
14500                 break;
14501
14502         case TCP_BBR_EXTRA_STATE:
14503                 BBR_OPTS_INC(tcp_extra_state);
14504                 if (optval)
14505                         bbr->rc_use_idle_restart = 1;
14506                 else
14507                         bbr->rc_use_idle_restart = 0;
14508                 break;
14509         case TCP_BBR_SEND_IWND_IN_TSO:
14510                 BBR_OPTS_INC(tcp_iwnd_tso);
14511                 if (optval) {
14512                         bbr->bbr_init_win_cheat = 1;
14513                         if (bbr->rc_past_init_win == 0) {
14514                                 uint32_t cts;
14515                                 cts = tcp_get_usecs(&bbr->rc_tv);
14516                                 tcp_bbr_tso_size_check(bbr, cts);
14517                         }
14518                 } else
14519                         bbr->bbr_init_win_cheat = 0;
14520                 break;
14521         case TCP_BBR_HDWR_PACE:
14522                 BBR_OPTS_INC(tcp_hdwr_pacing);
14523                 if (optval){
14524                         bbr->bbr_hdw_pace_ena = 1;
14525                         bbr->bbr_attempt_hdwr_pace = 0;
14526                 } else {
14527                         bbr->bbr_hdw_pace_ena = 0;
14528 #ifdef RATELIMIT
14529                         if (bbr->r_ctl.crte != NULL) {
14530                                 tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
14531                                 bbr->r_ctl.crte = NULL;
14532                         }
14533 #endif
14534                 }
14535                 break;
14536
14537         case TCP_DELACK:
14538                 BBR_OPTS_INC(tcp_delack);
14539                 if (optval < 100) {
14540                         if (optval == 0) /* off */
14541                                 tp->t_delayed_ack = 0;
14542                         else if (optval == 1) /* on which is 2 */
14543                                 tp->t_delayed_ack = 2;
14544                         else /* higher than 2 and less than 100 */
14545                                 tp->t_delayed_ack = optval;
14546                         if (tp->t_flags & TF_DELACK) {
14547                                 tp->t_flags &= ~TF_DELACK;
14548                                 tp->t_flags |= TF_ACKNOW;
14549                                 NET_EPOCH_ENTER(et);
14550                                 bbr_output(tp);
14551                                 NET_EPOCH_EXIT(et);
14552                         }
14553                 } else
14554                         error = EINVAL;
14555                 break;
14556         case TCP_RACK_PKT_DELAY:
14557                 /* RACK added ms i.e. rack-rtt + reord + N */
14558                 BBR_OPTS_INC(tcp_rack_pkt_delay);
14559                 bbr->r_ctl.rc_pkt_delay = optval;
14560                 break;
14561 #ifdef NETFLIX_PEAKRATE
14562         case TCP_MAXPEAKRATE:
14563                 BBR_OPTS_INC(tcp_maxpeak);
14564                 error = tcp_set_maxpeakrate(tp, optval);
14565                 if (!error)
14566                         tp->t_peakrate_thr = tp->t_maxpeakrate;
14567                 break;
14568 #endif
14569         case TCP_BBR_RETRAN_WTSO:
14570                 BBR_OPTS_INC(tcp_retran_wtso);
14571                 if (optval)
14572                         bbr->rc_resends_use_tso = 1;
14573                 else
14574                         bbr->rc_resends_use_tso = 0;
14575                 break;
14576         case TCP_DATA_AFTER_CLOSE:
14577                 BBR_OPTS_INC(tcp_data_ac);
14578                 if (optval)
14579                         bbr->rc_allow_data_af_clo = 1;
14580                 else
14581                         bbr->rc_allow_data_af_clo = 0;
14582                 break;
14583         case TCP_BBR_POLICER_DETECT:
14584                 BBR_OPTS_INC(tcp_policer_det);
14585                 if (bbr->rc_use_google == 0)
14586                         error = EINVAL;
14587                 else if (optval)
14588                         bbr->r_use_policer = 1;
14589                 else
14590                         bbr->r_use_policer = 0;
14591                 break;
14592
14593         case TCP_BBR_TSTMP_RAISES:
14594                 BBR_OPTS_INC(tcp_ts_raises);
14595                 if (optval)
14596                         bbr->ts_can_raise = 1;
14597                 else
14598                         bbr->ts_can_raise = 0;
14599                 break;
14600         case TCP_BBR_TMR_PACE_OH:
14601                 BBR_OPTS_INC(tcp_pacing_oh_tmr);
14602                 if (bbr->rc_use_google) {
14603                         error = EINVAL;
14604                 } else {
14605                         if (optval)
14606                                 bbr->r_ctl.rc_incr_tmrs = 1;
14607                         else
14608                                 bbr->r_ctl.rc_incr_tmrs = 0;
14609                 }
14610                 break;
14611         case TCP_BBR_PACE_OH:
14612                 BBR_OPTS_INC(tcp_pacing_oh);
14613                 if (bbr->rc_use_google) {
14614                         error = EINVAL;
14615                 } else {
14616                         if (optval > (BBR_INCL_TCP_OH|
14617                                       BBR_INCL_IP_OH|
14618                                       BBR_INCL_ENET_OH)) {
14619                                 error = EINVAL;
14620                                 break;
14621                         }
14622                         if (optval & BBR_INCL_TCP_OH)
14623                                 bbr->r_ctl.rc_inc_tcp_oh = 1;
14624                         else
14625                                 bbr->r_ctl.rc_inc_tcp_oh = 0;
14626                         if (optval & BBR_INCL_IP_OH)
14627                                 bbr->r_ctl.rc_inc_ip_oh = 1;
14628                         else
14629                                 bbr->r_ctl.rc_inc_ip_oh = 0;
14630                         if (optval & BBR_INCL_ENET_OH)
14631                                 bbr->r_ctl.rc_inc_enet_oh = 1;
14632                         else
14633                                 bbr->r_ctl.rc_inc_enet_oh = 0;
14634                 }
14635                 break;
14636         default:
14637                 return (tcp_default_ctloutput(so, sopt, inp, tp));
14638                 break;
14639         }
14640 #ifdef NETFLIX_STATS
14641         tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14642 #endif
14643         INP_WUNLOCK(inp);
14644         return (error);
14645 }
14646
14647 /*
14648  * return 0 on success, error-num on failure
14649  */
14650 static int
14651 bbr_get_sockopt(struct socket *so, struct sockopt *sopt,
14652     struct inpcb *inp, struct tcpcb *tp, struct tcp_bbr *bbr)
14653 {
14654         int32_t error, optval;
14655
14656         /*
14657          * Because all our options are either boolean or an int, we can just
14658          * pull everything into optval and then unlock and copy. If we ever
14659          * add a option that is not a int, then this will have quite an
14660          * impact to this routine.
14661          */
14662         switch (sopt->sopt_name) {
14663         case TCP_BBR_PACE_PER_SEC:
14664                 optval = bbr->r_ctl.bbr_hptsi_per_second;
14665                 break;
14666         case TCP_BBR_PACE_DEL_TAR:
14667                 optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14668                 break;
14669         case TCP_BBR_PACE_SEG_MAX:
14670                 optval = bbr->r_ctl.bbr_hptsi_segments_max;
14671                 break;
14672         case TCP_BBR_MIN_TOPACEOUT:
14673                 optval = bbr->no_pacing_until;
14674                 break;
14675         case TCP_BBR_PACE_SEG_MIN:
14676                 optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14677                 break;
14678         case TCP_BBR_PACE_CROSS:
14679                 optval = bbr->r_ctl.bbr_cross_over;
14680                 break;
14681         case TCP_BBR_ALGORITHM:
14682                 optval = bbr->rc_use_google;
14683                 break;
14684         case TCP_BBR_TSLIMITS:
14685                 optval = bbr->rc_use_ts_limit;
14686                 break;
14687         case TCP_BBR_IWINTSO:
14688                 optval = bbr->rc_init_win;
14689                 break;
14690         case TCP_BBR_STARTUP_PG:
14691                 optval = bbr->r_ctl.rc_startup_pg;
14692                 break;
14693         case TCP_BBR_DRAIN_PG:
14694                 optval = bbr->r_ctl.rc_drain_pg;
14695                 break;
14696         case TCP_BBR_PROBE_RTT_INT:
14697                 optval = bbr->r_ctl.rc_probertt_int;
14698                 break;
14699         case TCP_BBR_PROBE_RTT_LEN:
14700                 optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14701                 break;
14702         case TCP_BBR_PROBE_RTT_GAIN:
14703                 optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14704                 break;
14705         case TCP_BBR_STARTUP_LOSS_EXIT:
14706                 optval = bbr->rc_loss_exit;
14707                 break;
14708         case TCP_BBR_USEDEL_RATE:
14709                 error = EINVAL;
14710                 break;
14711         case TCP_BBR_MIN_RTO:
14712                 optval = bbr->r_ctl.rc_min_rto_ms;
14713                 break;
14714         case TCP_BBR_MAX_RTO:
14715                 optval = bbr->rc_max_rto_sec;
14716                 break;
14717         case TCP_RACK_PACE_MAX_SEG:
14718                 /* Max segments in a pace */
14719                 optval = bbr->r_ctl.rc_pace_max_segs;
14720                 break;
14721         case TCP_RACK_MIN_TO:
14722                 /* Minimum time between rack t-o's in ms */
14723                 optval = bbr->r_ctl.rc_min_to;
14724                 break;
14725         case TCP_RACK_REORD_THRESH:
14726                 /* RACK reorder threshold (shift amount) */
14727                 optval = bbr->r_ctl.rc_reorder_shift;
14728                 break;
14729         case TCP_RACK_REORD_FADE:
14730                 /* Does reordering fade after ms time */
14731                 optval = bbr->r_ctl.rc_reorder_fade;
14732                 break;
14733         case TCP_BBR_USE_RACK_CHEAT:
14734                 /* Do we use the rack cheat for rxt */
14735                 optval = bbr->bbr_use_rack_cheat;
14736                 break;
14737         case TCP_BBR_FLOOR_MIN_TSO:
14738                 optval = bbr->r_ctl.bbr_hptsi_segments_floor;
14739                 break;
14740         case TCP_BBR_UTTER_MAX_TSO:
14741                 optval = bbr->r_ctl.bbr_utter_max;
14742                 break;
14743         case TCP_BBR_SEND_IWND_IN_TSO:
14744                 /* Do we send TSO size segments initially */
14745                 optval = bbr->bbr_init_win_cheat;
14746                 break;
14747         case TCP_BBR_EXTRA_STATE:
14748                 optval = bbr->rc_use_idle_restart;
14749                 break;
14750         case TCP_RACK_TLP_THRESH:
14751                 /* RACK TLP theshold i.e. srtt+(srtt/N) */
14752                 optval = bbr->rc_tlp_threshold;
14753                 break;
14754         case TCP_RACK_PKT_DELAY:
14755                 /* RACK added ms i.e. rack-rtt + reord + N */
14756                 optval = bbr->r_ctl.rc_pkt_delay;
14757                 break;
14758         case TCP_BBR_RETRAN_WTSO:
14759                 optval = bbr->rc_resends_use_tso;
14760                 break;
14761         case TCP_DATA_AFTER_CLOSE:
14762                 optval = bbr->rc_allow_data_af_clo;
14763                 break;
14764         case TCP_DELACK:
14765                 optval = tp->t_delayed_ack;
14766                 break;
14767         case TCP_BBR_HDWR_PACE:
14768                 optval = bbr->bbr_hdw_pace_ena;
14769                 break;
14770         case TCP_BBR_POLICER_DETECT:
14771                 optval = bbr->r_use_policer;
14772                 break;
14773         case TCP_BBR_TSTMP_RAISES:
14774                 optval = bbr->ts_can_raise;
14775                 break;
14776         case TCP_BBR_TMR_PACE_OH:
14777                 optval = bbr->r_ctl.rc_incr_tmrs;
14778                 break;
14779         case TCP_BBR_PACE_OH:
14780                 optval = 0;
14781                 if (bbr->r_ctl.rc_inc_tcp_oh)
14782                         optval |= BBR_INCL_TCP_OH;
14783                 if (bbr->r_ctl.rc_inc_ip_oh)
14784                         optval |= BBR_INCL_IP_OH;
14785                 if (bbr->r_ctl.rc_inc_enet_oh)
14786                         optval |= BBR_INCL_ENET_OH;
14787                 break;
14788         default:
14789                 return (tcp_default_ctloutput(so, sopt, inp, tp));
14790                 break;
14791         }
14792         INP_WUNLOCK(inp);
14793         error = sooptcopyout(sopt, &optval, sizeof optval);
14794         return (error);
14795 }
14796
14797 /*
14798  * return 0 on success, error-num on failure
14799  */
14800 static int
14801 bbr_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp, struct tcpcb *tp)
14802 {
14803         int32_t error = EINVAL;
14804         struct tcp_bbr *bbr;
14805
14806         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14807         if (bbr == NULL) {
14808                 /* Huh? */
14809                 goto out;
14810         }
14811         if (sopt->sopt_dir == SOPT_SET) {
14812                 return (bbr_set_sockopt(so, sopt, inp, tp, bbr));
14813         } else if (sopt->sopt_dir == SOPT_GET) {
14814                 return (bbr_get_sockopt(so, sopt, inp, tp, bbr));
14815         }
14816 out:
14817         INP_WUNLOCK(inp);
14818         return (error);
14819 }
14820
14821 static const char *bbr_stack_names[] = {
14822         __XSTRING(STACKNAME),
14823 #ifdef STACKALIAS
14824         __XSTRING(STACKALIAS),
14825 #endif
14826 };
14827
14828 static bool bbr_mod_inited = false;
14829
14830 static int
14831 tcp_addbbr(module_t mod, int32_t type, void *data)
14832 {
14833         int32_t err = 0;
14834         int num_stacks;
14835
14836         switch (type) {
14837         case MOD_LOAD:
14838                 printf("Attempting to load " __XSTRING(MODNAME) "\n");
14839                 bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
14840                     sizeof(struct bbr_sendmap),
14841                     NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
14842                 bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
14843                     sizeof(struct tcp_bbr),
14844                     NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
14845                 sysctl_ctx_init(&bbr_sysctl_ctx);
14846                 bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
14847                     SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
14848                     OID_AUTO,
14849 #ifdef STACKALIAS
14850                     __XSTRING(STACKALIAS),
14851 #else
14852                     __XSTRING(STACKNAME),
14853 #endif
14854                     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
14855                     "");
14856                 if (bbr_sysctl_root == NULL) {
14857                         printf("Failed to add sysctl node\n");
14858                         err = EFAULT;
14859                         goto free_uma;
14860                 }
14861                 bbr_init_sysctls();
14862                 num_stacks = nitems(bbr_stack_names);
14863                 err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
14864                     bbr_stack_names, &num_stacks);
14865                 if (err) {
14866                         printf("Failed to register %s stack name for "
14867                             "%s module\n", bbr_stack_names[num_stacks],
14868                             __XSTRING(MODNAME));
14869                         sysctl_ctx_free(&bbr_sysctl_ctx);
14870         free_uma:
14871                         uma_zdestroy(bbr_zone);
14872                         uma_zdestroy(bbr_pcb_zone);
14873                         bbr_counter_destroy();
14874                         printf("Failed to register " __XSTRING(MODNAME)
14875                             " module err:%d\n", err);
14876                         return (err);
14877                 }
14878                 tcp_lro_reg_mbufq();
14879                 bbr_mod_inited = true;
14880                 printf(__XSTRING(MODNAME) " is now available\n");
14881                 break;
14882         case MOD_QUIESCE:
14883                 err = deregister_tcp_functions(&__tcp_bbr, true, false);
14884                 break;
14885         case MOD_UNLOAD:
14886                 err = deregister_tcp_functions(&__tcp_bbr, false, true);
14887                 if (err == EBUSY)
14888                         break;
14889                 if (bbr_mod_inited) {
14890                         uma_zdestroy(bbr_zone);
14891                         uma_zdestroy(bbr_pcb_zone);
14892                         sysctl_ctx_free(&bbr_sysctl_ctx);
14893                         bbr_counter_destroy();
14894                         printf(__XSTRING(MODNAME)
14895                             " is now no longer available\n");
14896                         bbr_mod_inited = false;
14897                 }
14898                 tcp_lro_dereg_mbufq();
14899                 err = 0;
14900                 break;
14901         default:
14902                 return (EOPNOTSUPP);
14903         }
14904         return (err);
14905 }
14906
14907 static moduledata_t tcp_bbr = {
14908         .name = __XSTRING(MODNAME),
14909             .evhand = tcp_addbbr,
14910             .priv = 0
14911 };
14912
14913 MODULE_VERSION(MODNAME, 1);
14914 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
14915 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);