]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/tcp_stacks/bbr.c
Don't set the ECT codepoint on retransmitted packets during SACK loss
[FreeBSD/FreeBSD.git] / sys / netinet / tcp_stacks / bbr.c
1 /*-
2  * Copyright (c) 2016-9
3  *      Netflix Inc.
4  *      All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  */
28 /**
29  * Author: Randall Stewart <rrs@netflix.com>
30  * This work is based on the ACM Queue paper
31  * BBR - Congestion Based Congestion Control
32  * and also numerous discussions with Neal, Yuchung and Van.
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include "opt_inet.h"
39 #include "opt_inet6.h"
40 #include "opt_ipsec.h"
41 #include "opt_tcpdebug.h"
42 #include "opt_ratelimit.h"
43 #include "opt_kern_tls.h"
44 #include <sys/param.h>
45 #include <sys/arb.h>
46 #include <sys/module.h>
47 #include <sys/kernel.h>
48 #ifdef TCP_HHOOK
49 #include <sys/hhook.h>
50 #endif
51 #include <sys/malloc.h>
52 #include <sys/mbuf.h>
53 #include <sys/proc.h>
54 #include <sys/socket.h>
55 #include <sys/socketvar.h>
56 #ifdef KERN_TLS
57 #include <sys/ktls.h>
58 #endif
59 #include <sys/sysctl.h>
60 #include <sys/systm.h>
61 #ifdef STATS
62 #include <sys/qmath.h>
63 #include <sys/tree.h>
64 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
65 #endif
66 #include <sys/refcount.h>
67 #include <sys/queue.h>
68 #include <sys/eventhandler.h>
69 #include <sys/smp.h>
70 #include <sys/kthread.h>
71 #include <sys/lock.h>
72 #include <sys/mutex.h>
73 #include <sys/tim_filter.h>
74 #include <sys/time.h>
75 #include <vm/uma.h>
76 #include <sys/kern_prefetch.h>
77
78 #include <net/route.h>
79 #include <net/vnet.h>
80
81 #define TCPSTATES               /* for logging */
82
83 #include <netinet/in.h>
84 #include <netinet/in_kdtrace.h>
85 #include <netinet/in_pcb.h>
86 #include <netinet/ip.h>
87 #include <netinet/ip_icmp.h>    /* required for icmp_var.h */
88 #include <netinet/icmp_var.h>   /* for ICMP_BANDLIM */
89 #include <netinet/ip_var.h>
90 #include <netinet/ip6.h>
91 #include <netinet6/in6_pcb.h>
92 #include <netinet6/ip6_var.h>
93 #define TCPOUTFLAGS
94 #include <netinet/tcp.h>
95 #include <netinet/tcp_fsm.h>
96 #include <netinet/tcp_seq.h>
97 #include <netinet/tcp_timer.h>
98 #include <netinet/tcp_var.h>
99 #include <netinet/tcpip.h>
100 #include <netinet/tcp_hpts.h>
101 #include <netinet/cc/cc.h>
102 #include <netinet/tcp_log_buf.h>
103 #include <netinet/tcp_ratelimit.h>
104 #include <netinet/tcp_lro.h>
105 #ifdef TCPDEBUG
106 #include <netinet/tcp_debug.h>
107 #endif                          /* TCPDEBUG */
108 #ifdef TCP_OFFLOAD
109 #include <netinet/tcp_offload.h>
110 #endif
111 #ifdef INET6
112 #include <netinet6/tcp6_var.h>
113 #endif
114 #include <netinet/tcp_fastopen.h>
115
116 #include <netipsec/ipsec_support.h>
117 #include <net/if.h>
118 #include <net/if_var.h>
119 #include <net/ethernet.h>
120
121 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
122 #include <netipsec/ipsec.h>
123 #include <netipsec/ipsec6.h>
124 #endif                          /* IPSEC */
125
126 #include <netinet/udp.h>
127 #include <netinet/udp_var.h>
128 #include <machine/in_cksum.h>
129
130 #ifdef MAC
131 #include <security/mac/mac_framework.h>
132 #endif
133
134 #include "sack_filter.h"
135 #include "tcp_bbr.h"
136 #include "rack_bbr_common.h"
137 uma_zone_t bbr_zone;
138 uma_zone_t bbr_pcb_zone;
139
140 struct sysctl_ctx_list bbr_sysctl_ctx;
141 struct sysctl_oid *bbr_sysctl_root;
142
143 #define TCPT_RANGESET_NOSLOP(tv, value, tvmin, tvmax) do { \
144         (tv) = (value); \
145         if ((u_long)(tv) < (u_long)(tvmin)) \
146                 (tv) = (tvmin); \
147         if ((u_long)(tv) > (u_long)(tvmax)) \
148                 (tv) = (tvmax); \
149 } while(0)
150
151 /*#define BBR_INVARIANT 1*/
152
153 /*
154  * initial window
155  */
156 static uint32_t bbr_def_init_win = 10;
157 static int32_t bbr_persist_min = 250000;        /* 250ms */
158 static int32_t bbr_persist_max = 1000000;       /* 1 Second */
159 static int32_t bbr_cwnd_may_shrink = 0;
160 static int32_t bbr_cwndtarget_rtt_touse = BBR_RTT_PROP;
161 static int32_t bbr_num_pktepo_for_del_limit = BBR_NUM_RTTS_FOR_DEL_LIMIT;
162 static int32_t bbr_hardware_pacing_limit = 8000;
163 static int32_t bbr_quanta = 3;  /* How much extra quanta do we get? */
164 static int32_t bbr_no_retran = 0;
165
166
167 static int32_t bbr_error_base_paceout = 10000; /* usec to pace */
168 static int32_t bbr_max_net_error_cnt = 10;
169 /* Should the following be dynamic too -- loss wise */
170 static int32_t bbr_rtt_gain_thresh = 0;
171 /* Measurement controls */
172 static int32_t bbr_use_google_algo = 1;
173 static int32_t bbr_ts_limiting = 1;
174 static int32_t bbr_ts_can_raise = 0;
175 static int32_t bbr_do_red = 600;
176 static int32_t bbr_red_scale = 20000;
177 static int32_t bbr_red_mul = 1;
178 static int32_t bbr_red_div = 2;
179 static int32_t bbr_red_growth_restrict = 1;
180 static int32_t  bbr_target_is_bbunit = 0;
181 static int32_t bbr_drop_limit = 0;
182 /*
183  * How much gain do we need to see to
184  * stay in startup?
185  */
186 static int32_t bbr_marks_rxt_sack_passed = 0;
187 static int32_t bbr_start_exit = 25;
188 static int32_t bbr_low_start_exit = 25; /* When we are in reduced gain */
189 static int32_t bbr_startup_loss_thresh = 2000;  /* 20.00% loss */
190 static int32_t bbr_hptsi_max_mul = 1;   /* These two mul/div assure a min pacing */
191 static int32_t bbr_hptsi_max_div = 2;   /* time, 0 means turned off. We need this
192                                          * if we go back ever to where the pacer
193                                          * has priority over timers.
194                                          */
195 static int32_t bbr_policer_call_from_rack_to = 0;
196 static int32_t bbr_policer_detection_enabled = 1;
197 static int32_t bbr_min_measurements_req = 1;    /* We need at least 2
198                                                  * measurments before we are
199                                                  * "good" note that 2 == 1.
200                                                  * This is because we use a >
201                                                  * comparison. This means if
202                                                  * min_measure was 0, it takes
203                                                  * num-measures > min(0) and
204                                                  * you get 1 measurement and
205                                                  * you are good. Set to 1, you
206                                                  * have to have two
207                                                  * measurements (this is done
208                                                  * to prevent it from being ok
209                                                  * to have no measurements). */
210 static int32_t bbr_no_pacing_until = 4;
211                                                  
212 static int32_t bbr_min_usec_delta = 20000;      /* 20,000 usecs */
213 static int32_t bbr_min_peer_delta = 20;         /* 20 units */
214 static int32_t bbr_delta_percent = 150;         /* 15.0 % */
215
216 static int32_t bbr_target_cwnd_mult_limit = 8;
217 /*
218  * bbr_cwnd_min_val is the number of
219  * segments we hold to in the RTT probe
220  * state typically 4.
221  */
222 static int32_t bbr_cwnd_min_val = BBR_PROBERTT_NUM_MSS;
223
224
225 static int32_t bbr_cwnd_min_val_hs = BBR_HIGHSPEED_NUM_MSS;
226
227 static int32_t bbr_gain_to_target = 1;
228 static int32_t bbr_gain_gets_extra_too = 1;
229 /*
230  * bbr_high_gain is the 2/ln(2) value we need
231  * to double the sending rate in startup. This
232  * is used for both cwnd and hptsi gain's.
233  */
234 static int32_t bbr_high_gain = BBR_UNIT * 2885 / 1000 + 1;
235 static int32_t bbr_startup_lower = BBR_UNIT * 1500 / 1000 + 1;
236 static int32_t bbr_use_lower_gain_in_startup = 1;
237
238 /* thresholds for reduction on drain in sub-states/drain */
239 static int32_t bbr_drain_rtt = BBR_SRTT;
240 static int32_t bbr_drain_floor = 88;
241 static int32_t google_allow_early_out = 1;
242 static int32_t google_consider_lost = 1;
243 static int32_t bbr_drain_drop_mul = 4;
244 static int32_t bbr_drain_drop_div = 5;
245 static int32_t bbr_rand_ot = 50;
246 static int32_t bbr_can_force_probertt = 0;
247 static int32_t bbr_can_adjust_probertt = 1;
248 static int32_t bbr_probertt_sets_rtt = 0;
249 static int32_t bbr_can_use_ts_for_rtt = 1;
250 static int32_t bbr_is_ratio = 0;
251 static int32_t bbr_sub_drain_app_limit = 1;
252 static int32_t bbr_prtt_slam_cwnd = 1;
253 static int32_t bbr_sub_drain_slam_cwnd = 1;
254 static int32_t bbr_slam_cwnd_in_main_drain = 1;
255 static int32_t bbr_filter_len_sec = 6;  /* How long does the rttProp filter
256                                          * hold */
257 static uint32_t bbr_rtt_probe_limit = (USECS_IN_SECOND * 4);
258 /*
259  * bbr_drain_gain is the reverse of the high_gain
260  * designed to drain back out the standing queue
261  * that is formed in startup by causing a larger
262  * hptsi gain and thus drainging the packets
263  * in flight.
264  */
265 static int32_t bbr_drain_gain = BBR_UNIT * 1000 / 2885;
266 static int32_t bbr_rttprobe_gain = 192;
267
268 /*
269  * The cwnd_gain is the default cwnd gain applied when
270  * calculating a target cwnd. Note that the cwnd is
271  * a secondary factor in the way BBR works (see the
272  * paper and think about it, it will take some time).
273  * Basically the hptsi_gain spreads the packets out
274  * so you never get more than BDP to the peer even
275  * if the cwnd is high. In our implemenation that
276  * means in non-recovery/retransmission scenarios
277  * cwnd will never be reached by the flight-size.
278  */
279 static int32_t bbr_cwnd_gain = BBR_UNIT * 2;
280 static int32_t bbr_tlp_type_to_use = BBR_SRTT;
281 static int32_t bbr_delack_time = 100000;        /* 100ms in useconds */
282 static int32_t bbr_sack_not_required = 0;       /* set to one to allow non-sack to use bbr */
283 static int32_t bbr_initial_bw_bps = 62500;      /* 500kbps in bytes ps */
284 static int32_t bbr_ignore_data_after_close = 1;
285 static int16_t bbr_hptsi_gain[] = {
286         (BBR_UNIT *5 / 4),
287         (BBR_UNIT * 3 / 4),
288         BBR_UNIT,
289         BBR_UNIT,
290         BBR_UNIT,
291         BBR_UNIT,
292         BBR_UNIT,
293         BBR_UNIT
294 };
295 int32_t bbr_use_rack_resend_cheat = 1;
296 int32_t bbr_sends_full_iwnd = 1;
297
298 #define BBR_HPTSI_GAIN_MAX 8
299 /*
300  * The BBR module incorporates a number of
301  * TCP ideas that have been put out into the IETF
302  * over the last few years:
303  * - Yuchung Cheng's RACK TCP (for which its named) that
304  *    will stop us using the number of dup acks and instead
305  *    use time as the gage of when we retransmit.
306  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
307  *    of Dukkipati et.al.
308  * - Van Jacobson's et.al BBR.
309  *
310  * RACK depends on SACK, so if an endpoint arrives that
311  * cannot do SACK the state machine below will shuttle the
312  * connection back to using the "default" TCP stack that is
313  * in FreeBSD.
314  *
315  * To implement BBR and RACK the original TCP stack was first decomposed
316  * into a functional state machine with individual states
317  * for each of the possible TCP connection states. The do_segement
318  * functions role in life is to mandate the connection supports SACK
319  * initially and then assure that the RACK state matches the conenction
320  * state before calling the states do_segment function. Data processing
321  * of inbound segments also now happens in the hpts_do_segment in general
322  * with only one exception. This is so we can keep the connection on
323  * a single CPU.
324  *
325  * Each state is simplified due to the fact that the original do_segment
326  * has been decomposed and we *know* what state we are in (no
327  * switches on the state) and all tests for SACK are gone. This
328  * greatly simplifies what each state does.
329  *
330  * TCP output is also over-written with a new version since it
331  * must maintain the new rack scoreboard and has had hptsi
332  * integrated as a requirment. Still todo is to eliminate the
333  * use of the callout_() system and use the hpts for all
334  * timers as well.
335  */
336 static uint32_t bbr_rtt_probe_time = 200000;    /* 200ms in micro seconds */
337 static uint32_t bbr_rtt_probe_cwndtarg = 4;     /* How many mss's outstanding */
338 static const int32_t bbr_min_req_free = 2;      /* The min we must have on the
339                                                  * free list */
340 static int32_t bbr_tlp_thresh = 1;
341 static int32_t bbr_reorder_thresh = 2;
342 static int32_t bbr_reorder_fade = 60000000;     /* 0 - never fade, def
343                                                  * 60,000,000 - 60 seconds */
344 static int32_t bbr_pkt_delay = 1000;
345 static int32_t bbr_min_to = 1000;       /* Number of usec's minimum timeout */
346 static int32_t bbr_incr_timers = 1;
347
348 static int32_t bbr_tlp_min = 10000;     /* 10ms in usecs */
349 static int32_t bbr_delayed_ack_time = 200000;   /* 200ms in usecs */
350 static int32_t bbr_exit_startup_at_loss = 1;
351
352 /*
353  * bbr_lt_bw_ratio is 1/8th
354  * bbr_lt_bw_diff is  < 4 Kbit/sec
355  */
356 static uint64_t bbr_lt_bw_diff = 4000 / 8;      /* In bytes per second */
357 static uint64_t bbr_lt_bw_ratio = 8;    /* For 1/8th */
358 static uint32_t bbr_lt_bw_max_rtts = 48;        /* How many rtt's do we use
359                                                  * the lt_bw for */
360 static uint32_t bbr_lt_intvl_min_rtts = 4;      /* Min num of RTT's to measure
361                                                  * lt_bw */
362 static int32_t bbr_lt_intvl_fp = 0;             /* False positive epoch diff */
363 static int32_t bbr_lt_loss_thresh = 196;        /* Lost vs delivered % */
364 static int32_t bbr_lt_fd_thresh = 100;          /* false detection % */
365
366 static int32_t bbr_verbose_logging = 0;
367 /*
368  * Currently regular tcp has a rto_min of 30ms
369  * the backoff goes 12 times so that ends up
370  * being a total of 122.850 seconds before a
371  * connection is killed.
372  */
373 static int32_t bbr_rto_min_ms = 30;     /* 30ms same as main freebsd */
374 static int32_t bbr_rto_max_sec = 4;     /* 4 seconds */
375
376 /****************************************************/
377 /* DEFAULT TSO SIZING  (cpu performance impacting)  */
378 /****************************************************/
379 /* What amount is our formula using to get TSO size */
380 static int32_t bbr_hptsi_per_second = 1000;
381
382 /*
383  * For hptsi under bbr_cross_over connections what is delay 
384  * target 7ms (in usec) combined with a seg_max of 2
385  * gets us close to identical google behavior in 
386  * TSO size selection (possibly more 1MSS sends).
387  */
388 static int32_t bbr_hptsi_segments_delay_tar = 7000;
389
390 /* Does pacing delay include overhead's in its time calculations? */
391 static int32_t bbr_include_enet_oh = 0;
392 static int32_t bbr_include_ip_oh = 1;
393 static int32_t bbr_include_tcp_oh = 1;
394 static int32_t bbr_google_discount = 10;
395
396 /* Do we use (nf mode) pkt-epoch to drive us or rttProp? */
397 static int32_t bbr_state_is_pkt_epoch = 0;
398 static int32_t bbr_state_drain_2_tar = 1;
399 /* What is the max the 0 - bbr_cross_over MBPS TSO target
400  * can reach using our delay target. Note that this
401  * value becomes the floor for the cross over
402  * algorithm.
403  */
404 static int32_t bbr_hptsi_segments_max = 2;
405 static int32_t bbr_hptsi_segments_floor = 1;
406 static int32_t bbr_hptsi_utter_max = 0;
407
408 /* What is the min the 0 - bbr_cross-over MBPS  TSO target can be */
409 static int32_t bbr_hptsi_bytes_min = 1460;
410 static int32_t bbr_all_get_min = 0;
411
412 /* Cross over point from algo-a to algo-b */
413 static uint32_t bbr_cross_over = TWENTY_THREE_MBPS;
414
415 /* Do we deal with our restart state? */
416 static int32_t bbr_uses_idle_restart = 0;
417 static int32_t bbr_idle_restart_threshold = 100000;     /* 100ms in useconds */
418
419 /* Do we allow hardware pacing? */
420 static int32_t bbr_allow_hdwr_pacing = 0;
421 static int32_t bbr_hdwr_pace_adjust = 2;        /* multipler when we calc the tso size */
422 static int32_t bbr_hdwr_pace_floor = 1;
423 static int32_t bbr_hdwr_pacing_delay_cnt = 10;
424
425 /****************************************************/
426 static int32_t bbr_resends_use_tso = 0;
427 static int32_t bbr_tlp_max_resend = 2;
428 static int32_t bbr_sack_block_limit = 128;
429
430 #define  BBR_MAX_STAT 19
431 counter_u64_t bbr_state_time[BBR_MAX_STAT];
432 counter_u64_t bbr_state_lost[BBR_MAX_STAT];
433 counter_u64_t bbr_state_resend[BBR_MAX_STAT];
434 counter_u64_t bbr_stat_arry[BBR_STAT_SIZE];
435 counter_u64_t bbr_opts_arry[BBR_OPTS_SIZE];
436 counter_u64_t bbr_out_size[TCP_MSS_ACCT_SIZE];
437 counter_u64_t bbr_flows_whdwr_pacing;
438 counter_u64_t bbr_flows_nohdwr_pacing;
439
440 counter_u64_t bbr_nohdwr_pacing_enobuf;
441 counter_u64_t bbr_hdwr_pacing_enobuf;
442
443 static inline uint64_t bbr_get_bw(struct tcp_bbr *bbr);
444
445 /*
446  * Static defintions we need for forward declarations.
447  */
448 static uint32_t
449 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain,
450     uint32_t useconds_time, uint64_t bw);
451 static uint32_t
452 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain);
453 static void
454      bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win);
455 static void
456 bbr_set_probebw_gains(struct tcp_bbr *bbr,  uint32_t cts, uint32_t losses);
457 static void
458 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int line,
459                     int dolog);
460 static uint32_t
461 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain);
462 static void
463 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch,
464                  int32_t pkt_epoch, uint32_t losses);
465 static uint32_t
466 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm);
467 static uint32_t bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp);
468 static uint32_t
469 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
470     struct bbr_sendmap *rsm, uint32_t srtt,
471     uint32_t cts);
472 static void
473 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
474     int32_t line);
475 static void
476      bbr_set_state_target(struct tcp_bbr *bbr, int line);
477 static void
478      bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line);
479
480 static void
481      bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line);
482
483 static void
484      tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts);
485
486 static void
487      bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts);
488
489 static void
490      bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied, uint32_t rtt,
491                          uint32_t line, uint8_t is_start, uint16_t set);
492
493 static struct bbr_sendmap *
494             bbr_find_lowest_rsm(struct tcp_bbr *bbr);
495 static __inline uint32_t
496 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type);
497 static void
498      bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which);
499
500 static void
501 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
502     uint32_t thresh, uint32_t to);
503 static void
504      bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag);
505
506 static void
507 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot,
508     uint32_t del_by, uint32_t cts, uint32_t sloton, uint32_t prev_delay);
509
510 static void
511 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr,
512     uint32_t cts, int32_t line);
513 static void
514      bbr_stop_all_timers(struct tcpcb *tp);
515 static void
516      bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts);
517 static void
518      bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts);
519 static void
520      bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts);
521
522
523 static void
524 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
525     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod);
526
527 static inline uint8_t
528 bbr_state_val(struct tcp_bbr *bbr)
529 {
530         return(bbr->rc_bbr_substate);
531 }
532
533 static inline uint32_t
534 get_min_cwnd(struct tcp_bbr *bbr)
535 {
536         int mss;
537
538         mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
539         if (bbr_get_rtt(bbr, BBR_RTT_PROP) < BBR_HIGH_SPEED)
540                 return (bbr_cwnd_min_val_hs * mss);
541         else
542                 return (bbr_cwnd_min_val * mss);
543 }
544
545 static uint32_t
546 bbr_get_persists_timer_val(struct tcpcb *tp, struct tcp_bbr *bbr)
547 {
548         uint64_t srtt, var;
549         uint64_t ret_val;
550
551         bbr->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
552         if (tp->t_srtt == 0) {
553                 srtt = (uint64_t)BBR_INITIAL_RTO;
554                 var = 0;
555         } else {
556                 srtt = ((uint64_t)TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
557                 var = ((uint64_t)TICKS_2_USEC(tp->t_rttvar) >> TCP_RTT_SHIFT);
558         }
559         TCPT_RANGESET_NOSLOP(ret_val, ((srtt + var) * tcp_backoff[tp->t_rxtshift]),
560             bbr_persist_min, bbr_persist_max);
561         return ((uint32_t)ret_val);
562 }
563
564 static uint32_t
565 bbr_timer_start(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
566 {
567         /*
568          * Start the FR timer, we do this based on getting the first one in
569          * the rc_tmap. Note that if its NULL we must stop the timer. in all
570          * events we need to stop the running timer (if its running) before
571          * starting the new one.
572          */
573         uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
574         int32_t idx;
575         int32_t is_tlp_timer = 0;
576         struct bbr_sendmap *rsm;
577
578         if (bbr->rc_all_timers_stopped) {
579                 /* All timers have been stopped none are to run */
580                 return (0);
581         }
582         if (bbr->rc_in_persist) {
583                 /* We can't start any timer in persists */
584                 return (bbr_get_persists_timer_val(tp, bbr));
585         }
586         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
587         if ((rsm == NULL) ||
588             ((tp->t_flags & TF_SACK_PERMIT) == 0) ||
589             (tp->t_state < TCPS_ESTABLISHED)) {
590                 /* Nothing on the send map */
591 activate_rxt:
592                 if (SEQ_LT(tp->snd_una, tp->snd_max) || sbavail(&(tp->t_inpcb->inp_socket->so_snd))) {
593                         uint64_t tov;
594
595                         time_since_sent = 0;
596                         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
597                         if (rsm) {
598                                 idx = rsm->r_rtr_cnt - 1;
599                                 if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time)) 
600                                         tstmp_touse = rsm->r_tim_lastsent[idx];
601                                 else 
602                                         tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
603                                 if (TSTMP_GT(tstmp_touse, cts))
604                                     time_since_sent = cts - tstmp_touse;
605                         }
606                         bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
607                         if (tp->t_srtt == 0)
608                                 tov = BBR_INITIAL_RTO;
609                         else
610                                 tov = ((uint64_t)(TICKS_2_USEC(tp->t_srtt) +
611                                     ((uint64_t)TICKS_2_USEC(tp->t_rttvar) * (uint64_t)4)) >> TCP_RTT_SHIFT);
612                         if (tp->t_rxtshift)
613                                 tov *= tcp_backoff[tp->t_rxtshift];
614                         if (tov > time_since_sent)
615                                 tov -= time_since_sent;
616                         else
617                                 tov = bbr->r_ctl.rc_min_to;
618                         TCPT_RANGESET_NOSLOP(to, tov,
619                             (bbr->r_ctl.rc_min_rto_ms * MS_IN_USEC),
620                             (bbr->rc_max_rto_sec * USECS_IN_SECOND));
621                         bbr_log_timer_var(bbr, 2, cts, 0, srtt, 0, to);
622                         return (to);
623                 }
624                 return (0);
625         }
626         if (rsm->r_flags & BBR_ACKED) {
627                 rsm = bbr_find_lowest_rsm(bbr);
628                 if (rsm == NULL) {
629                         /* No lowest? */
630                         goto activate_rxt;
631                 }
632         }
633         /* Convert from ms to usecs */
634         if (rsm->r_flags & BBR_SACK_PASSED) {
635                 if ((tp->t_flags & TF_SENTFIN) &&
636                     ((tp->snd_max - tp->snd_una) == 1) &&
637                     (rsm->r_flags & BBR_HAS_FIN)) {
638                         /*
639                          * We don't start a bbr rack timer if all we have is
640                          * a FIN outstanding.
641                          */
642                         goto activate_rxt;
643                 }
644                 srtt = bbr_get_rtt(bbr, BBR_RTT_RACK);
645                 thresh = bbr_calc_thresh_rack(bbr, srtt, cts, rsm);
646                 idx = rsm->r_rtr_cnt - 1;
647                 exp = rsm->r_tim_lastsent[idx] + thresh;
648                 if (SEQ_GEQ(exp, cts)) {
649                         to = exp - cts;
650                         if (to < bbr->r_ctl.rc_min_to) {
651                                 to = bbr->r_ctl.rc_min_to;
652                         }
653                 } else {
654                         to = bbr->r_ctl.rc_min_to;
655                 }
656         } else {
657                 /* Ok we need to do a TLP not RACK */
658                 if (bbr->rc_tlp_in_progress != 0) {
659                         /*
660                          * The previous send was a TLP.
661                          */
662                         goto activate_rxt;
663                 }
664                 rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
665                 if (rsm == NULL) {
666                         /* We found no rsm to TLP with. */
667                         goto activate_rxt;
668                 }
669                 if (rsm->r_flags & BBR_HAS_FIN) {
670                         /* If its a FIN we don't do TLP */
671                         rsm = NULL;
672                         goto activate_rxt;
673                 }
674                 time_since_sent = 0;
675                 idx = rsm->r_rtr_cnt - 1;
676                 if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time)) 
677                         tstmp_touse = rsm->r_tim_lastsent[idx];
678                 else 
679                         tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
680                 if (TSTMP_GT(tstmp_touse, cts))
681                     time_since_sent = cts - tstmp_touse;
682                 is_tlp_timer = 1;
683                 srtt = bbr_get_rtt(bbr, bbr_tlp_type_to_use);
684                 thresh = bbr_calc_thresh_tlp(tp, bbr, rsm, srtt, cts);
685                 if (thresh > time_since_sent)
686                         to = thresh - time_since_sent;
687                 else
688                         to = bbr->r_ctl.rc_min_to;
689                 if (to > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
690                         /*
691                          * If the TLP time works out to larger than the max
692                          * RTO lets not do TLP.. just RTO.
693                          */
694                         goto activate_rxt;
695                 }
696                 if ((bbr->rc_tlp_rtx_out == 1) &&
697                     (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq)) {
698                         /* 
699                          * Second retransmit of the same TLP 
700                          * lets not.
701                          */
702                         bbr->rc_tlp_rtx_out = 0; 
703                         goto activate_rxt;
704                 }
705                 if (rsm->r_start != bbr->r_ctl.rc_last_tlp_seq) {
706                         /*
707                          * The tail is no longer the last one I did a probe
708                          * on
709                          */
710                         bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
711                         bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
712                 }
713         }
714         if (is_tlp_timer == 0) {
715                 BBR_STAT_INC(bbr_to_arm_rack);
716                 bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
717         } else {
718                 bbr_log_timer_var(bbr, 1, cts, time_since_sent, srtt, thresh, to);
719                 if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
720                         /*
721                          * We have exceeded how many times we can retran the
722                          * current TLP timer, switch to the RTO timer.
723                          */
724                         goto activate_rxt;
725                 } else {
726                         BBR_STAT_INC(bbr_to_arm_tlp);
727                         bbr->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
728                 }
729         }
730         return (to);
731 }
732
733 static inline int32_t
734 bbr_minseg(struct tcp_bbr *bbr)
735 {
736         return (bbr->r_ctl.rc_pace_min_segs - bbr->rc_last_options);
737 }
738
739 static void
740 bbr_start_hpts_timer(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts, int32_t frm, int32_t slot, uint32_t tot_len)
741 {
742         struct inpcb *inp;
743         struct hpts_diag diag;
744         uint32_t delayed_ack = 0;
745         uint32_t left = 0;
746         uint32_t hpts_timeout;
747         uint8_t stopped;
748         int32_t delay_calc = 0;
749         uint32_t prev_delay = 0;
750
751         inp = tp->t_inpcb;
752         if (inp->inp_in_hpts) {
753                 /* A previous call is already set up */
754                 return;
755         }
756         if ((tp->t_state == TCPS_CLOSED) ||
757             (tp->t_state == TCPS_LISTEN)) {
758                 return;
759         }
760         stopped = bbr->rc_tmr_stopped;
761         if (stopped && TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
762                 left = bbr->r_ctl.rc_timer_exp - cts;
763         }
764         bbr->r_ctl.rc_hpts_flags = 0;
765         bbr->r_ctl.rc_timer_exp = 0;
766         prev_delay = bbr->r_ctl.rc_last_delay_val;
767         if (bbr->r_ctl.rc_last_delay_val &&
768             (slot == 0)) {
769                 /* 
770                  * If a previous pacer delay was in place we
771                  * are not coming from the output side (where
772                  * we calculate a delay, more likely a timer).
773                  */
774                 slot = bbr->r_ctl.rc_last_delay_val;
775                 if (TSTMP_GT(cts, bbr->rc_pacer_started)) {
776                         /* Compensate for time passed  */
777                         delay_calc = cts - bbr->rc_pacer_started;
778                         if (delay_calc <= slot)
779                                 slot -= delay_calc;
780                 } 
781         }
782         /* Do we have early to make up for by pushing out the pacing time? */
783         if (bbr->r_agg_early_set) {
784                 bbr_log_pacing_delay_calc(bbr, 0, bbr->r_ctl.rc_agg_early, cts, slot, 0, bbr->r_agg_early_set, 2);
785                 slot += bbr->r_ctl.rc_agg_early;
786                 bbr->r_ctl.rc_agg_early = 0;
787                 bbr->r_agg_early_set = 0;
788         }
789         /* Are we running a total debt that needs to be compensated for? */
790         if (bbr->r_ctl.rc_hptsi_agg_delay) {
791                 if (slot > bbr->r_ctl.rc_hptsi_agg_delay) {
792                         /* We nuke the delay */
793                         slot -= bbr->r_ctl.rc_hptsi_agg_delay;
794                         bbr->r_ctl.rc_hptsi_agg_delay = 0;
795                 } else {
796                         /* We nuke some of the delay, put in a minimal 100usecs  */
797                         bbr->r_ctl.rc_hptsi_agg_delay -= slot;
798                         bbr->r_ctl.rc_last_delay_val = slot = 100;
799                 }
800         }
801         bbr->r_ctl.rc_last_delay_val = slot;
802         hpts_timeout = bbr_timer_start(tp, bbr, cts);
803         if (tp->t_flags & TF_DELACK) {
804                 if (bbr->rc_in_persist == 0) {
805                         delayed_ack = bbr_delack_time;
806                 } else {
807                         /* 
808                          * We are in persists and have 
809                          * gotten a new data element.
810                          */
811                         if (hpts_timeout > bbr_delack_time) {
812                                 /*
813                                  * Lets make the persists timer (which acks)
814                                  * be the smaller of hpts_timeout and bbr_delack_time.
815                                  */
816                                 hpts_timeout = bbr_delack_time;
817                         }
818                 }
819         } 
820         if (delayed_ack &&
821             ((hpts_timeout == 0) ||
822              (delayed_ack < hpts_timeout))) {
823                 /* We need a Delayed ack timer */
824                 bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
825                 hpts_timeout = delayed_ack;
826         }
827         if (slot) {
828                 /* Mark that we have a pacing timer up */
829                 BBR_STAT_INC(bbr_paced_segments);
830                 bbr->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
831         }
832         /*
833          * If no timers are going to run and we will fall off thfe hptsi
834          * wheel, we resort to a keep-alive timer if its configured.
835          */
836         if ((hpts_timeout == 0) &&
837             (slot == 0)) {
838                 if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
839                     (tp->t_state <= TCPS_CLOSING)) {
840                         /*
841                          * Ok we have no timer (persists, rack, tlp, rxt  or
842                          * del-ack), we don't have segments being paced. So
843                          * all that is left is the keepalive timer.
844                          */
845                         if (TCPS_HAVEESTABLISHED(tp->t_state)) {
846                                 hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
847                         } else {
848                                 hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
849                         }
850                         bbr->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
851                 }
852         }
853         if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
854             (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
855                 /*
856                  * RACK, TLP, persists and RXT timers all are restartable
857                  * based on actions input .. i.e we received a packet (ack
858                  * or sack) and that changes things (rw, or snd_una etc).
859                  * Thus we can restart them with a new value. For
860                  * keep-alive, delayed_ack we keep track of what was left
861                  * and restart the timer with a smaller value.
862                  */
863                 if (left < hpts_timeout)
864                         hpts_timeout = left;
865         }
866         if (bbr->r_ctl.rc_incr_tmrs && slot &&
867             (bbr->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
868                 /*
869                  * If configured to do so, and the timer is either
870                  * the TLP or RXT timer, we need to increase the timeout
871                  * by the pacing time. Consider the bottleneck at my
872                  * machine as an example, we are sending something
873                  * to start a TLP on. The last packet won't be emitted
874                  * fully until the pacing time (the bottleneck will hold
875                  * the data in place). Once the packet is emitted that
876                  * is when we want to start waiting for the TLP. This
877                  * is most evident with hardware pacing (where the nic
878                  * is holding the packet(s) before emitting). But it
879                  * can also show up in the network so we do it for all
880                  * cases. Technically we would take off one packet from
881                  * this extra delay but this is easier and being more
882                  * conservative is probably better.
883                  */
884                 hpts_timeout += slot;
885         }
886         if (hpts_timeout) {
887                 /*
888                  * Hack alert for now we can't time-out over 2147 seconds (a
889                  * bit more than 35min)
890                  */
891                 if (hpts_timeout > 0x7ffffffe)
892                         hpts_timeout = 0x7ffffffe;
893                 bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
894         } else
895                 bbr->r_ctl.rc_timer_exp = 0;
896         if ((slot) &&
897             (bbr->rc_use_google ||
898              bbr->output_error_seen ||
899              (slot <= hpts_timeout))  ) {
900                 /*
901                  * Tell LRO that it can queue packets while
902                  * we pace.
903                  */
904                 bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
905                 if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
906                     (bbr->rc_cwnd_limited == 0)) {
907                         /*
908                          * If we are not cwnd limited and we
909                          * are running a rack timer we put on
910                          * the do not disturbe even for sack.
911                          */
912                         inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
913                 } else 
914                         inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
915                 bbr->rc_pacer_started = cts;
916                 
917                 (void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(slot),
918                                            __LINE__, &diag);
919                 bbr->rc_timer_first = 0;
920                 bbr->bbr_timer_src = frm;
921                 bbr_log_to_start(bbr, cts, hpts_timeout, slot, 1);
922                 bbr_log_hpts_diag(bbr, cts, &diag);
923         } else if (hpts_timeout) {
924                 (void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(hpts_timeout),
925                                            __LINE__, &diag);
926                 /* 
927                  * We add the flag here as well if the slot is set, 
928                  * since hpts will call in to clear the queue first before
929                  * calling the output routine (which does our timers).
930                  * We don't want to set the flag if its just a timer
931                  * else the arrival of data might (that causes us
932                  * to send more) might get delayed. Imagine being
933                  * on a keep-alive timer and a request comes in for
934                  * more data.
935                  */
936                 if (slot)
937                         bbr->rc_pacer_started = cts;
938                 if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
939                     (bbr->rc_cwnd_limited == 0)) {
940                         /* 
941                          * For a rack timer, don't wake us even
942                          * if a sack arrives as long as we are
943                          * not cwnd limited.
944                          */
945                         bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
946                         inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
947                 } else {
948                         /* All other timers wake us up */
949                         bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
950                         inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
951                 }
952                 bbr->bbr_timer_src = frm;
953                 bbr_log_to_start(bbr, cts, hpts_timeout, slot, 0);
954                 bbr_log_hpts_diag(bbr, cts, &diag);
955                 bbr->rc_timer_first = 1;
956         }
957         bbr->rc_tmr_stopped = 0;
958         bbr_log_type_bbrsnd(bbr, tot_len, slot, delay_calc, cts, frm, prev_delay);
959 }
960
961 static void
962 bbr_timer_audit(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, struct sockbuf *sb)
963 {
964         /*
965          * We received an ack, and then did not call send or were bounced
966          * out due to the hpts was running. Now a timer is up as well, is it
967          * the right timer?
968          */
969         struct inpcb *inp;
970         struct bbr_sendmap *rsm;
971         uint32_t hpts_timeout;
972         int tmr_up;
973
974         tmr_up = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
975         if (bbr->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
976                 return;
977         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
978         if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
979             (tmr_up == PACE_TMR_RXT)) {
980                 /* Should be an RXT */
981                 return;
982         }
983         inp = bbr->rc_inp;
984         if (rsm == NULL) {
985                 /* Nothing outstanding? */
986                 if (tp->t_flags & TF_DELACK) {
987                         if (tmr_up == PACE_TMR_DELACK)
988                                 /*
989                                  * We are supposed to have delayed ack up
990                                  * and we do
991                                  */
992                                 return;
993                 } else if (sbavail(&inp->inp_socket->so_snd) &&
994                     (tmr_up == PACE_TMR_RXT)) {
995                         /*
996                          * if we hit enobufs then we would expect the
997                          * possiblity of nothing outstanding and the RXT up
998                          * (and the hptsi timer).
999                          */
1000                         return;
1001                 } else if (((V_tcp_always_keepalive ||
1002                             inp->inp_socket->so_options & SO_KEEPALIVE) &&
1003                             (tp->t_state <= TCPS_CLOSING)) &&
1004                             (tmr_up == PACE_TMR_KEEP) &&
1005                     (tp->snd_max == tp->snd_una)) {
1006                         /* We should have keep alive up and we do */
1007                         return;
1008                 }
1009         }
1010         if (rsm && (rsm->r_flags & BBR_SACK_PASSED)) {
1011                 if ((tp->t_flags & TF_SENTFIN) &&
1012                     ((tp->snd_max - tp->snd_una) == 1) &&
1013                     (rsm->r_flags & BBR_HAS_FIN)) {
1014                         /* needs to be a RXT */
1015                         if (tmr_up == PACE_TMR_RXT)
1016                                 return;
1017                         else
1018                                 goto wrong_timer;
1019                 } else if (tmr_up == PACE_TMR_RACK)
1020                         return;
1021                 else
1022                         goto wrong_timer;
1023         } else if (rsm && (tmr_up == PACE_TMR_RACK)) {
1024                 /* Rack timer has priority if we have data out */
1025                 return;
1026         } else if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1027                     ((tmr_up == PACE_TMR_TLP) ||
1028             (tmr_up == PACE_TMR_RXT))) {
1029                 /*
1030                  * Either a TLP or RXT is fine if no sack-passed is in place
1031                  * and data is outstanding.
1032                  */
1033                 return;
1034         } else if (tmr_up == PACE_TMR_DELACK) {
1035                 /*
1036                  * If the delayed ack was going to go off before the
1037                  * rtx/tlp/rack timer were going to expire, then that would
1038                  * be the timer in control. Note we don't check the time
1039                  * here trusting the code is correct.
1040                  */
1041                 return;
1042         }
1043         if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1044             ((tmr_up == PACE_TMR_RXT) ||
1045              (tmr_up == PACE_TMR_TLP) ||
1046              (tmr_up == PACE_TMR_RACK))) {
1047                 /*
1048                  * We have outstanding data and
1049                  * we *do* have a RACK, TLP or RXT
1050                  * timer running. We won't restart
1051                  * anything here since thats probably ok we 
1052                  * will get called with some timer here shortly.
1053                  */
1054                 return;
1055         }
1056         /*
1057          * Ok the timer originally started is not what we want now. We will
1058          * force the hpts to be stopped if any, and restart with the slot
1059          * set to what was in the saved slot.
1060          */
1061 wrong_timer:
1062         if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) {
1063                 if (inp->inp_in_hpts)
1064                         tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
1065                 bbr_timer_cancel(bbr, __LINE__, cts);
1066                 bbr_start_hpts_timer(bbr, tp, cts, 1, bbr->r_ctl.rc_last_delay_val,
1067                     0);
1068         } else {
1069                 /*
1070                  * Output is hptsi so we just need to switch the type of
1071                  * timer. We don't bother with keep-alive, since when we
1072                  * jump through the output, it will start the keep-alive if
1073                  * nothing is sent.
1074                  *
1075                  * We only need a delayed-ack added and or the hpts_timeout.
1076                  */
1077                 hpts_timeout = bbr_timer_start(tp, bbr, cts);
1078                 if (tp->t_flags & TF_DELACK) {
1079                         if (hpts_timeout == 0) {
1080                                 hpts_timeout = bbr_delack_time;
1081                                 bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1082                         }
1083                         else if (hpts_timeout > bbr_delack_time) {
1084                                 hpts_timeout = bbr_delack_time;
1085                                 bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1086                         }
1087                 }
1088                 if (hpts_timeout) {
1089                         if (hpts_timeout > 0x7ffffffe)
1090                                 hpts_timeout = 0x7ffffffe;
1091                         bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
1092                 }
1093         }
1094 }
1095
1096 int32_t bbr_clear_lost = 0;
1097
1098 /*
1099  * Considers the two time values now (cts) and earlier.
1100  * If cts is smaller than earlier, we could have
1101  * had a sequence wrap (our counter wraps every
1102  * 70 min or so) or it could be just clock skew
1103  * getting us two differnt time values. Clock skew
1104  * will show up within 10ms or so. So in such
1105  * a case (where cts is behind earlier time by
1106  * less than 10ms) we return 0. Otherwise we
1107  * return the true difference between them.
1108  */
1109 static inline uint32_t
1110 bbr_calc_time(uint32_t cts, uint32_t earlier_time) {
1111         /*
1112          * Given two timestamps, the current time stamp cts, and some other
1113          * time-stamp taken in theory earlier return the difference. The
1114          * trick is here sometimes locking will get the other timestamp
1115          * after the cts. If this occurs we need to return 0.
1116          */
1117         if (TSTMP_GEQ(cts, earlier_time))
1118                 return (cts - earlier_time);
1119         /*
1120          * cts is behind earlier_time if its less than 10ms consider it 0.
1121          * If its more than 10ms difference then we had a time wrap. Else
1122          * its just the normal locking foo. I wonder if we should not go to
1123          * 64bit TS and get rid of this issue.
1124          */
1125         if (TSTMP_GEQ((cts + 10000), earlier_time))
1126                 return (0);
1127         /*
1128          * Ok the time must have wrapped. So we need to answer a large
1129          * amount of time, which the normal subtraction should do.
1130          */
1131         return (cts - earlier_time);
1132 }
1133
1134
1135
1136 static int
1137 sysctl_bbr_clear_lost(SYSCTL_HANDLER_ARGS)
1138 {
1139         uint32_t stat;
1140         int32_t error;
1141
1142         error = SYSCTL_OUT(req, &bbr_clear_lost, sizeof(uint32_t));
1143         if (error || req->newptr == NULL)
1144                 return error;
1145
1146         error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
1147         if (error)
1148                 return (error);
1149         if (stat == 1) {
1150 #ifdef BBR_INVARIANTS
1151                 printf("Clearing BBR lost counters\n");
1152 #endif
1153                 COUNTER_ARRAY_ZERO(bbr_state_lost, BBR_MAX_STAT);
1154                 COUNTER_ARRAY_ZERO(bbr_state_time, BBR_MAX_STAT);
1155                 COUNTER_ARRAY_ZERO(bbr_state_resend, BBR_MAX_STAT);
1156         } else if (stat == 2) {
1157 #ifdef BBR_INVARIANTS
1158                 printf("Clearing BBR option counters\n");
1159 #endif
1160                 COUNTER_ARRAY_ZERO(bbr_opts_arry, BBR_OPTS_SIZE);
1161         } else if (stat == 3) {
1162 #ifdef BBR_INVARIANTS
1163                 printf("Clearing BBR stats counters\n");
1164 #endif
1165                 COUNTER_ARRAY_ZERO(bbr_stat_arry, BBR_STAT_SIZE);
1166         } else if (stat == 4) {
1167 #ifdef BBR_INVARIANTS
1168                 printf("Clearing BBR out-size counters\n");
1169 #endif
1170                 COUNTER_ARRAY_ZERO(bbr_out_size, TCP_MSS_ACCT_SIZE);
1171         }
1172         bbr_clear_lost = 0;
1173         return (0);
1174 }
1175
1176 static void
1177 bbr_init_sysctls(void)
1178 {
1179         struct sysctl_oid *bbr_probertt;
1180         struct sysctl_oid *bbr_hptsi;
1181         struct sysctl_oid *bbr_measure;
1182         struct sysctl_oid *bbr_cwnd;
1183         struct sysctl_oid *bbr_timeout;
1184         struct sysctl_oid *bbr_states;
1185         struct sysctl_oid *bbr_startup;
1186         struct sysctl_oid *bbr_policer;
1187
1188         /* Probe rtt controls */
1189         bbr_probertt = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1190             SYSCTL_CHILDREN(bbr_sysctl_root),
1191             OID_AUTO,
1192             "probertt",
1193             CTLFLAG_RW, 0,
1194             "");
1195         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1196             SYSCTL_CHILDREN(bbr_probertt),
1197             OID_AUTO, "gain", CTLFLAG_RW,
1198             &bbr_rttprobe_gain, 192,
1199             "What is the filter gain drop in probe_rtt (0=disable)?");
1200         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1201             SYSCTL_CHILDREN(bbr_probertt),
1202             OID_AUTO, "cwnd", CTLFLAG_RW,
1203             &bbr_rtt_probe_cwndtarg, 4,
1204             "How many mss's are outstanding during probe-rtt");
1205         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1206             SYSCTL_CHILDREN(bbr_probertt),
1207             OID_AUTO, "int", CTLFLAG_RW,
1208             &bbr_rtt_probe_limit, 4000000,
1209             "If RTT has not shrank in this many micro-seconds enter probe-rtt");
1210         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1211             SYSCTL_CHILDREN(bbr_probertt),
1212             OID_AUTO, "mintime", CTLFLAG_RW,
1213             &bbr_rtt_probe_time, 200000,
1214             "How many microseconds in probe-rtt");
1215         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1216             SYSCTL_CHILDREN(bbr_probertt),
1217             OID_AUTO, "filter_len_sec", CTLFLAG_RW,
1218             &bbr_filter_len_sec, 6,
1219             "How long in seconds does the rttProp filter run?");
1220         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1221             SYSCTL_CHILDREN(bbr_probertt),
1222             OID_AUTO, "drain_rtt", CTLFLAG_RW,
1223             &bbr_drain_rtt, BBR_SRTT,
1224             "What is the drain rtt to use in probeRTT (rtt_prop=0, rtt_rack=1, rtt_pkt=2, rtt_srtt=3?");
1225         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1226             SYSCTL_CHILDREN(bbr_probertt),
1227             OID_AUTO, "can_force", CTLFLAG_RW,
1228             &bbr_can_force_probertt, 0,
1229             "If we keep setting new low rtt's but delay going in probe-rtt can we force in??");
1230         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1231             SYSCTL_CHILDREN(bbr_probertt),
1232             OID_AUTO, "enter_sets_force", CTLFLAG_RW,
1233             &bbr_probertt_sets_rtt, 0,
1234             "In NF mode, do we imitate google_mode and set the rttProp on entry to probe-rtt?");
1235         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1236             SYSCTL_CHILDREN(bbr_probertt),
1237             OID_AUTO, "can_adjust", CTLFLAG_RW,
1238             &bbr_can_adjust_probertt, 1,
1239             "Can we dynamically adjust the probe-rtt limits and times?");
1240         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1241             SYSCTL_CHILDREN(bbr_probertt),
1242             OID_AUTO, "is_ratio", CTLFLAG_RW,
1243             &bbr_is_ratio, 0,
1244             "is the limit to filter a ratio?");
1245         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1246             SYSCTL_CHILDREN(bbr_probertt),
1247             OID_AUTO, "use_cwnd", CTLFLAG_RW,
1248             &bbr_prtt_slam_cwnd, 0,
1249             "Should we set/recover cwnd?");
1250         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1251             SYSCTL_CHILDREN(bbr_probertt),
1252             OID_AUTO, "can_use_ts", CTLFLAG_RW,
1253             &bbr_can_use_ts_for_rtt, 1,
1254             "Can we use the ms timestamp if available for retransmistted rtt calculations?");
1255
1256         /* Pacing controls */
1257         bbr_hptsi = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1258             SYSCTL_CHILDREN(bbr_sysctl_root),
1259             OID_AUTO,
1260             "pacing",
1261             CTLFLAG_RW, 0,
1262             "");
1263         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1264             SYSCTL_CHILDREN(bbr_hptsi),
1265             OID_AUTO, "hw_pacing", CTLFLAG_RW,
1266             &bbr_allow_hdwr_pacing, 1,
1267             "Do we allow hardware pacing?");
1268         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1269             SYSCTL_CHILDREN(bbr_hptsi),
1270             OID_AUTO, "hw_pacing_limit", CTLFLAG_RW,
1271             &bbr_hardware_pacing_limit, 4000,
1272             "Do we have a limited number of connections for pacing chelsio (0=no limit)?");
1273         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1274             SYSCTL_CHILDREN(bbr_hptsi),
1275             OID_AUTO, "hw_pacing_adj", CTLFLAG_RW,
1276             &bbr_hdwr_pace_adjust, 2,
1277             "Multiplier to calculated tso size?");
1278         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1279             SYSCTL_CHILDREN(bbr_hptsi),
1280             OID_AUTO, "hw_pacing_floor", CTLFLAG_RW,
1281             &bbr_hdwr_pace_floor, 1,
1282             "Do we invoke the hardware pacing floor?");
1283         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1284             SYSCTL_CHILDREN(bbr_hptsi),
1285             OID_AUTO, "hw_pacing_delay_cnt", CTLFLAG_RW,
1286             &bbr_hdwr_pacing_delay_cnt, 10,
1287             "How many packets must be sent after hdwr pacing is enabled");
1288         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1289             SYSCTL_CHILDREN(bbr_hptsi),
1290             OID_AUTO, "bw_cross", CTLFLAG_RW,
1291             &bbr_cross_over, 3000000,
1292             "What is the point where we cross over to linux like TSO size set");
1293         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1294             SYSCTL_CHILDREN(bbr_hptsi),
1295             OID_AUTO, "seg_deltarg", CTLFLAG_RW,
1296             &bbr_hptsi_segments_delay_tar, 7000,
1297             "What is the worse case delay target for hptsi < 48Mbp connections");
1298         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1299             SYSCTL_CHILDREN(bbr_hptsi),
1300             OID_AUTO, "enet_oh", CTLFLAG_RW,
1301             &bbr_include_enet_oh, 0,
1302             "Do we include the ethernet overhead in calculating pacing delay?");
1303         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1304             SYSCTL_CHILDREN(bbr_hptsi),
1305             OID_AUTO, "ip_oh", CTLFLAG_RW,
1306             &bbr_include_ip_oh, 1,
1307             "Do we include the IP overhead in calculating pacing delay?");
1308         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1309             SYSCTL_CHILDREN(bbr_hptsi),
1310             OID_AUTO, "tcp_oh", CTLFLAG_RW,
1311             &bbr_include_tcp_oh, 0,
1312             "Do we include the TCP overhead in calculating pacing delay?");
1313         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1314             SYSCTL_CHILDREN(bbr_hptsi),
1315             OID_AUTO, "google_discount", CTLFLAG_RW,
1316             &bbr_google_discount, 10,
1317             "What is the default google discount percentage wise for pacing (11 = 1.1%%)?");
1318         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1319             SYSCTL_CHILDREN(bbr_hptsi),
1320             OID_AUTO, "all_get_min", CTLFLAG_RW,
1321             &bbr_all_get_min, 0,
1322             "If you are less than a MSS do you just get the min?");
1323         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1324             SYSCTL_CHILDREN(bbr_hptsi),
1325             OID_AUTO, "tso_min", CTLFLAG_RW,
1326             &bbr_hptsi_bytes_min, 1460,
1327             "For 0 -> 24Mbps what is floor number of segments for TSO");
1328         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1329             SYSCTL_CHILDREN(bbr_hptsi),
1330             OID_AUTO, "seg_tso_max", CTLFLAG_RW,
1331             &bbr_hptsi_segments_max, 6,
1332             "For 0 -> 24Mbps what is top number of segments for TSO");
1333         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1334             SYSCTL_CHILDREN(bbr_hptsi),
1335             OID_AUTO, "seg_floor", CTLFLAG_RW,
1336             &bbr_hptsi_segments_floor, 1,
1337             "Minimum TSO size we will fall too in segments");
1338         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1339             SYSCTL_CHILDREN(bbr_hptsi),
1340             OID_AUTO, "utter_max", CTLFLAG_RW,
1341             &bbr_hptsi_utter_max, 0,
1342             "The absolute maximum that any pacing (outside of hardware) can be");
1343         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1344             SYSCTL_CHILDREN(bbr_hptsi),
1345             OID_AUTO, "seg_divisor", CTLFLAG_RW,
1346             &bbr_hptsi_per_second, 100,
1347             "What is the divisor in our hptsi TSO calculation 512Mbps < X > 24Mbps ");
1348         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1349             SYSCTL_CHILDREN(bbr_hptsi),
1350             OID_AUTO, "srtt_mul", CTLFLAG_RW,
1351             &bbr_hptsi_max_mul, 1,
1352             "The multiplier for pace len max");
1353         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1354             SYSCTL_CHILDREN(bbr_hptsi),
1355             OID_AUTO, "srtt_div", CTLFLAG_RW,
1356             &bbr_hptsi_max_div, 2,
1357             "The divisor for pace len max");
1358         /* Measurement controls */
1359         bbr_measure = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1360             SYSCTL_CHILDREN(bbr_sysctl_root),
1361             OID_AUTO,
1362             "measure",
1363             CTLFLAG_RW, 0,
1364             "Measurement controls");
1365         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1366             SYSCTL_CHILDREN(bbr_measure),
1367             OID_AUTO, "min_i_bw", CTLFLAG_RW,
1368             &bbr_initial_bw_bps, 62500,
1369             "Minimum initial b/w in bytes per second");
1370         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1371             SYSCTL_CHILDREN(bbr_measure),
1372             OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1373             &bbr_sack_not_required, 0,
1374             "Do we allow bbr to run on connections not supporting SACK?");
1375         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1376             SYSCTL_CHILDREN(bbr_measure),
1377             OID_AUTO, "use_google", CTLFLAG_RW,
1378             &bbr_use_google_algo, 0,
1379             "Use has close to google V1.0 has possible?");
1380         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1381             SYSCTL_CHILDREN(bbr_measure),
1382             OID_AUTO, "ts_limiting", CTLFLAG_RW,
1383             &bbr_ts_limiting, 1,
1384             "Do we attempt to use the peers timestamp to limit b/w caculations?");
1385         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1386             SYSCTL_CHILDREN(bbr_measure),
1387             OID_AUTO, "ts_can_raise", CTLFLAG_RW,
1388             &bbr_ts_can_raise, 0,
1389             "Can we raise the b/w via timestamp b/w calculation?");
1390         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1391             SYSCTL_CHILDREN(bbr_measure),
1392             OID_AUTO, "ts_delta", CTLFLAG_RW,
1393             &bbr_min_usec_delta, 20000,
1394             "How long in usec between ts of our sends in ts validation code?");
1395         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1396             SYSCTL_CHILDREN(bbr_measure),
1397             OID_AUTO, "ts_peer_delta", CTLFLAG_RW,
1398             &bbr_min_peer_delta, 20,
1399             "What min numerical value should be between the peer deltas?");
1400         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1401             SYSCTL_CHILDREN(bbr_measure),
1402             OID_AUTO, "ts_delta_percent", CTLFLAG_RW,
1403             &bbr_delta_percent, 150,
1404             "What percentage (150 = 15.0) do we allow variance for?");
1405         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1406             SYSCTL_CHILDREN(bbr_measure),
1407             OID_AUTO, "min_measure_good_bw", CTLFLAG_RW,
1408             &bbr_min_measurements_req, 1,
1409             "What is the minimum measurment count we need before we switch to our b/w estimate");
1410         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1411             SYSCTL_CHILDREN(bbr_measure),
1412             OID_AUTO, "min_measure_before_pace", CTLFLAG_RW,
1413             &bbr_no_pacing_until, 4,
1414             "How many pkt-epoch's (0 is off) do we need before pacing is on?");
1415         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1416             SYSCTL_CHILDREN(bbr_measure),
1417             OID_AUTO, "quanta", CTLFLAG_RW,
1418             &bbr_quanta, 2,
1419             "Extra quanta to add when calculating the target (ID section 4.2.3.2).");
1420         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1421             SYSCTL_CHILDREN(bbr_measure),
1422             OID_AUTO, "noretran", CTLFLAG_RW,
1423             &bbr_no_retran, 0,
1424             "Should google mode not use retransmission measurements for the b/w estimation?");
1425         /* State controls */
1426         bbr_states = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1427             SYSCTL_CHILDREN(bbr_sysctl_root),
1428             OID_AUTO,
1429             "states",
1430             CTLFLAG_RW, 0,
1431             "State controls");
1432         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1433             SYSCTL_CHILDREN(bbr_states),
1434             OID_AUTO, "idle_restart", CTLFLAG_RW,
1435             &bbr_uses_idle_restart, 0,
1436             "Do we use a new special idle_restart state to ramp back up quickly?");
1437         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1438             SYSCTL_CHILDREN(bbr_states),
1439             OID_AUTO, "idle_restart_threshold", CTLFLAG_RW,
1440             &bbr_idle_restart_threshold, 100000,
1441             "How long must we be idle before we restart??");
1442         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1443             SYSCTL_CHILDREN(bbr_states),
1444             OID_AUTO, "use_pkt_epoch", CTLFLAG_RW,
1445             &bbr_state_is_pkt_epoch, 0,
1446             "Do we use a pkt-epoch for substate if 0 rttProp?");
1447         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1448             SYSCTL_CHILDREN(bbr_states),
1449             OID_AUTO, "startup_rtt_gain", CTLFLAG_RW,
1450             &bbr_rtt_gain_thresh, 0,
1451             "What increase in RTT triggers us to stop ignoring no-loss and possibly exit startup?");
1452         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1453             SYSCTL_CHILDREN(bbr_states),
1454             OID_AUTO, "drain_floor", CTLFLAG_RW,
1455             &bbr_drain_floor, 88,
1456             "What is the lowest we can drain (pg) too?");
1457         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1458             SYSCTL_CHILDREN(bbr_states),
1459             OID_AUTO, "drain_2_target", CTLFLAG_RW,
1460             &bbr_state_drain_2_tar, 1,
1461             "Do we drain to target in drain substate?");
1462         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1463             SYSCTL_CHILDREN(bbr_states),
1464             OID_AUTO, "gain_2_target", CTLFLAG_RW,
1465             &bbr_gain_to_target, 1,
1466             "Does probe bw gain to target??");
1467         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1468             SYSCTL_CHILDREN(bbr_states),
1469             OID_AUTO, "gain_extra_time", CTLFLAG_RW,
1470             &bbr_gain_gets_extra_too, 1,
1471             "Does probe bw gain get the extra time too?");
1472         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1473             SYSCTL_CHILDREN(bbr_states),
1474             OID_AUTO, "ld_div", CTLFLAG_RW,
1475             &bbr_drain_drop_div, 5,
1476             "Long drain drop divider?");
1477         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1478             SYSCTL_CHILDREN(bbr_states),
1479             OID_AUTO, "ld_mul", CTLFLAG_RW,
1480             &bbr_drain_drop_mul, 4,
1481             "Long drain drop multiplier?");
1482         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1483             SYSCTL_CHILDREN(bbr_states),
1484             OID_AUTO, "rand_ot_disc", CTLFLAG_RW,
1485             &bbr_rand_ot, 50,
1486             "Random discount of the ot?");
1487         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1488             SYSCTL_CHILDREN(bbr_states),
1489             OID_AUTO, "dr_filter_life", CTLFLAG_RW,
1490             &bbr_num_pktepo_for_del_limit, BBR_NUM_RTTS_FOR_DEL_LIMIT,
1491             "How many packet-epochs does the b/w delivery rate last?");
1492         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1493             SYSCTL_CHILDREN(bbr_states),
1494             OID_AUTO, "subdrain_applimited", CTLFLAG_RW,
1495             &bbr_sub_drain_app_limit, 0,
1496             "Does our sub-state drain invoke app limited if its long?");
1497         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1498             SYSCTL_CHILDREN(bbr_states),
1499             OID_AUTO, "use_cwnd_subdrain", CTLFLAG_RW,
1500             &bbr_sub_drain_slam_cwnd, 0,
1501             "Should we set/recover cwnd for sub-state drain?");
1502         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1503             SYSCTL_CHILDREN(bbr_states),
1504             OID_AUTO, "use_cwnd_maindrain", CTLFLAG_RW,
1505             &bbr_slam_cwnd_in_main_drain, 0,
1506             "Should we set/recover cwnd for main-state drain?");
1507         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1508             SYSCTL_CHILDREN(bbr_states),
1509             OID_AUTO, "google_gets_earlyout", CTLFLAG_RW,
1510             &google_allow_early_out, 1,
1511             "Should we allow google probe-bw/drain to exit early at flight target?");
1512         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1513             SYSCTL_CHILDREN(bbr_states),
1514             OID_AUTO, "google_exit_loss", CTLFLAG_RW,
1515             &google_consider_lost, 1,
1516             "Should we have losses exit gain of probebw in google mode??");
1517         /* Startup controls */
1518         bbr_startup = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1519             SYSCTL_CHILDREN(bbr_sysctl_root),
1520             OID_AUTO,
1521             "startup",
1522             CTLFLAG_RW, 0,
1523             "Startup controls");
1524         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1525             SYSCTL_CHILDREN(bbr_startup),
1526             OID_AUTO, "cheat_iwnd", CTLFLAG_RW,
1527             &bbr_sends_full_iwnd, 1,
1528             "Do we not pace but burst out initial windows has our TSO size?");
1529         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1530             SYSCTL_CHILDREN(bbr_startup),
1531             OID_AUTO, "loss_threshold", CTLFLAG_RW,
1532             &bbr_startup_loss_thresh, 2000,
1533             "In startup what is the loss threshold in a pe that will exit us from startup?");
1534         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1535             SYSCTL_CHILDREN(bbr_startup),
1536             OID_AUTO, "use_lowerpg", CTLFLAG_RW,
1537             &bbr_use_lower_gain_in_startup, 1,
1538             "Should we use a lower hptsi gain if we see loss in startup?");
1539         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1540             SYSCTL_CHILDREN(bbr_startup),
1541             OID_AUTO, "gain", CTLFLAG_RW,
1542             &bbr_start_exit, 25,
1543             "What gain percent do we need to see to stay in startup??");
1544         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1545             SYSCTL_CHILDREN(bbr_startup),
1546             OID_AUTO, "low_gain", CTLFLAG_RW,
1547             &bbr_low_start_exit, 15,
1548             "What gain percent do we need to see to stay in the lower gain startup??");
1549         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1550             SYSCTL_CHILDREN(bbr_startup),
1551             OID_AUTO, "loss_exit", CTLFLAG_RW,
1552             &bbr_exit_startup_at_loss, 1,
1553             "Should we exit startup at loss in an epoch if we are not gaining?");
1554         /* CWND controls */
1555         bbr_cwnd = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1556             SYSCTL_CHILDREN(bbr_sysctl_root),
1557             OID_AUTO,
1558             "cwnd",
1559             CTLFLAG_RW, 0,
1560             "Cwnd controls");
1561         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1562             SYSCTL_CHILDREN(bbr_cwnd),
1563             OID_AUTO, "tar_rtt", CTLFLAG_RW,
1564             &bbr_cwndtarget_rtt_touse, 0,
1565             "Target cwnd rtt measurment to use (0=rtt_prop, 1=rtt_rack, 2=pkt_rtt, 3=srtt)?");
1566         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1567             SYSCTL_CHILDREN(bbr_cwnd),
1568             OID_AUTO, "may_shrink", CTLFLAG_RW,
1569             &bbr_cwnd_may_shrink, 0,
1570             "Can the cwnd shrink if it would grow to more than the target?");
1571         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1572             SYSCTL_CHILDREN(bbr_cwnd),
1573             OID_AUTO, "max_target_limit", CTLFLAG_RW,
1574             &bbr_target_cwnd_mult_limit, 8,
1575             "Do we limit the cwnd to some multiple of the cwnd target if cwnd can't shrink 0=no?");
1576         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1577             SYSCTL_CHILDREN(bbr_cwnd),
1578             OID_AUTO, "highspeed_min", CTLFLAG_RW,
1579             &bbr_cwnd_min_val_hs, BBR_HIGHSPEED_NUM_MSS,
1580             "What is the high-speed min cwnd (rttProp under 1ms)");
1581         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1582             SYSCTL_CHILDREN(bbr_cwnd),
1583             OID_AUTO, "lowspeed_min", CTLFLAG_RW,
1584             &bbr_cwnd_min_val, BBR_PROBERTT_NUM_MSS,
1585             "What is the min cwnd (rttProp > 1ms)");
1586         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1587             SYSCTL_CHILDREN(bbr_cwnd),
1588             OID_AUTO, "initwin", CTLFLAG_RW,
1589             &bbr_def_init_win, 10,
1590             "What is the BBR initial window, if 0 use tcp version");
1591         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1592             SYSCTL_CHILDREN(bbr_cwnd),
1593             OID_AUTO, "do_loss_red", CTLFLAG_RW,
1594             &bbr_do_red, 600,
1595             "Do we reduce the b/w at exit from recovery based on ratio of prop/srtt (800=80.0, 0=off)?");
1596         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1597             SYSCTL_CHILDREN(bbr_cwnd),
1598             OID_AUTO, "red_scale", CTLFLAG_RW,
1599             &bbr_red_scale, 20000,
1600             "What RTT do we scale with?");
1601         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1602             SYSCTL_CHILDREN(bbr_cwnd),
1603             OID_AUTO, "red_growslow", CTLFLAG_RW,
1604             &bbr_red_growth_restrict, 1,
1605             "Do we restrict cwnd growth for whats in flight?");
1606         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1607             SYSCTL_CHILDREN(bbr_cwnd),
1608             OID_AUTO, "red_div", CTLFLAG_RW,
1609             &bbr_red_div, 2,
1610             "If we reduce whats the divisor?");
1611         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1612             SYSCTL_CHILDREN(bbr_cwnd),
1613             OID_AUTO, "red_mul", CTLFLAG_RW,
1614             &bbr_red_mul, 1,
1615             "If we reduce whats the mulitiplier?");
1616         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1617             SYSCTL_CHILDREN(bbr_cwnd),
1618             OID_AUTO, "target_is_unit", CTLFLAG_RW,
1619             &bbr_target_is_bbunit, 0,
1620             "Is the state target the pacing_gain or BBR_UNIT?");
1621         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1622             SYSCTL_CHILDREN(bbr_cwnd),
1623             OID_AUTO, "drop_limit", CTLFLAG_RW,
1624             &bbr_drop_limit, 0,
1625             "Number of segments limit for drop (0=use min_cwnd w/flight)?");
1626
1627         /* Timeout controls */
1628         bbr_timeout = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1629             SYSCTL_CHILDREN(bbr_sysctl_root),
1630             OID_AUTO,
1631             "timeout",
1632             CTLFLAG_RW, 0,
1633             "Time out controls");
1634         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1635             SYSCTL_CHILDREN(bbr_timeout),
1636             OID_AUTO, "delack", CTLFLAG_RW,
1637             &bbr_delack_time, 100000,
1638             "BBR's delayed ack time");
1639         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1640             SYSCTL_CHILDREN(bbr_timeout),
1641             OID_AUTO, "tlp_uses", CTLFLAG_RW,
1642             &bbr_tlp_type_to_use, 3,
1643             "RTT that TLP uses in its calculations, 0=rttProp, 1=Rack_rtt, 2=pkt_rtt and 3=srtt");
1644         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1645             SYSCTL_CHILDREN(bbr_timeout),
1646             OID_AUTO, "persmin", CTLFLAG_RW,
1647             &bbr_persist_min, 250000,
1648             "What is the minimum time in microseconds between persists");
1649         SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1650             SYSCTL_CHILDREN(bbr_timeout),
1651             OID_AUTO, "persmax", CTLFLAG_RW,
1652             &bbr_persist_max, 1000000,
1653             "What is the largest delay in microseconds between persists");
1654         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1655             SYSCTL_CHILDREN(bbr_timeout),
1656             OID_AUTO, "tlp_minto", CTLFLAG_RW,
1657             &bbr_tlp_min, 10000,
1658             "TLP Min timeout in usecs");
1659         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1660             SYSCTL_CHILDREN(bbr_timeout),
1661             OID_AUTO, "tlp_dack_time", CTLFLAG_RW,
1662             &bbr_delayed_ack_time, 200000,
1663             "TLP delayed ack compensation value");
1664         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1665             SYSCTL_CHILDREN(bbr_sysctl_root),
1666             OID_AUTO, "minrto", CTLFLAG_RW,
1667             &bbr_rto_min_ms, 30,
1668             "Minimum RTO in ms");
1669         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1670             SYSCTL_CHILDREN(bbr_timeout),
1671             OID_AUTO, "maxrto", CTLFLAG_RW,
1672             &bbr_rto_max_sec, 4,
1673             "Maxiumum RTO in seconds -- should be at least as large as min_rto");
1674         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1675             SYSCTL_CHILDREN(bbr_timeout),
1676             OID_AUTO, "tlp_retry", CTLFLAG_RW,
1677             &bbr_tlp_max_resend, 2,
1678             "How many times does TLP retry a single segment or multiple with no ACK");
1679         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1680             SYSCTL_CHILDREN(bbr_timeout),
1681             OID_AUTO, "minto", CTLFLAG_RW,
1682             &bbr_min_to, 1000,
1683             "Minimum rack timeout in useconds");
1684         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1685             SYSCTL_CHILDREN(bbr_timeout),
1686             OID_AUTO, "pktdelay", CTLFLAG_RW,
1687             &bbr_pkt_delay, 1000,
1688             "Extra RACK time (in useconds) besides reordering thresh");
1689         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1690             SYSCTL_CHILDREN(bbr_timeout),
1691             OID_AUTO, "incr_tmrs", CTLFLAG_RW,
1692             &bbr_incr_timers, 1,
1693             "Increase the RXT/TLP timer by the pacing time used?");
1694         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1695             SYSCTL_CHILDREN(bbr_timeout),
1696             OID_AUTO, "rxtmark_sackpassed", CTLFLAG_RW,
1697             &bbr_marks_rxt_sack_passed, 0,
1698             "Mark sack passed on all those not ack'd when a RXT hits?");
1699         /* Policer controls */
1700         bbr_policer = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1701             SYSCTL_CHILDREN(bbr_sysctl_root),
1702             OID_AUTO,
1703             "policer",
1704             CTLFLAG_RW, 0,
1705             "Policer controls");
1706         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1707             SYSCTL_CHILDREN(bbr_policer),
1708             OID_AUTO, "detect_enable", CTLFLAG_RW,
1709             &bbr_policer_detection_enabled, 1,
1710             "Is policer detection enabled??");
1711         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1712             SYSCTL_CHILDREN(bbr_policer),
1713             OID_AUTO, "min_pes", CTLFLAG_RW,
1714             &bbr_lt_intvl_min_rtts, 4,
1715             "Minimum number of PE's?");
1716         SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1717             SYSCTL_CHILDREN(bbr_policer),
1718             OID_AUTO, "bwdiff", CTLFLAG_RW,
1719             &bbr_lt_bw_diff, (4000/8),
1720             "Minimal bw diff?");
1721         SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1722             SYSCTL_CHILDREN(bbr_policer),
1723             OID_AUTO, "bwratio", CTLFLAG_RW,
1724             &bbr_lt_bw_ratio, 8,
1725             "Minimal bw diff?");
1726         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1727             SYSCTL_CHILDREN(bbr_policer),
1728             OID_AUTO, "from_rack_rxt", CTLFLAG_RW,
1729             &bbr_policer_call_from_rack_to, 0,
1730             "Do we call the policer detection code from a rack-timeout?");
1731         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1732             SYSCTL_CHILDREN(bbr_policer),
1733             OID_AUTO, "false_postive", CTLFLAG_RW,
1734             &bbr_lt_intvl_fp, 0,
1735             "What packet epoch do we do false-postive detection at (0=no)?");
1736         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1737             SYSCTL_CHILDREN(bbr_policer),
1738             OID_AUTO, "loss_thresh", CTLFLAG_RW,
1739             &bbr_lt_loss_thresh, 196,
1740             "Loss threshold 196 = 19.6%?");
1741         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1742             SYSCTL_CHILDREN(bbr_policer),
1743             OID_AUTO, "false_postive_thresh", CTLFLAG_RW,
1744             &bbr_lt_fd_thresh, 100,
1745             "What percentage is the false detection threshold (150=15.0)?");
1746         /* All the rest */
1747         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1748             SYSCTL_CHILDREN(bbr_sysctl_root),
1749             OID_AUTO, "cheat_rxt", CTLFLAG_RW,
1750             &bbr_use_rack_resend_cheat, 0,
1751             "Do we burst 1ms between sends on retransmissions (like rack)?");
1752         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1753             SYSCTL_CHILDREN(bbr_sysctl_root),
1754             OID_AUTO, "error_paceout", CTLFLAG_RW,
1755             &bbr_error_base_paceout, 10000,
1756             "When we hit an error what is the min to pace out in usec's?");
1757         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1758             SYSCTL_CHILDREN(bbr_sysctl_root),
1759             OID_AUTO, "kill_paceout", CTLFLAG_RW,
1760             &bbr_max_net_error_cnt, 10,
1761             "When we hit this many errors in a row, kill the session?");
1762         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1763             SYSCTL_CHILDREN(bbr_sysctl_root),
1764             OID_AUTO, "data_after_close", CTLFLAG_RW,
1765             &bbr_ignore_data_after_close, 1,
1766             "Do we hold off sending a RST until all pending data is ack'd");
1767         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1768             SYSCTL_CHILDREN(bbr_sysctl_root),
1769             OID_AUTO, "resend_use_tso", CTLFLAG_RW,
1770             &bbr_resends_use_tso, 0,
1771             "Can resends use TSO?");
1772         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1773             SYSCTL_CHILDREN(bbr_sysctl_root),
1774             OID_AUTO, "sblklimit", CTLFLAG_RW,
1775             &bbr_sack_block_limit, 128,
1776             "When do we start ignoring small sack blocks");
1777         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1778             SYSCTL_CHILDREN(bbr_sysctl_root),
1779             OID_AUTO, "bb_verbose", CTLFLAG_RW,
1780             &bbr_verbose_logging, 0,
1781             "Should BBR black box logging be verbose");
1782         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1783             SYSCTL_CHILDREN(bbr_sysctl_root),
1784             OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1785             &bbr_reorder_thresh, 2,
1786             "What factor for rack will be added when seeing reordering (shift right)");
1787         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1788             SYSCTL_CHILDREN(bbr_sysctl_root),
1789             OID_AUTO, "reorder_fade", CTLFLAG_RW,
1790             &bbr_reorder_fade, 0,
1791             "Does reorder detection fade, if so how many ms (0 means never)");
1792         SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1793             SYSCTL_CHILDREN(bbr_sysctl_root),
1794             OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1795             &bbr_tlp_thresh, 1,
1796             "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1797         /* Stats and counters */
1798         /* The pacing counters for hdwr/software can't be in the array */
1799         bbr_nohdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1800         bbr_hdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1801         SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1802             SYSCTL_CHILDREN(bbr_sysctl_root),
1803             OID_AUTO, "enob_hdwr_pacing", CTLFLAG_RD,
1804             &bbr_hdwr_pacing_enobuf,
1805             "Total number of enobufs for hardware paced flows");
1806         SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1807             SYSCTL_CHILDREN(bbr_sysctl_root),
1808             OID_AUTO, "enob_no_hdwr_pacing", CTLFLAG_RD,
1809             &bbr_nohdwr_pacing_enobuf,
1810             "Total number of enobufs for non-hardware paced flows");
1811
1812
1813         bbr_flows_whdwr_pacing = counter_u64_alloc(M_WAITOK);
1814         SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1815             SYSCTL_CHILDREN(bbr_sysctl_root),
1816             OID_AUTO, "hdwr_pacing", CTLFLAG_RD,
1817             &bbr_flows_whdwr_pacing,
1818             "Total number of hardware paced flows");
1819         bbr_flows_nohdwr_pacing = counter_u64_alloc(M_WAITOK);
1820         SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1821             SYSCTL_CHILDREN(bbr_sysctl_root),
1822             OID_AUTO, "software_pacing", CTLFLAG_RD,
1823             &bbr_flows_nohdwr_pacing,
1824             "Total number of software paced flows");
1825         COUNTER_ARRAY_ALLOC(bbr_stat_arry, BBR_STAT_SIZE, M_WAITOK);
1826         SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1827             OID_AUTO, "stats", CTLFLAG_RD,
1828             bbr_stat_arry, BBR_STAT_SIZE, "BBR Stats");
1829         COUNTER_ARRAY_ALLOC(bbr_opts_arry, BBR_OPTS_SIZE, M_WAITOK);
1830         SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1831             OID_AUTO, "opts", CTLFLAG_RD,
1832             bbr_opts_arry, BBR_OPTS_SIZE, "BBR Option Stats");
1833         COUNTER_ARRAY_ALLOC(bbr_state_lost, BBR_MAX_STAT, M_WAITOK);
1834         SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1835             OID_AUTO, "lost", CTLFLAG_RD,
1836             bbr_state_lost, BBR_MAX_STAT, "Stats of when losses occur");
1837         COUNTER_ARRAY_ALLOC(bbr_state_resend, BBR_MAX_STAT, M_WAITOK);
1838         SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1839             OID_AUTO, "stateresend", CTLFLAG_RD,
1840             bbr_state_resend, BBR_MAX_STAT, "Stats of what states resend");
1841         COUNTER_ARRAY_ALLOC(bbr_state_time, BBR_MAX_STAT, M_WAITOK);
1842         SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1843             OID_AUTO, "statetime", CTLFLAG_RD,
1844             bbr_state_time, BBR_MAX_STAT, "Stats of time spent in the states");
1845         COUNTER_ARRAY_ALLOC(bbr_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1846         SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1847             OID_AUTO, "outsize", CTLFLAG_RD,
1848             bbr_out_size, TCP_MSS_ACCT_SIZE, "Size of output calls");
1849         SYSCTL_ADD_PROC(&bbr_sysctl_ctx,
1850             SYSCTL_CHILDREN(bbr_sysctl_root),
1851             OID_AUTO, "clrlost", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1852             &bbr_clear_lost, 0, sysctl_bbr_clear_lost, "IU", "Clear lost counters");
1853 }
1854
1855 static inline int32_t
1856 bbr_progress_timeout_check(struct tcp_bbr *bbr)
1857 {
1858         if (bbr->rc_tp->t_maxunacktime && bbr->rc_tp->t_acktime &&
1859             TSTMP_GT(ticks, bbr->rc_tp->t_acktime)) {
1860                 if ((((uint32_t)ticks - bbr->rc_tp->t_acktime)) >= bbr->rc_tp->t_maxunacktime) {
1861                         /*
1862                          * There is an assumption here that the caller will
1863                          * drop the connection, so we increment the
1864                          * statistics.
1865                          */
1866                         bbr_log_progress_event(bbr, bbr->rc_tp, ticks, PROGRESS_DROP, __LINE__);
1867                         BBR_STAT_INC(bbr_progress_drops);
1868 #ifdef NETFLIX_STATS
1869                         TCPSTAT_INC(tcps_progdrops);
1870 #endif
1871                         return (1);
1872                 }
1873         }
1874         return (0);
1875 }
1876
1877 static void
1878 bbr_counter_destroy(void)
1879 {
1880         COUNTER_ARRAY_FREE(bbr_stat_arry, BBR_STAT_SIZE);
1881         COUNTER_ARRAY_FREE(bbr_opts_arry, BBR_OPTS_SIZE);
1882         COUNTER_ARRAY_FREE(bbr_out_size, TCP_MSS_ACCT_SIZE);
1883         COUNTER_ARRAY_FREE(bbr_state_lost, BBR_MAX_STAT);
1884         COUNTER_ARRAY_FREE(bbr_state_time, BBR_MAX_STAT);
1885         COUNTER_ARRAY_FREE(bbr_state_resend, BBR_MAX_STAT);
1886         counter_u64_free(bbr_flows_whdwr_pacing);
1887         counter_u64_free(bbr_flows_nohdwr_pacing);
1888
1889 }
1890
1891 static __inline void
1892 bbr_fill_in_logging_data(struct tcp_bbr *bbr, struct tcp_log_bbr *l, uint32_t cts)
1893 {
1894         memset(l, 0, sizeof(union tcp_log_stackspecific));
1895         l->cur_del_rate = bbr->r_ctl.rc_bbr_cur_del_rate;
1896         l->delRate = get_filter_value(&bbr->r_ctl.rc_delrate);
1897         l->rttProp = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
1898         l->bw_inuse = bbr_get_bw(bbr);
1899         l->inflight = ctf_flight_size(bbr->rc_tp,
1900                           (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
1901         l->applimited = bbr->r_ctl.r_app_limited_until;
1902         l->delivered = bbr->r_ctl.rc_delivered;
1903         l->timeStamp = cts;
1904         l->lost = bbr->r_ctl.rc_lost;
1905         l->bbr_state = bbr->rc_bbr_state;
1906         l->bbr_substate = bbr_state_val(bbr);
1907         l->epoch = bbr->r_ctl.rc_rtt_epoch;
1908         l->lt_epoch = bbr->r_ctl.rc_lt_epoch;
1909         l->pacing_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
1910         l->cwnd_gain = bbr->r_ctl.rc_bbr_cwnd_gain;
1911         l->inhpts = bbr->rc_inp->inp_in_hpts;
1912         l->ininput = bbr->rc_inp->inp_in_input;
1913         l->use_lt_bw = bbr->rc_lt_use_bw;
1914         l->pkts_out = bbr->r_ctl.rc_flight_at_input;
1915         l->pkt_epoch = bbr->r_ctl.rc_pkt_epoch;
1916 }
1917
1918 static void
1919 bbr_log_type_bw_reduce(struct tcp_bbr *bbr, int reason)
1920 {
1921         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1922                 union tcp_log_stackspecific log;
1923
1924                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1925                 log.u_bbr.flex1 = 0;
1926                 log.u_bbr.flex2 = 0;
1927                 log.u_bbr.flex5 = 0;
1928                 log.u_bbr.flex3 = 0;
1929                 log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_loss_rate;
1930                 log.u_bbr.flex7 = reason;
1931                 log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_enters_probertt;
1932                 log.u_bbr.flex8 = 0;
1933                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1934                     &bbr->rc_inp->inp_socket->so_rcv,
1935                     &bbr->rc_inp->inp_socket->so_snd,
1936                     BBR_LOG_BW_RED_EV, 0,
1937                     0, &log, false, &bbr->rc_tv);
1938         }
1939 }
1940
1941 static void
1942 bbr_log_type_rwnd_collapse(struct tcp_bbr *bbr, int seq, int mode, uint32_t count)
1943 {
1944         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1945                 union tcp_log_stackspecific log;
1946
1947                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1948                 log.u_bbr.flex1 = seq;
1949                 log.u_bbr.flex2 = count;
1950                 log.u_bbr.flex8 = mode;
1951                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1952                     &bbr->rc_inp->inp_socket->so_rcv,
1953                     &bbr->rc_inp->inp_socket->so_snd,
1954                     BBR_LOG_LOWGAIN, 0,
1955                     0, &log, false, &bbr->rc_tv);
1956         }
1957 }
1958
1959
1960
1961 static void
1962 bbr_log_type_just_return(struct tcp_bbr *bbr, uint32_t cts, uint32_t tlen, uint8_t hpts_calling,
1963     uint8_t reason, uint32_t p_maxseg, int len)
1964 {
1965         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1966                 union tcp_log_stackspecific log;
1967
1968                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1969                 log.u_bbr.flex1 = p_maxseg;
1970                 log.u_bbr.flex2 = bbr->r_ctl.rc_hpts_flags;
1971                 log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
1972                 log.u_bbr.flex4 = reason;
1973                 log.u_bbr.flex5 = bbr->rc_in_persist;
1974                 log.u_bbr.flex6 = bbr->r_ctl.rc_last_delay_val;
1975                 log.u_bbr.flex7 = p_maxseg;
1976                 log.u_bbr.flex8 = bbr->rc_in_persist;
1977                 log.u_bbr.pkts_out = 0;
1978                 log.u_bbr.applimited = len;
1979                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1980                     &bbr->rc_inp->inp_socket->so_rcv,
1981                     &bbr->rc_inp->inp_socket->so_snd,
1982                     BBR_LOG_JUSTRET, 0,
1983                     tlen, &log, false, &bbr->rc_tv);
1984         }
1985 }
1986
1987
1988 static void
1989 bbr_log_type_enter_rec(struct tcp_bbr *bbr, uint32_t seq)
1990 {
1991         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1992                 union tcp_log_stackspecific log;
1993
1994                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1995                 log.u_bbr.flex1 = seq;
1996                 log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
1997                 log.u_bbr.flex3 = bbr->r_ctl.rc_recovery_start;
1998                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1999                     &bbr->rc_inp->inp_socket->so_rcv,
2000                     &bbr->rc_inp->inp_socket->so_snd,
2001                     BBR_LOG_ENTREC, 0,
2002                     0, &log, false, &bbr->rc_tv);
2003         }
2004 }
2005
2006 static void
2007 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)
2008 {
2009         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
2010                 union tcp_log_stackspecific log;
2011
2012                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2013                 log.u_bbr.flex1 = tso;
2014                 log.u_bbr.flex2 = maxseg;
2015                 log.u_bbr.flex3 = mtu;
2016                 log.u_bbr.flex4 = csum_flags;
2017                 TCP_LOG_EVENTP(tp, NULL,
2018                     &bbr->rc_inp->inp_socket->so_rcv,
2019                     &bbr->rc_inp->inp_socket->so_snd,
2020                     BBR_LOG_MSGSIZE, 0,
2021                     0, &log, false, &bbr->rc_tv);
2022         }
2023 }
2024
2025 static void
2026 bbr_log_flowend(struct tcp_bbr *bbr)
2027 {
2028         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2029                 union tcp_log_stackspecific log;
2030                 struct sockbuf *r, *s;
2031                 struct timeval tv;
2032
2033                 if (bbr->rc_inp->inp_socket) {
2034                         r = &bbr->rc_inp->inp_socket->so_rcv;
2035                         s = &bbr->rc_inp->inp_socket->so_snd;
2036                 } else {
2037                         r = s = NULL;
2038                 }
2039                 bbr_fill_in_logging_data(bbr, &log.u_bbr, tcp_get_usecs(&tv));
2040                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2041                     r, s,
2042                     TCP_LOG_FLOWEND, 0,
2043                     0, &log, false, &tv);
2044         }
2045 }
2046
2047 static void
2048 bbr_log_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line,
2049     uint32_t lost, uint32_t del)
2050 {
2051         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2052                 union tcp_log_stackspecific log;
2053
2054                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2055                 log.u_bbr.flex1 = lost;
2056                 log.u_bbr.flex2 = del;
2057                 log.u_bbr.flex3 = bbr->r_ctl.rc_bbr_lastbtlbw;
2058                 log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_rtt;
2059                 log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2060                 log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2061                 log.u_bbr.flex7 = line;
2062                 log.u_bbr.flex8 = 0;
2063                 log.u_bbr.inflight = bbr->r_ctl.r_measurement_count;
2064                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2065                     &bbr->rc_inp->inp_socket->so_rcv,
2066                     &bbr->rc_inp->inp_socket->so_snd,
2067                     BBR_LOG_PKT_EPOCH, 0,
2068                     0, &log, false, &bbr->rc_tv);
2069         }
2070 }
2071
2072 static void
2073 bbr_log_time_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line, uint32_t epoch_time)
2074 {
2075         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2076                 union tcp_log_stackspecific log;
2077
2078                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2079                 log.u_bbr.flex1 = bbr->r_ctl.rc_lost;
2080                 log.u_bbr.flex2 = bbr->rc_inp->inp_socket->so_snd.sb_lowat;
2081                 log.u_bbr.flex3 = bbr->rc_inp->inp_socket->so_snd.sb_hiwat;
2082                 log.u_bbr.flex7 = line;
2083                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2084                     &bbr->rc_inp->inp_socket->so_rcv,
2085                     &bbr->rc_inp->inp_socket->so_snd,
2086                     BBR_LOG_TIME_EPOCH, 0,
2087                     0, &log, false, &bbr->rc_tv);
2088         }
2089 }
2090
2091 static void
2092 bbr_log_set_of_state_target(struct tcp_bbr *bbr, uint32_t new_tar, int line, int meth)
2093 {
2094         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2095                 union tcp_log_stackspecific log;
2096
2097                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2098                 log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2099                 log.u_bbr.flex2 = new_tar;
2100                 log.u_bbr.flex3 = line;
2101                 log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2102                 log.u_bbr.flex5 = bbr_quanta;
2103                 log.u_bbr.flex6 = bbr->r_ctl.rc_pace_min_segs;
2104                 log.u_bbr.flex7 = bbr->rc_last_options;
2105                 log.u_bbr.flex8 = meth;
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_TARGET, 0,
2110                     0, &log, false, &bbr->rc_tv);
2111         }
2112
2113 }
2114
2115 static void
2116 bbr_log_type_statechange(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
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.rc_probertt_int;
2125                 if (bbr_state_is_pkt_epoch)
2126                         log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
2127                 else
2128                         log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PROP);
2129                 log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2130                 log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2131                 log.u_bbr.flex7 = (bbr->r_ctl.rc_target_at_state/1000);
2132                 log.u_bbr.lt_epoch = bbr->r_ctl.rc_level_state_extra;
2133                 log.u_bbr.pkts_out = bbr->r_ctl.rc_target_at_state;
2134                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2135                     &bbr->rc_inp->inp_socket->so_rcv,
2136                     &bbr->rc_inp->inp_socket->so_snd,
2137                     BBR_LOG_STATE, 0,
2138                     0, &log, false, &bbr->rc_tv);
2139         }
2140 }
2141
2142 static void
2143 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
2144                     uint32_t rtt, uint32_t line, uint8_t reas, uint16_t cond)
2145 {
2146         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2147                 union tcp_log_stackspecific log;
2148
2149                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2150                 log.u_bbr.flex1 = line;
2151                 log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2152                 log.u_bbr.flex3 = bbr->r_ctl.last_in_probertt;
2153                 log.u_bbr.flex4 = applied;
2154                 log.u_bbr.flex5 = rtt;
2155                 log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2156                 log.u_bbr.flex7 = cond;
2157                 log.u_bbr.flex8 = reas;
2158                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2159                     &bbr->rc_inp->inp_socket->so_rcv,
2160                     &bbr->rc_inp->inp_socket->so_snd,
2161                     BBR_LOG_RTT_SHRINKS, 0,
2162                     0, &log, false, &bbr->rc_tv);
2163         }
2164 }
2165
2166 static void
2167 bbr_log_type_exit_rec(struct tcp_bbr *bbr)
2168 {
2169         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2170                 union tcp_log_stackspecific log;
2171
2172                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2173                 log.u_bbr.flex1 = bbr->r_ctl.rc_recovery_start;
2174                 log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
2175                 log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2176                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2177                     &bbr->rc_inp->inp_socket->so_rcv,
2178                     &bbr->rc_inp->inp_socket->so_snd,
2179                     BBR_LOG_EXITREC, 0,
2180                     0, &log, false, &bbr->rc_tv);
2181         }
2182 }
2183
2184 static void
2185 bbr_log_type_cwndupd(struct tcp_bbr *bbr, uint32_t bytes_this_ack, uint32_t chg,
2186     uint32_t prev_acked, int32_t meth, uint32_t target, uint32_t th_ack, int32_t line)
2187 {
2188         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2189                 union tcp_log_stackspecific log;
2190
2191                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2192                 log.u_bbr.flex1 = line;
2193                 log.u_bbr.flex2 = prev_acked;
2194                 log.u_bbr.flex3 = bytes_this_ack;
2195                 log.u_bbr.flex4 = chg;
2196                 log.u_bbr.flex5 = th_ack;
2197                 log.u_bbr.flex6 = target;
2198                 log.u_bbr.flex8 = meth;
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                     BBR_LOG_CWND, 0,
2203                     0, &log, false, &bbr->rc_tv);
2204         }
2205 }
2206
2207 static void
2208 bbr_log_rtt_sample(struct tcp_bbr *bbr, uint32_t rtt, uint32_t tsin)
2209 {
2210         /*
2211          * Log the rtt sample we are applying to the srtt algorithm in
2212          * useconds.
2213          */
2214         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2215                 union tcp_log_stackspecific log;
2216
2217                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2218                 log.u_bbr.flex1 = rtt;
2219                 log.u_bbr.flex2 = bbr->r_ctl.rc_bbr_state_time;
2220                 log.u_bbr.flex3 = bbr->r_ctl.rc_ack_hdwr_delay;
2221                 log.u_bbr.flex4 = bbr->rc_tp->ts_offset;
2222                 log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2223                 log.u_bbr.pkts_out = tcp_tv_to_mssectick(&bbr->rc_tv);
2224                 log.u_bbr.flex6 = tsin;
2225                 log.u_bbr.flex7 = 0;
2226                 log.u_bbr.flex8 = bbr->rc_ack_was_delayed;     
2227                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2228                     &bbr->rc_inp->inp_socket->so_rcv,
2229                     &bbr->rc_inp->inp_socket->so_snd,
2230                     TCP_LOG_RTT, 0,
2231                     0, &log, false, &bbr->rc_tv);
2232         }
2233 }
2234
2235 static void
2236 bbr_log_type_pesist(struct tcp_bbr *bbr, uint32_t cts, uint32_t time_in, int32_t line, uint8_t enter_exit)
2237 {
2238         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2239                 union tcp_log_stackspecific log;
2240
2241                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2242                 log.u_bbr.flex1 = time_in;
2243                 log.u_bbr.flex2 = line;
2244                 log.u_bbr.flex8 = enter_exit;
2245                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2246                     &bbr->rc_inp->inp_socket->so_rcv,
2247                     &bbr->rc_inp->inp_socket->so_snd,
2248                     BBR_LOG_PERSIST, 0,
2249                     0, &log, false, &bbr->rc_tv);
2250         }
2251 }
2252 static void
2253 bbr_log_ack_clear(struct tcp_bbr *bbr, uint32_t cts)
2254 {
2255         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2256                 union tcp_log_stackspecific log;
2257
2258                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2259                 log.u_bbr.flex1 = bbr->rc_tp->ts_recent_age;
2260                 log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2261                 log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2262                 log.u_bbr.flex4 = bbr->r_ctl.rc_went_idle_time;
2263                 log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2264                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2265                     &bbr->rc_inp->inp_socket->so_rcv,
2266                     &bbr->rc_inp->inp_socket->so_snd,
2267                     BBR_LOG_ACKCLEAR, 0,
2268                     0, &log, false, &bbr->rc_tv);
2269         }
2270 }
2271
2272 static void
2273 bbr_log_ack_event(struct tcp_bbr *bbr, struct tcphdr *th, struct tcpopt *to, uint32_t tlen,
2274                   uint16_t nsegs, uint32_t cts, int32_t nxt_pkt, struct mbuf *m)
2275 {
2276         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2277                 union tcp_log_stackspecific log;
2278                 struct timeval tv;
2279
2280                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2281                 log.u_bbr.flex1 = nsegs;
2282                 log.u_bbr.flex2 = bbr->r_ctl.rc_lost_bytes;
2283                 if (m) {
2284                         struct timespec ts;
2285
2286                         log.u_bbr.flex3 = m->m_flags;
2287                         if (m->m_flags & M_TSTMP) {
2288                                 mbuf_tstmp2timespec(m, &ts);
2289                                 tv.tv_sec = ts.tv_sec;
2290                                 tv.tv_usec = ts.tv_nsec / 1000;
2291                                 log.u_bbr.lt_epoch = tcp_tv_to_usectick(&tv);
2292                         } else {
2293                                 log.u_bbr.lt_epoch = 0;
2294                         }
2295                         if (m->m_flags & M_TSTMP_LRO) {
2296                                 tv.tv_sec = m->m_pkthdr.rcv_tstmp / 1000000000;
2297                                 tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000) / 1000;
2298                                 log.u_bbr.flex5 = tcp_tv_to_usectick(&tv);
2299                         } else {
2300                                 /* No arrival timestamp */
2301                                 log.u_bbr.flex5 = 0;
2302                         }
2303
2304                         log.u_bbr.pkts_out = tcp_get_usecs(&tv);
2305                 } else {
2306                         log.u_bbr.flex3 = 0;
2307                         log.u_bbr.flex5 = 0;
2308                         log.u_bbr.flex6 = 0;
2309                         log.u_bbr.pkts_out = 0;
2310                 }
2311                 log.u_bbr.flex4 = bbr->r_ctl.rc_target_at_state;
2312                 log.u_bbr.flex7 = bbr->r_wanted_output;
2313                 log.u_bbr.flex8 = bbr->rc_in_persist;
2314                 TCP_LOG_EVENTP(bbr->rc_tp, th,
2315                     &bbr->rc_inp->inp_socket->so_rcv,
2316                     &bbr->rc_inp->inp_socket->so_snd,
2317                     TCP_LOG_IN, 0,
2318                     tlen, &log, true, &bbr->rc_tv);
2319         }
2320 }
2321
2322 static void
2323 bbr_log_doseg_done(struct tcp_bbr *bbr, uint32_t cts, int32_t nxt_pkt, int32_t did_out)
2324 {
2325         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2326                 union tcp_log_stackspecific log;
2327
2328                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2329                 log.u_bbr.flex1 = did_out;
2330                 log.u_bbr.flex2 = nxt_pkt;
2331                 log.u_bbr.flex3 = bbr->r_ctl.rc_last_delay_val;
2332                 log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2333                 log.u_bbr.flex5 = bbr->r_ctl.rc_timer_exp;
2334                 log.u_bbr.flex6 = bbr->r_ctl.rc_lost_bytes;
2335                 log.u_bbr.flex7 = bbr->r_wanted_output;
2336                 log.u_bbr.flex8 = bbr->rc_in_persist;
2337                 log.u_bbr.pkts_out = bbr->r_ctl.highest_hdwr_delay;
2338                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2339                     &bbr->rc_inp->inp_socket->so_rcv,
2340                     &bbr->rc_inp->inp_socket->so_snd,
2341                     BBR_LOG_DOSEG_DONE, 0,
2342                     0, &log, true, &bbr->rc_tv);
2343         }
2344 }
2345
2346 static void
2347 bbr_log_enobuf_jmp(struct tcp_bbr *bbr, uint32_t len, uint32_t cts,
2348     int32_t line, uint32_t o_len, uint32_t segcnt, uint32_t segsiz)
2349 {
2350         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2351                 union tcp_log_stackspecific log;
2352
2353                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2354                 log.u_bbr.flex1 = line;
2355                 log.u_bbr.flex2 = o_len;
2356                 log.u_bbr.flex3 = segcnt;
2357                 log.u_bbr.flex4 = segsiz;
2358                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2359                     &bbr->rc_inp->inp_socket->so_rcv,
2360                     &bbr->rc_inp->inp_socket->so_snd,
2361                     BBR_LOG_ENOBUF_JMP, ENOBUFS,
2362                     len, &log, true, &bbr->rc_tv);
2363         }
2364 }
2365
2366 static void
2367 bbr_log_to_processing(struct tcp_bbr *bbr, uint32_t cts, int32_t ret, int32_t timers, uint8_t hpts_calling)
2368 {
2369         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2370                 union tcp_log_stackspecific log;
2371
2372                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2373                 log.u_bbr.flex1 = timers;
2374                 log.u_bbr.flex2 = ret;
2375                 log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
2376                 log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2377                 log.u_bbr.flex5 = cts;
2378                 log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2379                 log.u_bbr.flex8 = hpts_calling;
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_TO_PROCESS, 0,
2384                     0, &log, false, &bbr->rc_tv);
2385         }
2386 }
2387
2388 static void
2389 bbr_log_to_event(struct tcp_bbr *bbr, uint32_t cts, int32_t to_num)
2390 {
2391         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2392                 union tcp_log_stackspecific log;
2393                 uint64_t ar;
2394
2395                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2396                 log.u_bbr.flex1 = bbr->bbr_timer_src;
2397                 log.u_bbr.flex2 = 0;
2398                 log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2399                 ar = (uint64_t)(bbr->r_ctl.rc_resend);
2400                 ar >>= 32;
2401                 ar &= 0x00000000ffffffff;
2402                 log.u_bbr.flex4 = (uint32_t)ar;
2403                 ar = (uint64_t)bbr->r_ctl.rc_resend;
2404                 ar &= 0x00000000ffffffff;
2405                 log.u_bbr.flex5 = (uint32_t)ar;
2406                 log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2407                 log.u_bbr.flex8 = to_num;
2408                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2409                     &bbr->rc_inp->inp_socket->so_rcv,
2410                     &bbr->rc_inp->inp_socket->so_snd,
2411                     BBR_LOG_RTO, 0,
2412                     0, &log, false, &bbr->rc_tv);
2413         }
2414 }
2415
2416 static void
2417 bbr_log_startup_event(struct tcp_bbr *bbr, uint32_t cts, uint32_t flex1, uint32_t flex2, uint32_t flex3, uint8_t reason)
2418 {
2419         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2420                 union tcp_log_stackspecific log;
2421
2422                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2423                 log.u_bbr.flex1 = flex1;
2424                 log.u_bbr.flex2 = flex2;
2425                 log.u_bbr.flex3 = flex3;
2426                 log.u_bbr.flex4 = 0; 
2427                 log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2428                 log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2429                 log.u_bbr.flex8 = reason;
2430                 log.u_bbr.cur_del_rate = bbr->r_ctl.rc_bbr_lastbtlbw;
2431                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2432                     &bbr->rc_inp->inp_socket->so_rcv,
2433                     &bbr->rc_inp->inp_socket->so_snd,
2434                     BBR_LOG_REDUCE, 0,
2435                     0, &log, false, &bbr->rc_tv);
2436         }
2437 }
2438
2439 static void
2440 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag)
2441 {
2442         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2443                 union tcp_log_stackspecific log;
2444
2445                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2446                 log.u_bbr.flex1 = diag->p_nxt_slot;
2447                 log.u_bbr.flex2 = diag->p_cur_slot;
2448                 log.u_bbr.flex3 = diag->slot_req;
2449                 log.u_bbr.flex4 = diag->inp_hptsslot;
2450                 log.u_bbr.flex5 = diag->slot_remaining;
2451                 log.u_bbr.flex6 = diag->need_new_to;
2452                 log.u_bbr.flex7 = diag->p_hpts_active;
2453                 log.u_bbr.flex8 = diag->p_on_min_sleep;
2454                 /* Hijack other fields as needed  */
2455                 log.u_bbr.epoch = diag->have_slept;
2456                 log.u_bbr.lt_epoch = diag->yet_to_sleep;
2457                 log.u_bbr.pkts_out = diag->co_ret;
2458                 log.u_bbr.applimited = diag->hpts_sleep_time;
2459                 log.u_bbr.delivered = diag->p_prev_slot;
2460                 log.u_bbr.inflight = diag->p_runningtick;
2461                 log.u_bbr.bw_inuse = diag->wheel_tick;
2462                 log.u_bbr.rttProp = diag->wheel_cts;
2463                 log.u_bbr.delRate = diag->maxticks;
2464                 log.u_bbr.cur_del_rate = diag->p_curtick;
2465                 log.u_bbr.cur_del_rate <<= 32;
2466                 log.u_bbr.cur_del_rate |= diag->p_lasttick;
2467                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2468                     &bbr->rc_inp->inp_socket->so_rcv,
2469                     &bbr->rc_inp->inp_socket->so_snd,
2470                     BBR_LOG_HPTSDIAG, 0,
2471                     0, &log, false, &bbr->rc_tv);
2472         }
2473 }
2474
2475 static void
2476 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
2477     uint32_t thresh, uint32_t to)
2478 {
2479         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2480                 union tcp_log_stackspecific log;
2481
2482                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2483                 log.u_bbr.flex1 = bbr->rc_tp->t_rttvar;
2484                 log.u_bbr.flex2 = time_since_sent;
2485                 log.u_bbr.flex3 = srtt;
2486                 log.u_bbr.flex4 = thresh;
2487                 log.u_bbr.flex5 = to;
2488                 log.u_bbr.flex6 = bbr->rc_tp->t_srtt;
2489                 log.u_bbr.flex8 = mode;
2490                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2491                     &bbr->rc_inp->inp_socket->so_rcv,
2492                     &bbr->rc_inp->inp_socket->so_snd,
2493                     BBR_LOG_TIMERPREP, 0,
2494                     0, &log, false, &bbr->rc_tv);
2495         }
2496 }
2497
2498 static void
2499 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
2500     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod)
2501 {
2502         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2503                 union tcp_log_stackspecific log;
2504
2505                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2506                 log.u_bbr.flex1 = usecs;
2507                 log.u_bbr.flex2 = len;
2508                 log.u_bbr.flex3 = (uint32_t)((bw >> 32) & 0x00000000ffffffff);
2509                 log.u_bbr.flex4 = (uint32_t)(bw & 0x00000000ffffffff);
2510                 if (override)
2511                         log.u_bbr.flex5 = (1 << 2);
2512                 else
2513                         log.u_bbr.flex5 = 0;
2514                 log.u_bbr.flex6 = override;
2515                 log.u_bbr.flex7 = gain;
2516                 log.u_bbr.flex8 = mod;
2517                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2518                     &bbr->rc_inp->inp_socket->so_rcv,
2519                     &bbr->rc_inp->inp_socket->so_snd,
2520                     BBR_LOG_HPTSI_CALC, 0,
2521                     len, &log, false, &bbr->rc_tv);
2522         }
2523 }
2524
2525 static void
2526 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2527 {
2528         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2529                 union tcp_log_stackspecific log;
2530
2531                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2532
2533                 log.u_bbr.flex1 = bbr->bbr_timer_src;
2534                 log.u_bbr.flex2 = to;
2535                 log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2536                 log.u_bbr.flex4 = slot;
2537                 log.u_bbr.flex5 = bbr->rc_inp->inp_hptsslot;
2538                 log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2539                 log.u_bbr.pkts_out = bbr->rc_inp->inp_flags2;
2540                 log.u_bbr.flex8 = which;
2541                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2542                     &bbr->rc_inp->inp_socket->so_rcv,
2543                     &bbr->rc_inp->inp_socket->so_snd,
2544                     BBR_LOG_TIMERSTAR, 0,
2545                     0, &log, false, &bbr->rc_tv);
2546         }
2547 }
2548
2549 static void
2550 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)
2551 {
2552         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2553                 union tcp_log_stackspecific log;
2554
2555                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2556                 log.u_bbr.flex1 = thresh;
2557                 log.u_bbr.flex2 = lro;
2558                 log.u_bbr.flex3 = bbr->r_ctl.rc_reorder_ts;
2559                 log.u_bbr.flex4 = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
2560                 log.u_bbr.flex5 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2561                 log.u_bbr.flex6 = srtt;
2562                 log.u_bbr.flex7 = bbr->r_ctl.rc_reorder_shift;
2563                 log.u_bbr.flex8 = frm;
2564                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2565                     &bbr->rc_inp->inp_socket->so_rcv,
2566                     &bbr->rc_inp->inp_socket->so_snd,
2567                     BBR_LOG_THRESH_CALC, 0,
2568                     0, &log, false, &bbr->rc_tv);
2569         }
2570 }
2571
2572 static void
2573 bbr_log_to_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts, uint8_t hpts_removed)
2574 {
2575         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2576                 union tcp_log_stackspecific log;
2577
2578                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2579                 log.u_bbr.flex1 = line;
2580                 log.u_bbr.flex2 = bbr->bbr_timer_src;
2581                 log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2582                 log.u_bbr.flex4 = bbr->rc_in_persist;
2583                 log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2584                 log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2585                 log.u_bbr.flex8 = hpts_removed;
2586                 log.u_bbr.pkts_out = bbr->rc_pacer_started;
2587                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2588                     &bbr->rc_inp->inp_socket->so_rcv,
2589                     &bbr->rc_inp->inp_socket->so_snd,
2590                     BBR_LOG_TIMERCANC, 0,
2591                     0, &log, false, &bbr->rc_tv);
2592         }
2593 }
2594
2595
2596 static void
2597 bbr_log_tstmp_validation(struct tcp_bbr *bbr, uint64_t peer_delta, uint64_t delta)
2598 {
2599         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2600                 union tcp_log_stackspecific log;
2601
2602                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2603                 log.u_bbr.flex1 = bbr->r_ctl.bbr_peer_tsratio;
2604                 log.u_bbr.flex2 = (peer_delta >> 32);
2605                 log.u_bbr.flex3 = (peer_delta & 0x00000000ffffffff);
2606                 log.u_bbr.flex4 = (delta >> 32);
2607                 log.u_bbr.flex5 = (delta & 0x00000000ffffffff);
2608                 log.u_bbr.flex7 = bbr->rc_ts_clock_set;
2609                 log.u_bbr.flex8 = bbr->rc_ts_cant_be_used;
2610                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2611                     &bbr->rc_inp->inp_socket->so_rcv,
2612                     &bbr->rc_inp->inp_socket->so_snd,
2613                     BBR_LOG_TSTMP_VAL, 0,
2614                     0, &log, false, &bbr->rc_tv);
2615
2616         }
2617 }
2618
2619 static void
2620 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)
2621 {
2622         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2623                 union tcp_log_stackspecific log;
2624
2625                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2626                 log.u_bbr.flex1 = tsosz;
2627                 log.u_bbr.flex2 = tls;
2628                 log.u_bbr.flex3 = tcp_min_hptsi_time;
2629                 log.u_bbr.flex4 = bbr->r_ctl.bbr_hptsi_bytes_min;
2630                 log.u_bbr.flex5 = old_val;
2631                 log.u_bbr.flex6 = maxseg;
2632                 log.u_bbr.flex7 = bbr->rc_no_pacing;
2633                 log.u_bbr.flex7 <<= 1;
2634                 log.u_bbr.flex7 |= bbr->rc_past_init_win;
2635                 if (hdwr)
2636                         log.u_bbr.flex8 = 0x80 | bbr->rc_use_google;
2637                 else
2638                         log.u_bbr.flex8 = bbr->rc_use_google;
2639                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2640                     &bbr->rc_inp->inp_socket->so_rcv,
2641                     &bbr->rc_inp->inp_socket->so_snd,
2642                     BBR_LOG_BBRTSO, 0,
2643                     0, &log, false, &bbr->rc_tv);
2644         }
2645 }
2646
2647 static void
2648 bbr_log_type_rsmclear(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm,
2649                       uint32_t flags, uint32_t line)
2650 {
2651         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2652                 union tcp_log_stackspecific log;
2653
2654                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2655                 log.u_bbr.flex1 = line;
2656                 log.u_bbr.flex2 = rsm->r_start;
2657                 log.u_bbr.flex3 = rsm->r_end;
2658                 log.u_bbr.flex4 = rsm->r_delivered;
2659                 log.u_bbr.flex5 = rsm->r_rtr_cnt;
2660                 log.u_bbr.flex6 = rsm->r_dupack;
2661                 log.u_bbr.flex7 = rsm->r_tim_lastsent[0];
2662                 log.u_bbr.flex8 = rsm->r_flags;
2663                 /* Hijack the pkts_out fids */
2664                 log.u_bbr.applimited = flags;
2665                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2666                     &bbr->rc_inp->inp_socket->so_rcv,
2667                     &bbr->rc_inp->inp_socket->so_snd,
2668                     BBR_RSM_CLEARED, 0,
2669                     0, &log, false, &bbr->rc_tv);
2670         }
2671 }
2672
2673 static void
2674 bbr_log_type_bbrupd(struct tcp_bbr *bbr, uint8_t flex8, uint32_t cts,
2675     uint32_t flex3, uint32_t flex2, uint32_t flex5,
2676     uint32_t flex6, uint32_t pkts_out, int flex7,
2677     uint32_t flex4, uint32_t flex1)
2678 {
2679
2680         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2681                 union tcp_log_stackspecific log;
2682
2683                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2684                 log.u_bbr.flex1 = flex1;
2685                 log.u_bbr.flex2 = flex2;
2686                 log.u_bbr.flex3 = flex3;
2687                 log.u_bbr.flex4 = flex4;
2688                 log.u_bbr.flex5 = flex5;
2689                 log.u_bbr.flex6 = flex6;
2690                 log.u_bbr.flex7 = flex7;
2691                 /* Hijack the pkts_out fids */
2692                 log.u_bbr.pkts_out = pkts_out;
2693                 log.u_bbr.flex8 = flex8;
2694                 if (bbr->rc_ack_was_delayed)
2695                         log.u_bbr.epoch = bbr->r_ctl.rc_ack_hdwr_delay;
2696                 else 
2697                         log.u_bbr.epoch = 0;
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_BBRUPD, 0,
2702                     flex2, &log, false, &bbr->rc_tv);
2703         }
2704 }
2705
2706
2707 static void
2708 bbr_log_type_ltbw(struct tcp_bbr *bbr, uint32_t cts, int32_t reason,
2709         uint32_t newbw, uint32_t obw, uint32_t diff,
2710         uint32_t tim)
2711 {
2712         if (/*bbr_verbose_logging && */(bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2713                 union tcp_log_stackspecific log;
2714
2715                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2716                 log.u_bbr.flex1 = reason;
2717                 log.u_bbr.flex2 = newbw;
2718                 log.u_bbr.flex3 = obw;
2719                 log.u_bbr.flex4 = diff;
2720                 log.u_bbr.flex5 = bbr->r_ctl.rc_lt_lost;
2721                 log.u_bbr.flex6 = bbr->r_ctl.rc_lt_del;
2722                 log.u_bbr.flex7 = bbr->rc_lt_is_sampling;
2723                 log.u_bbr.pkts_out = tim;
2724                 log.u_bbr.bw_inuse = bbr->r_ctl.rc_lt_bw;
2725                 if (bbr->rc_lt_use_bw == 0)
2726                         log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
2727                 else
2728                         log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;                 
2729                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2730                     &bbr->rc_inp->inp_socket->so_rcv,
2731                     &bbr->rc_inp->inp_socket->so_snd,
2732                     BBR_LOG_BWSAMP, 0,
2733                     0, &log, false, &bbr->rc_tv);
2734         }
2735 }
2736
2737 static inline void
2738 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line)
2739 {
2740         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2741                 union tcp_log_stackspecific log;
2742
2743                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2744                 log.u_bbr.flex1 = line;
2745                 log.u_bbr.flex2 = tick;
2746                 log.u_bbr.flex3 = tp->t_maxunacktime;
2747                 log.u_bbr.flex4 = tp->t_acktime;
2748                 log.u_bbr.flex8 = event;
2749                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2750                     &bbr->rc_inp->inp_socket->so_rcv,
2751                     &bbr->rc_inp->inp_socket->so_snd,
2752                     BBR_LOG_PROGRESS, 0,
2753                     0, &log, false, &bbr->rc_tv);
2754         }
2755 }
2756
2757 static void
2758 bbr_type_log_hdwr_pacing(struct tcp_bbr *bbr, const struct ifnet *ifp,
2759                          uint64_t rate, uint64_t hw_rate, int line, uint32_t cts,
2760                          int error)
2761 {
2762         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2763                 union tcp_log_stackspecific log;
2764
2765                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2766                 log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2767                 log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2768                 log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2769                 log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2770                 log.u_bbr.bw_inuse = rate;
2771                 log.u_bbr.flex5 = line;
2772                 log.u_bbr.flex6 = error;
2773                 log.u_bbr.flex8 = bbr->skip_gain;
2774                 log.u_bbr.flex8 <<= 1;
2775                 log.u_bbr.flex8 |= bbr->gain_is_limited;
2776                 log.u_bbr.flex8 <<= 1;
2777                 log.u_bbr.flex8 |= bbr->bbr_hdrw_pacing;
2778                 log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
2779                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2780                     &bbr->rc_inp->inp_socket->so_rcv,
2781                     &bbr->rc_inp->inp_socket->so_snd,
2782                     BBR_LOG_HDWR_PACE, 0,
2783                     0, &log, false, &bbr->rc_tv);
2784         }
2785 }
2786
2787 static void
2788 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)
2789 {
2790         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2791                 union tcp_log_stackspecific log;
2792
2793                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2794                 log.u_bbr.flex1 = slot;
2795                 log.u_bbr.flex2 = del_by;
2796                 log.u_bbr.flex3 = prev_delay;
2797                 log.u_bbr.flex4 = line;
2798                 log.u_bbr.flex5 = bbr->r_ctl.rc_last_delay_val;
2799                 log.u_bbr.flex6 = bbr->r_ctl.rc_hptsi_agg_delay;
2800                 log.u_bbr.flex7 = (0x0000ffff & bbr->r_ctl.rc_hpts_flags);
2801                 log.u_bbr.flex8 = bbr->rc_in_persist;
2802                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2803                     &bbr->rc_inp->inp_socket->so_rcv,
2804                     &bbr->rc_inp->inp_socket->so_snd,
2805                     BBR_LOG_BBRSND, 0,
2806                     len, &log, false, &bbr->rc_tv);
2807         }
2808 }
2809
2810 static void
2811 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)
2812 {
2813         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2814                 union tcp_log_stackspecific log;
2815
2816                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2817                 log.u_bbr.flex1 = bbr->r_ctl.rc_delivered;
2818                 log.u_bbr.flex2 = 0;
2819                 log.u_bbr.flex3 = bbr->r_ctl.rc_lowest_rtt;
2820                 log.u_bbr.flex4 = end;
2821                 log.u_bbr.flex5 = seq;
2822                 log.u_bbr.flex6 = t;
2823                 log.u_bbr.flex7 = match;
2824                 log.u_bbr.flex8 = flags;
2825                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2826                     &bbr->rc_inp->inp_socket->so_rcv,
2827                     &bbr->rc_inp->inp_socket->so_snd,
2828                     BBR_LOG_BBRRTT, 0,
2829                     0, &log, false, &bbr->rc_tv);
2830         }
2831 }
2832
2833 static void
2834 bbr_log_exit_gain(struct tcp_bbr *bbr, uint32_t cts, int32_t entry_method)
2835 {
2836         if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2837                 union tcp_log_stackspecific log;
2838
2839                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2840                 log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2841                 log.u_bbr.flex2 = (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
2842                 log.u_bbr.flex3 = bbr->r_ctl.gain_epoch;
2843                 log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2844                 log.u_bbr.flex5 = bbr->r_ctl.rc_pace_min_segs;
2845                 log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_state_atflight;
2846                 log.u_bbr.flex7 = 0;
2847                 log.u_bbr.flex8 = entry_method;
2848                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2849                     &bbr->rc_inp->inp_socket->so_rcv,
2850                     &bbr->rc_inp->inp_socket->so_snd,
2851                     BBR_LOG_EXIT_GAIN, 0,
2852                     0, &log, false, &bbr->rc_tv);
2853         }
2854 }
2855
2856 static void
2857 bbr_log_settings_change(struct tcp_bbr *bbr, int settings_desired)
2858 {
2859         if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2860                 union tcp_log_stackspecific log;
2861
2862                 bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2863                 /* R-HU */
2864                 log.u_bbr.flex1 = 0;
2865                 log.u_bbr.flex2 = 0;
2866                 log.u_bbr.flex3 = 0;
2867                 log.u_bbr.flex4 = 0;
2868                 log.u_bbr.flex7 = 0;
2869                 log.u_bbr.flex8 = settings_desired;
2870
2871                 TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2872                     &bbr->rc_inp->inp_socket->so_rcv,
2873                     &bbr->rc_inp->inp_socket->so_snd,
2874                     BBR_LOG_SETTINGS_CHG, 0,
2875                     0, &log, false, &bbr->rc_tv);
2876         }
2877 }
2878
2879 /*
2880  * Returns the bw from the our filter.
2881  */
2882 static inline uint64_t
2883 bbr_get_full_bw(struct tcp_bbr *bbr)
2884 {
2885         uint64_t bw;
2886
2887         bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2888
2889         return (bw);
2890 }
2891
2892 static inline void
2893 bbr_set_pktepoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2894 {
2895         uint64_t calclr;
2896         uint32_t lost, del;
2897
2898         if (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_pktepoch)
2899                 lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lost_at_pktepoch;
2900         else
2901                 lost = 0;
2902         del = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_pkt_epoch_del;
2903         if (lost == 0)  {
2904                 calclr = 0;
2905         } else if (del) {
2906                 calclr = lost;
2907                 calclr *= (uint64_t)1000;
2908                 calclr /= (uint64_t)del;
2909         } else {
2910                 /* Nothing delivered? 100.0% loss */
2911                 calclr = 1000; 
2912         }
2913         bbr->r_ctl.rc_pkt_epoch_loss_rate =  (uint32_t)calclr;
2914         if (IN_RECOVERY(bbr->rc_tp->t_flags)) 
2915                 bbr->r_ctl.recovery_lr += (uint32_t)calclr;
2916         bbr->r_ctl.rc_pkt_epoch++;
2917         if (bbr->rc_no_pacing &&
2918             (bbr->r_ctl.rc_pkt_epoch >= bbr->no_pacing_until)) {
2919                 bbr->rc_no_pacing = 0;
2920                 tcp_bbr_tso_size_check(bbr, cts);
2921         }
2922         bbr->r_ctl.rc_pkt_epoch_rtt = bbr_calc_time(cts, bbr->r_ctl.rc_pkt_epoch_time);
2923         bbr->r_ctl.rc_pkt_epoch_time = cts;
2924         /* What was our loss rate */
2925         bbr_log_pkt_epoch(bbr, cts, line, lost, del);
2926         bbr->r_ctl.rc_pkt_epoch_del = bbr->r_ctl.rc_delivered;
2927         bbr->r_ctl.rc_lost_at_pktepoch = bbr->r_ctl.rc_lost;
2928 }
2929
2930 static inline void
2931 bbr_set_epoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2932 {
2933         uint32_t epoch_time;
2934
2935         /* Tick the RTT clock */
2936         bbr->r_ctl.rc_rtt_epoch++;
2937         epoch_time = cts - bbr->r_ctl.rc_rcv_epoch_start;
2938         bbr_log_time_epoch(bbr, cts, line, epoch_time);
2939         bbr->r_ctl.rc_rcv_epoch_start = cts;
2940 }
2941
2942
2943 static inline void
2944 bbr_isit_a_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm, int32_t line, int32_t cum_acked)
2945 {
2946         if (SEQ_GEQ(rsm->r_delivered, bbr->r_ctl.rc_pkt_epoch_del)) {
2947                 bbr->rc_is_pkt_epoch_now = 1;
2948         }
2949 }
2950
2951 /*
2952  * Returns the bw from either the b/w filter
2953  * or from the lt_bw (if the connection is being
2954  * policed).
2955  */
2956 static inline uint64_t
2957 __bbr_get_bw(struct tcp_bbr *bbr)
2958 {
2959         uint64_t bw, min_bw;
2960         uint64_t rtt;
2961         int gm_measure_cnt = 1;
2962         
2963         /* 
2964          * For startup we make, like google, a
2965          * minimum b/w. This is generated from the
2966          * IW and the rttProp. We do fall back to srtt
2967          * if for some reason (initial handshake) we don't
2968          * have a rttProp. We, in the worst case, fall back
2969          * to the configured min_bw (rc_initial_hptsi_bw).
2970          */
2971         if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
2972                 /* Attempt first to use rttProp */
2973                 rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);         
2974                 if (rtt && (rtt < 0xffffffff)) {
2975 measure:
2976                         min_bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2977                                 ((uint64_t)1000000);
2978                         min_bw /= rtt;
2979                         if (min_bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2980                                 min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2981                         }
2982
2983                 } else if (bbr->rc_tp->t_srtt != 0) {
2984                         /* No rttProp, use srtt? */
2985                         rtt = bbr_get_rtt(bbr, BBR_SRTT);
2986                         goto measure;
2987                 } else {
2988                         min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2989                 }
2990         } else
2991                 min_bw = 0;
2992
2993         if ((bbr->rc_past_init_win == 0) &&
2994             (bbr->r_ctl.rc_delivered > bbr_initial_cwnd(bbr, bbr->rc_tp)))
2995                 bbr->rc_past_init_win = 1;
2996         if ((bbr->rc_use_google)  && (bbr->r_ctl.r_measurement_count >= 1))
2997                 gm_measure_cnt = 0;
2998         if (gm_measure_cnt &&
2999             ((bbr->r_ctl.r_measurement_count < bbr_min_measurements_req) ||
3000              (bbr->rc_past_init_win == 0))) {
3001                 /* For google we use our guess rate until we get 1 measurement */
3002
3003 use_initial_window:
3004                 rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
3005                 if (rtt && (rtt < 0xffffffff)) {
3006                         /*
3007                          * We have an RTT measurment. Use that in
3008                          * combination with our initial window to calculate
3009                          * a b/w.
3010                          */
3011                         bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
3012                                 ((uint64_t)1000000);
3013                         bw /= rtt;
3014                         if (bw < bbr->r_ctl.rc_initial_hptsi_bw) {
3015                                 bw = bbr->r_ctl.rc_initial_hptsi_bw;
3016                         }
3017                 } else {
3018                         /* Drop back to the 40 and punt to a default */
3019                         bw = bbr->r_ctl.rc_initial_hptsi_bw;
3020                 }
3021                 if (bw < 1)
3022                         /* Probably should panic */
3023                         bw = 1;
3024                 if (bw > min_bw)
3025                         return (bw);
3026                 else
3027                         return (min_bw);
3028         }
3029         if (bbr->rc_lt_use_bw)
3030                 bw = bbr->r_ctl.rc_lt_bw;
3031         else if (bbr->r_recovery_bw && (bbr->rc_use_google == 0))
3032                 bw = bbr->r_ctl.red_bw;
3033         else
3034                 bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3035         if (bbr->rc_tp->t_peakrate_thr && (bbr->rc_use_google == 0)) {
3036                 /*
3037                  * Enforce user set rate limit, keep in mind that
3038                  * t_peakrate_thr is in B/s already
3039                  */
3040                 bw = uqmin((uint64_t)bbr->rc_tp->t_peakrate_thr, bw);
3041         }
3042         if (bw == 0) {
3043                 /* We should not be at 0, go to the initial window then  */
3044                 goto use_initial_window;
3045         }
3046         if (bw < 1)
3047                 /* Probably should panic */
3048                 bw = 1;
3049         if (bw < min_bw)
3050                 bw = min_bw;
3051         return (bw);
3052 }
3053
3054 static inline uint64_t
3055 bbr_get_bw(struct tcp_bbr *bbr)
3056 {
3057         uint64_t bw;
3058
3059         bw = __bbr_get_bw(bbr);
3060         return (bw);
3061 }
3062
3063 static inline void
3064 bbr_reset_lt_bw_interval(struct tcp_bbr *bbr, uint32_t cts)
3065 {
3066         bbr->r_ctl.rc_lt_epoch = bbr->r_ctl.rc_pkt_epoch;
3067         bbr->r_ctl.rc_lt_time = bbr->r_ctl.rc_del_time;
3068         bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3069         bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3070 }
3071
3072 static inline void
3073 bbr_reset_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts)
3074 {
3075         bbr->rc_lt_is_sampling = 0;
3076         bbr->rc_lt_use_bw = 0;
3077         bbr->r_ctl.rc_lt_bw = 0;
3078         bbr_reset_lt_bw_interval(bbr, cts);
3079 }
3080
3081 static inline void
3082 bbr_lt_bw_samp_done(struct tcp_bbr *bbr, uint64_t bw, uint32_t cts, uint32_t timin)
3083 {
3084         uint64_t diff;
3085
3086         /* Do we have a previous sample? */
3087         if (bbr->r_ctl.rc_lt_bw) {
3088                 /* Get the diff in bytes per second */
3089                 if (bbr->r_ctl.rc_lt_bw > bw)
3090                         diff = bbr->r_ctl.rc_lt_bw - bw;
3091                 else
3092                         diff = bw - bbr->r_ctl.rc_lt_bw;
3093                 if ((diff <= bbr_lt_bw_diff) ||
3094                     (diff <= (bbr->r_ctl.rc_lt_bw / bbr_lt_bw_ratio))) {
3095                         /* Consider us policed */
3096                         uint32_t saved_bw;
3097
3098                         saved_bw = (uint32_t)bbr->r_ctl.rc_lt_bw;
3099                         bbr->r_ctl.rc_lt_bw = (bw + bbr->r_ctl.rc_lt_bw) / 2;   /* average of two */
3100                         bbr->rc_lt_use_bw = 1;
3101                         bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
3102                         /*
3103                          * Use pkt based epoch for measuring length of
3104                          * policer up
3105                          */
3106                         bbr->r_ctl.rc_lt_epoch_use = bbr->r_ctl.rc_pkt_epoch;
3107                         /*
3108                          * reason 4 is we need to start consider being
3109                          * policed
3110                          */
3111                         bbr_log_type_ltbw(bbr, cts, 4, (uint32_t)bw, saved_bw, (uint32_t)diff, timin);
3112                         return;
3113                 }
3114         }
3115         bbr->r_ctl.rc_lt_bw = bw;
3116         bbr_reset_lt_bw_interval(bbr, cts);
3117         bbr_log_type_ltbw(bbr, cts, 5, 0, (uint32_t)bw, 0, timin);
3118 }
3119
3120 /*
3121  * RRS: Copied from user space!
3122  * Calculate a uniformly distributed random number less than upper_bound
3123  * avoiding "modulo bias".
3124  *
3125  * Uniformity is achieved by generating new random numbers until the one
3126  * returned is outside the range [0, 2**32 % upper_bound).  This
3127  * guarantees the selected random number will be inside
3128  * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
3129  * after reduction modulo upper_bound.
3130  */
3131 static uint32_t
3132 arc4random_uniform(uint32_t upper_bound)
3133 {
3134         uint32_t r, min;
3135
3136         if (upper_bound < 2)
3137                 return 0;
3138
3139         /* 2**32 % x == (2**32 - x) % x */
3140         min = -upper_bound % upper_bound;
3141
3142         /*
3143          * This could theoretically loop forever but each retry has
3144          * p > 0.5 (worst case, usually far better) of selecting a
3145          * number inside the range we need, so it should rarely need
3146          * to re-roll.
3147          */
3148         for (;;) {
3149                 r = arc4random();
3150                 if (r >= min)
3151                         break;
3152         }
3153
3154         return r % upper_bound;
3155 }
3156
3157 static void
3158 bbr_randomize_extra_state_time(struct tcp_bbr *bbr)
3159 {
3160         uint32_t ran, deduct;
3161         
3162         ran = arc4random_uniform(bbr_rand_ot);
3163         if (ran) {
3164                 deduct = bbr->r_ctl.rc_level_state_extra / ran;
3165                 bbr->r_ctl.rc_level_state_extra -= deduct;
3166         }
3167 }
3168 /*
3169  * Return randomly the starting state
3170  * to use in probebw.
3171  */
3172 static uint8_t
3173 bbr_pick_probebw_substate(struct tcp_bbr *bbr, uint32_t cts)
3174 {
3175         uint32_t ran;
3176         uint8_t ret_val;
3177
3178         /* Initialize the offset to 0 */
3179         bbr->r_ctl.rc_exta_time_gd = 0;
3180         bbr->rc_hit_state_1 = 0;
3181         bbr->r_ctl.rc_level_state_extra = 0;
3182         ran = arc4random_uniform((BBR_SUBSTATE_COUNT-1));
3183         /*
3184          * The math works funny here :) the return value is used to set the
3185          * substate and then the state change is called which increments by
3186          * one. So if we return 1 (DRAIN) we will increment to 2 (LEVEL1) when
3187          * we fully enter the state. Note that the (8 - 1 - ran) assures that
3188          * we return 1 - 7, so we dont return 0 and end up starting in
3189          * state 1 (DRAIN).
3190          */
3191         ret_val = BBR_SUBSTATE_COUNT - 1 - ran;
3192         /* Set an epoch */
3193         if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP))
3194                 bbr_set_epoch(bbr, cts, __LINE__);
3195
3196         bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
3197         return (ret_val);
3198 }
3199
3200 static void
3201 bbr_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts, int32_t loss_detected)
3202 {
3203         uint32_t diff, d_time;
3204         uint64_t del_time, bw, lost, delivered;
3205
3206         if (bbr->r_use_policer == 0)
3207                 return;
3208         if (bbr->rc_lt_use_bw) {
3209                 /* We are using lt bw do we stop yet? */
3210                 diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
3211                 if (diff > bbr_lt_bw_max_rtts) {
3212                         /* Reset it all */
3213 reset_all:
3214                         bbr_reset_lt_bw_sampling(bbr, cts);
3215                         if (bbr->rc_filled_pipe) {
3216                                 bbr_set_epoch(bbr, cts, __LINE__);
3217                                 bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
3218                                 bbr_substate_change(bbr, cts, __LINE__, 0);
3219                                 bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
3220                                 bbr_log_type_statechange(bbr, cts, __LINE__);
3221                         } else {
3222                                 /* 
3223                                  * This should not happen really 
3224                                  * unless we remove the startup/drain
3225                                  * restrictions above.
3226                                  */
3227                                 bbr->rc_bbr_state = BBR_STATE_STARTUP;
3228                                 bbr_set_epoch(bbr, cts, __LINE__);
3229                                 bbr->r_ctl.rc_bbr_state_time = cts;
3230                                 bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
3231                                 bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
3232                                 bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
3233                                 bbr_set_state_target(bbr, __LINE__);
3234                                 bbr_log_type_statechange(bbr, cts, __LINE__);
3235                         }
3236                         /* reason 0 is to stop using lt-bw */
3237                         bbr_log_type_ltbw(bbr, cts, 0, 0, 0, 0, 0);
3238                         return;
3239                 }
3240                 if (bbr_lt_intvl_fp == 0) {
3241                         /* Not doing false-postive detection */
3242                         return;
3243                 }
3244                 /* False positive detection */
3245                 if (diff == bbr_lt_intvl_fp) {
3246                         /* At bbr_lt_intvl_fp we record the lost */
3247                         bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3248                         bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3249                 } else if (diff > (bbr_lt_intvl_min_rtts + bbr_lt_intvl_fp)) {
3250                         /* Now is our loss rate still high? */
3251                         lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3252                         delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3253                         if ((delivered == 0) ||
3254                             (((lost * 1000)/delivered) < bbr_lt_fd_thresh)) {
3255                                 /* No still below our threshold */
3256                                 bbr_log_type_ltbw(bbr, cts, 7, lost, delivered, 0, 0);
3257                         } else {
3258                                 /* Yikes its still high, it must be a false positive */
3259                                 bbr_log_type_ltbw(bbr, cts, 8, lost, delivered, 0, 0);
3260                                 goto reset_all;
3261                         }
3262                 }
3263                 return;
3264         }
3265         /*
3266          * Wait for the first loss before sampling, to let the policer
3267          * exhaust its tokens and estimate the steady-state rate allowed by
3268          * the policer. Starting samples earlier includes bursts that
3269          * over-estimate the bw.
3270          */
3271         if (bbr->rc_lt_is_sampling == 0) {
3272                 /* reason 1 is to begin doing the sampling  */
3273                 if (loss_detected == 0)
3274                         return;
3275                 bbr_reset_lt_bw_interval(bbr, cts);
3276                 bbr->rc_lt_is_sampling = 1;
3277                 bbr_log_type_ltbw(bbr, cts, 1, 0, 0, 0, 0);
3278                 return;
3279         }
3280         /* Now how long were we delivering long term last> */
3281         if (TSTMP_GEQ(bbr->r_ctl.rc_del_time, bbr->r_ctl.rc_lt_time))
3282                 d_time = bbr->r_ctl.rc_del_time - bbr->r_ctl.rc_lt_time;
3283         else
3284                 d_time = 0;
3285
3286         /* To avoid underestimates, reset sampling if we run out of data. */
3287         if (bbr->r_ctl.r_app_limited_until) {
3288                 /* Can not measure in app-limited state */
3289                 bbr_reset_lt_bw_sampling(bbr, cts);
3290                 /* reason 2 is to reset sampling due to app limits  */
3291                 bbr_log_type_ltbw(bbr, cts, 2, 0, 0, 0, d_time);
3292                 return;
3293         }
3294         diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
3295         if (diff < bbr_lt_intvl_min_rtts) {
3296                 /* 
3297                  * need more samples (we don't
3298                  * start on a round like linux so
3299                  * we need 1 more).
3300                  */
3301                 /* 6 is not_enough time or no-loss */
3302                 bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3303                 return;
3304         }
3305         if (diff > (4 * bbr_lt_intvl_min_rtts)) {
3306                 /*
3307                  * For now if we wait too long, reset all sampling. We need
3308                  * to do some research here, its possible that we should
3309                  * base this on how much loss as occurred.. something like
3310                  * if its under 10% (or some thresh) reset all otherwise
3311                  * don't.  Thats for phase II I guess.
3312                  */
3313                 bbr_reset_lt_bw_sampling(bbr, cts);
3314                 /* reason 3 is to reset sampling due too long of sampling */
3315                 bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3316                 return;
3317         }
3318         /*
3319          * End sampling interval when a packet is lost, so we estimate the
3320          * policer tokens were exhausted. Stopping the sampling before the
3321          * tokens are exhausted under-estimates the policed rate.
3322          */
3323         if (loss_detected == 0) {
3324                 /* 6 is not_enough time or no-loss */
3325                 bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3326                 return;
3327         }
3328         /* Calculate packets lost and delivered in sampling interval. */
3329         lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3330         delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3331         if ((delivered == 0) ||
3332             (((lost * 1000)/delivered) < bbr_lt_loss_thresh)) {
3333                 bbr_log_type_ltbw(bbr, cts, 6, lost, delivered, 0, d_time);
3334                 return;
3335         }
3336         if (d_time < 1000) {
3337                 /* Not enough time. wait */
3338                 /* 6 is not_enough time or no-loss */
3339                 bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3340                 return;
3341         }
3342         if (d_time >= (0xffffffff / USECS_IN_MSEC)) {
3343                 /* Too long */
3344                 bbr_reset_lt_bw_sampling(bbr, cts);
3345                 /* reason 3 is to reset sampling due too long of sampling */
3346                 bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3347                 return;
3348         }
3349         del_time = d_time;
3350         bw = delivered;
3351         bw *= (uint64_t)USECS_IN_SECOND;
3352         bw /= del_time;
3353         bbr_lt_bw_samp_done(bbr, bw, cts, d_time);
3354 }
3355
3356 /*
3357  * Allocate a sendmap from our zone.
3358  */
3359 static struct bbr_sendmap *
3360 bbr_alloc(struct tcp_bbr *bbr)
3361 {
3362         struct bbr_sendmap *rsm;
3363
3364         BBR_STAT_INC(bbr_to_alloc);
3365         rsm = uma_zalloc(bbr_zone, (M_NOWAIT | M_ZERO));
3366         if (rsm) {
3367                 bbr->r_ctl.rc_num_maps_alloced++;
3368                 return (rsm);
3369         }
3370         if (bbr->r_ctl.rc_free_cnt) {
3371                 BBR_STAT_INC(bbr_to_alloc_emerg);
3372                 rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
3373                 TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
3374                 bbr->r_ctl.rc_free_cnt--;
3375                 return (rsm);
3376         }
3377         BBR_STAT_INC(bbr_to_alloc_failed);
3378         return (NULL);
3379 }
3380
3381 static struct bbr_sendmap *
3382 bbr_alloc_full_limit(struct tcp_bbr *bbr)
3383 {
3384         if ((V_tcp_map_entries_limit > 0) &&
3385             (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
3386                 BBR_STAT_INC(bbr_alloc_limited);
3387                 if (!bbr->alloc_limit_reported) {
3388                         bbr->alloc_limit_reported = 1;
3389                         BBR_STAT_INC(bbr_alloc_limited_conns);
3390                 }
3391                 return (NULL);
3392         }
3393         return (bbr_alloc(bbr));
3394 }
3395
3396
3397 /* wrapper to allocate a sendmap entry, subject to a specific limit */
3398 static struct bbr_sendmap *
3399 bbr_alloc_limit(struct tcp_bbr *bbr, uint8_t limit_type)
3400 {
3401         struct bbr_sendmap *rsm;
3402
3403         if (limit_type) {
3404                 /* currently there is only one limit type */
3405                 if (V_tcp_map_split_limit > 0 &&
3406                     bbr->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
3407                         BBR_STAT_INC(bbr_split_limited);
3408                         if (!bbr->alloc_limit_reported) {
3409                                 bbr->alloc_limit_reported = 1;
3410                                 BBR_STAT_INC(bbr_alloc_limited_conns);
3411                         }
3412                         return (NULL);
3413                 }
3414         }
3415
3416         /* allocate and mark in the limit type, if set */
3417         rsm = bbr_alloc(bbr);
3418         if (rsm != NULL && limit_type) {
3419                 rsm->r_limit_type = limit_type;
3420                 bbr->r_ctl.rc_num_split_allocs++;
3421         }
3422         return (rsm);
3423 }
3424
3425 static void
3426 bbr_free(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
3427 {
3428         if (rsm->r_limit_type) {
3429                 /* currently there is only one limit type */
3430                 bbr->r_ctl.rc_num_split_allocs--;
3431         }
3432         if (rsm->r_is_smallmap)
3433                 bbr->r_ctl.rc_num_small_maps_alloced--;
3434         if (bbr->r_ctl.rc_tlp_send == rsm)
3435                 bbr->r_ctl.rc_tlp_send = NULL;
3436         if (bbr->r_ctl.rc_resend == rsm) {
3437                 bbr->r_ctl.rc_resend = NULL;
3438         }
3439         if (bbr->r_ctl.rc_next == rsm)
3440                 bbr->r_ctl.rc_next = NULL;
3441         if (bbr->r_ctl.rc_sacklast == rsm)
3442                 bbr->r_ctl.rc_sacklast = NULL;
3443         if (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
3444                 memset(rsm, 0, sizeof(struct bbr_sendmap));
3445                 TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
3446                 rsm->r_limit_type = 0;
3447                 bbr->r_ctl.rc_free_cnt++;
3448                 return;
3449         }
3450         bbr->r_ctl.rc_num_maps_alloced--;
3451         uma_zfree(bbr_zone, rsm);
3452 }
3453
3454 /*
3455  * Returns the BDP.
3456  */
3457 static uint64_t
3458 bbr_get_bw_delay_prod(uint64_t rtt, uint64_t bw) {
3459         /*
3460          * Calculate the bytes in flight needed given the bw (in bytes per
3461          * second) and the specifyed rtt in useconds. We need to put out the
3462          * returned value per RTT to match that rate. Gain will normaly
3463          * raise it up from there.
3464          *
3465          * This should not overflow as long as the bandwidth is below 1
3466          * TByte per second (bw < 10**12 = 2**40) and the rtt is smaller
3467          * than 1000 seconds (rtt < 10**3 * 10**6 = 10**9 = 2**30).
3468          */
3469         uint64_t usec_per_sec;
3470
3471         usec_per_sec = USECS_IN_SECOND;
3472         return ((rtt * bw) / usec_per_sec);
3473 }
3474
3475 /*
3476  * Return the initial cwnd.
3477  */
3478 static uint32_t
3479 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp)
3480 {
3481         uint32_t i_cwnd;
3482
3483         if (bbr->rc_init_win) {
3484                 i_cwnd = bbr->rc_init_win * tp->t_maxseg;
3485         } else if (V_tcp_initcwnd_segments)
3486                 i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
3487                     max(2 * tp->t_maxseg, 14600));
3488         else if (V_tcp_do_rfc3390)
3489                 i_cwnd = min(4 * tp->t_maxseg,
3490                     max(2 * tp->t_maxseg, 4380));
3491         else {
3492                 /* Per RFC5681 Section 3.1 */
3493                 if (tp->t_maxseg > 2190)
3494                         i_cwnd = 2 * tp->t_maxseg;
3495                 else if (tp->t_maxseg > 1095)
3496                         i_cwnd = 3 * tp->t_maxseg;
3497                 else
3498                         i_cwnd = 4 * tp->t_maxseg;
3499         }
3500         return (i_cwnd);
3501 }
3502
3503 /*
3504  * Given a specified gain, return the target
3505  * cwnd based on that gain.
3506  */
3507 static uint32_t
3508 bbr_get_raw_target_cwnd(struct tcp_bbr *bbr, uint32_t gain, uint64_t bw)
3509 {
3510         uint64_t bdp, rtt;
3511         uint32_t cwnd;
3512
3513         if ((get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) ||
3514             (bbr_get_full_bw(bbr) == 0)) {
3515                 /* No measurements yet */
3516                 return (bbr_initial_cwnd(bbr, bbr->rc_tp));
3517         }
3518         /*
3519          * Get bytes per RTT needed (rttProp is normally in
3520          * bbr_cwndtarget_rtt_touse)
3521          */
3522         rtt = bbr_get_rtt(bbr, bbr_cwndtarget_rtt_touse);
3523         /* Get the bdp from the two values */
3524         bdp = bbr_get_bw_delay_prod(rtt, bw);
3525         /* Now apply the gain */
3526         cwnd = (uint32_t)(((bdp * ((uint64_t)gain)) + (uint64_t)(BBR_UNIT - 1)) / ((uint64_t)BBR_UNIT));
3527
3528         return (cwnd);
3529 }
3530
3531 static uint32_t
3532 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain)
3533 {
3534         uint32_t cwnd, mss;
3535
3536         mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
3537         /* Get the base cwnd with gain rounded to a mss */
3538         cwnd = roundup(bbr_get_raw_target_cwnd(bbr, bw, gain), mss);
3539         /* 
3540          * Add in N (2 default since we do not have a
3541          * fq layer to trap packets in) quanta's per the I-D 
3542          * section 4.2.3.2 quanta adjust. 
3543          */
3544         cwnd += (bbr_quanta * bbr->r_ctl.rc_pace_max_segs);
3545         if (bbr->rc_use_google) {
3546                 if((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3547                    (bbr_state_val(bbr) == BBR_SUB_GAIN)) {
3548                         /* 
3549                          * The linux implementation adds
3550                          * an extra 2 x mss in gain cycle which
3551                          * is documented no-where except in the code.
3552                          * so we add more for Neal undocumented feature 
3553                          */
3554                         cwnd += 2 * mss;
3555                 }
3556                 if ((cwnd / mss) & 0x1) {
3557                         /* Round up for odd num mss */
3558                         cwnd += mss;
3559                 }
3560         }
3561         /* Are we below the min cwnd? */
3562         if (cwnd < get_min_cwnd(bbr))
3563                 return (get_min_cwnd(bbr));
3564         return (cwnd);
3565 }
3566
3567 static uint16_t
3568 bbr_gain_adjust(struct tcp_bbr *bbr, uint16_t gain)
3569 {
3570         if (gain < 1)
3571                 gain = 1;
3572         return (gain);
3573 }
3574
3575 static uint32_t
3576 bbr_get_header_oh(struct tcp_bbr *bbr)
3577 {
3578         int seg_oh;
3579
3580         seg_oh = 0;
3581         if (bbr->r_ctl.rc_inc_tcp_oh) {
3582                 /* Do we include TCP overhead? */
3583                 seg_oh = (bbr->rc_last_options + sizeof(struct tcphdr));
3584         }
3585         if (bbr->r_ctl.rc_inc_ip_oh) {
3586                 /* Do we include IP overhead? */
3587 #ifdef INET6
3588                 if (bbr->r_is_v6)
3589                         seg_oh += sizeof(struct ip6_hdr);
3590                 else
3591 #endif
3592 #ifdef INET
3593                         seg_oh += sizeof(struct ip);
3594 #endif
3595         }
3596         if (bbr->r_ctl.rc_inc_enet_oh) {
3597                 /* Do we include the ethernet overhead?  */
3598                 seg_oh += sizeof(struct ether_header);
3599         }
3600         return(seg_oh);
3601 }
3602
3603
3604 static uint32_t
3605 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain, uint32_t useconds_time, uint64_t bw)
3606 {
3607         uint64_t divor, res, tim;
3608         
3609         if (useconds_time == 0)
3610                 return (0);
3611         gain = bbr_gain_adjust(bbr, gain);
3612         divor = (uint64_t)USECS_IN_SECOND * (uint64_t)BBR_UNIT;
3613         tim = useconds_time;
3614         res = (tim * bw * gain) / divor;
3615         if (res == 0)
3616                 res = 1;
3617         return ((uint32_t)res);
3618 }
3619
3620 /*
3621  * Given a gain and a length return the delay in useconds that
3622  * should be used to evenly space out packets
3623  * on the connection (based on the gain factor).
3624  */
3625 static uint32_t
3626 bbr_get_pacing_delay(struct tcp_bbr *bbr, uint16_t gain, int32_t len, uint32_t cts, int nolog)
3627 {
3628         uint64_t bw, lentim, res;
3629         uint32_t usecs, srtt, over = 0;
3630         uint32_t seg_oh, num_segs, maxseg;
3631
3632         if (len == 0)
3633                 return (0);
3634
3635         maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
3636         num_segs = (len + maxseg - 1) / maxseg;
3637         if (bbr->rc_use_google == 0) {
3638                 seg_oh = bbr_get_header_oh(bbr);
3639                 len += (num_segs * seg_oh);
3640         }
3641         gain = bbr_gain_adjust(bbr, gain);
3642         bw = bbr_get_bw(bbr);
3643         if (bbr->rc_use_google) {
3644                 uint64_t cbw;
3645                 
3646                 /* 
3647                  * Reduce the b/w by the google discount
3648                  * factor 10 = 1%.
3649                  */
3650                 cbw = bw *  (uint64_t)(1000 - bbr->r_ctl.bbr_google_discount);
3651                 cbw /= (uint64_t)1000;
3652                 /* We don't apply a discount if it results in 0 */
3653                 if (cbw > 0)
3654                         bw = cbw;
3655         }
3656         lentim = ((uint64_t)len *
3657                   (uint64_t)USECS_IN_SECOND *
3658                   (uint64_t)BBR_UNIT);
3659         res = lentim / ((uint64_t)gain * bw);
3660         if (res == 0)
3661                 res = 1;
3662         usecs = (uint32_t)res;
3663         srtt = bbr_get_rtt(bbr, BBR_SRTT);
3664         if (bbr_hptsi_max_mul && bbr_hptsi_max_div &&
3665             (bbr->rc_use_google == 0) &&
3666             (usecs > ((srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div))) {
3667                 /*
3668                  * We cannot let the delay be more than 1/2 the srtt time.
3669                  * Otherwise we cannot pace out or send properly.
3670                  */
3671                 over = usecs = (srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div;
3672                 BBR_STAT_INC(bbr_hpts_min_time);
3673         }
3674         if (!nolog)
3675                 bbr_log_pacing_delay_calc(bbr, gain, len, cts, usecs, bw, over, 1);
3676         return (usecs);
3677 }
3678
3679 static void
3680 bbr_ack_received(struct tcpcb *tp, struct tcp_bbr *bbr, struct tcphdr *th, uint32_t bytes_this_ack,
3681                  uint32_t sack_changed, uint32_t prev_acked, int32_t line, uint32_t losses)
3682 {
3683         INP_WLOCK_ASSERT(tp->t_inpcb);
3684         uint64_t bw;
3685         uint32_t cwnd, target_cwnd, saved_bytes, maxseg;
3686         int32_t meth;
3687
3688 #ifdef STATS
3689         if ((tp->t_flags & TF_GPUTINPROG) &&
3690             SEQ_GEQ(th->th_ack, tp->gput_ack)) {
3691                 /*
3692                  * Strech acks and compressed acks will cause this to
3693                  * oscillate but we are doing it the same way as the main
3694                  * stack so it will be compariable (though possibly not
3695                  * ideal).
3696                  */
3697                 int32_t cgput;
3698                 int64_t gput, time_stamp;
3699
3700                 gput = (int64_t) (th->th_ack - tp->gput_seq) * 8;
3701                 time_stamp = max(1, ((bbr->r_ctl.rc_rcvtime - tp->gput_ts) / 1000));
3702                 cgput = gput / time_stamp;
3703                 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
3704                                          cgput);
3705                 if (tp->t_stats_gput_prev > 0)
3706                         stats_voi_update_abs_s32(tp->t_stats,
3707                                                  VOI_TCP_GPUT_ND,
3708                                                  ((gput - tp->t_stats_gput_prev) * 100) /
3709                                                  tp->t_stats_gput_prev);
3710                 tp->t_flags &= ~TF_GPUTINPROG;
3711                 tp->t_stats_gput_prev = cgput;
3712         }
3713 #endif
3714         if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3715             ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
3716                 /* We don't change anything in probe-rtt */
3717                 return;
3718         }
3719         maxseg = tp->t_maxseg - bbr->rc_last_options;
3720         saved_bytes = bytes_this_ack;
3721         bytes_this_ack += sack_changed;
3722         if (bytes_this_ack > prev_acked) {
3723                 bytes_this_ack -= prev_acked;
3724                 /* 
3725                  * A byte ack'd gives us a full mss 
3726                  * to be like linux i.e. they count packets.
3727                  */
3728                 if ((bytes_this_ack < maxseg) && bbr->rc_use_google)
3729                         bytes_this_ack = maxseg;
3730         } else {
3731                 /* Unlikely */
3732                 bytes_this_ack = 0;
3733         }
3734         cwnd = tp->snd_cwnd;
3735         bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3736         if (bw) 
3737                 target_cwnd = bbr_get_target_cwnd(bbr,
3738                                                   bw,
3739                                                   (uint32_t)bbr->r_ctl.rc_bbr_cwnd_gain);
3740         else
3741                 target_cwnd = bbr_initial_cwnd(bbr, bbr->rc_tp);
3742         if (IN_RECOVERY(tp->t_flags) &&
3743             (bbr->bbr_prev_in_rec == 0)) {
3744                 /* 
3745                  * We are entering recovery and
3746                  * thus packet conservation.
3747                  */
3748                 bbr->pkt_conservation = 1;
3749                 bbr->r_ctl.rc_recovery_start = bbr->r_ctl.rc_rcvtime;
3750                 cwnd = ctf_flight_size(tp,
3751                                        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3752                         bytes_this_ack;
3753         }
3754         if (IN_RECOVERY(tp->t_flags)) {
3755                 uint32_t flight;
3756
3757                 bbr->bbr_prev_in_rec = 1;
3758                 if (cwnd > losses) {
3759                         cwnd -= losses;
3760                         if (cwnd < maxseg)
3761                                 cwnd = maxseg;
3762                 } else
3763                         cwnd = maxseg;
3764                 flight = ctf_flight_size(tp,
3765                                          (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3766                 bbr_log_type_cwndupd(bbr, flight, 0,
3767                                      losses, 10, 0, 0, line);
3768                 if (bbr->pkt_conservation) {
3769                         uint32_t time_in;
3770
3771                         if (TSTMP_GEQ(bbr->r_ctl.rc_rcvtime, bbr->r_ctl.rc_recovery_start))
3772                                 time_in = bbr->r_ctl.rc_rcvtime - bbr->r_ctl.rc_recovery_start;
3773                         else 
3774                                 time_in = 0;
3775
3776                         if (time_in >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
3777                                 /* Clear packet conservation after an rttProp */
3778                                 bbr->pkt_conservation = 0;
3779                         } else {
3780                                 if ((flight + bytes_this_ack) > cwnd)
3781                                         cwnd = flight + bytes_this_ack;
3782                                 if (cwnd < get_min_cwnd(bbr))
3783                                         cwnd = get_min_cwnd(bbr);
3784                                 tp->snd_cwnd = cwnd;
3785                                 bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed,
3786                                                      prev_acked, 1, target_cwnd, th->th_ack, line);
3787                                 return;
3788                         }
3789                 }
3790         } else
3791                 bbr->bbr_prev_in_rec = 0;
3792         if ((bbr->rc_use_google == 0) && bbr->r_ctl.restrict_growth) {
3793                 bbr->r_ctl.restrict_growth--;
3794                 if (bytes_this_ack > maxseg)
3795                         bytes_this_ack = maxseg;
3796         }
3797         if (bbr->rc_filled_pipe) {
3798                 /*
3799                  * Here we have exited startup and filled the pipe. We will
3800                  * thus allow the cwnd to shrink to the target. We hit here
3801                  * mostly.
3802                  */
3803                 uint32_t s_cwnd;
3804
3805                 meth = 2;
3806                 s_cwnd = min((cwnd + bytes_this_ack), target_cwnd);
3807                 if (s_cwnd > cwnd)
3808                         cwnd = s_cwnd;
3809                 else if (bbr_cwnd_may_shrink || bbr->rc_use_google || bbr->rc_no_pacing)
3810                         cwnd = s_cwnd;
3811         } else {
3812                 /*
3813                  * Here we are still in startup, we increase cwnd by what
3814                  * has been acked.
3815                  */
3816                 if ((cwnd < target_cwnd) ||
3817                     (bbr->rc_past_init_win == 0)) {
3818                         meth = 3;
3819                         cwnd += bytes_this_ack;
3820                 } else {
3821                         /* 
3822                          * Method 4 means we are at target so no gain in
3823                          * startup and past the initial window.
3824                          */
3825                         meth = 4;
3826                 }
3827         }
3828         tp->snd_cwnd = max(cwnd, get_min_cwnd(bbr));
3829         bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed, prev_acked, meth, target_cwnd, th->th_ack, line);
3830 }
3831
3832 static void
3833 tcp_bbr_partialack(struct tcpcb *tp)
3834 {
3835         struct tcp_bbr *bbr;
3836
3837         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3838         INP_WLOCK_ASSERT(tp->t_inpcb);
3839         if (ctf_flight_size(tp,
3840                 (bbr->r_ctl.rc_sacked  + bbr->r_ctl.rc_lost_bytes)) <=
3841             tp->snd_cwnd) {
3842                 bbr->r_wanted_output = 1;
3843         }
3844 }
3845
3846 static void
3847 bbr_post_recovery(struct tcpcb *tp)
3848 {
3849         struct tcp_bbr *bbr;
3850         uint32_t  flight;
3851
3852         INP_WLOCK_ASSERT(tp->t_inpcb);
3853         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3854         /*
3855          * Here we just exit recovery.
3856          */
3857         EXIT_RECOVERY(tp->t_flags);
3858         /* Lock in our b/w reduction for the specified number of pkt-epochs */
3859         bbr->r_recovery_bw = 0;
3860         tp->snd_recover = tp->snd_una;
3861         tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3862         bbr->pkt_conservation = 0;
3863         if (bbr->rc_use_google == 0) {
3864                 /*
3865                  * For non-google mode lets
3866                  * go ahead and make sure we clear
3867                  * the recovery state so if we
3868                  * bounce back in to recovery we
3869                  * will do PC.
3870                  */
3871                 bbr->bbr_prev_in_rec = 0;
3872         }
3873         bbr_log_type_exit_rec(bbr);
3874         if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3875                 tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3876                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 15, 0, 0, __LINE__);
3877         } else {
3878                 /* For probe-rtt case lets fix up its saved_cwnd */
3879                 if (bbr->r_ctl.rc_saved_cwnd < bbr->r_ctl.rc_cwnd_on_ent) {
3880                         bbr->r_ctl.rc_saved_cwnd = bbr->r_ctl.rc_cwnd_on_ent;
3881                         bbr_log_type_cwndupd(bbr, 0, 0, 0, 16, 0, 0, __LINE__);
3882                 }
3883         }
3884         flight = ctf_flight_size(tp,
3885                      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3886         if ((bbr->rc_use_google == 0) &&
3887             bbr_do_red) {
3888                 uint64_t val, lr2use;
3889                 uint32_t maxseg, newcwnd, acks_inflight, ratio, cwnd;
3890                 uint32_t *cwnd_p;
3891                 
3892                 if (bbr_get_rtt(bbr, BBR_SRTT)) {
3893                         val = ((uint64_t)bbr_get_rtt(bbr, BBR_RTT_PROP) * (uint64_t)1000);
3894                         val /= bbr_get_rtt(bbr, BBR_SRTT);
3895                         ratio = (uint32_t)val;
3896                 } else
3897                         ratio = 1000;
3898
3899                 bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div,
3900                                      bbr->r_ctl.recovery_lr, 21,
3901                                      ratio,
3902                                      bbr->r_ctl.rc_red_cwnd_pe,
3903                                      __LINE__);
3904                 if ((ratio < bbr_do_red) || (bbr_do_red == 0))
3905                         goto done;
3906                 if (((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3907                      bbr_prtt_slam_cwnd) ||
3908                     (bbr_sub_drain_slam_cwnd &&
3909                      (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3910                      bbr->rc_hit_state_1 &&
3911                      (bbr_state_val(bbr) == BBR_SUB_DRAIN)) ||
3912                     ((bbr->rc_bbr_state == BBR_STATE_DRAIN) &&
3913                      bbr_slam_cwnd_in_main_drain)) {
3914                         /* 
3915                          * Here we must poke at the saved cwnd 
3916                          * as well as the cwnd.
3917                          */
3918                         cwnd = bbr->r_ctl.rc_saved_cwnd;
3919                         cwnd_p = &bbr->r_ctl.rc_saved_cwnd;
3920                 } else {
3921                         cwnd = tp->snd_cwnd;
3922                         cwnd_p = &tp->snd_cwnd;
3923                 }
3924                 maxseg = tp->t_maxseg - bbr->rc_last_options;
3925                 /* Add the overall lr with the recovery lr */
3926                 if (bbr->r_ctl.rc_lost == 0)
3927                         lr2use = 0;
3928                 else if (bbr->r_ctl.rc_delivered == 0)
3929                         lr2use = 1000;
3930                 else {
3931                         lr2use = bbr->r_ctl.rc_lost * 1000;
3932                         lr2use /= bbr->r_ctl.rc_delivered;
3933                 }
3934                 lr2use += bbr->r_ctl.recovery_lr;
3935                 acks_inflight = (flight / (maxseg * 2));
3936                 if (bbr_red_scale) {
3937                         lr2use *= bbr_get_rtt(bbr, BBR_SRTT);
3938                         lr2use /= bbr_red_scale;
3939                         if ((bbr_red_growth_restrict) &&
3940                             ((bbr_get_rtt(bbr, BBR_SRTT)/bbr_red_scale) > 1))
3941                             bbr->r_ctl.restrict_growth += acks_inflight;
3942                 }
3943                 if (lr2use) {
3944                         val = (uint64_t)cwnd * lr2use;
3945                         val /= 1000;
3946                         if (cwnd > val)
3947                                 newcwnd = roundup((cwnd - val), maxseg);
3948                         else
3949                                 newcwnd = maxseg;
3950                 } else {
3951                         val = (uint64_t)cwnd * (uint64_t)bbr_red_mul;
3952                         val /= (uint64_t)bbr_red_div;
3953                         newcwnd = roundup((uint32_t)val, maxseg);
3954                 }
3955                 /* with standard delayed acks how many acks can I expect? */
3956                 if (bbr_drop_limit == 0) {
3957                         /* 
3958                          * Anticpate how much we will
3959                          * raise the cwnd based on the acks.
3960                          */
3961                         if ((newcwnd + (acks_inflight * maxseg)) < get_min_cwnd(bbr)) {
3962                                 /* We do enforce the min (with the acks) */
3963                                 newcwnd = (get_min_cwnd(bbr) - acks_inflight);
3964                         }
3965                 } else {
3966                         /*
3967                          * A strict drop limit of N is is inplace
3968                          */
3969                         if (newcwnd < (bbr_drop_limit * maxseg)) {
3970                                 newcwnd = bbr_drop_limit * maxseg;
3971                         }
3972                 }
3973                 /* For the next N acks do we restrict the growth */
3974                 *cwnd_p = newcwnd;
3975                 if (tp->snd_cwnd > newcwnd)
3976                         tp->snd_cwnd = newcwnd;
3977                 bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div, val, 22,
3978                                      (uint32_t)lr2use,
3979                                      bbr_get_rtt(bbr, BBR_SRTT), __LINE__);
3980                 bbr->r_ctl.rc_red_cwnd_pe = bbr->r_ctl.rc_pkt_epoch;
3981         }
3982 done:
3983         bbr->r_ctl.recovery_lr = 0;
3984         if (flight <= tp->snd_cwnd) {
3985                 bbr->r_wanted_output = 1;
3986         }
3987         tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3988 }
3989
3990 static void
3991 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts)
3992 {
3993         bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3994         /* Limit the drop in b/w to 1/2 our current filter. */
3995         if (bbr->r_ctl.red_bw > bbr->r_ctl.rc_bbr_cur_del_rate)
3996                 bbr->r_ctl.red_bw = bbr->r_ctl.rc_bbr_cur_del_rate;
3997         if (bbr->r_ctl.red_bw < (get_filter_value(&bbr->r_ctl.rc_delrate) / 2))
3998                 bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate) / 2;
3999         tcp_bbr_tso_size_check(bbr, cts);
4000 }
4001
4002 static void
4003 bbr_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type, struct bbr_sendmap *rsm)
4004 {
4005         struct tcp_bbr *bbr;
4006
4007         INP_WLOCK_ASSERT(tp->t_inpcb);
4008         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4009         switch (type) {
4010         case CC_NDUPACK:
4011                 if (!IN_RECOVERY(tp->t_flags)) {
4012                         tp->snd_recover = tp->snd_max;
4013                         /* Start a new epoch */
4014                         bbr_set_pktepoch(bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
4015                         if (bbr->rc_lt_is_sampling || bbr->rc_lt_use_bw) {
4016                                 /* 
4017                                  * Move forward the lt epoch 
4018                                  * so it won't count the truncated
4019                                  * epoch.
4020                                  */
4021                                 bbr->r_ctl.rc_lt_epoch++;
4022                         }
4023                         if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
4024                                 /*
4025                                  * Just like the policer detection code 
4026                                  * if we are in startup we must push
4027                                  * forward the last startup epoch
4028                                  * to hide the truncated PE.
4029                                  */
4030                                 bbr->r_ctl.rc_bbr_last_startup_epoch++;
4031                         }
4032                         bbr->r_ctl.rc_cwnd_on_ent = tp->snd_cwnd;
4033                         ENTER_RECOVERY(tp->t_flags);
4034                         bbr->rc_tlp_rtx_out = 0;
4035                         bbr->r_ctl.recovery_lr = bbr->r_ctl.rc_pkt_epoch_loss_rate;
4036                         tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
4037                         if (bbr->rc_inp->inp_in_hpts &&
4038                             ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) == 0)) {
4039                                 /* 
4040                                  * When we enter recovery, we need to restart
4041                                  * any timers. This may mean we gain an agg
4042                                  * early, which will be made up for at the last
4043                                  * rxt out.
4044                                  */
4045                                 bbr->rc_timer_first = 1;
4046                                 bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
4047                         }
4048                         /*
4049                          * Calculate a new cwnd based on to the current
4050                          * delivery rate with no gain. We get the bdp
4051                          * without gaining it up like we normally would and
4052                          * we use the last cur_del_rate.
4053                          */
4054                         if ((bbr->rc_use_google == 0) &&
4055                             (bbr->r_ctl.bbr_rttprobe_gain_val ||
4056                              (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT))) {
4057                                 tp->snd_cwnd = ctf_flight_size(tp,
4058                                                    (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
4059                                         (tp->t_maxseg - bbr->rc_last_options);
4060                                 if (tp->snd_cwnd < get_min_cwnd(bbr)) {
4061                                         /* We always gate to min cwnd */
4062                                         tp->snd_cwnd = get_min_cwnd(bbr);
4063                                 }
4064                                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 14, 0, 0, __LINE__);
4065                         }
4066                         bbr_log_type_enter_rec(bbr, rsm->r_start);
4067                 }
4068                 break;
4069         case CC_RTO_ERR:
4070                 TCPSTAT_INC(tcps_sndrexmitbad);
4071                 /* RTO was unnecessary, so reset everything. */
4072                 bbr_reset_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime);
4073                 if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
4074                         tp->snd_cwnd = tp->snd_cwnd_prev;
4075                         tp->snd_ssthresh = tp->snd_ssthresh_prev;
4076                         tp->snd_recover = tp->snd_recover_prev;
4077                         tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
4078                         bbr_log_type_cwndupd(bbr, 0, 0, 0, 13, 0, 0, __LINE__);
4079                 }
4080                 tp->t_badrxtwin = 0;
4081                 break;
4082         }
4083 }
4084
4085 /*
4086  * Indicate whether this ack should be delayed.  We can delay the ack if
4087  * following conditions are met:
4088  *      - There is no delayed ack timer in progress.
4089  *      - Our last ack wasn't a 0-sized window. We never want to delay
4090  *        the ack that opens up a 0-sized window.
4091  *      - LRO wasn't used for this segment. We make sure by checking that the
4092  *        segment size is not larger than the MSS.
4093  *      - Delayed acks are enabled or this is a half-synchronized T/TCP
4094  *        connection.
4095  *      - The data being acked is less than a full segment (a stretch ack
4096  *        of more than a segment we should ack.
4097  *      - nsegs is 1 (if its more than that we received more than 1 ack).
4098  */
4099 #define DELAY_ACK(tp, bbr, nsegs)                               \
4100         (((tp->t_flags & TF_RXWIN0SENT) == 0) &&                \
4101          ((bbr->bbr_segs_rcvd + nsegs) < tp->t_delayed_ack) &&  \
4102          (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4103
4104 /*
4105  * Return the lowest RSM in the map of
4106  * packets still in flight that is not acked.
4107  * This should normally find on the first one
4108  * since we remove packets from the send
4109  * map after they are marked ACKED.
4110  */
4111 static struct bbr_sendmap *
4112 bbr_find_lowest_rsm(struct tcp_bbr *bbr)
4113 {
4114         struct bbr_sendmap *rsm;
4115
4116         /*
4117          * Walk the time-order transmitted list looking for an rsm that is
4118          * not acked. This will be the one that was sent the longest time
4119          * ago that is still outstanding.
4120          */
4121         TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_tmap, r_tnext) {
4122                 if (rsm->r_flags & BBR_ACKED) {
4123                         continue;
4124                 }
4125                 goto finish;
4126         }
4127 finish:
4128         return (rsm);
4129 }
4130
4131 static struct bbr_sendmap *
4132 bbr_find_high_nonack(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
4133 {
4134         struct bbr_sendmap *prsm;
4135
4136         /*
4137          * Walk the sequence order list backward until we hit and arrive at
4138          * the highest seq not acked. In theory when this is called it
4139          * should be the last segment (which it was not).
4140          */
4141         prsm = rsm;
4142         TAILQ_FOREACH_REVERSE_FROM(prsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4143                 if (prsm->r_flags & (BBR_ACKED | BBR_HAS_FIN)) {
4144                         continue;
4145                 }
4146                 return (prsm);
4147         }
4148         return (NULL);
4149 }
4150
4151 /*
4152  * Returns to the caller the number of microseconds that
4153  * the packet can be outstanding before we think we
4154  * should have had an ack returned.
4155  */
4156 static uint32_t
4157 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm)
4158 {
4159         /*
4160          * lro is the flag we use to determine if we have seen reordering.
4161          * If it gets set we have seen reordering. The reorder logic either
4162          * works in one of two ways:
4163          *
4164          * If reorder-fade is configured, then we track the last time we saw
4165          * re-ordering occur. If we reach the point where enough time as
4166          * passed we no longer consider reordering has occuring.
4167          *
4168          * Or if reorder-face is 0, then once we see reordering we consider
4169          * the connection to alway be subject to reordering and just set lro
4170          * to 1.
4171          *
4172          * In the end if lro is non-zero we add the extra time for
4173          * reordering in.
4174          */
4175         int32_t lro;
4176         uint32_t thresh, t_rxtcur;
4177
4178         if (srtt == 0)
4179                 srtt = 1;
4180         if (bbr->r_ctl.rc_reorder_ts) {
4181                 if (bbr->r_ctl.rc_reorder_fade) {
4182                         if (SEQ_GEQ(cts, bbr->r_ctl.rc_reorder_ts)) {
4183                                 lro = cts - bbr->r_ctl.rc_reorder_ts;
4184                                 if (lro == 0) {
4185                                         /*
4186                                          * No time as passed since the last
4187                                          * reorder, mark it as reordering.
4188                                          */
4189                                         lro = 1;
4190                                 }
4191                         } else {
4192                                 /* Negative time? */
4193                                 lro = 0;
4194                         }
4195                         if (lro > bbr->r_ctl.rc_reorder_fade) {
4196                                 /* Turn off reordering seen too */
4197                                 bbr->r_ctl.rc_reorder_ts = 0;
4198                                 lro = 0;
4199                         }
4200                 } else {
4201                         /* Reodering does not fade */
4202                         lro = 1;
4203                 }
4204         } else {
4205                 lro = 0;
4206         }
4207         thresh = srtt + bbr->r_ctl.rc_pkt_delay;
4208         if (lro) {
4209                 /* It must be set, if not you get 1/4 rtt */
4210                 if (bbr->r_ctl.rc_reorder_shift)
4211                         thresh += (srtt >> bbr->r_ctl.rc_reorder_shift);
4212                 else
4213                         thresh += (srtt >> 2);
4214         } else {
4215                 thresh += 1000;
4216         }
4217         /* We don't let the rack timeout be above a RTO */
4218         if ((bbr->rc_tp)->t_srtt == 0)
4219                 t_rxtcur = BBR_INITIAL_RTO;
4220         else
4221                 t_rxtcur = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
4222         if (thresh > t_rxtcur) {
4223                 thresh = t_rxtcur;
4224         }
4225         /* And we don't want it above the RTO max either */
4226         if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4227                 thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4228         }
4229         bbr_log_thresh_choice(bbr, cts, thresh, lro, srtt, rsm, BBR_TO_FRM_RACK);
4230         return (thresh);
4231 }
4232
4233 /*
4234  * Return to the caller the amount of time in mico-seconds
4235  * that should be used for the TLP timer from the last
4236  * send time of this packet.
4237  */
4238 static uint32_t
4239 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
4240     struct bbr_sendmap *rsm, uint32_t srtt,
4241     uint32_t cts)
4242 {
4243         uint32_t thresh, len, maxseg, t_rxtcur;
4244         struct bbr_sendmap *prsm;
4245
4246         if (srtt == 0)
4247                 srtt = 1;
4248         if (bbr->rc_tlp_threshold)
4249                 thresh = srtt + (srtt / bbr->rc_tlp_threshold);
4250         else
4251                 thresh = (srtt * 2);
4252         maxseg = tp->t_maxseg - bbr->rc_last_options;
4253         /* Get the previous sent packet, if any  */
4254         len = rsm->r_end - rsm->r_start;
4255
4256         /* 2.1 behavior */
4257         prsm = TAILQ_PREV(rsm, bbr_head, r_tnext);
4258         if (prsm && (len <= maxseg)) {
4259                 /*
4260                  * Two packets outstanding, thresh should be (2*srtt) +
4261                  * possible inter-packet delay (if any).
4262                  */
4263                 uint32_t inter_gap = 0;
4264                 int idx, nidx;
4265
4266                 idx = rsm->r_rtr_cnt - 1;
4267                 nidx = prsm->r_rtr_cnt - 1;
4268                 if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
4269                         /* Yes it was sent later (or at the same time) */
4270                         inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
4271                 }
4272                 thresh += inter_gap;
4273         } else if (len <= maxseg) {
4274                 /*
4275                  * Possibly compensate for delayed-ack.
4276                  */
4277                 uint32_t alt_thresh;
4278
4279                 alt_thresh = srtt + (srtt / 2) + bbr_delayed_ack_time;
4280                 if (alt_thresh > thresh)
4281                         thresh = alt_thresh;
4282         }
4283         /* Not above the current  RTO */
4284         if (tp->t_srtt == 0)
4285                 t_rxtcur = BBR_INITIAL_RTO;
4286         else
4287                 t_rxtcur = TICKS_2_USEC(tp->t_rxtcur);
4288
4289         bbr_log_thresh_choice(bbr, cts, thresh, t_rxtcur, srtt, rsm, BBR_TO_FRM_TLP);
4290         /* Not above an RTO */
4291         if (thresh > t_rxtcur) {
4292                 thresh = t_rxtcur;
4293         }
4294         /* Not above a RTO max */
4295         if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4296                 thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4297         }
4298         /* And now apply the user TLP min */
4299         if (thresh < bbr_tlp_min) {
4300                 thresh = bbr_tlp_min;
4301         }
4302         return (thresh);
4303 }
4304
4305 /*
4306  * Return one of three RTTs to use (in microseconds).
4307  */
4308 static __inline uint32_t
4309 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type)
4310 {
4311         uint32_t f_rtt;
4312         uint32_t srtt;
4313
4314         f_rtt = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
4315         if (get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) {
4316                 /* We have no rtt at all */
4317                 if (bbr->rc_tp->t_srtt == 0)
4318                         f_rtt = BBR_INITIAL_RTO;
4319                 else
4320                         f_rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4321                 /*
4322                  * Since we don't know how good the rtt is apply a
4323                  * delayed-ack min
4324                  */
4325                 if (f_rtt < bbr_delayed_ack_time) {
4326                         f_rtt = bbr_delayed_ack_time;
4327                 }
4328         }
4329         /* Take the filter version or last measured pkt-rtt */
4330         if (rtt_type == BBR_RTT_PROP) {
4331                 srtt = f_rtt;
4332         } else if (rtt_type == BBR_RTT_PKTRTT) {
4333                 if (bbr->r_ctl.rc_pkt_epoch_rtt) {
4334                         srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
4335                 } else {
4336                         /* No pkt rtt yet */
4337                         srtt = f_rtt;
4338                 }
4339         } else if (rtt_type == BBR_RTT_RACK) {
4340                 srtt = bbr->r_ctl.rc_last_rtt;
4341                 /* We need to add in any internal delay for our timer */
4342                 if (bbr->rc_ack_was_delayed)
4343                         srtt += bbr->r_ctl.rc_ack_hdwr_delay;
4344         } else if (rtt_type == BBR_SRTT) {
4345                 srtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4346         } else {
4347                 /* TSNH */
4348                 srtt = f_rtt;
4349 #ifdef BBR_INVARIANTS
4350                 panic("Unknown rtt request type %d", rtt_type);
4351 #endif
4352         }
4353         return (srtt);
4354 }
4355
4356 static int
4357 bbr_is_lost(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t cts)
4358 {
4359         uint32_t thresh;
4360
4361         
4362         thresh = bbr_calc_thresh_rack(bbr, bbr_get_rtt(bbr, BBR_RTT_RACK),
4363                                       cts, rsm);
4364         if ((cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)]) >= thresh) {
4365                 /* It is lost (past time) */
4366                 return (1);
4367         }
4368         return (0);
4369 }
4370
4371 /*
4372  * Return a sendmap if we need to retransmit something.
4373  */
4374 static struct bbr_sendmap *
4375 bbr_check_recovery_mode(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4376 {
4377         /*
4378          * Check to see that we don't need to fall into recovery. We will
4379          * need to do so if our oldest transmit is past the time we should
4380          * have had an ack.
4381          */
4382
4383         struct bbr_sendmap *rsm;
4384         int32_t idx;
4385
4386         if (TAILQ_EMPTY(&bbr->r_ctl.rc_map)) {
4387                 /* Nothing outstanding that we know of */
4388                 return (NULL);
4389         }
4390         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
4391         if (rsm == NULL) {
4392                 /* Nothing in the transmit map */
4393                 return (NULL);
4394         }
4395         if (tp->t_flags & TF_SENTFIN) {
4396                 /* Fin restricted, don't find anything once a fin is sent */
4397                 return (NULL);
4398         }
4399         if (rsm->r_flags & BBR_ACKED) {
4400                 /*
4401                  * Ok the first one is acked (this really should not happen
4402                  * since we remove the from the tmap once they are acked)
4403                  */
4404                 rsm = bbr_find_lowest_rsm(bbr);
4405                 if (rsm == NULL)
4406                         return (NULL);
4407         }
4408         idx = rsm->r_rtr_cnt - 1;
4409         if (SEQ_LEQ(cts, rsm->r_tim_lastsent[idx])) {
4410                 /* Send timestamp is the same or less? can't be ready */
4411                 return (NULL);
4412         }
4413         /* Get our RTT time */
4414         if (bbr_is_lost(bbr, rsm, cts) &&
4415             ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
4416              (rsm->r_flags & BBR_SACK_PASSED))) {
4417                 if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4418                         rsm->r_flags |= BBR_MARKED_LOST;
4419                         bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4420                         bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4421                 }
4422                 bbr_cong_signal(tp, NULL, CC_NDUPACK, rsm);
4423 #ifdef BBR_INVARIANTS
4424                 if ((rsm->r_end - rsm->r_start) == 0)
4425                         panic("tp:%p bbr:%p rsm:%p length is 0?", tp, bbr, rsm);
4426 #endif
4427                 return (rsm);
4428         }
4429         return (NULL);
4430 }
4431
4432 /*
4433  * RACK Timer, here we simply do logging and house keeping.
4434  * the normal bbr_output_wtime() function will call the
4435  * appropriate thing to check if we need to do a RACK retransmit.
4436  * We return 1, saying don't proceed with bbr_output_wtime only
4437  * when all timers have been stopped (destroyed PCB?).
4438  */
4439 static int
4440 bbr_timeout_rack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4441 {
4442         /*
4443          * This timer simply provides an internal trigger to send out data.
4444          * The check_recovery_mode call will see if there are needed
4445          * retransmissions, if so we will enter fast-recovery. The output
4446          * call may or may not do the same thing depending on sysctl
4447          * settings.
4448          */
4449         uint32_t lost;
4450         
4451         if (bbr->rc_all_timers_stopped) {
4452                 return (1);
4453         }
4454         if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4455                 /* Its not time yet */
4456                 return (0);
4457         }
4458         BBR_STAT_INC(bbr_to_tot);
4459         lost = bbr->r_ctl.rc_lost;
4460         if (bbr->r_state && (bbr->r_state != tp->t_state))
4461                 bbr_set_state(tp, bbr, 0);
4462         bbr_log_to_event(bbr, cts, BBR_TO_FRM_RACK);
4463         if (bbr->r_ctl.rc_resend == NULL) {
4464                 /* Lets do the check here */
4465                 bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
4466         }
4467         if (bbr_policer_call_from_rack_to)
4468                 bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4469         bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
4470         return (0);
4471 }
4472
4473 static __inline void
4474 bbr_clone_rsm(struct tcp_bbr *bbr, struct bbr_sendmap *nrsm, struct bbr_sendmap *rsm, uint32_t start)
4475 {
4476         int idx;
4477
4478         nrsm->r_start = start;
4479         nrsm->r_end = rsm->r_end;
4480         nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4481         nrsm->r_flags = rsm->r_flags;
4482         /* We don't transfer forward the SYN flag */
4483         nrsm->r_flags &= ~BBR_HAS_SYN;
4484         /* We move forward the FIN flag, not that this should happen */
4485         rsm->r_flags &= ~BBR_HAS_FIN;
4486         nrsm->r_dupack = rsm->r_dupack;
4487         nrsm->r_rtr_bytes = 0;
4488         nrsm->r_is_gain = rsm->r_is_gain;
4489         nrsm->r_is_drain = rsm->r_is_drain;
4490         nrsm->r_delivered = rsm->r_delivered;
4491         nrsm->r_ts_valid = rsm->r_ts_valid;
4492         nrsm->r_del_ack_ts = rsm->r_del_ack_ts;
4493         nrsm->r_del_time = rsm->r_del_time;
4494         nrsm->r_app_limited = rsm->r_app_limited;
4495         nrsm->r_first_sent_time = rsm->r_first_sent_time;
4496         nrsm->r_flight_at_send = rsm->r_flight_at_send;
4497         /* We split a piece the lower section looses any just_ret flag. */
4498         nrsm->r_bbr_state = rsm->r_bbr_state;
4499         for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4500                 nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4501         }
4502         rsm->r_end = nrsm->r_start;
4503         idx = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
4504         idx /= 8;
4505         /* Check if we got too small */
4506         if ((rsm->r_is_smallmap == 0) &&
4507             ((rsm->r_end - rsm->r_start) <= idx)) {
4508                 bbr->r_ctl.rc_num_small_maps_alloced++;
4509                 rsm->r_is_smallmap = 1;
4510         }
4511         /* Check the new one as well */
4512         if ((nrsm->r_end - nrsm->r_start) <= idx) {
4513                 bbr->r_ctl.rc_num_small_maps_alloced++;
4514                 nrsm->r_is_smallmap = 1;
4515         }
4516 }
4517
4518 static int
4519 bbr_sack_mergable(struct bbr_sendmap *at,
4520                   uint32_t start, uint32_t end)
4521 {
4522         /* 
4523          * Given a sack block defined by
4524          * start and end, and a current postion
4525          * at. Return 1 if either side of at
4526          * would show that the block is mergable
4527          * to that side. A block to be mergable
4528          * must have overlap with the start/end
4529          * and be in the SACK'd state.
4530          */
4531         struct bbr_sendmap *l_rsm;
4532         struct bbr_sendmap *r_rsm;
4533
4534         /* first get the either side blocks */
4535         l_rsm = TAILQ_PREV(at, bbr_head, r_next);
4536         r_rsm = TAILQ_NEXT(at, r_next);
4537         if (l_rsm && (l_rsm->r_flags & BBR_ACKED)) {
4538                 /* Potentially mergeable */
4539                 if ((l_rsm->r_end == start) ||
4540                     (SEQ_LT(start, l_rsm->r_end) &&
4541                      SEQ_GT(end, l_rsm->r_end))) {
4542                             /*
4543                              * map blk   |------|
4544                              * sack blk         |------|
4545                              * <or>
4546                              * map blk   |------|
4547                              * sack blk      |------|
4548                              */
4549                             return (1);
4550                     }
4551         }
4552         if (r_rsm && (r_rsm->r_flags & BBR_ACKED)) {
4553                 /* Potentially mergeable */
4554                 if ((r_rsm->r_start == end) ||
4555                     (SEQ_LT(start, r_rsm->r_start) &&
4556                      SEQ_GT(end, r_rsm->r_start))) {
4557                         /* 
4558                          * map blk          |---------|
4559                          * sack blk    |----|
4560                          * <or>
4561                          * map blk          |---------|
4562                          * sack blk    |-------|
4563                          */
4564                         return (1);
4565                 }
4566         }
4567         return (0);
4568 }
4569
4570 static struct bbr_sendmap *
4571 bbr_merge_rsm(struct tcp_bbr *bbr,
4572               struct bbr_sendmap *l_rsm,
4573               struct bbr_sendmap *r_rsm)
4574 {
4575         /* 
4576          * We are merging two ack'd RSM's,
4577          * the l_rsm is on the left (lower seq
4578          * values) and the r_rsm is on the right
4579          * (higher seq value). The simplest way
4580          * to merge these is to move the right
4581          * one into the left. I don't think there
4582          * is any reason we need to try to find
4583          * the oldest (or last oldest retransmitted).
4584          */
4585         l_rsm->r_end = r_rsm->r_end;
4586         if (l_rsm->r_dupack < r_rsm->r_dupack)
4587                 l_rsm->r_dupack = r_rsm->r_dupack;
4588         if (r_rsm->r_rtr_bytes)
4589                 l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
4590         if (r_rsm->r_in_tmap) {
4591                 /* This really should not happen */
4592                 TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, r_rsm, r_tnext);
4593         }
4594         if (r_rsm->r_app_limited)
4595                 l_rsm->r_app_limited = r_rsm->r_app_limited;
4596         /* Now the flags */
4597         if (r_rsm->r_flags & BBR_HAS_FIN)
4598                 l_rsm->r_flags |= BBR_HAS_FIN;
4599         if (r_rsm->r_flags & BBR_TLP)
4600                 l_rsm->r_flags |= BBR_TLP;
4601         if (r_rsm->r_flags & BBR_RWND_COLLAPSED)
4602                 l_rsm->r_flags |= BBR_RWND_COLLAPSED;
4603         if (r_rsm->r_flags & BBR_MARKED_LOST) {
4604                 /* This really should not happen */
4605                 bbr->r_ctl.rc_lost_bytes -= r_rsm->r_end - r_rsm->r_start;
4606         }
4607         TAILQ_REMOVE(&bbr->r_ctl.rc_map, r_rsm, r_next);        
4608         if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
4609                 /* Transfer the split limit to the map we free */
4610                 r_rsm->r_limit_type = l_rsm->r_limit_type;
4611                 l_rsm->r_limit_type = 0;
4612         }
4613         bbr_free(bbr, r_rsm);
4614         return(l_rsm);
4615 }
4616
4617 /*
4618  * TLP Timer, here we simply setup what segment we want to
4619  * have the TLP expire on, the normal bbr_output_wtime() will then
4620  * send it out.
4621  *
4622  * We return 1, saying don't proceed with bbr_output_wtime only
4623  * when all timers have been stopped (destroyed PCB?).
4624  */
4625 static int
4626 bbr_timeout_tlp(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4627 {
4628         /*
4629          * Tail Loss Probe.
4630          */
4631         struct bbr_sendmap *rsm = NULL;
4632         struct socket *so;
4633         uint32_t amm;
4634         uint32_t out, avail;
4635         uint32_t maxseg;
4636         int collapsed_win = 0;
4637
4638         if (bbr->rc_all_timers_stopped) {
4639                 return (1);
4640         }
4641         if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4642                 /* Its not time yet */
4643                 return (0);
4644         }
4645         if (bbr_progress_timeout_check(bbr)) {
4646                 tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4647                 return (1);
4648         }
4649         /* Did we somehow get into persists? */
4650         if (bbr->rc_in_persist) {
4651                 return (0);
4652         }
4653         if (bbr->r_state && (bbr->r_state != tp->t_state))
4654                 bbr_set_state(tp, bbr, 0);
4655         BBR_STAT_INC(bbr_tlp_tot);
4656         maxseg = tp->t_maxseg - bbr->rc_last_options;
4657 #ifdef KERN_TLS
4658         if (bbr->rc_inp->inp_socket->so_snd.sb_flags & SB_TLS_IFNET) {
4659                 /*
4660                  * For hardware TLS we do *not* want to send
4661                  * new data.
4662                  */
4663                 goto need_retran;
4664         }
4665 #endif
4666         /*
4667          * A TLP timer has expired. We have been idle for 2 rtts. So we now
4668          * need to figure out how to force a full MSS segment out.
4669          */
4670         so = tp->t_inpcb->inp_socket;
4671         avail = sbavail(&so->so_snd);
4672         out = ctf_outstanding(tp);
4673         if (out > tp->snd_wnd) {
4674                 /* special case, we need a retransmission */
4675                 collapsed_win = 1;
4676                 goto need_retran;
4677         }
4678         if (avail > out) {
4679                 /* New data is available */
4680                 amm = avail - out;
4681                 if (amm > maxseg) {
4682                         amm = maxseg;
4683                 } else if ((amm < maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
4684                         /* not enough to fill a MTU and no-delay is off */
4685                         goto need_retran;
4686                 }
4687                 /* Set the send-new override */
4688                 if ((out + amm) <= tp->snd_wnd) {
4689                         bbr->rc_tlp_new_data = 1;
4690                 } else {
4691                         goto need_retran;
4692                 }
4693                 bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4694                 bbr->r_ctl.rc_last_tlp_seq = tp->snd_max;
4695                 bbr->r_ctl.rc_tlp_send = NULL;
4696                 /* cap any slots */
4697                 BBR_STAT_INC(bbr_tlp_newdata);
4698                 goto send;
4699         }
4700 need_retran:
4701         /*
4702          * Ok we need to arrange the last un-acked segment to be re-sent, or
4703          * optionally the first un-acked segment.
4704          */
4705         if (collapsed_win == 0) {
4706                 rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
4707                 if (rsm && (BBR_ACKED | BBR_HAS_FIN)) {
4708                         rsm = bbr_find_high_nonack(bbr, rsm);
4709                 }
4710                 if (rsm == NULL) {
4711                         goto restore;
4712                 }
4713         } else {
4714                 /* 
4715                  * We must find the last segment 
4716                  * that was acceptable by the client.
4717                  */
4718                 TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4719                         if ((rsm->r_flags & BBR_RWND_COLLAPSED) == 0) {
4720                                 /* Found one */
4721                                 break;
4722                         }
4723                 }
4724                 if (rsm == NULL) {
4725                         /* None? if so send the first */
4726                         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4727                         if (rsm == NULL)
4728                                 goto restore;
4729                 }
4730         }
4731         if ((rsm->r_end - rsm->r_start) > maxseg) {
4732                 /*
4733                  * We need to split this the last segment in two.
4734                  */
4735                 struct bbr_sendmap *nrsm;
4736
4737                 nrsm = bbr_alloc_full_limit(bbr);
4738                 if (nrsm == NULL) {
4739                         /*
4740                          * We can't get memory to split, we can either just
4741                          * not split it. Or retransmit the whole piece, lets
4742                          * do the large send (BTLP :-) ).
4743                          */
4744                         goto go_for_it;
4745                 }
4746                 bbr_clone_rsm(bbr, nrsm, rsm, (rsm->r_end - maxseg));
4747                 TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
4748                 if (rsm->r_in_tmap) {
4749                         TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4750                         nrsm->r_in_tmap = 1;
4751                 }
4752                 rsm->r_flags &= (~BBR_HAS_FIN);
4753                 rsm = nrsm;
4754         }
4755 go_for_it:
4756         bbr->r_ctl.rc_tlp_send = rsm;
4757         bbr->rc_tlp_rtx_out = 1;
4758         if (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) {
4759                 bbr->r_ctl.rc_tlp_seg_send_cnt++;
4760                 tp->t_rxtshift++;
4761         } else {
4762                 bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
4763                 bbr->r_ctl.rc_tlp_seg_send_cnt = 1;
4764         }
4765 send:
4766         if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
4767                 /*
4768                  * Can't [re]/transmit a segment we have retranmitted the
4769                  * max times. We need the retransmit timer to take over.
4770                  */
4771 restore:
4772                 bbr->rc_tlp_new_data = 0;
4773                 bbr->r_ctl.rc_tlp_send = NULL;
4774                 if (rsm)
4775                         rsm->r_flags &= ~BBR_TLP;
4776                 BBR_STAT_INC(bbr_tlp_retran_fail);
4777                 return (0);
4778         } else if (rsm) {
4779                 rsm->r_flags |= BBR_TLP;
4780         }
4781         if (rsm && (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) &&
4782             (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend)) {
4783                 /*
4784                  * We have retransmitted to many times for TLP. Switch to
4785                  * the regular RTO timer
4786                  */
4787                 goto restore;
4788         }
4789         bbr_log_to_event(bbr, cts, BBR_TO_FRM_TLP);
4790         bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
4791         return (0);
4792 }
4793
4794 /*
4795  * Delayed ack Timer, here we simply need to setup the
4796  * ACK_NOW flag and remove the DELACK flag. From there
4797  * the output routine will send the ack out.
4798  *
4799  * We only return 1, saying don't proceed, if all timers
4800  * are stopped (destroyed PCB?).
4801  */
4802 static int
4803 bbr_timeout_delack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4804 {
4805         if (bbr->rc_all_timers_stopped) {
4806                 return (1);
4807         }
4808         bbr_log_to_event(bbr, cts, BBR_TO_FRM_DELACK);
4809         tp->t_flags &= ~TF_DELACK;
4810         tp->t_flags |= TF_ACKNOW;
4811         TCPSTAT_INC(tcps_delack);
4812         bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
4813         return (0);
4814 }
4815
4816 /*
4817  * Persists timer, here we simply need to setup the
4818  * FORCE-DATA flag the output routine will send
4819  * the one byte send.
4820  *
4821  * We only return 1, saying don't proceed, if all timers
4822  * are stopped (destroyed PCB?).
4823  */
4824 static int
4825 bbr_timeout_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4826 {
4827         struct tcptemp *t_template;
4828         int32_t retval = 1;
4829
4830         if (bbr->rc_all_timers_stopped) {
4831                 return (1);
4832         }
4833         if (bbr->rc_in_persist == 0)
4834                 return (0);
4835         KASSERT(tp->t_inpcb != NULL,
4836             ("%s: tp %p tp->t_inpcb == NULL", __func__, tp));
4837         /*
4838          * Persistence timer into zero window. Force a byte to be output, if
4839          * possible.
4840          */
4841         bbr_log_to_event(bbr, cts, BBR_TO_FRM_PERSIST);
4842         bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
4843         TCPSTAT_INC(tcps_persisttimeo);
4844         /*
4845          * Have we exceeded the user specified progress time?
4846          */
4847         if (bbr_progress_timeout_check(bbr)) {
4848                 tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4849                 goto out;
4850         }
4851         /*
4852          * Hack: if the peer is dead/unreachable, we do not time out if the
4853          * window is closed.  After a full backoff, drop the connection if
4854          * the idle time (no responses to probes) reaches the maximum
4855          * backoff that we would use if retransmitting.
4856          */
4857         if (tp->t_rxtshift == TCP_MAXRXTSHIFT &&
4858             (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
4859             ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
4860                 TCPSTAT_INC(tcps_persistdrop);
4861                 tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4862                 goto out;
4863         }
4864         if ((sbavail(&bbr->rc_inp->inp_socket->so_snd) == 0) &&
4865             tp->snd_una == tp->snd_max) {
4866                 bbr_exit_persist(tp, bbr, cts, __LINE__);
4867                 retval = 0;
4868                 goto out;
4869         }
4870         /*
4871          * If the user has closed the socket then drop a persisting
4872          * connection after a much reduced timeout.
4873          */
4874         if (tp->t_state > TCPS_CLOSE_WAIT &&
4875             (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
4876                 TCPSTAT_INC(tcps_persistdrop);
4877                 tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4878                 goto out;
4879         }
4880         t_template = tcpip_maketemplate(bbr->rc_inp);
4881         if (t_template) {
4882                 tcp_respond(tp, t_template->tt_ipgen,
4883                             &t_template->tt_t, (struct mbuf *)NULL,
4884                             tp->rcv_nxt, tp->snd_una - 1, 0);
4885                 /* This sends an ack */
4886                 if (tp->t_flags & TF_DELACK)
4887                         tp->t_flags &= ~TF_DELACK;
4888                 free(t_template, M_TEMP);
4889         }
4890         if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
4891                 tp->t_rxtshift++;
4892         bbr_start_hpts_timer(bbr, tp, cts, 3, 0, 0);
4893 out:
4894         return (retval);
4895 }
4896
4897 /*
4898  * If a keepalive goes off, we had no other timers
4899  * happening. We always return 1 here since this
4900  * routine either drops the connection or sends
4901  * out a segment with respond.
4902  */
4903 static int
4904 bbr_timeout_keepalive(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4905 {
4906         struct tcptemp *t_template;
4907         struct inpcb *inp;
4908
4909         if (bbr->rc_all_timers_stopped) {
4910                 return (1);
4911         }
4912         bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
4913         inp = tp->t_inpcb;
4914         bbr_log_to_event(bbr, cts, BBR_TO_FRM_KEEP);
4915         /*
4916          * Keep-alive timer went off; send something or drop connection if
4917          * idle for too long.
4918          */
4919         TCPSTAT_INC(tcps_keeptimeo);
4920         if (tp->t_state < TCPS_ESTABLISHED)
4921                 goto dropit;
4922         if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
4923             tp->t_state <= TCPS_CLOSING) {
4924                 if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
4925                         goto dropit;
4926                 /*
4927                  * Send a packet designed to force a response if the peer is
4928                  * up and reachable: either an ACK if the connection is
4929                  * still alive, or an RST if the peer has closed the
4930                  * connection due to timeout or reboot. Using sequence
4931                  * number tp->snd_una-1 causes the transmitted zero-length
4932                  * segment to lie outside the receive window; by the
4933                  * protocol spec, this requires the correspondent TCP to
4934                  * respond.
4935                  */
4936                 TCPSTAT_INC(tcps_keepprobe);
4937                 t_template = tcpip_maketemplate(inp);
4938                 if (t_template) {
4939                         tcp_respond(tp, t_template->tt_ipgen,
4940                             &t_template->tt_t, (struct mbuf *)NULL,
4941                             tp->rcv_nxt, tp->snd_una - 1, 0);
4942                         free(t_template, M_TEMP);
4943                 }
4944         }
4945         bbr_start_hpts_timer(bbr, tp, cts, 4, 0, 0);
4946         return (1);
4947 dropit:
4948         TCPSTAT_INC(tcps_keepdrops);
4949         tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4950         return (1);
4951 }
4952
4953 /*
4954  * Retransmit helper function, clear up all the ack
4955  * flags and take care of important book keeping.
4956  */
4957 static void
4958 bbr_remxt_tmr(struct tcpcb *tp)
4959 {
4960         /*
4961          * The retransmit timer went off, all sack'd blocks must be
4962          * un-acked.
4963          */
4964         struct bbr_sendmap *rsm, *trsm = NULL;
4965         struct tcp_bbr *bbr;
4966         uint32_t cts, lost;
4967
4968         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4969         cts = tcp_get_usecs(&bbr->rc_tv);
4970         lost = bbr->r_ctl.rc_lost;
4971         if (bbr->r_state && (bbr->r_state != tp->t_state))
4972                 bbr_set_state(tp, bbr, 0);
4973
4974         TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
4975                 if (rsm->r_flags & BBR_ACKED) {
4976                         uint32_t old_flags;
4977                         
4978                         rsm->r_dupack = 0;
4979                         if (rsm->r_in_tmap == 0) {
4980                                 /* We must re-add it back to the tlist */
4981                                 if (trsm == NULL) {
4982                                         TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
4983                                 } else {
4984                                         TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, trsm, rsm, r_tnext);
4985                                 }
4986                                 rsm->r_in_tmap = 1;
4987                         }
4988                         old_flags = rsm->r_flags;
4989                         rsm->r_flags |= BBR_RXT_CLEARED;
4990                         rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS);
4991                         bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
4992                 } else {
4993                         if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4994                                 bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4995                                 bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4996                         }
4997                         if (bbr_marks_rxt_sack_passed) {
4998                                 /*
4999                                  * With this option, we will rack out 
5000                                  * in 1ms increments the rest of the packets.
5001                                  */
5002                                 rsm->r_flags |= BBR_SACK_PASSED | BBR_MARKED_LOST;
5003                                 rsm->r_flags &= ~BBR_WAS_SACKPASS;
5004                         } else {
5005                                 /*
5006                                  * With this option we only mark them lost
5007                                  * and remove all sack'd markings. We will run
5008                                  * another RXT or a TLP. This will cause
5009                                  * us to eventually send more based on what
5010                                  * ack's come in.
5011                                  */
5012                                 rsm->r_flags |= BBR_MARKED_LOST;
5013                                 rsm->r_flags &= ~BBR_WAS_SACKPASS;
5014                                 rsm->r_flags &= ~BBR_SACK_PASSED;
5015                         }
5016                 }
5017                 trsm = rsm;
5018         }
5019         bbr->r_ctl.rc_resend = TAILQ_FIRST(&bbr->r_ctl.rc_map);
5020         /* Clear the count (we just un-acked them) */
5021         bbr_log_to_event(bbr, cts, BBR_TO_FRM_TMR);
5022         bbr->rc_tlp_new_data = 0;
5023         bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
5024         /* zap the behindness on a rxt */
5025         bbr->r_ctl.rc_hptsi_agg_delay = 0;
5026         bbr->r_agg_early_set = 0;
5027         bbr->r_ctl.rc_agg_early = 0;
5028         bbr->rc_tlp_rtx_out = 0;
5029         bbr->r_ctl.rc_sacked = 0;
5030         bbr->r_ctl.rc_sacklast = NULL;
5031         bbr->r_timer_override = 1;
5032         bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
5033 }
5034
5035 /*
5036  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
5037  * we will setup to retransmit the lowest seq number outstanding.
5038  */
5039 static int
5040 bbr_timeout_rxt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
5041 {
5042         int32_t rexmt;
5043         int32_t retval = 0;
5044
5045         bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
5046         if (bbr->rc_all_timers_stopped) {
5047                 return (1);
5048         }
5049         if (TCPS_HAVEESTABLISHED(tp->t_state) &&
5050             (tp->snd_una == tp->snd_max)) {
5051                 /* Nothing outstanding .. nothing to do */
5052                 return (0);
5053         }
5054         /*
5055          * Retransmission timer went off.  Message has not been acked within
5056          * retransmit interval.  Back off to a longer retransmit interval
5057          * and retransmit one segment.
5058          */
5059         if (bbr_progress_timeout_check(bbr)) {
5060                 retval = 1;
5061                 tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
5062                 goto out;
5063         }
5064         bbr_remxt_tmr(tp);
5065         if ((bbr->r_ctl.rc_resend == NULL) ||
5066             ((bbr->r_ctl.rc_resend->r_flags & BBR_RWND_COLLAPSED) == 0)) {
5067                 /*
5068                  * If the rwnd collapsed on
5069                  * the one we are retransmitting
5070                  * it does not count against the
5071                  * rxt count.
5072                  */
5073                 tp->t_rxtshift++;
5074         }
5075         if (tp->t_rxtshift > TCP_MAXRXTSHIFT) {
5076                 tp->t_rxtshift = TCP_MAXRXTSHIFT;
5077                 TCPSTAT_INC(tcps_timeoutdrop);
5078                 retval = 1;
5079                 tcp_set_inp_to_drop(bbr->rc_inp,
5080                     (tp->t_softerror ? (uint16_t) tp->t_softerror : ETIMEDOUT));
5081                 goto out;
5082         }
5083         if (tp->t_state == TCPS_SYN_SENT) {
5084                 /*
5085                  * If the SYN was retransmitted, indicate CWND to be limited
5086                  * to 1 segment in cc_conn_init().
5087                  */
5088                 tp->snd_cwnd = 1;
5089         } else if (tp->t_rxtshift == 1) {
5090                 /*
5091                  * first retransmit; record ssthresh and cwnd so they can be
5092                  * recovered if this turns out to be a "bad" retransmit. A
5093                  * retransmit is considered "bad" if an ACK for this segment
5094                  * is received within RTT/2 interval; the assumption here is
5095                  * that the ACK was already in flight.  See "On Estimating
5096                  * End-to-End Network Path Properties" by Allman and Paxson
5097                  * for more details.
5098                  */
5099                 tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5100                 if (!IN_RECOVERY(tp->t_flags)) {
5101                         tp->snd_cwnd_prev = tp->snd_cwnd;
5102                         tp->snd_ssthresh_prev = tp->snd_ssthresh;
5103                         tp->snd_recover_prev = tp->snd_recover;
5104                         tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
5105                         tp->t_flags |= TF_PREVVALID;
5106                 } else {
5107                         tp->t_flags &= ~TF_PREVVALID;
5108                 }
5109                 tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5110         } else {
5111                 tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5112                 tp->t_flags &= ~TF_PREVVALID;
5113         }
5114         TCPSTAT_INC(tcps_rexmttimeo);
5115         if ((tp->t_state == TCPS_SYN_SENT) ||
5116             (tp->t_state == TCPS_SYN_RECEIVED))
5117                 rexmt = USEC_2_TICKS(BBR_INITIAL_RTO) * tcp_backoff[tp->t_rxtshift];
5118         else
5119                 rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
5120         TCPT_RANGESET(tp->t_rxtcur, rexmt,
5121             MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms),
5122             MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
5123         /*
5124          * We enter the path for PLMTUD if connection is established or, if
5125          * connection is FIN_WAIT_1 status, reason for the last is that if
5126          * amount of data we send is very small, we could send it in couple
5127          * of packets and process straight to FIN. In that case we won't
5128          * catch ESTABLISHED state.
5129          */
5130         if (V_tcp_pmtud_blackhole_detect && (((tp->t_state == TCPS_ESTABLISHED))
5131             || (tp->t_state == TCPS_FIN_WAIT_1))) {
5132 #ifdef INET6
5133                 int32_t isipv6;
5134 #endif
5135
5136                 /*
5137                  * Idea here is that at each stage of mtu probe (usually,
5138                  * 1448 -> 1188 -> 524) should be given 2 chances to recover
5139                  * before further clamping down. 'tp->t_rxtshift % 2 == 0'
5140                  * should take care of that.
5141                  */
5142                 if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
5143                     (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
5144                     (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
5145                     tp->t_rxtshift % 2 == 0)) {
5146                         /*
5147                          * Enter Path MTU Black-hole Detection mechanism: -
5148                          * Disable Path MTU Discovery (IP "DF" bit). -
5149                          * Reduce MTU to lower value than what we negotiated
5150                          * with peer.
5151                          */
5152                         if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
5153                                 /*
5154                                  * Record that we may have found a black
5155                                  * hole.
5156                                  */
5157                                 tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
5158                                 /* Keep track of previous MSS. */
5159                                 tp->t_pmtud_saved_maxseg = tp->t_maxseg;
5160                         }
5161                         /*
5162                          * Reduce the MSS to blackhole value or to the
5163                          * default in an attempt to retransmit.
5164                          */
5165 #ifdef INET6
5166                         isipv6 = bbr->r_is_v6;
5167                         if (isipv6 &&
5168                             tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
5169                                 /* Use the sysctl tuneable blackhole MSS. */
5170                                 tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
5171                                 TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5172                         } else if (isipv6) {
5173                                 /* Use the default MSS. */
5174                                 tp->t_maxseg = V_tcp_v6mssdflt;
5175                                 /*
5176                                  * Disable Path MTU Discovery when we switch
5177                                  * to minmss.
5178                                  */
5179                                 tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5180                                 TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5181                         }
5182 #endif
5183 #if defined(INET6) && defined(INET)
5184                         else
5185 #endif
5186 #ifdef INET
5187                         if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
5188                                 /* Use the sysctl tuneable blackhole MSS. */
5189                                 tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
5190                                 TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5191                         } else {
5192                                 /* Use the default MSS. */
5193                                 tp->t_maxseg = V_tcp_mssdflt;
5194                                 /*
5195                                  * Disable Path MTU Discovery when we switch
5196                                  * to minmss.
5197                                  */
5198                                 tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5199                                 TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5200                         }
5201 #endif
5202                 } else {
5203                         /*
5204                          * If further retransmissions are still unsuccessful
5205                          * with a lowered MTU, maybe this isn't a blackhole
5206                          * and we restore the previous MSS and blackhole
5207                          * detection flags. The limit '6' is determined by
5208                          * giving each probe stage (1448, 1188, 524) 2
5209                          * chances to recover.
5210                          */
5211                         if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
5212                             (tp->t_rxtshift >= 6)) {
5213                                 tp->t_flags2 |= TF2_PLPMTU_PMTUD;
5214                                 tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
5215                                 tp->t_maxseg = tp->t_pmtud_saved_maxseg;
5216                                 TCPSTAT_INC(tcps_pmtud_blackhole_failed);
5217                         }
5218                 }
5219         }
5220         /*
5221          * Disable RFC1323 and SACK if we haven't got any response to our
5222          * third SYN to work-around some broken terminal servers (most of
5223          * which have hopefully been retired) that have bad VJ header
5224          * compression code which trashes TCP segments containing
5225          * unknown-to-them TCP options.
5226          */
5227         if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
5228             (tp->t_rxtshift == 3))
5229                 tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
5230         /*
5231          * If we backed off this far, our srtt estimate is probably bogus.
5232          * Clobber it so we'll take the next rtt measurement as our srtt;
5233          * move the current srtt into rttvar to keep the current retransmit
5234          * times until then.
5235          */
5236         if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
5237 #ifdef INET6
5238                 if (bbr->r_is_v6)
5239                         in6_losing(tp->t_inpcb);
5240                 else
5241 #endif
5242                         in_losing(tp->t_inpcb);
5243                 tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
5244                 tp->t_srtt = 0;
5245         }
5246         sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
5247         tp->snd_recover = tp->snd_max;
5248         tp->t_flags |= TF_ACKNOW;
5249         tp->t_rtttime = 0;
5250 out:
5251         return (retval);
5252 }
5253
5254 static int
5255 bbr_process_timers(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, uint8_t hpts_calling)
5256 {
5257         int32_t ret = 0;
5258         int32_t timers = (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
5259
5260         if (timers == 0) {
5261                 return (0);
5262         }
5263         if (tp->t_state == TCPS_LISTEN) {
5264                 /* no timers on listen sockets */
5265                 if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
5266                         return (0);
5267                 return (1);
5268         }
5269         if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
5270                 uint32_t left;
5271
5272                 if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
5273                         ret = -1;
5274                         bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5275                         return (0);
5276                 }
5277                 if (hpts_calling == 0) {
5278                         ret = -2;
5279                         bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5280                         return (0);
5281                 }
5282                 /*
5283                  * Ok our timer went off early and we are not paced false
5284                  * alarm, go back to sleep.
5285                  */
5286                 left = bbr->r_ctl.rc_timer_exp - cts;
5287                 ret = -3;
5288                 bbr_log_to_processing(bbr, cts, ret, left, hpts_calling);
5289                 tcp_hpts_insert(tp->t_inpcb, HPTS_USEC_TO_SLOTS(left));
5290                 return (1);
5291         }
5292         bbr->rc_tmr_stopped = 0;
5293         bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
5294         if (timers & PACE_TMR_DELACK) {
5295                 ret = bbr_timeout_delack(tp, bbr, cts);
5296         } else if (timers & PACE_TMR_PERSIT) {
5297                 ret = bbr_timeout_persist(tp, bbr, cts);
5298         } else if (timers & PACE_TMR_RACK) {
5299                 bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5300                 ret = bbr_timeout_rack(tp, bbr, cts);
5301         } else if (timers & PACE_TMR_TLP) {
5302                 bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5303                 ret = bbr_timeout_tlp(tp, bbr, cts);
5304         } else if (timers & PACE_TMR_RXT) {
5305                 bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5306                 ret = bbr_timeout_rxt(tp, bbr, cts);
5307         } else if (timers & PACE_TMR_KEEP) {
5308                 ret = bbr_timeout_keepalive(tp, bbr, cts);
5309         }
5310         bbr_log_to_processing(bbr, cts, ret, timers, hpts_calling);
5311         return (ret);
5312 }
5313
5314 static void
5315 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts)
5316 {
5317         if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
5318                 uint8_t hpts_removed = 0;
5319
5320                 if (bbr->rc_inp->inp_in_hpts &&
5321                     (bbr->rc_timer_first == 1)) {
5322                         /*
5323                          * If we are canceling timer's when we have the
5324                          * timer ahead of the output being paced. We also
5325                          * must remove ourselves from the hpts.
5326                          */
5327                         hpts_removed = 1;
5328                         tcp_hpts_remove(bbr->rc_inp, HPTS_REMOVE_OUTPUT);
5329                         if (bbr->r_ctl.rc_last_delay_val) {
5330                                 /* Update the last hptsi delay too */
5331                                 uint32_t time_since_send;
5332
5333                                 if (TSTMP_GT(cts, bbr->rc_pacer_started))
5334                                         time_since_send = cts - bbr->rc_pacer_started;
5335                                 else
5336                                         time_since_send = 0;
5337                                 if (bbr->r_ctl.rc_last_delay_val > time_since_send) {
5338                                         /* Cut down our slot time */
5339                                         bbr->r_ctl.rc_last_delay_val -= time_since_send;
5340                                 } else {
5341                                         bbr->r_ctl.rc_last_delay_val = 0;
5342                                 }
5343                                 bbr->rc_pacer_started = cts;
5344                         }
5345                 }
5346                 bbr->rc_timer_first = 0;
5347                 bbr_log_to_cancel(bbr, line, cts, hpts_removed);
5348                 bbr->rc_tmr_stopped = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
5349                 bbr->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
5350         }
5351 }
5352
5353 static void
5354 bbr_timer_stop(struct tcpcb *tp, uint32_t timer_type)
5355 {
5356         struct tcp_bbr *bbr;
5357
5358         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
5359         bbr->rc_all_timers_stopped = 1;
5360         return;
5361 }
5362
5363 /*
5364  * stop all timers always returning 0.
5365  */
5366 static int
5367 bbr_stopall(struct tcpcb *tp)
5368 {
5369         return (0);
5370 }
5371
5372 static void
5373 bbr_timer_activate(struct tcpcb *tp, uint32_t timer_type, uint32_t delta)
5374 {
5375         return;
5376 }
5377
5378 /*
5379  * return true if a bbr timer (rack or tlp) is active.
5380  */
5381 static int
5382 bbr_timer_active(struct tcpcb *tp, uint32_t timer_type)
5383 {
5384         return (0);
5385 }
5386
5387 static uint32_t
5388 bbr_get_earliest_send_outstanding(struct tcp_bbr *bbr, struct bbr_sendmap *u_rsm, uint32_t cts)
5389 {
5390         struct bbr_sendmap *rsm;
5391         
5392         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
5393         if ((rsm == NULL) || (u_rsm == rsm))
5394                 return (cts);
5395         return(rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
5396 }
5397
5398 static void
5399 bbr_update_rsm(struct tcpcb *tp, struct tcp_bbr *bbr,
5400      struct bbr_sendmap *rsm, uint32_t cts, uint32_t pacing_time)
5401 {
5402         int32_t idx;
5403
5404         rsm->r_rtr_cnt++;
5405         rsm->r_dupack = 0;
5406         if (rsm->r_rtr_cnt > BBR_NUM_OF_RETRANS) {
5407                 rsm->r_rtr_cnt = BBR_NUM_OF_RETRANS;
5408                 rsm->r_flags |= BBR_OVERMAX;
5409         }
5410         if (rsm->r_flags & BBR_RWND_COLLAPSED) {
5411                 /* Take off the collapsed flag at rxt */
5412                 rsm->r_flags &= ~BBR_RWND_COLLAPSED;
5413         }
5414         if (rsm->r_flags & BBR_MARKED_LOST) {
5415                 /* We have retransmitted, its no longer lost */
5416                 rsm->r_flags &= ~BBR_MARKED_LOST;
5417                 bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;          
5418         }
5419         if (rsm->r_flags & BBR_RXT_CLEARED) {
5420                 /*
5421                  * We hit a RXT timer on it and
5422                  * we cleared the "acked" flag.
5423                  * We now have it going back into
5424                  * flight, we can remove the cleared
5425                  * flag and possibly do accounting on
5426                  * this piece.
5427                  */
5428                 rsm->r_flags &= ~BBR_RXT_CLEARED;
5429         }
5430         if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & BBR_TLP) == 0)) {
5431                 bbr->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
5432                 rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
5433         }
5434         idx = rsm->r_rtr_cnt - 1;
5435         rsm->r_tim_lastsent[idx] = cts;
5436         rsm->r_pacing_delay = pacing_time;
5437         rsm->r_delivered = bbr->r_ctl.rc_delivered;
5438         rsm->r_ts_valid = bbr->rc_ts_valid;
5439         if (bbr->rc_ts_valid) 
5440                 rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5441         if (bbr->r_ctl.r_app_limited_until)
5442                 rsm->r_app_limited = 1;
5443         else
5444                 rsm->r_app_limited = 0;
5445         if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5446                 rsm->r_bbr_state = bbr_state_val(bbr);
5447         else
5448                 rsm->r_bbr_state = 8;
5449         if (rsm->r_flags & BBR_ACKED) {
5450                 /* Problably MTU discovery messing with us */
5451                 uint32_t old_flags;
5452
5453                 old_flags = rsm->r_flags;
5454                 rsm->r_flags &= ~BBR_ACKED;
5455                 bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
5456                 bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
5457                 if (bbr->r_ctl.rc_sacked == 0)
5458                         bbr->r_ctl.rc_sacklast = NULL;
5459         }
5460         if (rsm->r_in_tmap) {
5461                 TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5462         }
5463         TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5464         rsm->r_in_tmap = 1;
5465         if (rsm->r_flags & BBR_SACK_PASSED) {
5466                 /* We have retransmitted due to the SACK pass */
5467                 rsm->r_flags &= ~BBR_SACK_PASSED;
5468                 rsm->r_flags |= BBR_WAS_SACKPASS;
5469         }
5470         rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5471         rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5472                                                 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5473         bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
5474         if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5475                 rsm->r_is_gain = 1;
5476                 rsm->r_is_drain = 0;
5477         } else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5478                 rsm->r_is_drain = 1;
5479                 rsm->r_is_gain = 0;
5480         } else {
5481                 rsm->r_is_drain = 0;
5482                 rsm->r_is_gain = 0;
5483         }
5484         rsm->r_del_time = bbr->r_ctl.rc_del_time; /* TEMP GOOGLE CODE */
5485 }
5486
5487 /*
5488  * Returns 0, or the sequence where we stopped
5489  * updating. We also update the lenp to be the amount
5490  * of data left.
5491  */
5492
5493 static uint32_t
5494 bbr_update_entry(struct tcpcb *tp, struct tcp_bbr *bbr,
5495     struct bbr_sendmap *rsm, uint32_t cts, int32_t *lenp, uint32_t pacing_time)
5496 {
5497         /*
5498          * We (re-)transmitted starting at rsm->r_start for some length
5499          * (possibly less than r_end.
5500          */
5501         struct bbr_sendmap *nrsm;
5502         uint32_t c_end;
5503         int32_t len;
5504
5505         len = *lenp;
5506         c_end = rsm->r_start + len;
5507         if (SEQ_GEQ(c_end, rsm->r_end)) {
5508                 /*
5509                  * We retransmitted the whole piece or more than the whole
5510                  * slopping into the next rsm.
5511                  */
5512                 bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5513                 if (c_end == rsm->r_end) {
5514                         *lenp = 0;
5515                         return (0);
5516                 } else {
5517                         int32_t act_len;
5518
5519                         /* Hangs over the end return whats left */
5520                         act_len = rsm->r_end - rsm->r_start;
5521                         *lenp = (len - act_len);
5522                         return (rsm->r_end);
5523                 }
5524                 /* We don't get out of this block. */
5525         }
5526         /*
5527          * Here we retransmitted less than the whole thing which means we
5528          * have to split this into what was transmitted and what was not.
5529          */
5530         nrsm = bbr_alloc_full_limit(bbr);
5531         if (nrsm == NULL) {
5532                 *lenp = 0;
5533                 return (0);
5534         }
5535         /*
5536          * So here we are going to take the original rsm and make it what we
5537          * retransmitted. nrsm will be the tail portion we did not
5538          * retransmit. For example say the chunk was 1, 11 (10 bytes). And
5539          * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
5540          * 1, 6 and the new piece will be 6, 11.
5541          */
5542         bbr_clone_rsm(bbr, nrsm, rsm, c_end);
5543         TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
5544         nrsm->r_dupack = 0;
5545         if (rsm->r_in_tmap) {
5546                 TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
5547                 nrsm->r_in_tmap = 1;
5548         }
5549         rsm->r_flags &= (~BBR_HAS_FIN);
5550         bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5551         *lenp = 0;
5552         return (0);
5553 }
5554
5555 static uint64_t
5556 bbr_get_hardware_rate(struct tcp_bbr *bbr)
5557 {
5558         uint64_t bw;
5559         
5560         bw = bbr_get_bw(bbr);
5561         bw *= (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN];
5562         bw /= (uint64_t)BBR_UNIT;
5563         return(bw);
5564 }
5565
5566 static void
5567 bbr_setup_less_of_rate(struct tcp_bbr *bbr, uint32_t cts,
5568                        uint64_t act_rate, uint64_t rate_wanted)
5569 {
5570         /*
5571          * We could not get a full gains worth
5572          * of rate.
5573          */
5574         if (get_filter_value(&bbr->r_ctl.rc_delrate) >= act_rate) {
5575                 /* we can't even get the real rate */
5576                 uint64_t red;
5577
5578                 bbr->skip_gain = 1;
5579                 bbr->gain_is_limited = 0;
5580                 red = get_filter_value(&bbr->r_ctl.rc_delrate) - act_rate;
5581                 if (red)
5582                         filter_reduce_by(&bbr->r_ctl.rc_delrate, red, cts);
5583         } else {
5584                 /* We can use a lower gain */
5585                 bbr->skip_gain = 0;
5586                 bbr->gain_is_limited = 1;
5587         }
5588 }
5589
5590 static void
5591 bbr_update_hardware_pacing_rate(struct tcp_bbr *bbr, uint32_t cts)
5592 {
5593         const struct tcp_hwrate_limit_table *nrte;
5594         int error, rate = -1;
5595         
5596         if (bbr->r_ctl.crte == NULL)
5597                 return;
5598         if ((bbr->rc_inp->inp_route.ro_rt == NULL) ||
5599             (bbr->rc_inp->inp_route.ro_rt->rt_ifp == NULL)) {
5600                 /* Lost our routes? */
5601                 /* Clear the way for a re-attempt */
5602                 bbr->bbr_attempt_hdwr_pace = 0;
5603 lost_rate:
5604                 bbr->gain_is_limited = 0;
5605                 bbr->skip_gain = 0;
5606                 bbr->bbr_hdrw_pacing = 0;
5607                 counter_u64_add(bbr_flows_whdwr_pacing, -1);
5608                 counter_u64_add(bbr_flows_nohdwr_pacing, 1);
5609                 tcp_bbr_tso_size_check(bbr, cts);
5610                 return;
5611         }
5612         rate = bbr_get_hardware_rate(bbr);
5613         nrte = tcp_chg_pacing_rate(bbr->r_ctl.crte,
5614                                    bbr->rc_tp,
5615                                    bbr->rc_inp->inp_route.ro_rt->rt_ifp,
5616                                    rate,
5617                                    (RS_PACING_GEQ|RS_PACING_SUB_OK),
5618                                    &error);
5619         if (nrte == NULL) {
5620                 goto lost_rate;
5621         }
5622         if (nrte != bbr->r_ctl.crte) {
5623                 bbr->r_ctl.crte = nrte;
5624                 if (error == 0)  {
5625                         BBR_STAT_INC(bbr_hdwr_rl_mod_ok);
5626                         if (bbr->r_ctl.crte->rate < rate) {
5627                                 /* We have a problem */
5628                                 bbr_setup_less_of_rate(bbr, cts,
5629                                                        bbr->r_ctl.crte->rate, rate);
5630                         } else {
5631                                 /* We are good */
5632                                 bbr->gain_is_limited = 0;
5633                                 bbr->skip_gain = 0;
5634                         }
5635                 } else {
5636                         /* A failure should release the tag */
5637                         BBR_STAT_INC(bbr_hdwr_rl_mod_fail);
5638                         bbr->gain_is_limited = 0;
5639                         bbr->skip_gain = 0;
5640                         bbr->bbr_hdrw_pacing = 0;
5641                 }
5642                 bbr_type_log_hdwr_pacing(bbr,
5643                                          bbr->r_ctl.crte->ptbl->rs_ifp,
5644                                          rate,
5645                                          ((bbr->r_ctl.crte == NULL) ? 0 : bbr->r_ctl.crte->rate),
5646                                          __LINE__,
5647                                          cts,
5648                                          error);
5649         }
5650 }
5651
5652 static void
5653 bbr_adjust_for_hw_pacing(struct tcp_bbr *bbr, uint32_t cts)
5654 {
5655         /*
5656          * If we have hardware pacing support
5657          * we need to factor that in for our
5658          * TSO size.
5659          */
5660         const struct tcp_hwrate_limit_table *rlp;
5661         uint32_t cur_delay, seg_sz, maxseg, new_tso, delta, hdwr_delay;
5662
5663         if ((bbr->bbr_hdrw_pacing == 0) ||
5664             (IN_RECOVERY(bbr->rc_tp->t_flags)) ||
5665             (bbr->r_ctl.crte == NULL))
5666                 return;
5667         if (bbr->hw_pacing_set == 0) {
5668                 /* Not yet by the hdwr pacing count delay */
5669                 return;
5670         }
5671         if (bbr_hdwr_pace_adjust == 0) {
5672                 /* No adjustment */
5673                 return;
5674         }
5675         rlp = bbr->r_ctl.crte;
5676         if (bbr->rc_tp->t_maxseg > bbr->rc_last_options)
5677                 maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5678         else
5679                 maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5680         /*
5681          * So lets first get the
5682          * time we will take between
5683          * TSO sized sends currently without
5684          * hardware help.
5685          */
5686         cur_delay = bbr_get_pacing_delay(bbr, BBR_UNIT,
5687                         bbr->r_ctl.rc_pace_max_segs, cts, 1);
5688         hdwr_delay = bbr->r_ctl.rc_pace_max_segs / maxseg;
5689         hdwr_delay *= rlp->time_between;
5690         if (cur_delay > hdwr_delay)
5691                 delta = cur_delay - hdwr_delay;
5692         else
5693                 delta = 0;
5694         bbr_log_type_tsosize(bbr, cts, delta, cur_delay, hdwr_delay,
5695                              (bbr->r_ctl.rc_pace_max_segs / maxseg),
5696                              1);
5697         if (delta &&
5698             (delta < (max(rlp->time_between,
5699                           bbr->r_ctl.bbr_hptsi_segments_delay_tar)))) {
5700                 /*
5701                  * Now lets divide by the pacing
5702                  * time between each segment the
5703                  * hardware sends rounding up and
5704                  * derive a bytes from that. We multiply
5705                  * that by bbr_hdwr_pace_adjust to get 
5706                  * more bang for our buck.
5707                  *
5708                  * The goal is to have the software pacer
5709                  * waiting no more than an additional
5710                  * pacing delay if we can (without the 
5711                  * compensation i.e. x bbr_hdwr_pace_adjust).
5712                  */
5713                 seg_sz = max(((cur_delay + rlp->time_between)/rlp->time_between),
5714                              (bbr->r_ctl.rc_pace_max_segs/maxseg));
5715                 seg_sz *= bbr_hdwr_pace_adjust;
5716                 if (bbr_hdwr_pace_floor &&
5717                     (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5718                         /* Currently hardware paces
5719                          * out rs_min_seg segments at a time.
5720                          * We need to make sure we always send at least
5721                          * a full burst of bbr_hdwr_pace_floor down.
5722                          */
5723                         seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5724                 }
5725                 seg_sz *= maxseg;
5726         } else if (delta == 0) {
5727                 /* 
5728                  * The highest pacing rate is
5729                  * above our b/w gained. This means
5730                  * we probably are going quite fast at
5731                  * the hardware highest rate. Lets just multiply
5732                  * the calculated TSO size by the 
5733                  * multiplier factor (its probably
5734                  * 4 segments in the default config for
5735                  * mlx).
5736                  */
5737                 seg_sz = bbr->r_ctl.rc_pace_max_segs * bbr_hdwr_pace_adjust;
5738                 if (bbr_hdwr_pace_floor &&
5739                     (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5740                         /* Currently hardware paces
5741                          * out rs_min_seg segments at a time.
5742                          * We need to make sure we always send at least
5743                          * a full burst of bbr_hdwr_pace_floor down.
5744                          */
5745                         seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5746                 }
5747         } else {
5748                 /*
5749                  * The pacing time difference is so
5750                  * big that the hardware will
5751                  * pace out more rapidly then we
5752                  * really want and then we
5753                  * will have a long delay. Lets just keep
5754                  * the same TSO size so its as if
5755                  * we were not using hdwr pacing (we
5756                  * just gain a bit of spacing from the
5757                  * hardware if seg_sz > 1).
5758                  */
5759                 seg_sz = bbr->r_ctl.rc_pace_max_segs;
5760         }
5761         if (seg_sz > bbr->r_ctl.rc_pace_max_segs)
5762                 new_tso = seg_sz;
5763         else
5764                 new_tso = bbr->r_ctl.rc_pace_max_segs;
5765         if (new_tso >= (PACE_MAX_IP_BYTES-maxseg))
5766                 new_tso = PACE_MAX_IP_BYTES - maxseg;
5767         
5768         if (new_tso != bbr->r_ctl.rc_pace_max_segs) {
5769                 bbr_log_type_tsosize(bbr, cts, new_tso, 0, bbr->r_ctl.rc_pace_max_segs, maxseg, 0);
5770                 bbr->r_ctl.rc_pace_max_segs = new_tso;
5771         }
5772 }
5773
5774 static void
5775 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts)
5776 {
5777         uint64_t bw;
5778         uint32_t old_tso = 0, new_tso;
5779         uint32_t maxseg, bytes;
5780         uint32_t tls_seg=0;
5781         /* 
5782          * Google/linux uses the following algorithm to determine
5783          * the TSO size based on the b/w of the link (from Neal Cardwell email 9/27/18):
5784          *
5785          *  bytes = bw_in_bytes_per_second / 1000
5786          *  bytes = min(bytes, 64k)
5787          *  tso_segs = bytes / MSS
5788          *  if (bw < 1.2Mbs)
5789          *      min_tso_segs = 1
5790          *  else
5791          *      min_tso_segs = 2
5792          * tso_segs = max(tso_segs, min_tso_segs)
5793          *
5794          * * Note apply a device specific limit (we apply this in the 
5795          *   tcp_m_copym).
5796          * Note that before the initial measurement is made google bursts out
5797          * a full iwnd just like new-reno/cubic.
5798          *
5799          * We do not use this algorithm. Instead we
5800          * use a two phased approach:
5801          *
5802          *  if ( bw <= per-tcb-cross-over)
5803          *     goal_tso =  calculate how much with this bw we
5804          *                 can send in goal-time seconds.
5805          *     if (goal_tso > mss)
5806          *         seg = goal_tso / mss
5807          *         tso = seg * mss
5808          *     else
5809          *         tso = mss
5810          *     if (tso > per-tcb-max)
5811          *         tso = per-tcb-max
5812          *  else if ( bw > 512Mbps)
5813          *     tso = max-tso (64k/mss)
5814          *  else
5815          *     goal_tso = bw / per-tcb-divsor
5816          *     seg = (goal_tso + mss-1)/mss
5817          *     tso = seg * mss
5818          *
5819          * if (tso < per-tcb-floor)
5820          *    tso = per-tcb-floor
5821          * if (tso > per-tcb-utter_max)
5822          *    tso = per-tcb-utter_max
5823          *
5824          * Note the default per-tcb-divisor is 1000 (same as google).
5825          * the goal cross over is 30Mbps however. To recreate googles
5826          * algorithm you need to set:
5827          * 
5828          * cross-over = 23,168,000 bps
5829          * goal-time = 18000
5830          * per-tcb-max = 2
5831          * per-tcb-divisor = 1000
5832          * per-tcb-floor = 1
5833          *
5834          * This will get you "google bbr" behavior with respect to tso size.
5835          *
5836          * Note we do set anything TSO size until we are past the initial
5837          * window. Before that we gnerally use either a single MSS
5838          * or we use the full IW size (so we burst a IW at a time)
5839          * Also note that Hardware-TLS is special and does alternate
5840          * things to minimize PCI Bus Bandwidth use.
5841          */
5842
5843         if (bbr->rc_tp->t_maxseg > bbr->rc_last_options) {
5844                 maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5845         } else {
5846                 maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5847         }
5848 #ifdef KERN_TLS
5849         if (bbr->rc_inp->inp_socket->so_snd.sb_flags & SB_TLS_IFNET) {
5850                 tls_seg =  ctf_get_opt_tls_size(bbr->rc_inp->inp_socket, bbr->rc_tp->snd_wnd);
5851                 bbr->r_ctl.rc_pace_min_segs = (tls_seg + bbr->rc_last_options);
5852         }
5853 #endif
5854         old_tso = bbr->r_ctl.rc_pace_max_segs;
5855         if (bbr->rc_past_init_win == 0) {
5856                 /*
5857                  * Not enough data has been acknowledged to make a
5858                  * judgement unless we are hardware TLS. Set up
5859                  * the inital TSO based on if we are sending a
5860                  * full IW at once or not.
5861                  */
5862                 if (bbr->rc_use_google)
5863                         bbr->r_ctl.rc_pace_max_segs = ((bbr->rc_tp->t_maxseg - bbr->rc_last_options) * 2);
5864                 else if (bbr->bbr_init_win_cheat)
5865                         bbr->r_ctl.rc_pace_max_segs = bbr_initial_cwnd(bbr, bbr->rc_tp);
5866                 else
5867                         bbr->r_ctl.rc_pace_max_segs = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5868                 if (bbr->r_ctl.rc_pace_min_segs != bbr->rc_tp->t_maxseg)
5869                         bbr->r_ctl.rc_pace_min_segs = bbr->rc_tp->t_maxseg;
5870 #ifdef KERN_TLS
5871                 if ((bbr->rc_inp->inp_socket->so_snd.sb_flags & SB_TLS_IFNET) && tls_seg) {
5872                         /*
5873                          * For hardware TLS we set our min to the tls_seg size.
5874                          */
5875                         bbr->r_ctl.rc_pace_max_segs = tls_seg;
5876                         bbr->r_ctl.rc_pace_min_segs = tls_seg + bbr->rc_last_options;
5877                 }
5878 #endif
5879                 if (bbr->r_ctl.rc_pace_max_segs == 0) {
5880                         bbr->r_ctl.rc_pace_max_segs = maxseg;
5881                 }
5882                 bbr_log_type_tsosize(bbr, cts, bbr->r_ctl.rc_pace_max_segs, tls_seg, old_tso, maxseg, 0);
5883 #ifdef KERN_TLS
5884                 if ((bbr->rc_inp->inp_socket->so_snd.sb_flags & SB_TLS_IFNET) == 0)
5885 #endif
5886                         bbr_adjust_for_hw_pacing(bbr, cts);
5887                 return;
5888         }
5889         /**
5890          * Now lets set the TSO goal based on our delivery rate in
5891          * bytes per second. Note we only do this if
5892          * we have acked at least the initial cwnd worth of data.
5893          */
5894         bw = bbr_get_bw(bbr);
5895         if (IN_RECOVERY(bbr->rc_tp->t_flags) &&
5896              (bbr->rc_use_google == 0)) {
5897                 /* We clamp to one MSS in recovery */
5898                 new_tso = maxseg;
5899         } else if (bbr->rc_use_google) {
5900                 int min_tso_segs;
5901                 
5902                 /* Google considers the gain too */
5903                 if (bbr->r_ctl.rc_bbr_hptsi_gain != BBR_UNIT) {
5904                         bw *= bbr->r_ctl.rc_bbr_hptsi_gain;
5905                         bw /= BBR_UNIT;
5906                 }
5907                 bytes = bw / 1024;
5908                 if (bytes > (64 * 1024))
5909                         bytes = 64 * 1024;
5910                 new_tso = bytes / maxseg;
5911                 if (bw < ONE_POINT_TWO_MEG)
5912                         min_tso_segs = 1;
5913                 else
5914                         min_tso_segs = 2;
5915                 if (new_tso < min_tso_segs)
5916                         new_tso = min_tso_segs;
5917                 new_tso *= maxseg;
5918         } else if (bbr->rc_no_pacing) {
5919                 new_tso = (PACE_MAX_IP_BYTES / maxseg) * maxseg;
5920         } else if (bw <= bbr->r_ctl.bbr_cross_over) {
5921                 /*
5922                  * Calculate the worse case b/w TSO if we are inserting no
5923                  * more than a delay_target number of TSO's.
5924                  */
5925                 uint32_t tso_len, min_tso;
5926
5927                 tso_len = bbr_get_pacing_length(bbr, BBR_UNIT, bbr->r_ctl.bbr_hptsi_segments_delay_tar, bw);
5928                 if (tso_len > maxseg) {
5929                         new_tso = tso_len / maxseg;
5930                         if (new_tso > bbr->r_ctl.bbr_hptsi_segments_max)
5931                                 new_tso = bbr->r_ctl.bbr_hptsi_segments_max;
5932                         new_tso *= maxseg;
5933                 } else {
5934                         /*
5935                          * less than a full sized frame yikes.. long rtt or
5936                          * low bw?
5937                          */
5938                         min_tso = bbr_minseg(bbr);
5939                         if ((tso_len > min_tso) && (bbr_all_get_min == 0))
5940                                 new_tso = rounddown(tso_len, min_tso);
5941                         else
5942                                 new_tso = min_tso;
5943                 }
5944         } else if (bw > FIVETWELVE_MBPS) {
5945                 /*
5946                  * This guy is so fast b/w wise that we can TSO as large as
5947                  * possible of segments that the NIC will allow.
5948                  */
5949                 new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5950         } else {
5951                 /*
5952                  * This formula is based on attempting to send a segment or
5953                  * more every bbr_hptsi_per_second. The default is 1000
5954                  * which means you are targeting what you can send every 1ms
5955                  * based on the peers bw.
5956                  *
5957                  * If the number drops to say 500, then you are looking more
5958                  * at 2ms and you will raise how much we send in a single
5959                  * TSO thus saving CPU (less bbr_output_wtime() calls). The
5960                  * trade off of course is you will send more at once and
5961                  * thus tend to clump up the sends into larger "bursts"
5962                  * building a queue.
5963                  */
5964                 bw /= bbr->r_ctl.bbr_hptsi_per_second;
5965                 new_tso = roundup(bw, (uint64_t)maxseg);
5966                 /*
5967                  * Gate the floor to match what our lower than 48Mbps
5968                  * algorithm does. The ceiling (bbr_hptsi_segments_max) thus
5969                  * becomes the floor for this calculation.
5970                  */
5971                 if (new_tso < (bbr->r_ctl.bbr_hptsi_segments_max * maxseg))
5972                         new_tso = (bbr->r_ctl.bbr_hptsi_segments_max * maxseg);
5973         }
5974         if (bbr->r_ctl.bbr_hptsi_segments_floor && (new_tso < (maxseg * bbr->r_ctl.bbr_hptsi_segments_floor)))
5975                 new_tso = maxseg * bbr->r_ctl.bbr_hptsi_segments_floor;
5976         if (new_tso > PACE_MAX_IP_BYTES)
5977                 new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5978         /* Enforce an utter maximum if we are not HW-TLS */
5979 #ifdef KERN_TLS
5980         if ((bbr->rc_inp->inp_socket->so_snd.sb_flags & SB_TLS_IFNET) == 0)
5981 #endif
5982                 if (bbr->r_ctl.bbr_utter_max && (new_tso > (bbr->r_ctl.bbr_utter_max * maxseg))) {
5983                         new_tso = bbr->r_ctl.bbr_utter_max * maxseg;
5984                 }
5985 #ifdef KERN_TLS
5986         if (tls_seg) {
5987                 /* 
5988                  * Lets move the output size
5989                  * up to 1 or more TLS record sizes.
5990                  */
5991                 uint32_t temp;
5992
5993                 temp = roundup(new_tso, tls_seg);
5994                 new_tso = temp;
5995                 /* Back down if needed to under a full frame */
5996                 while (new_tso > PACE_MAX_IP_BYTES)
5997                         new_tso -= tls_seg;
5998         }
5999 #endif
6000         if (old_tso != new_tso) {
6001                 /* Only log changes */
6002                 bbr_log_type_tsosize(bbr, cts, new_tso, tls_seg, old_tso, maxseg, 0);
6003                 bbr->r_ctl.rc_pace_max_segs = new_tso;
6004         }
6005 #ifdef KERN_TLS
6006         if ((bbr->rc_inp->inp_socket->so_snd.sb_flags & SB_TLS_IFNET) &&
6007              tls_seg) {
6008                 bbr->r_ctl.rc_pace_min_segs = tls_seg + bbr->rc_last_options;
6009         } else
6010 #endif
6011                 /* We have hardware pacing and not hardware TLS! */
6012                 bbr_adjust_for_hw_pacing(bbr, cts);
6013 }
6014
6015 static void
6016 bbr_log_output(struct tcp_bbr *bbr, struct tcpcb *tp, struct tcpopt *to, int32_t len,
6017     uint32_t seq_out, uint8_t th_flags, int32_t err, uint32_t cts,
6018     struct mbuf *mb, int32_t * abandon, struct bbr_sendmap *hintrsm, uint32_t delay_calc,
6019     struct sockbuf *sb)
6020 {
6021
6022         struct bbr_sendmap *rsm, *nrsm;
6023         register uint32_t snd_max, snd_una;
6024         uint32_t pacing_time;
6025         /*
6026          * Add to the RACK log of packets in flight or retransmitted. If
6027          * there is a TS option we will use the TS echoed, if not we will
6028          * grab a TS.
6029          *
6030          * Retransmissions will increment the count and move the ts to its
6031          * proper place. Note that if options do not include TS's then we
6032          * won't be able to effectively use the ACK for an RTT on a retran.
6033          *
6034          * Notes about r_start and r_end. Lets consider a send starting at
6035          * sequence 1 for 10 bytes. In such an example the r_start would be
6036          * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
6037          * This means that r_end is actually the first sequence for the next
6038          * slot (11).
6039          *
6040          */
6041         INP_WLOCK_ASSERT(tp->t_inpcb);
6042         if (err) {
6043                 /*
6044                  * We don't log errors -- we could but snd_max does not
6045                  * advance in this case either.
6046                  */
6047                 return;
6048         }
6049         if (th_flags & TH_RST) {
6050                 /*
6051                  * We don't log resets and we return immediately from
6052                  * sending
6053                  */
6054                 *abandon = 1;
6055                 return;
6056         }
6057         snd_una = tp->snd_una;
6058         if (th_flags & (TH_SYN | TH_FIN) && (hintrsm == NULL)) {
6059                 /*
6060                  * The call to bbr_log_output is made before bumping
6061                  * snd_max. This means we can record one extra byte on a SYN
6062                  * or FIN if seq_out is adding more on and a FIN is present
6063                  * (and we are not resending).
6064                  */
6065                 if (th_flags & TH_SYN)
6066                         len++;
6067                 if (th_flags & TH_FIN)
6068                         len++;
6069         }
6070         if (SEQ_LEQ((seq_out + len), snd_una)) {
6071                 /* Are sending an old segment to induce an ack (keep-alive)? */
6072                 return;
6073         }
6074         if (SEQ_LT(seq_out, snd_una)) {
6075                 /* huh? should we panic? */
6076                 uint32_t end;
6077
6078                 end = seq_out + len;
6079                 seq_out = snd_una;
6080                 len = end - seq_out;
6081         }
6082         snd_max = tp->snd_max;
6083         if (len == 0) {
6084                 /* We don't log zero window probes */
6085                 return;
6086         }
6087         pacing_time = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, len, cts, 1);
6088         /* First question is it a retransmission? */
6089         if (seq_out == snd_max) {
6090 again:
6091                 rsm = bbr_alloc(bbr);
6092                 if (rsm == NULL) {
6093                         return;
6094                 }
6095                 rsm->r_flags = 0;
6096                 if (th_flags & TH_SYN)
6097                         rsm->r_flags |= BBR_HAS_SYN;
6098                 if (th_flags & TH_FIN)
6099                         rsm->r_flags |= BBR_HAS_FIN;
6100                 rsm->r_tim_lastsent[0] = cts;
6101                 rsm->r_rtr_cnt = 1;
6102                 rsm->r_rtr_bytes = 0;
6103                 rsm->r_start = seq_out;
6104                 rsm->r_end = rsm->r_start + len;
6105                 rsm->r_dupack = 0;
6106                 rsm->r_delivered = bbr->r_ctl.rc_delivered;
6107                 rsm->r_pacing_delay = pacing_time;
6108                 rsm->r_ts_valid = bbr->rc_ts_valid;
6109                 if (bbr->rc_ts_valid)
6110                         rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
6111                 rsm->r_del_time = bbr->r_ctl.rc_del_time;
6112                 if (bbr->r_ctl.r_app_limited_until)
6113                         rsm->r_app_limited = 1;
6114                 else
6115                         rsm->r_app_limited = 0;
6116                 rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
6117                 rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
6118                                                 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
6119                 /* 
6120                  * Here we must also add in this rsm since snd_max
6121                  * is updated after we return from a new send.
6122                  */
6123                 rsm->r_flight_at_send += len;
6124                 TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
6125                 TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
6126                 rsm->r_in_tmap = 1;
6127                 if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
6128                         rsm->r_bbr_state = bbr_state_val(bbr);
6129                 else
6130                         rsm->r_bbr_state = 8;
6131                 if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
6132                         rsm->r_is_gain = 1;
6133                         rsm->r_is_drain = 0;
6134                 } else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
6135                         rsm->r_is_drain = 1;
6136                         rsm->r_is_gain = 0;
6137                 } else {
6138                         rsm->r_is_drain = 0;
6139                         rsm->r_is_gain = 0;
6140                 }
6141                 return;
6142         }
6143         /*
6144          * If we reach here its a retransmission and we need to find it.
6145          */
6146 more:
6147         if (hintrsm && (hintrsm->r_start == seq_out)) {
6148                 rsm = hintrsm;
6149                 hintrsm = NULL;
6150         } else if (bbr->r_ctl.rc_next) {
6151                 /* We have a hint from a previous run */
6152                 rsm = bbr->r_ctl.rc_next;
6153         } else {
6154                 /* No hints sorry */
6155                 rsm = NULL;
6156         }
6157         if ((rsm) && (rsm->r_start == seq_out)) {
6158                 /*
6159                  * We used rc_next or hintrsm  to retransmit, hopefully the
6160                  * likely case.
6161                  */
6162                 seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6163                 if (len == 0) {
6164                         return;
6165                 } else {
6166                         goto more;
6167                 }
6168         }
6169         /* Ok it was not the last pointer go through it the hard way. */
6170         TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6171                 if (rsm->r_start == seq_out) {
6172                         seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6173                         bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
6174                         if (len == 0) {
6175                                 return;
6176                         } else {
6177                                 continue;
6178                         }
6179                 }
6180                 if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
6181                         /* Transmitted within this piece */
6182                         /*
6183                          * Ok we must split off the front and then let the
6184                          * update do the rest
6185                          */
6186                         nrsm = bbr_alloc_full_limit(bbr);
6187                         if (nrsm == NULL) {
6188                                 bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
6189                                 return;
6190                         }
6191                         /*
6192                          * copy rsm to nrsm and then trim the front of rsm
6193                          * to not include this part.
6194                          */
6195                         bbr_clone_rsm(bbr, nrsm, rsm, seq_out);
6196                         TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
6197                         if (rsm->r_in_tmap) {
6198                                 TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6199                                 nrsm->r_in_tmap = 1;
6200                         }
6201                         rsm->r_flags &= (~BBR_HAS_FIN);
6202                         seq_out = bbr_update_entry(tp, bbr, nrsm, cts, &len, pacing_time);
6203                         if (len == 0) {
6204                                 return;
6205                         }
6206                 }
6207         }
6208         /*
6209          * Hmm not found in map did they retransmit both old and on into the
6210          * new?
6211          */
6212         if (seq_out == tp->snd_max) {
6213                 goto again;
6214         } else if (SEQ_LT(seq_out, tp->snd_max)) {
6215 #ifdef BBR_INVARIANTS
6216                 printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
6217                     seq_out, len, tp->snd_una, tp->snd_max);
6218                 printf("Starting Dump of all rack entries\n");
6219                 TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6220                         printf("rsm:%p start:%u end:%u\n",
6221                             rsm, rsm->r_start, rsm->r_end);
6222                 }
6223                 printf("Dump complete\n");
6224                 panic("seq_out not found rack:%p tp:%p",
6225                     bbr, tp);
6226 #endif
6227         } else {
6228 #ifdef BBR_INVARIANTS
6229                 /*
6230                  * Hmm beyond sndmax? (only if we are using the new rtt-pack
6231                  * flag)
6232                  */
6233                 panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
6234                     seq_out, len, tp->snd_max, tp);
6235 #endif
6236         }
6237 }
6238
6239 static void
6240 bbr_collapse_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, int32_t rtt)
6241 {
6242         /*
6243          * Collapse timeout back the cum-ack moved.
6244          */
6245         tp->t_rxtshift = 0;
6246         tp->t_softerror = 0;
6247 }
6248
6249
6250 static void
6251 tcp_bbr_xmit_timer(struct tcp_bbr *bbr, uint32_t rtt_usecs, uint32_t rsm_send_time, uint32_t r_start, uint32_t tsin)
6252 {
6253         bbr->rtt_valid = 1;
6254         bbr->r_ctl.cur_rtt = rtt_usecs;
6255         bbr->r_ctl.ts_in = tsin;
6256         if (rsm_send_time)
6257                 bbr->r_ctl.cur_rtt_send_time = rsm_send_time;
6258 }
6259
6260 static void
6261 bbr_make_timestamp_determination(struct tcp_bbr *bbr)
6262 {
6263         /**
6264          * We have in our bbr control:
6265          * 1) The timestamp we started observing cum-acks (bbr->r_ctl.bbr_ts_check_tstmp).
6266          * 2) Our timestamp indicating when we sent that packet (bbr->r_ctl.rsm->bbr_ts_check_our_cts).
6267          * 3) The current timestamp that just came in (bbr->r_ctl.last_inbound_ts)
6268          * 4) The time that the packet that generated that ack was sent (bbr->r_ctl.cur_rtt_send_time)
6269          *
6270          * Now we can calculate the time between the sends by doing:
6271          *
6272          * delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts
6273          *
6274          * And the peer's time between receiving them by doing:
6275          *
6276          * peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp
6277          * 
6278          * We want to figure out if the timestamp values are in msec, 10msec or usec.
6279          * We also may find that we can't use the timestamps if say we see
6280          * that the peer_delta indicates that though we may have taken 10ms to
6281          * pace out the data, it only saw 1ms between the two packets. This would
6282          * indicate that somewhere on the path is a batching entity that is giving
6283          * out time-slices of the actual b/w. This would mean we could not use
6284          * reliably the peers timestamps.
6285          *
6286          * We expect delta > peer_delta initially. Until we figure out the
6287          * timestamp difference which we will store in bbr->r_ctl.bbr_peer_tsratio.
6288          * If we place 1000 there then its a ms vs our usec. If we place 10000 there
6289          * then its 10ms vs our usec. If the peer is running a usec clock we would
6290          * put a 1 there. If the value is faster then ours, we will disable the
6291          * use of timestamps (though we could revist this later if we find it to be not
6292          * just an isolated one or two flows)).
6293          * 
6294          * To detect the batching middle boxes we will come up with our compensation and
6295          * if with it in place, we find the peer is drastically off (by some margin) in
6296          * the smaller direction, then we will assume the worst case and disable use of timestamps.
6297          * 
6298          */
6299         uint64_t delta, peer_delta, delta_up;
6300
6301         delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts;
6302         if (delta < bbr_min_usec_delta) {
6303                 /*
6304                  * Have not seen a min amount of time
6305                  * between our send times so we can
6306                  * make a determination of the timestamp
6307                  * yet.
6308                  */
6309                 return;
6310         }
6311         peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp;
6312         if (peer_delta < bbr_min_peer_delta) {
6313                 /*
6314                  * We may have enough in the form of
6315                  * our delta but the peers number
6316                  * has not changed that much. It could
6317                  * be its clock ratio is such that
6318                  * we need more data (10ms tick) or
6319                  * there may be other compression scenarios
6320                  * going on. In any event we need the
6321                  * spread to be larger.
6322                  */
6323                 return;
6324         }
6325         /* Ok lets first see which way our delta is going */
6326         if (peer_delta > delta) {
6327                 /* Very unlikely, the peer without
6328                  * compensation shows that it saw
6329                  * the two sends arrive further apart
6330                  * then we saw then in micro-seconds. 
6331                  */
6332                 if (peer_delta < (delta + ((delta * (uint64_t)1000)/ (uint64_t)bbr_delta_percent))) {
6333                         /* well it looks like the peer is a micro-second clock. */
6334                         bbr->rc_ts_clock_set = 1;
6335                         bbr->r_ctl.bbr_peer_tsratio = 1;
6336                 } else {
6337                         bbr->rc_ts_cant_be_used = 1;
6338                         bbr->rc_ts_clock_set = 1;
6339                 }
6340                 return;
6341         }
6342         /* Ok we know that the peer_delta is smaller than our send distance */
6343         bbr->rc_ts_clock_set = 1;
6344         /* First question is it within the percentage that they are using usec time? */
6345         delta_up = (peer_delta * 1000) / (uint64_t)bbr_delta_percent;
6346         if ((peer_delta + delta_up) >= delta) {
6347                 /* Its a usec clock */
6348                 bbr->r_ctl.bbr_peer_tsratio = 1;
6349                 bbr_log_tstmp_validation(bbr, peer_delta, delta);
6350                 return;
6351         }
6352         /* Ok if not usec, what about 10usec (though unlikely)? */
6353         delta_up = (peer_delta * 1000 * 10) / (uint64_t)bbr_delta_percent;
6354         if (((peer_delta * 10) + delta_up) >= delta) {
6355                 bbr->r_ctl.bbr_peer_tsratio = 10; 
6356                 bbr_log_tstmp_validation(bbr, peer_delta, delta);
6357                 return;
6358         }
6359         /* And what about 100usec (though again unlikely)? */
6360         delta_up = (peer_delta * 1000 * 100) / (uint64_t)bbr_delta_percent;
6361         if (((peer_delta * 100) + delta_up) >= delta) {
6362                 bbr->r_ctl.bbr_peer_tsratio = 100;
6363                 bbr_log_tstmp_validation(bbr, peer_delta, delta);
6364                 return;
6365         }
6366         /* And how about 1 msec (the most likely one)? */
6367         delta_up = (peer_delta * 1000 * 1000) / (uint64_t)bbr_delta_percent;
6368         if (((peer_delta * 1000) + delta_up) >= delta) {
6369                 bbr->r_ctl.bbr_peer_tsratio = 1000;
6370                 bbr_log_tstmp_validation(bbr, peer_delta, delta);
6371                 return;
6372         }
6373         /* Ok if not msec could it be 10 msec? */
6374         delta_up = (peer_delta * 1000 * 10000) / (uint64_t)bbr_delta_percent;
6375         if (((peer_delta * 10000) + delta_up) >= delta) {
6376                 bbr->r_ctl.bbr_peer_tsratio = 10000;
6377                 return;
6378         }
6379         /* If we fall down here the clock tick so slowly we can't use it */
6380         bbr->rc_ts_cant_be_used = 1;
6381         bbr->r_ctl.bbr_peer_tsratio = 0;
6382         bbr_log_tstmp_validation(bbr, peer_delta, delta);
6383 }
6384
6385 /*
6386  * Collect new round-trip time estimate
6387  * and update averages and current timeout.
6388  */
6389 static void
6390 tcp_bbr_xmit_timer_commit(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts)
6391 {
6392         int32_t delta;
6393         uint32_t rtt, tsin;
6394         int32_t rtt_ticks;
6395
6396
6397         if (bbr->rtt_valid == 0)
6398                 /* No valid sample */
6399                 return;
6400
6401         rtt = bbr->r_ctl.cur_rtt;
6402         tsin = bbr->r_ctl.ts_in;
6403         if (bbr->rc_prtt_set_ts) {
6404                 /* 
6405                  * We are to force feed the rttProp filter due
6406                  * to an entry into PROBE_RTT. This assures
6407                  * that the times are sync'd between when we
6408                  * go into PROBE_RTT and the filter expiration.
6409                  *
6410                  * Google does not use a true filter, so they do
6411                  * this implicitly since they only keep one value
6412                  * and when they enter probe-rtt they update the
6413                  * value to the newest rtt.
6414                  */
6415                 uint32_t rtt_prop;
6416                 
6417                 bbr->rc_prtt_set_ts = 0;
6418                 rtt_prop = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
6419                 if (rtt > rtt_prop)
6420                         filter_increase_by_small(&bbr->r_ctl.rc_rttprop, (rtt - rtt_prop), cts);
6421                 else
6422                         apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);       
6423         }
6424         if (bbr->rc_ack_was_delayed)
6425                 rtt += bbr->r_ctl.rc_ack_hdwr_delay;
6426
6427         if (rtt < bbr->r_ctl.rc_lowest_rtt)
6428                 bbr->r_ctl.rc_lowest_rtt = rtt;
6429         bbr_log_rtt_sample(bbr, rtt, tsin);
6430         if (bbr->r_init_rtt) {
6431                 /*
6432                  * The initial rtt is not-trusted, nuke it and lets get
6433                  * our first valid measurement in.
6434                  */
6435                 bbr->r_init_rtt = 0;
6436                 tp->t_srtt = 0;
6437         }
6438         if ((bbr->rc_ts_clock_set == 0) && bbr->rc_ts_valid) {
6439                 /*
6440                  * So we have not yet figured out
6441                  * what the peers TSTMP value is
6442                  * in (most likely ms). We need a
6443                  * series of cum-ack's to determine
6444                  * this reliably.
6445                  */
6446                 if (bbr->rc_ack_is_cumack) {
6447                         if (bbr->rc_ts_data_set) {
6448                                 /* Lets attempt to determine the timestamp granularity. */
6449                                 bbr_make_timestamp_determination(bbr);
6450                         } else {
6451                                 bbr->rc_ts_data_set = 1;
6452                                 bbr->r_ctl.bbr_ts_check_tstmp = bbr->r_ctl.last_inbound_ts;
6453                                 bbr->r_ctl.bbr_ts_check_our_cts = bbr->r_ctl.cur_rtt_send_time;
6454                         }
6455                 } else {
6456                         /* 
6457                          * We have to have consecutive acks 
6458                          * reset any "filled" state to none.
6459                          */
6460                         bbr->rc_ts_data_set = 0;
6461                 }
6462         }
6463         /* Round it up */
6464         rtt_ticks = USEC_2_TICKS((rtt + (USECS_IN_MSEC - 1)));
6465         if (rtt_ticks == 0)
6466                 rtt_ticks = 1;
6467         if (tp->t_srtt != 0) {
6468                 /*
6469                  * srtt is stored as fixed point with 5 bits after the
6470                  * binary point (i.e., scaled by 8).  The following magic is
6471                  * equivalent to the smoothing algorithm in rfc793 with an
6472                  * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6473                  * Adjust rtt to origin 0.
6474                  */
6475
6476                 delta = ((rtt_ticks - 1) << TCP_DELTA_SHIFT)
6477                     - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6478
6479                 tp->t_srtt += delta;
6480                 if (tp->t_srtt <= 0)
6481                         tp->t_srtt = 1;
6482
6483                 /*
6484                  * We accumulate a smoothed rtt variance (actually, a
6485                  * smoothed mean difference), then set the retransmit timer
6486                  * to smoothed rtt + 4 times the smoothed variance. rttvar
6487                  * is stored as fixed point with 4 bits after the binary
6488                  * point (scaled by 16).  The following is equivalent to
6489                  * rfc793 smoothing with an alpha of .75 (rttvar =
6490                  * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
6491                  * wired-in beta.
6492                  */
6493                 if (delta < 0)
6494                         delta = -delta;
6495                 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6496                 tp->t_rttvar += delta;
6497                 if (tp->t_rttvar <= 0)
6498                         tp->t_rttvar = 1;
6499                 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
6500                         tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6501         } else {
6502                 /*
6503                  * No rtt measurement yet - use the unsmoothed rtt. Set the
6504                  * variance to half the rtt (so our first retransmit happens
6505                  * at 3*rtt).
6506                  */
6507                 tp->t_srtt = rtt_ticks << TCP_RTT_SHIFT;
6508                 tp->t_rttvar = rtt_ticks << (TCP_RTTVAR_SHIFT - 1);
6509                 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6510         }
6511         TCPSTAT_INC(tcps_rttupdated);
6512         tp->t_rttupdated++;
6513 #ifdef STATS
6514         stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt_ticks));
6515 #endif
6516         /*
6517          * the retransmit should happen at rtt + 4 * rttvar. Because of the
6518          * way we do the smoothing, srtt and rttvar will each average +1/2
6519          * tick of bias.  When we compute the retransmit timer, we want 1/2
6520          * tick of rounding and 1 extra tick because of +-1/2 tick
6521          * uncertainty in the firing of the timer.  The bias will give us
6522          * exactly the 1.5 tick we need.  But, because the bias is
6523          * statistical, we have to test that we don't drop below the minimum
6524          * feasible timer (which is 2 ticks).
6525          */
6526         TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6527             max(MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms), rtt_ticks + 2),
6528             MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
6529
6530         /*
6531          * We received an ack for a packet that wasn't retransmitted; it is
6532          * probably safe to discard any error indications we've received
6533          * recently.  This isn't quite right, but close enough for now (a
6534          * route might have failed after we sent a segment, and the return
6535          * path might not be symmetrical).
6536          */
6537         tp->t_softerror = 0;
6538         rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
6539         if (bbr->r_ctl.bbr_smallest_srtt_this_state > rtt)
6540                 bbr->r_ctl.bbr_smallest_srtt_this_state = rtt;
6541 }
6542
6543 static void
6544 bbr_earlier_retran(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm,
6545                    uint32_t t, uint32_t cts, int ack_type)
6546 {
6547         /*
6548          * For this RSM, we acknowledged the data from a previous
6549          * transmission, not the last one we made. This means we did a false
6550          * retransmit.
6551          */
6552         if (rsm->r_flags & BBR_HAS_FIN) {
6553                 /*
6554                  * The sending of the FIN often is multiple sent when we
6555                  * have everything outstanding ack'd. We ignore this case
6556                  * since its over now.
6557                  */
6558                 return;
6559         }
6560         if (rsm->r_flags & BBR_TLP) {
6561                 /*
6562                  * We expect TLP's to have this occur often
6563                  */
6564                 bbr->rc_tlp_rtx_out = 0;
6565                 return;
6566         }
6567         if (ack_type != BBR_CUM_ACKED) {
6568                 /*
6569                  * If it was not a cum-ack we
6570                  * don't really know for sure since
6571                  * the timestamp could be from some
6572                  * other transmission.
6573                  */
6574                 return;
6575         }
6576                 
6577         if (rsm->r_flags & BBR_WAS_SACKPASS) {
6578                 /*
6579                  * We retransmitted based on a sack and the earlier
6580                  * retransmission ack'd it - re-ordering is occuring.
6581                  */
6582                 BBR_STAT_INC(bbr_reorder_seen);
6583                 bbr->r_ctl.rc_reorder_ts = cts;
6584         }
6585         /* Back down the loss count */
6586         if (rsm->r_flags & BBR_MARKED_LOST) {
6587                 bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
6588                 bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
6589                 rsm->r_flags &= ~BBR_MARKED_LOST;               
6590                 if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
6591                         /* LT sampling also needs adjustment */
6592                         bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
6593         }
6594         /***** RRS HERE ************************/
6595         /* Do we need to do this???            */
6596         /* bbr_reset_lt_bw_sampling(bbr, cts); */
6597         /***** RRS HERE ************************/
6598         BBR_STAT_INC(bbr_badfr);
6599         BBR_STAT_ADD(bbr_badfr_bytes, (rsm->r_end - rsm->r_start));
6600 }
6601
6602
6603 static void
6604 bbr_set_reduced_rtt(struct tcp_bbr *bbr, uint32_t cts, uint32_t line)
6605 {
6606         bbr->r_ctl.rc_rtt_shrinks = cts;
6607         if (bbr_can_force_probertt &&
6608             (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
6609             ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
6610                 /* 
6611                  * We should enter probe-rtt its been too long 
6612                  * since we have been there.
6613                  */
6614                 bbr_enter_probe_rtt(bbr, cts, __LINE__);
6615         } else
6616                 bbr_check_probe_rtt_limits(bbr, cts);
6617 }
6618
6619 static void
6620 tcp_bbr_commit_bw(struct tcp_bbr *bbr, uint32_t cts)
6621 {
6622         uint64_t orig_bw;
6623
6624         if (bbr->r_ctl.rc_bbr_cur_del_rate == 0) {
6625                 /* We never apply a zero measurment */
6626                 bbr_log_type_bbrupd(bbr, 20, cts, 0, 0,
6627                                     0, 0, 0, 0, 0, 0);
6628                 return;
6629         }
6630         if (bbr->r_ctl.r_measurement_count < 0xffffffff)
6631                 bbr->r_ctl.r_measurement_count++;
6632         orig_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
6633         apply_filter_max(&bbr->r_ctl.rc_delrate, bbr->r_ctl.rc_bbr_cur_del_rate, bbr->r_ctl.rc_pkt_epoch);
6634         bbr_log_type_bbrupd(bbr, 21, cts, (uint32_t)orig_bw,
6635                             (uint32_t)get_filter_value(&bbr->r_ctl.rc_delrate),
6636                             0, 0, 0, 0, 0, 0);
6637         if (orig_bw &&
6638             (orig_bw != get_filter_value(&bbr->r_ctl.rc_delrate))) {
6639                 if (bbr->bbr_hdrw_pacing) {
6640                         /*
6641                          * Apply a new rate to the hardware
6642                          * possibly.
6643                          */
6644                         bbr_update_hardware_pacing_rate(bbr, cts);
6645                 }
6646                 bbr_set_state_target(bbr, __LINE__);
6647                 tcp_bbr_tso_size_check(bbr, cts);
6648                 if (bbr->r_recovery_bw)  {
6649                         bbr_setup_red_bw(bbr, cts);
6650                         bbr_log_type_bw_reduce(bbr, BBR_RED_BW_USELRBW);
6651                 }
6652         } else if ((orig_bw == 0) && get_filter_value(&bbr->r_ctl.rc_delrate))
6653                 tcp_bbr_tso_size_check(bbr, cts);
6654 }
6655
6656 static void
6657 bbr_nf_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6658 {
6659         if (bbr->rc_in_persist == 0) {
6660                 /* We log only when not in persist */
6661                 /* Translate to a Bytes Per Second */
6662                 uint64_t tim, bw, ts_diff, ts_bw;
6663                 uint32_t upper, lower, delivered;
6664
6665                 if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6666                         tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6667                 else
6668                         tim = 1;
6669                 /* 
6670                  * Now that we have processed the tim (skipping the sample
6671                  * or possibly updating the time, go ahead and
6672                  * calculate the cdr.
6673                  */
6674                 delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6675                 bw = (uint64_t)delivered;
6676                 bw *= (uint64_t)USECS_IN_SECOND;
6677                 bw /= tim;
6678                 if (bw == 0) {
6679                         /* We must have a calculatable amount */
6680                         return;
6681                 }
6682                 upper = (bw >> 32) & 0x00000000ffffffff;
6683                 lower = bw & 0x00000000ffffffff;
6684                 /* 
6685                  * If we are using this b/w shove it in now so we
6686                  * can see in the trace viewer if it gets over-ridden.
6687                  */
6688                 if (rsm->r_ts_valid &&
6689                     bbr->rc_ts_valid &&
6690                     bbr->rc_ts_clock_set &&
6691                     (bbr->rc_ts_cant_be_used == 0) &&
6692                     bbr->rc_use_ts_limit) {
6693                         ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6694                         ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6695                         if ((delivered == 0) ||
6696                             (rtt < 1000)) {
6697                                 /* Can't use the ts */
6698                                 bbr_log_type_bbrupd(bbr, 61, cts,
6699                                                     ts_diff,
6700                                                     bbr->r_ctl.last_inbound_ts,
6701                                                     rsm->r_del_ack_ts, 0,
6702                                                     0, 0, 0, delivered);
6703                         } else {
6704                                 ts_bw = (uint64_t)delivered;
6705                                 ts_bw *= (uint64_t)USECS_IN_SECOND;
6706                                 ts_bw /= ts_diff;
6707                                 bbr_log_type_bbrupd(bbr, 62, cts,
6708                                                     (ts_bw >> 32),
6709                                                     (ts_bw & 0xffffffff), 0, 0,
6710                                                     0, 0, ts_diff, delivered);
6711                                 if ((bbr->ts_can_raise) &&
6712                                     (ts_bw > bw)) {
6713                                         bbr_log_type_bbrupd(bbr, 8, cts,
6714                                                             delivered,
6715                                                             ts_diff,
6716                                                             (bw >> 32),
6717                                                             (bw & 0x00000000ffffffff),
6718                                                             0, 0, 0, 0);
6719                                         bw = ts_bw;
6720                                 } else if (ts_bw && (ts_bw < bw)) {
6721                                         bbr_log_type_bbrupd(bbr, 7, cts,
6722                                                             delivered,
6723                                                             ts_diff,
6724                                                             (bw >> 32),
6725                                                             (bw & 0x00000000ffffffff),
6726                                                             0, 0, 0, 0);
6727                                         bw = ts_bw;
6728                                 }
6729                         }
6730                 }
6731                 if (rsm->r_first_sent_time &&
6732                     TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6733                         uint64_t sbw, sti;
6734                         /*
6735                          * We use what was in flight at the time of our
6736                          * send  and the size of this send to figure
6737                          * out what we have been sending at (amount).
6738                          * For the time we take from the time of
6739                          * the send of the first send outstanding
6740                          * until this send plus this sends pacing
6741                          * time. This gives us a good calculation
6742                          * as to the rate we have been sending at.
6743                          */
6744
6745                         sbw = (uint64_t)(rsm->r_flight_at_send);
6746                         sbw *= (uint64_t)USECS_IN_SECOND;
6747                         sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6748                         sti += rsm->r_pacing_delay;
6749                         sbw /= sti;
6750                         if (sbw < bw) {
6751                                 bbr_log_type_bbrupd(bbr, 6, cts,
6752                                                     delivered,
6753                                                     (uint32_t)sti,
6754                                                     (bw >> 32),
6755                                                     (uint32_t)bw,
6756                                                     rsm->r_first_sent_time, 0, (sbw >> 32),
6757                                                     (uint32_t)sbw);
6758                                 bw = sbw;
6759                         }
6760                 }
6761                 /* Use the google algorithm for b/w measurements */
6762                 bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6763                 if ((rsm->r_app_limited == 0) ||
6764                     (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6765                         tcp_bbr_commit_bw(bbr, cts);
6766                         bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6767                                             0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6768                 }
6769         }
6770 }
6771
6772 static void
6773 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6774 {
6775         if (bbr->rc_in_persist == 0) {
6776                 /* We log only when not in persist */
6777                 /* Translate to a Bytes Per Second */
6778                 uint64_t tim, bw;
6779                 uint32_t upper, lower, delivered;
6780                 int no_apply = 0;
6781
6782                 if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6783                         tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6784                 else
6785                         tim = 1;
6786                 /* 
6787                  * Now that we have processed the tim (skipping the sample
6788                  * or possibly updating the time, go ahead and
6789                  * calculate the cdr.
6790                  */
6791                 delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6792                 bw = (uint64_t)delivered;
6793                 bw *= (uint64_t)USECS_IN_SECOND;
6794                 bw /= tim;
6795                 if (tim < bbr->r_ctl.rc_lowest_rtt) {
6796                         bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6797                                             tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6798
6799                         no_apply = 1;
6800                 }
6801                 upper = (bw >> 32) & 0x00000000ffffffff;
6802                 lower = bw & 0x00000000ffffffff;
6803                 /* 
6804                  * If we are using this b/w shove it in now so we
6805                  * can see in the trace viewer if it gets over-ridden.
6806                  */
6807                 bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6808                 /* Gate by the sending rate */
6809                 if (rsm->r_first_sent_time &&
6810                     TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6811                         uint64_t sbw, sti;
6812                         /*
6813                          * We use what was in flight at the time of our
6814                          * send  and the size of this send to figure
6815                          * out what we have been sending at (amount).
6816                          * For the time we take from the time of
6817                          * the send of the first send outstanding
6818                          * until this send plus this sends pacing
6819                          * time. This gives us a good calculation
6820                          * as to the rate we have been sending at.
6821                          */
6822
6823                         sbw = (uint64_t)(rsm->r_flight_at_send);
6824                         sbw *= (uint64_t)USECS_IN_SECOND;
6825                         sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6826                         sti += rsm->r_pacing_delay;
6827                         sbw /= sti;
6828                         if (sbw < bw) {
6829                                 bbr_log_type_bbrupd(bbr, 6, cts,
6830                                                     delivered,
6831                                                     (uint32_t)sti,
6832                                                     (bw >> 32),
6833                                                     (uint32_t)bw,
6834                                                     rsm->r_first_sent_time, 0, (sbw >> 32),
6835                                                     (uint32_t)sbw);
6836                                 bw = sbw;
6837                         }
6838                         if ((sti > tim) &&
6839                             (sti < bbr->r_ctl.rc_lowest_rtt)) {
6840                                 bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6841                                                     (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6842                                 no_apply = 1;
6843                         } else
6844                                 no_apply = 0;
6845                 }
6846                 bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6847                 if ((no_apply == 0) &&
6848                     ((rsm->r_app_limited == 0) ||
6849                      (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6850                         tcp_bbr_commit_bw(bbr, cts);
6851                         bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6852                                             0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6853                 }
6854         }
6855 }
6856
6857
6858 static void
6859 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6860     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6861 {
6862         uint64_t old_rttprop;
6863
6864         /* Update our delivery time and amount */
6865         bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6866         bbr->r_ctl.rc_del_time = cts;
6867         if (rtt == 0) {
6868                 /*
6869                  * 0 means its a retransmit, for now we don't use these for
6870                  * the rest of BBR.
6871                  */
6872                 return;
6873         }
6874         if ((bbr->rc_use_google == 0) &&
6875             (match != BBR_RTT_BY_EXACTMATCH) &&
6876             (match != BBR_RTT_BY_TIMESTAMP)){
6877                 /*
6878                  * We get a lot of rtt updates, lets not pay attention to
6879                  * any that are not an exact match. That way we don't have
6880                  * to worry about timestamps and the whole nonsense of
6881                  * unsure if its a retransmission etc (if we ever had the
6882                  * timestamp fixed to always have the last thing sent this
6883                  * would not be a issue).
6884                  */
6885                 return;
6886         }
6887         if ((bbr_no_retran && bbr->rc_use_google) &&
6888             (match != BBR_RTT_BY_EXACTMATCH) &&
6889             (match != BBR_RTT_BY_TIMESTAMP)){
6890                 /*
6891                  * We only do measurements in google mode
6892                  * with bbr_no_retran on for sure things.
6893                  */
6894                 return;
6895         }
6896         /* Only update srtt if we know by exact match */
6897         tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6898         if (ack_type == BBR_CUM_ACKED)
6899                 bbr->rc_ack_is_cumack = 1;
6900         else
6901                 bbr->rc_ack_is_cumack = 0;
6902         old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6903         /* 
6904          * Note the following code differs to the original
6905          * BBR spec. It calls for <= not <. However after a
6906          * long discussion in email with Neal, he acknowledged
6907          * that it should be < than so that we will have flows
6908          * going into probe-rtt (we were seeing cases where that
6909          * did not happen and caused ugly things to occur). We
6910          * have added this agreed upon fix to our code base.
6911          */
6912         if (rtt < old_rttprop) {
6913                 /* Update when we last saw a rtt drop */
6914                 bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6915                 bbr_set_reduced_rtt(bbr, cts, __LINE__);
6916         }
6917         bbr_log_type_bbrrttprop(bbr, rtt, (rsm ? rsm->r_end : 0), uts, cts,
6918             match, rsm->r_start, rsm->r_flags);
6919         apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6920         if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6921                 /*
6922                  * The RTT-prop moved, reset the target (may be a
6923                  * nop for some states).
6924                  */
6925                 bbr_set_state_target(bbr, __LINE__);
6926                 if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6927                         bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6928                                             __LINE__, BBR_RTTS_NEW_TARGET, 0);
6929                 else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6930                         /* It went up */
6931                         bbr_check_probe_rtt_limits(bbr, cts);
6932         }
6933         if ((bbr->rc_use_google == 0) &&
6934             (match == BBR_RTT_BY_TIMESTAMP)) {
6935                 /* 
6936                  * We don't do b/w update with
6937                  * these since they are not really
6938                  * reliable.
6939                  */
6940                 return;
6941         }
6942         if (bbr->r_ctl.r_app_limited_until &&
6943             (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6944                 /* We are no longer app-limited */
6945                 bbr->r_ctl.r_app_limited_until = 0;
6946         }
6947         if (bbr->rc_use_google) {
6948                 bbr_google_measurement(bbr, rsm, rtt, cts);
6949         } else {
6950                 bbr_nf_measurement(bbr, rsm, rtt, cts);
6951         }
6952 }
6953
6954 /*
6955  * Convert a timestamp that the main stack
6956  * uses (milliseconds) into one that bbr uses
6957  * (microseconds). Return that converted timestamp.
6958  */
6959 static uint32_t
6960 bbr_ts_convert(uint32_t cts) {
6961         uint32_t sec, msec;
6962
6963         sec = cts / MS_IN_USEC;
6964         msec = cts - (MS_IN_USEC * sec);
6965         return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6966 }
6967
6968 /*
6969  * Return 0 if we did not update the RTT time, return
6970  * 1 if we did.
6971  */
6972 static int
6973 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6974     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6975 {
6976         int32_t i;
6977         uint32_t t, uts = 0;
6978
6979         if ((rsm->r_flags & BBR_ACKED) ||
6980             (rsm->r_flags & BBR_WAS_RENEGED) ||
6981             (rsm->r_flags & BBR_RXT_CLEARED)) {
6982                 /* Already done */
6983                 return (0);
6984         }
6985         if (rsm->r_rtr_cnt == 1) {
6986                 /*
6987                  * Only one transmit. Hopefully the normal case.
6988                  */
6989                 if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6990                         t = cts - rsm->r_tim_lastsent[0];
6991                 else
6992                         t = 1;
6993                 if ((int)t <= 0)
6994                         t = 1;
6995                 bbr->r_ctl.rc_last_rtt = t;
6996                 bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6997                                     BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6998                 return (1);
6999         }
7000         /* Convert to usecs */
7001         if ((bbr_can_use_ts_for_rtt == 1) &&
7002             (bbr->rc_use_google == 1) &&
7003             (ack_type == BBR_CUM_ACKED) &&
7004             (to->to_flags & TOF_TS) &&
7005             (to->to_tsecr != 0)) {
7006
7007                 t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
7008                 if (t < 1)
7009                         t = 1;
7010                 t *= MS_IN_USEC;
7011                 bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
7012                                     BBR_RTT_BY_TIMESTAMP,
7013                                     rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
7014                                     ack_type, to);
7015                 return (1);
7016         }
7017         uts = bbr_ts_convert(to->to_tsecr);
7018         if ((to->to_flags & TOF_TS) &&
7019             (to->to_tsecr != 0) &&
7020             (ack_type == BBR_CUM_ACKED) &&
7021             ((rsm->r_flags & BBR_OVERMAX) == 0)) {
7022                 /*
7023                  * Now which timestamp does it match? In this block the ACK
7024                  * may be coming from a previous transmission.
7025                  */
7026                 uint32_t fudge;
7027
7028                 fudge = BBR_TIMER_FUDGE;
7029                 for (i = 0; i < rsm->r_rtr_cnt; i++) {
7030                         if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
7031                             (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
7032                                 if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
7033                                         t = cts - rsm->r_tim_lastsent[i];
7034                                 else
7035                                         t = 1;
7036                                 if ((int)t <= 0)
7037                                         t = 1;
7038                                 bbr->r_ctl.rc_last_rtt = t;
7039                                 bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
7040                                                     rsm->r_tim_lastsent[i], ack_type, to);
7041                                 if ((i + 1) < rsm->r_rtr_cnt) {
7042                                         /* Likely */
7043                                         bbr_earlier_retran(tp, bbr, rsm, t, cts, ack_type);
7044                                 } else if (rsm->r_flags & BBR_TLP) {
7045                                         bbr->rc_tlp_rtx_out = 0;
7046                                 }
7047                                 return (1);
7048                         }
7049                 }
7050                 /* Fall through if we can't find a matching timestamp */
7051         }
7052         /*
7053          * Ok its a SACK block that we retransmitted. or a windows
7054          * machine without timestamps. We can tell nothing from the
7055          * time-stamp since its not there or the time the peer last
7056          * recieved a segment that moved forward its cum-ack point.
7057          *
7058          * Lets look at the last retransmit and see what we can tell
7059          * (with BBR for space we only keep 2 note we have to keep
7060          * at least 2 so the map can not be condensed more).
7061          */
7062         i = rsm->r_rtr_cnt - 1;
7063         if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
7064                 t = cts - rsm->r_tim_lastsent[i];
7065         else
7066                 goto not_sure;
7067         if (t < bbr->r_ctl.rc_lowest_rtt) {
7068                 /*
7069                  * We retransmitted and the ack came back in less
7070                  * than the smallest rtt we have observed in the
7071                  * windowed rtt. We most likey did an improper
7072                  * retransmit as outlined in 4.2 Step 3 point 2 in
7073                  * the rack-draft.
7074                  *
7075                  * Use the prior transmission to update all the
7076                  * information as long as there is only one prior
7077                  * transmission.
7078                  */
7079                 if ((rsm->r_flags & BBR_OVERMAX) == 0) {
7080 #ifdef BBR_INVARIANTS
7081                         if (rsm->r_rtr_cnt == 1)
7082                                 panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
7083 #endif
7084                         i = rsm->r_rtr_cnt - 2;
7085                         if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
7086                                 t = cts - rsm->r_tim_lastsent[i];
7087                         else
7088                                 t = 1;
7089                         bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
7090                                             rsm->r_tim_lastsent[i], ack_type, to);
7091                         bbr_earlier_retran(tp, bbr, rsm, t, cts, ack_type);
7092                 } else {
7093                         /*
7094                          * Too many prior transmissions, just
7095                          * updated BBR delivered
7096                          */
7097 not_sure:
7098                         bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
7099                                             BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
7100                 }
7101         } else {
7102                 /*
7103                  * We retransmitted it and the retransmit did the
7104                  * job.
7105                  */
7106                 if (rsm->r_flags & BBR_TLP)
7107                         bbr->rc_tlp_rtx_out = 0;
7108                 if ((rsm->r_flags & BBR_OVERMAX) == 0)
7109                         bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
7110                                             BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
7111                 else
7112                         bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
7113                                             BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
7114                 return (1);
7115         }
7116         return (0);
7117 }
7118
7119 /*
7120  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
7121  */
7122 static void
7123 bbr_log_sack_passed(struct tcpcb *tp,
7124     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
7125 {
7126         struct bbr_sendmap *nrsm;
7127
7128         nrsm = rsm;
7129         TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
7130             bbr_head, r_tnext) {
7131                 if (nrsm == rsm) {
7132                         /* Skip orginal segment he is acked */
7133                         continue;
7134                 }
7135                 if (nrsm->r_flags & BBR_ACKED) {
7136                         /* Skip ack'd segments */
7137                         continue;
7138                 }
7139                 if (nrsm->r_flags & BBR_SACK_PASSED) {
7140                         /* 
7141                          * We found one that is already marked
7142                          * passed, we have been here before and
7143                          * so all others below this are marked.
7144                          */
7145                         break;
7146                 }
7147                 BBR_STAT_INC(bbr_sack_passed);
7148                 nrsm->r_flags |= BBR_SACK_PASSED;
7149                 if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
7150                     bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
7151                         bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
7152                         bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
7153                         nrsm->r_flags |= BBR_MARKED_LOST;
7154                 }
7155                 nrsm->r_flags &= ~BBR_WAS_SACKPASS;
7156         }
7157 }
7158
7159 /*
7160  * Returns the number of bytes that were
7161  * newly ack'd by sack blocks.
7162  */
7163 static uint32_t
7164 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
7165     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
7166 {
7167         int32_t times = 0;
7168         uint32_t start, end, maxseg, changed = 0;
7169         struct bbr_sendmap *rsm, *nrsm;
7170         int32_t used_ref = 1;
7171         uint8_t went_back = 0, went_fwd = 0;
7172
7173         maxseg = tp->t_maxseg - bbr->rc_last_options;
7174         start = sack->start;
7175         end = sack->end;
7176         rsm = *prsm;
7177         if (rsm == NULL)
7178                 used_ref = 0;
7179
7180         /* Do we locate the block behind where we last were? */
7181         if (rsm && SEQ_LT(start, rsm->r_start)) {
7182                 went_back = 1;
7183                 TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
7184                         if (SEQ_GEQ(start, rsm->r_start) &&
7185                             SEQ_LT(start, rsm->r_end)) {
7186                                 goto do_rest_ofb;
7187                         }
7188                 }
7189         }
7190 start_at_beginning:
7191         went_fwd = 1;
7192         /*
7193          * Ok lets locate the block where this guy is fwd from rsm (if its
7194          * set)
7195          */
7196         TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
7197                 if (SEQ_GEQ(start, rsm->r_start) &&
7198                     SEQ_LT(start, rsm->r_end)) {
7199                         break;
7200                 }
7201         }
7202 do_rest_ofb:
7203         if (rsm == NULL) {
7204                 /*
7205                  * This happens when we get duplicate sack blocks with the
7206                  * same end. For example SACK 4: 100 SACK 3: 100 The sort
7207                  * will not change there location so we would just start at
7208                  * the end of the first one and get lost.
7209                  */
7210                 if (tp->t_flags & TF_SENTFIN) {
7211                         /*
7212                          * Check to see if we have not logged the FIN that
7213                          * went out.
7214                          */
7215                         nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7216                         if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
7217                                 /*
7218                                  * Ok we did not get the FIN logged.
7219                                  */
7220                                 nrsm->r_end++;
7221                                 rsm = nrsm;
7222                                 goto do_rest_ofb;
7223                         }
7224                 }
7225                 if (times == 1) {
7226 #ifdef BBR_INVARIANTS
7227                         panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7228                             tp, bbr, sack, to, prsm);
7229 #else
7230                         goto out;
7231 #endif
7232                 }
7233                 times++;
7234                 BBR_STAT_INC(bbr_sack_proc_restart);
7235                 rsm = NULL;
7236                 goto start_at_beginning;
7237         }
7238         /* Ok we have an ACK for some piece of rsm */
7239         if (rsm->r_start != start) {
7240                 /*
7241                  * Need to split this in two pieces the before and after.
7242                  */
7243                 if (bbr_sack_mergable(rsm, start, end)) 
7244                         nrsm = bbr_alloc_full_limit(bbr);
7245                 else
7246                         nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7247                 if (nrsm == NULL) {
7248                         /* We could not allocate ignore the sack */
7249                         struct sackblk blk;
7250
7251                         blk.start = start;
7252                         blk.end = end;
7253                         sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7254                         goto out;
7255                 }
7256                 bbr_clone_rsm(bbr, nrsm, rsm, start);
7257                 TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7258                 if (rsm->r_in_tmap) {
7259                         TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7260                         nrsm->r_in_tmap = 1;
7261                 }
7262                 rsm->r_flags &= (~BBR_HAS_FIN);
7263                 rsm = nrsm;
7264         }
7265         if (SEQ_GEQ(end, rsm->r_end)) {
7266                 /*
7267                  * The end of this block is either beyond this guy or right
7268                  * at this guy.
7269                  */
7270                 if ((rsm->r_flags & BBR_ACKED) == 0) {
7271                         bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7272                         changed += (rsm->r_end - rsm->r_start);
7273                         bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7274                         bbr_log_sack_passed(tp, bbr, rsm);
7275                         if (rsm->r_flags & BBR_MARKED_LOST) {
7276                                 bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7277                         }
7278                         /* Is Reordering occuring? */
7279                         if (rsm->r_flags & BBR_SACK_PASSED) {
7280                                 BBR_STAT_INC(bbr_reorder_seen);
7281                                 bbr->r_ctl.rc_reorder_ts = cts;
7282                                 if (rsm->r_flags & BBR_MARKED_LOST) {
7283                                         bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7284                                         if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7285                                                 /* LT sampling also needs adjustment */
7286                                                 bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7287                                 }
7288                         }
7289                         rsm->r_flags |= BBR_ACKED;
7290                         rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7291                         if (rsm->r_in_tmap) {
7292                                 TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7293                                 rsm->r_in_tmap = 0;
7294                         }
7295                 }
7296                 bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7297                 if (end == rsm->r_end) {
7298                         /* This block only - done */
7299                         goto out;
7300                 }
7301                 /* There is more not coverend by this rsm move on */
7302                 start = rsm->r_end;
7303                 nrsm = TAILQ_NEXT(rsm, r_next);
7304                 rsm = nrsm;
7305                 times = 0;
7306                 goto do_rest_ofb;
7307         }
7308         if (rsm->r_flags & BBR_ACKED) {
7309                 /* Been here done that */
7310                 goto out;
7311         }
7312         /* Ok we need to split off this one at the tail */
7313         if (bbr_sack_mergable(rsm, start, end)) 
7314                 nrsm = bbr_alloc_full_limit(bbr);
7315         else
7316                 nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7317         if (nrsm == NULL) {
7318                 /* failed XXXrrs what can we do but loose the sack info? */
7319                 struct sackblk blk;
7320
7321                 blk.start = start;
7322                 blk.end = end;
7323                 sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7324                 goto out;
7325         }
7326         /* Clone it */
7327         bbr_clone_rsm(bbr, nrsm, rsm, end);
7328         /* The sack block does not cover this guy fully */
7329         rsm->r_flags &= (~BBR_HAS_FIN);
7330         TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7331         if (rsm->r_in_tmap) {
7332                 TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7333                 nrsm->r_in_tmap = 1;
7334         }
7335         nrsm->r_dupack = 0;
7336         bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7337         bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7338         changed += (rsm->r_end - rsm->r_start);
7339         bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7340         bbr_log_sack_passed(tp, bbr, rsm);
7341         /* Is Reordering occuring? */
7342         if (rsm->r_flags & BBR_MARKED_LOST) {
7343                 bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7344         }
7345         if (rsm->r_flags & BBR_SACK_PASSED) {
7346                 BBR_STAT_INC(bbr_reorder_seen);
7347                 bbr->r_ctl.rc_reorder_ts = cts;
7348                 if (rsm->r_flags & BBR_MARKED_LOST) {
7349                         bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7350                         if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7351                                 /* LT sampling also needs adjustment */
7352                                 bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7353                 }
7354         }
7355         rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7356         rsm->r_flags |= BBR_ACKED;
7357         if (rsm->r_in_tmap) {
7358                 TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7359                 rsm->r_in_tmap = 0;
7360         }
7361 out:
7362         if (rsm && (rsm->r_flags & BBR_ACKED)) {
7363                 /* 
7364                  * Now can we merge this newly acked
7365                  * block with either the previous or
7366                  * next block?
7367                  */
7368                 nrsm = TAILQ_NEXT(rsm, r_next);
7369                 if (nrsm &&
7370                     (nrsm->r_flags & BBR_ACKED)) {
7371                         /* yep this and next can be merged */
7372                         rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7373                 }
7374                 /* Now what about the previous? */
7375                 nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7376                 if (nrsm &&
7377                     (nrsm->r_flags & BBR_ACKED)) {
7378                         /* yep the previous and this can be merged */
7379                         rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7380                 }
7381         }
7382         if (used_ref == 0) {
7383                 BBR_STAT_INC(bbr_sack_proc_all);
7384         } else {
7385                 BBR_STAT_INC(bbr_sack_proc_short);
7386         }
7387         if (went_fwd && went_back) {
7388                 BBR_STAT_INC(bbr_sack_search_both);
7389         } else if (went_fwd) {
7390                 BBR_STAT_INC(bbr_sack_search_fwd);
7391         } else if (went_back) {
7392                 BBR_STAT_INC(bbr_sack_search_back);
7393         }
7394         /* Save off where the next seq is */
7395         if (rsm)
7396                 bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7397         else
7398                 bbr->r_ctl.rc_sacklast = NULL;
7399         *prsm = rsm;
7400         return (changed);
7401 }
7402
7403
7404 static void inline
7405 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7406 {
7407         struct bbr_sendmap *tmap;
7408
7409         BBR_STAT_INC(bbr_reneges_seen);
7410         tmap = NULL;
7411         while (rsm && (rsm->r_flags & BBR_ACKED)) {
7412                 /* Its no longer sacked, mark it so */
7413                 uint32_t oflags;
7414                 bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7415 #ifdef BBR_INVARIANTS
7416                 if (rsm->r_in_tmap) {
7417                         panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7418                             bbr, rsm, rsm->r_flags);
7419                 }
7420 #endif
7421                 oflags = rsm->r_flags;
7422                 if (rsm->r_flags & BBR_MARKED_LOST) {
7423                         bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7424                         bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7425                         if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7426                                 /* LT sampling also needs adjustment */
7427                                 bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7428                 }
7429                 rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7430                 rsm->r_flags |= BBR_WAS_RENEGED;
7431                 rsm->r_flags |= BBR_RXT_CLEARED;
7432                 bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7433                 /* Rebuild it into our tmap */
7434                 if (tmap == NULL) {
7435                         TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7436                         tmap = rsm;
7437                 } else {
7438                         TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7439                         tmap = rsm;
7440                 }
7441                 tmap->r_in_tmap = 1;
7442                 /*
7443                  * XXXrrs Delivered? Should we do anything here?
7444                  *
7445                  * Of course we don't on a rxt timeout so maybe its ok that
7446                  * we don't?
7447                  *
7448                  * For now lets not.
7449                  */
7450                 rsm = TAILQ_NEXT(rsm, r_next);
7451         }
7452         /*
7453          * Now lets possibly clear the sack filter so we start recognizing
7454          * sacks that cover this area.
7455          */
7456         sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7457 }
7458
7459 static void
7460 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7461 {
7462         struct tcp_bbr *bbr;
7463         struct bbr_sendmap *rsm;
7464         uint32_t cts;
7465         
7466         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7467         cts = bbr->r_ctl.rc_rcvtime;
7468         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7469         if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7470                 if ((rsm->r_end - rsm->r_start) <= 1) {
7471                         /* Log out the SYN completely */
7472                         bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7473                         rsm->r_rtr_bytes = 0;
7474                         TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7475                         if (rsm->r_in_tmap) {
7476                                 TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7477                                 rsm->r_in_tmap = 0;
7478                         }
7479                         if (bbr->r_ctl.rc_next == rsm) {
7480                                 /* scoot along the marker */
7481                                 bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7482                         }
7483                         if (to != NULL)
7484                                 bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7485                         bbr_free(bbr, rsm);
7486                 } else {
7487                         /* There is more (Fast open)? strip out SYN. */
7488                         rsm->r_flags &= ~BBR_HAS_SYN;
7489                         rsm->r_start++;
7490                 }
7491         }
7492 }
7493
7494 /*
7495  * Returns the number of bytes that were
7496  * acknowledged by SACK blocks.
7497  */
7498
7499 static uint32_t
7500 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7501     uint32_t *prev_acked)
7502 {
7503         uint32_t changed, last_seq, entered_recovery = 0;
7504         struct tcp_bbr *bbr;
7505         struct bbr_sendmap *rsm;
7506         struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7507         register uint32_t th_ack;
7508         int32_t i, j, k, new_sb, num_sack_blks = 0;
7509         uint32_t cts, acked, ack_point, sack_changed = 0;
7510         uint32_t p_maxseg, maxseg, p_acked = 0;
7511
7512         INP_WLOCK_ASSERT(tp->t_inpcb);
7513         if (th->th_flags & TH_RST) {
7514                 /* We don't log resets */
7515                 return (0);
7516         }
7517         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7518         cts = bbr->r_ctl.rc_rcvtime;
7519
7520         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7521         changed = 0;
7522         maxseg = tp->t_maxseg - bbr->rc_last_options;
7523         p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7524         th_ack = th->th_ack;
7525         if (SEQ_GT(th_ack, tp->snd_una)) {
7526                 acked = th_ack - tp->snd_una;
7527                 bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7528                 bbr->rc_tp->t_acktime = ticks;
7529         } else 
7530                 acked = 0;
7531         if (SEQ_LEQ(th_ack, tp->snd_una)) {
7532                 /* Only sent here for sack processing */
7533                 goto proc_sack;
7534         }
7535         if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7536                 changed = th_ack - rsm->r_start;
7537         } else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7538                 /*
7539                  * For the SYN incoming case we will not have called
7540                  * tcp_output for the sending of the SYN, so there will be
7541                  * no map. All other cases should probably be a panic.
7542                  */
7543                 if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7544                         /*
7545                          * We have a timestamp that can be used to generate
7546                          * an initial RTT.
7547                          */
7548                         uint32_t ts, now, rtt;
7549
7550                         ts = bbr_ts_convert(to->to_tsecr);
7551                         now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7552                         rtt = now - ts;
7553                         if (rtt < 1)
7554                                 rtt = 1;
7555                         bbr_log_type_bbrrttprop(bbr, rtt,
7556                                                 tp->iss, 0, cts,
7557                                                 BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7558                         apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7559                         changed = 1;
7560                         bbr->r_wanted_output = 1;
7561                         goto out;
7562                 }
7563                 goto proc_sack;
7564         } else if (rsm == NULL) {
7565                 goto out;
7566         }
7567         if (changed) {
7568                 /*
7569                  * The ACK point is advancing to th_ack, we must drop off
7570                  * the packets in the rack log and calculate any eligble
7571                  * RTT's.
7572                  */
7573                 bbr->r_wanted_output = 1;
7574 more:
7575                 if (rsm == NULL) {
7576
7577                         if (tp->t_flags & TF_SENTFIN) {
7578                                 /* if we send a FIN we will not hav a map */
7579                                 goto proc_sack;
7580                         }
7581 #ifdef BBR_INVARIANTS
7582                         panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7583                             tp,
7584                             th, tp->t_state, bbr,
7585                             tp->snd_una, tp->snd_max, changed);
7586 #endif
7587                         goto proc_sack;
7588                 }
7589         }
7590         if (SEQ_LT(th_ack, rsm->r_start)) {
7591                 /* Huh map is missing this */
7592 #ifdef BBR_INVARIANTS
7593                 printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7594                     rsm->r_start,
7595                     th_ack, tp->t_state,
7596                     bbr->r_state, bbr);
7597                 panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7598 #endif
7599                 goto proc_sack;
7600         } else if (th_ack == rsm->r_start) {
7601                 /* None here to ack */
7602                 goto proc_sack;
7603         }
7604         /* 
7605          * Clear the dup ack counter, it will
7606          * either be freed or if there is some
7607          * remaining we need to start it at zero.
7608          */
7609         rsm->r_dupack = 0;
7610         /* Now do we consume the whole thing? */
7611         if (SEQ_GEQ(th_ack, rsm->r_end)) {
7612                 /* Its all consumed. */
7613                 uint32_t left;
7614
7615                 if (rsm->r_flags & BBR_ACKED) {
7616                         /*
7617                          * It was acked on the scoreboard -- remove it from
7618                          * total
7619                          */
7620                         p_acked += (rsm->r_end - rsm->r_start);
7621                         bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7622                         if (bbr->r_ctl.rc_sacked == 0)
7623                                 bbr->r_ctl.rc_sacklast = NULL;
7624                 } else {
7625                         bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7626                         if (rsm->r_flags & BBR_MARKED_LOST) {
7627                                 bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7628                         }
7629                         if (rsm->r_flags & BBR_SACK_PASSED) {
7630                                 /*
7631                                  * There are acked segments ACKED on the
7632                                  * scoreboard further up. We are seeing
7633                                  * reordering.
7634                                  */
7635                                 BBR_STAT_INC(bbr_reorder_seen);
7636                                 bbr->r_ctl.rc_reorder_ts = cts;
7637                                 if (rsm->r_flags & BBR_MARKED_LOST) {
7638                                         bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7639                                         if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7640                                                 /* LT sampling also needs adjustment */
7641                                                 bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7642                                 }
7643                         }
7644                         rsm->r_flags &= ~BBR_MARKED_LOST;
7645                 }
7646                 bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7647                 rsm->r_rtr_bytes = 0;
7648                 TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7649                 if (rsm->r_in_tmap) {
7650                         TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7651                         rsm->r_in_tmap = 0;
7652                 }
7653                 if (bbr->r_ctl.rc_next == rsm) {
7654                         /* scoot along the marker */
7655                         bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7656                 }
7657                 bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7658                 /* Adjust the packet counts */
7659                 left = th_ack - rsm->r_end;
7660                 /* Free back to zone */
7661                 bbr_free(bbr, rsm);
7662                 if (left) {
7663                         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7664                         goto more;
7665                 }
7666                 goto proc_sack;
7667         }
7668         if (rsm->r_flags & BBR_ACKED) {
7669                 /*
7670                  * It was acked on the scoreboard -- remove it from total
7671                  * for the part being cum-acked.
7672                  */
7673                 p_acked += (rsm->r_end - rsm->r_start);
7674                 bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7675                 if (bbr->r_ctl.rc_sacked == 0)
7676                         bbr->r_ctl.rc_sacklast = NULL;
7677         } else {
7678                 /*
7679                  * It was acked up to th_ack point for the first time
7680                  */
7681                 struct bbr_sendmap lrsm;
7682
7683                 memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7684                 lrsm.r_end = th_ack;
7685                 bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7686         }
7687         if ((rsm->r_flags & BBR_MARKED_LOST) &&
7688             ((rsm->r_flags & BBR_ACKED) == 0)) {
7689                 /* 
7690                  * It was marked lost and partly ack'd now 
7691                  * for the first time. We lower the rc_lost_bytes
7692                  * and still leave it MARKED.
7693                  */
7694                 bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7695         }
7696         bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7697         bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7698         rsm->r_rtr_bytes = 0;
7699         /* adjust packet count */
7700         rsm->r_start = th_ack;
7701 proc_sack:
7702         /* Check for reneging */
7703         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7704         if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7705                 /*
7706                  * The peer has moved snd_una up to the edge of this send,
7707                  * i.e. one that it had previously acked. The only way that
7708                  * can be true if the peer threw away data (space issues)
7709                  * that it had previously sacked (else it would have given
7710                  * us snd_una up to (rsm->r_end). We need to undo the acked
7711                  * markings here.
7712                  *
7713                  * Note we have to look to make sure th_ack is our
7714                  * rsm->r_start in case we get an old ack where th_ack is
7715                  * behind snd_una.
7716                  */
7717                 bbr_peer_reneges(bbr, rsm, th->th_ack);
7718         }
7719         if ((to->to_flags & TOF_SACK) == 0) {
7720                 /* We are done nothing left to log */
7721                 goto out;
7722         }
7723         rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7724         if (rsm) {
7725                 last_seq = rsm->r_end;
7726         } else {
7727                 last_seq = tp->snd_max;
7728         }
7729         /* Sack block processing */
7730         if (SEQ_GT(th_ack, tp->snd_una))
7731                 ack_point = th_ack;
7732         else
7733                 ack_point = tp->snd_una;
7734         for (i = 0; i < to->to_nsacks; i++) {
7735                 bcopy((to->to_sacks + i * TCPOLEN_SACK),
7736                     &sack, sizeof(sack));
7737                 sack.start = ntohl(sack.start);
7738                 sack.end = ntohl(sack.end);
7739                 if (SEQ_GT(sack.end, sack.start) &&
7740                     SEQ_GT(sack.start, ack_point) &&
7741                     SEQ_LT(sack.start, tp->snd_max) &&
7742                     SEQ_GT(sack.end, ack_point) &&
7743                     SEQ_LEQ(sack.end, tp->snd_max)) {
7744                         if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7745                             (SEQ_LT(sack.end, last_seq)) &&
7746                             ((sack.end - sack.start) < (p_maxseg / 8))) {
7747                                 /*
7748                                  * Not the last piece and its smaller than
7749                                  * 1/8th of a p_maxseg. We ignore this.
7750                                  */
7751                                 BBR_STAT_INC(bbr_runt_sacks);
7752                                 continue;
7753                         }
7754                         sack_blocks[num_sack_blks] = sack;
7755                         num_sack_blks++;
7756 #ifdef NETFLIX_STATS
7757                 } else if (SEQ_LEQ(sack.start, th_ack) &&
7758                     SEQ_LEQ(sack.end, th_ack)) {
7759                         /*
7760                          * Its a D-SACK block.
7761                          */
7762                         tcp_record_dsack(sack.start, sack.end);
7763 #endif
7764                 }
7765         }
7766         if (num_sack_blks == 0)
7767                 goto out;
7768         /*
7769          * Sort the SACK blocks so we can update the rack scoreboard with
7770          * just one pass.
7771          */
7772         new_sb = sack_filter_blks(&bbr->r_ctl.bbr_sf, sack_blocks,
7773                                   num_sack_blks, th->th_ack);
7774         ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7775         BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7776         BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7777         num_sack_blks = new_sb;
7778         if (num_sack_blks < 2) {
7779                 goto do_sack_work;
7780         }
7781         /* Sort the sacks */
7782         for (i = 0; i < num_sack_blks; i++) {
7783                 for (j = i + 1; j < num_sack_blks; j++) {
7784                         if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7785                                 sack = sack_blocks[i];
7786                                 sack_blocks[i] = sack_blocks[j];
7787                                 sack_blocks[j] = sack;
7788                         }
7789                 }
7790         }
7791         /*
7792          * Now are any of the sack block ends the same (yes some
7793          * implememtations send these)?
7794          */
7795 again:
7796         if (num_sack_blks > 1) {
7797                 for (i = 0; i < num_sack_blks; i++) {
7798                         for (j = i + 1; j < num_sack_blks; j++) {
7799                                 if (sack_blocks[i].end == sack_blocks[j].end) {
7800                                         /*
7801                                          * Ok these two have the same end we
7802                                          * want the smallest end and then
7803                                          * throw away the larger and start
7804                                          * again.
7805                                          */
7806                                         if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7807                                                 /*
7808                                                  * The second block covers
7809                                                  * more area use that
7810                                                  */
7811                                                 sack_blocks[i].start = sack_blocks[j].start;
7812                                         }
7813                                         /*
7814                                          * Now collapse out the dup-sack and
7815                                          * lower the count
7816                                          */
7817                                         for (k = (j + 1); k < num_sack_blks; k++) {
7818                                                 sack_blocks[j].start = sack_blocks[k].start;
7819                                                 sack_blocks[j].end = sack_blocks[k].end;
7820                                                 j++;
7821                                         }
7822                                         num_sack_blks--;
7823                                         goto again;
7824                                 }
7825                         }
7826                 }
7827         }
7828 do_sack_work:
7829         rsm = bbr->r_ctl.rc_sacklast;
7830         for (i = 0; i < num_sack_blks; i++) {
7831                 acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7832                 if (acked) {
7833                         bbr->r_wanted_output = 1;
7834                         changed += acked;
7835                         sack_changed += acked;
7836                 }
7837         }
7838 out:
7839         *prev_acked = p_acked;
7840         if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7841                 /*
7842                  * Ok we have a high probability that we need to go in to
7843                  * recovery since we have data sack'd
7844                  */
7845                 struct bbr_sendmap *rsm;
7846
7847                 rsm = bbr_check_recovery_mode(tp, bbr, cts);
7848                 if (rsm) {
7849                         /* Enter recovery */
7850                         entered_recovery = 1;
7851                         bbr->r_wanted_output = 1;
7852                         /*
7853                          * When we enter recovery we need to assure we send
7854                          * one packet.
7855                          */
7856                         if (bbr->r_ctl.rc_resend == NULL) {
7857                                 bbr->r_ctl.rc_resend = rsm;
7858                         }
7859                 }
7860         }
7861         if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7862                 /*
7863                  * See if we need to rack-retransmit anything if so set it
7864                  * up as the thing to resend assuming something else is not
7865                  * already in that position.
7866                  */
7867                 if (bbr->r_ctl.rc_resend == NULL) {
7868                         bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7869                 }
7870         }
7871         /*
7872          * We return the amount that changed via sack, this is used by the
7873          * ack-received code to augment what was changed between th_ack <->
7874          * snd_una.
7875          */
7876         return (sack_changed);
7877 }
7878
7879 static void
7880 bbr_strike_dupack(struct tcp_bbr *bbr)
7881 {
7882         struct bbr_sendmap *rsm;
7883
7884         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7885         if (rsm && (rsm->r_dupack < 0xff)) {
7886                 rsm->r_dupack++;
7887                 if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7888                         bbr->r_wanted_output = 1;
7889         }
7890 }
7891
7892 /*
7893  * Return value of 1, we do not need to call bbr_process_data().
7894  * return value of 0, bbr_process_data can be called.
7895  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7896  * its unlocked and probably unsafe to touch the TCB.
7897  */
7898 static int
7899 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7900     struct tcpcb *tp, struct tcpopt *to,
7901     uint32_t tiwin, int32_t tlen,
7902     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7903 {
7904         int32_t ourfinisacked = 0;
7905         int32_t acked_amount;
7906         uint16_t nsegs;
7907         int32_t acked;
7908         uint32_t lost, sack_changed = 0;
7909         struct mbuf *mfree;
7910         struct tcp_bbr *bbr;
7911         uint32_t prev_acked = 0;
7912
7913         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7914         lost = bbr->r_ctl.rc_lost;
7915         nsegs = max(1, m->m_pkthdr.lro_nsegs);
7916         if (SEQ_GT(th->th_ack, tp->snd_max)) {
7917                 ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7918                 bbr->r_wanted_output = 1;
7919                 return (1);
7920         }
7921         if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7922                 /* Process the ack */
7923                 if (bbr->rc_in_persist)
7924                         tp->t_rxtshift = 0;
7925                 if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7926                         bbr_strike_dupack(bbr);
7927                 sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7928         }
7929         bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7930         if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7931                 /*
7932                  * Old ack, behind the last one rcv'd or a duplicate ack
7933                  * with SACK info.
7934                  */
7935                 if (th->th_ack == tp->snd_una) {
7936                         bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7937                         if (bbr->r_state == TCPS_SYN_SENT) {
7938                                 /*
7939                                  * Special case on where we sent SYN. When
7940                                  * the SYN-ACK is processed in syn_sent
7941                                  * state it bumps the snd_una. This causes
7942                                  * us to hit here even though we did ack 1
7943                                  * byte.
7944                                  *
7945                                  * Go through the nothing left case so we
7946                                  * send data.
7947                                  */
7948                                 goto nothing_left;
7949                         }
7950                 }
7951                 return (0);
7952         }
7953         /*
7954          * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7955          * something we sent.
7956          */
7957         if (tp->t_flags & TF_NEEDSYN) {
7958                 /*
7959                  * T/TCP: Connection was half-synchronized, and our SYN has
7960                  * been ACK'd (so connection is now fully synchronized).  Go
7961                  * to non-starred state, increment snd_una for ACK of SYN,
7962                  * and check if we can do window scaling.
7963                  */
7964                 tp->t_flags &= ~TF_NEEDSYN;
7965                 tp->snd_una++;
7966                 /* Do window scaling? */
7967                 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7968                     (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7969                         tp->rcv_scale = tp->request_r_scale;
7970                         /* Send window already scaled. */
7971                 }
7972         }
7973         INP_WLOCK_ASSERT(tp->t_inpcb);
7974
7975         acked = BYTES_THIS_ACK(tp, th);
7976         TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7977         TCPSTAT_ADD(tcps_rcvackbyte, acked);
7978
7979         /*
7980          * If we just performed our first retransmit, and the ACK arrives
7981          * within our recovery window, then it was a mistake to do the
7982          * retransmit in the first place.  Recover our original cwnd and
7983          * ssthresh, and proceed to transmit where we left off.
7984          */
7985         if (tp->t_flags & TF_PREVVALID) {
7986                 tp->t_flags &= ~TF_PREVVALID;
7987                 if (tp->t_rxtshift == 1 &&
7988                     (int)(ticks - tp->t_badrxtwin) < 0)
7989                         bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7990         }
7991         SOCKBUF_LOCK(&so->so_snd);
7992         acked_amount = min(acked, (int)sbavail(&so->so_snd));
7993         tp->snd_wnd -= acked_amount;
7994         mfree = sbcut_locked(&so->so_snd, acked_amount);
7995         /* NB: sowwakeup_locked() does an implicit unlock. */
7996         sowwakeup_locked(so);
7997         m_freem(mfree);
7998         if (SEQ_GT(th->th_ack, tp->snd_una)) {
7999                 bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8000         }
8001         tp->snd_una = th->th_ack;
8002         bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
8003         if (IN_RECOVERY(tp->t_flags)) {
8004                 if (SEQ_LT(th->th_ack, tp->snd_recover) &&
8005                     (SEQ_LT(th->th_ack, tp->snd_max))) {
8006                         tcp_bbr_partialack(tp);
8007                 } else {
8008                         bbr_post_recovery(tp);
8009                 }
8010         }
8011         if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8012                 tp->snd_recover = tp->snd_una;
8013         }
8014         if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
8015                 tp->snd_nxt = tp->snd_max;
8016         }
8017         if (tp->snd_una == tp->snd_max) {
8018                 /* Nothing left outstanding */
8019 nothing_left:
8020                 bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8021                 if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
8022                         bbr->rc_tp->t_acktime = 0;
8023                 if ((sbused(&so->so_snd) == 0) &&
8024                     (tp->t_flags & TF_SENTFIN)) {
8025                         ourfinisacked = 1;
8026                 }
8027                 bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8028                 if (bbr->rc_in_persist == 0) {
8029                         bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8030                 }
8031                 sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8032                 bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8033                 /* 
8034                  * We invalidate the last ack here since we
8035                  * don't want to transfer forward the time
8036                  * for our sum's calculations.
8037                  */
8038                 if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
8039                     (sbavail(&so->so_snd) == 0) &&
8040                     (tp->t_flags2 & TF2_DROP_AF_DATA)) {
8041                         /*
8042                          * The socket was gone and the peer sent data, time
8043                          * to reset him.
8044                          */
8045                         *ret_val = 1;
8046                         tp = tcp_close(tp);
8047                         ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
8048                         BBR_STAT_INC(bbr_dropped_af_data);
8049                         return (1);
8050                 }
8051                 /* Set need output so persist might get set */
8052                 bbr->r_wanted_output = 1;
8053         }
8054         if (ofia)
8055                 *ofia = ourfinisacked;
8056         return (0);
8057 }
8058
8059 static void
8060 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
8061 {
8062         if (bbr->rc_in_persist == 0) {
8063                 bbr_timer_cancel(bbr, __LINE__, cts);
8064                 bbr->r_ctl.rc_last_delay_val = 0;
8065                 tp->t_rxtshift = 0;
8066                 bbr->rc_in_persist = 1;
8067                 bbr->r_ctl.rc_went_idle_time = cts;
8068                 /* We should be capped when rw went to 0 but just in case */
8069                 bbr_log_type_pesist(bbr, cts, 0, line, 1);
8070                 /* Time freezes for the state, so do the accounting now */
8071                 if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
8072                         uint32_t time_in;
8073
8074                         time_in = cts - bbr->r_ctl.rc_bbr_state_time;
8075                         if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
8076                                 int32_t idx;
8077
8078                                 idx = bbr_state_val(bbr);
8079                                 counter_u64_add(bbr_state_time[(idx + 5)], time_in);
8080                         } else {
8081                                 counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
8082                         }
8083                 }
8084                 bbr->r_ctl.rc_bbr_state_time = cts;
8085         }
8086 }
8087
8088 static void
8089 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
8090 {
8091         /*
8092          * Note that if idle time does not exceed our
8093          * threshold, we do nothing continuing the state
8094          * transitions we were last walking through.
8095          */ 
8096         if (idle_time >= bbr_idle_restart_threshold) {
8097                 if (bbr->rc_use_idle_restart) {
8098                         bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
8099                         /* 
8100                          * Set our target using BBR_UNIT, so
8101                          * we increase at a dramatic rate but
8102                          * we stop when we get the pipe
8103                          * full again for our current b/w estimate.
8104                          */
8105                         bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
8106                         bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
8107                         bbr_set_state_target(bbr, __LINE__);
8108                         /* Now setup our gains to ramp up */
8109                         bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
8110                         bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
8111                         bbr_log_type_statechange(bbr, cts, __LINE__);
8112                 } else {
8113                         bbr_substate_change(bbr, cts, __LINE__, 1);
8114                 }
8115         }
8116 }
8117
8118 static void
8119 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
8120 {
8121         uint32_t idle_time;
8122
8123         if (bbr->rc_in_persist == 0)
8124                 return;
8125         idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
8126         bbr->rc_in_persist = 0;
8127         bbr->rc_hit_state_1 = 0;
8128         tp->t_flags &= ~TF_FORCEDATA;
8129         bbr->r_ctl.rc_del_time = cts;
8130         /* 
8131          * We invalidate the last ack here since we
8132          * don't want to transfer forward the time
8133          * for our sum's calculations.
8134          */
8135         if (bbr->rc_inp->inp_in_hpts) {
8136                 tcp_hpts_remove(bbr->rc_inp, HPTS_REMOVE_OUTPUT);
8137                 bbr->rc_timer_first = 0;
8138                 bbr->r_ctl.rc_hpts_flags = 0;
8139                 bbr->r_ctl.rc_last_delay_val = 0;
8140                 bbr->r_ctl.rc_hptsi_agg_delay = 0;
8141                 bbr->r_agg_early_set = 0;
8142                 bbr->r_ctl.rc_agg_early = 0;
8143         }
8144         bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
8145         if (idle_time >= bbr_rtt_probe_time) {
8146                 /*
8147                  * This qualifies as a RTT_PROBE session since we drop the
8148                  * data outstanding to nothing and waited more than
8149                  * bbr_rtt_probe_time.
8150                  */
8151                 bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
8152                 bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
8153         }
8154         tp->t_rxtshift = 0;
8155         /*
8156          * If in probeBW and we have persisted more than an RTT lets do
8157          * special handling.
8158          */
8159         /* Force a time based epoch */
8160         bbr_set_epoch(bbr, cts, __LINE__);
8161         /*
8162          * Setup the lost so we don't count anything against the guy
8163          * we have been stuck with during persists.
8164          */
8165         bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
8166         /* Time un-freezes for the state */
8167         bbr->r_ctl.rc_bbr_state_time = cts;
8168         if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
8169             (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
8170                 /* 
8171                  * If we are going back to probe-bw
8172                  * or probe_rtt, we may need to possibly
8173                  * do a fast restart.
8174                  */
8175                 bbr_restart_after_idle(bbr, cts, idle_time);
8176         }
8177 }
8178
8179 static void
8180 bbr_collapsed_window(struct tcp_bbr *bbr)
8181 {
8182         /*
8183          * Now we must walk the
8184          * send map and divide the 
8185          * ones left stranded. These
8186          * guys can't cause us to abort
8187          * the connection and are really
8188          * "unsent". However if a buggy
8189          * client actually did keep some
8190          * of the data i.e. collapsed the win
8191          * and refused to ack and then opened
8192          * the win and acked that data. We would
8193          * get into an ack war, the simplier
8194          * method then of just pretending we
8195          * did not send those segments something 
8196          * won't work.
8197          */
8198         struct bbr_sendmap *rsm, *nrsm;
8199         tcp_seq max_seq;
8200         uint32_t maxseg;
8201         int can_split = 0;
8202         int fnd = 0;
8203
8204         maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
8205         max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
8206         bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
8207         TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
8208                 /* Find the first seq past or at maxseq */
8209                 if (rsm->r_flags & BBR_RWND_COLLAPSED)
8210                         rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8211                 if (SEQ_GEQ(max_seq, rsm->r_start) &&
8212                     SEQ_GEQ(rsm->r_end, max_seq)) {
8213                         fnd = 1;
8214                         break;
8215                 }
8216         }
8217         bbr->rc_has_collapsed = 0;
8218         if (!fnd) {
8219                 /* Nothing to do strange */
8220                 return;
8221         }
8222         /* 
8223          * Now can we split? 
8224          *
8225          * We don't want to split if splitting
8226          * would generate too many small segments
8227          * less we let an attacker fragment our
8228          * send_map and leave us out of memory.
8229          */
8230         if ((max_seq != rsm->r_start) &&
8231             (max_seq != rsm->r_end)){
8232                 /* can we split? */
8233                 int res1, res2;
8234
8235                 res1 = max_seq - rsm->r_start;
8236                 res2 = rsm->r_end - max_seq;
8237                 if ((res1 >= (maxseg/8)) &&
8238                     (res2 >= (maxseg/8))) {
8239                         /* No small pieces here */
8240                         can_split = 1;
8241                 } else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8242                         /* We are under the limit */
8243                         can_split = 1;
8244                 }
8245         }
8246         /* Ok do we need to split this rsm? */
8247         if (max_seq == rsm->r_start) {
8248                 /* It's this guy no split required */
8249                 nrsm = rsm;
8250         } else if (max_seq == rsm->r_end) {
8251                 /* It's the next one no split required. */
8252                 nrsm = TAILQ_NEXT(rsm, r_next);
8253                 if (nrsm == NULL) {
8254                         /* Huh? */
8255                         return;
8256                 }
8257         } else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8258                 /* yep we need to split it */
8259                 nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8260                 if (nrsm == NULL) {
8261                         /* failed XXXrrs what can we do mark the whole? */
8262                         nrsm = rsm;
8263                         goto no_split;
8264                 }
8265                 /* Clone it */
8266                 bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8267                 bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8268                 TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8269                 if (rsm->r_in_tmap) {
8270                         TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8271                         nrsm->r_in_tmap = 1;
8272                 }
8273         } else {
8274                 /* 
8275                  * Split not allowed just start here just
8276                  * use this guy.
8277                  */
8278                 nrsm = rsm;
8279         }
8280 no_split:
8281         BBR_STAT_INC(bbr_collapsed_win);
8282         /* reuse fnd as a count */
8283         fnd = 0;
8284         TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8285                 nrsm->r_flags |= BBR_RWND_COLLAPSED;
8286                 fnd++;
8287                 bbr->rc_has_collapsed = 1;
8288         }
8289         bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8290 }
8291
8292 static void
8293 bbr_un_collapse_window(struct tcp_bbr *bbr)
8294 {
8295         struct bbr_sendmap *rsm;
8296         int cleared = 0;
8297         
8298         TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8299                 if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8300                         /* Clear the flag */
8301                         rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8302                         cleared++;
8303                 } else
8304                         break;
8305         }
8306         bbr_log_type_rwnd_collapse(bbr,
8307                                    (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8308         bbr->rc_has_collapsed = 0;
8309 }
8310
8311 /*
8312  * Return value of 1, the TCB is unlocked and most
8313  * likely gone, return value of 0, the TCB is still
8314  * locked.
8315  */
8316 static int
8317 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8318     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8319     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8320 {
8321         /*
8322          * Update window information. Don't look at window if no ACK: TAC's
8323          * send garbage on first SYN.
8324          */
8325         uint16_t nsegs;
8326         int32_t tfo_syn;
8327         struct tcp_bbr *bbr;
8328
8329         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8330         INP_WLOCK_ASSERT(tp->t_inpcb);
8331         nsegs = max(1, m->m_pkthdr.lro_nsegs);
8332         if ((thflags & TH_ACK) &&
8333             (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8334             (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8335             (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8336                 /* keep track of pure window updates */
8337                 if (tlen == 0 &&
8338                     tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8339                         TCPSTAT_INC(tcps_rcvwinupd);
8340                 tp->snd_wnd = tiwin;
8341                 tp->snd_wl1 = th->th_seq;
8342                 tp->snd_wl2 = th->th_ack;
8343                 if (tp->snd_wnd > tp->max_sndwnd)
8344                         tp->max_sndwnd = tp->snd_wnd;
8345                 bbr->r_wanted_output = 1;
8346         } else if (thflags & TH_ACK) {
8347                 if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8348                         tp->snd_wnd = tiwin;
8349                         tp->snd_wl1 = th->th_seq;
8350                         tp->snd_wl2 = th->th_ack;
8351                 }
8352         }
8353         if (tp->snd_wnd < ctf_outstanding(tp))
8354                 /* The peer collapsed its window on us */
8355                 bbr_collapsed_window(bbr);
8356         else if (bbr->rc_has_collapsed)
8357                 bbr_un_collapse_window(bbr);
8358         /* Was persist timer active and now we have window space? */
8359         if ((bbr->rc_in_persist != 0) &&
8360             (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8361                                 bbr_minseg(bbr)))) {
8362                 /*
8363                  * Make the rate persist at end of persist mode if idle long
8364                  * enough
8365                  */
8366                 bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8367
8368                 /* Make sure we output to start the timer */
8369                 bbr->r_wanted_output = 1;
8370         }
8371         /* Do we need to enter persist? */
8372         if ((bbr->rc_in_persist == 0) &&
8373             (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8374             TCPS_HAVEESTABLISHED(tp->t_state) &&
8375             (tp->snd_max == tp->snd_una) &&
8376             sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
8377             (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
8378                 /* No send window.. we must enter persist */
8379                 bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8380         }
8381         if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8382                 m_freem(m);
8383                 return (0);
8384         }
8385         /*
8386          * Process segments with URG.
8387          */
8388         if ((thflags & TH_URG) && th->th_urp &&
8389             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8390                 /*
8391                  * This is a kludge, but if we receive and accept random
8392                  * urgent pointers, we'll crash in soreceive.  It's hard to
8393                  * imagine someone actually wanting to send this much urgent
8394                  * data.
8395                  */
8396                 SOCKBUF_LOCK(&so->so_rcv);
8397                 if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
8398                         th->th_urp = 0; /* XXX */
8399                         thflags &= ~TH_URG;     /* XXX */
8400                         SOCKBUF_UNLOCK(&so->so_rcv);    /* XXX */
8401                         goto dodata;    /* XXX */
8402                 }
8403                 /*
8404                  * If this segment advances the known urgent pointer, then
8405                  * mark the data stream.  This should not happen in
8406                  * CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since a
8407                  * FIN has been received from the remote side. In these
8408                  * states we ignore the URG.
8409                  *
8410                  * According to RFC961 (Assigned Protocols), the urgent
8411                  * pointer points to the last octet of urgent data.  We
8412                  * continue, however, to consider it to indicate the first
8413                  * octet of data past the urgent section as the original
8414                  * spec states (in one of two places).
8415                  */
8416                 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
8417                         tp->rcv_up = th->th_seq + th->th_urp;
8418                         so->so_oobmark = sbavail(&so->so_rcv) +
8419                             (tp->rcv_up - tp->rcv_nxt) - 1;
8420                         if (so->so_oobmark == 0)
8421                                 so->so_rcv.sb_state |= SBS_RCVATMARK;
8422                         sohasoutofband(so);
8423                         tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
8424                 }
8425                 SOCKBUF_UNLOCK(&so->so_rcv);
8426                 /*
8427                  * Remove out of band data so doesn't get presented to user.
8428                  * This can happen independent of advancing the URG pointer,
8429                  * but if two URG's are pending at once, some out-of-band
8430                  * data may creep in... ick.
8431                  */
8432                 if (th->th_urp <= (uint32_t)tlen &&
8433                     !(so->so_options & SO_OOBINLINE)) {
8434                         /* hdr drop is delayed */
8435                         tcp_pulloutofband(so, th, m, drop_hdrlen);
8436                 }
8437         } else {
8438                 /*
8439                  * If no out of band data is expected, pull receive urgent
8440                  * pointer along with the receive window.
8441                  */
8442                 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
8443                         tp->rcv_up = tp->rcv_nxt;
8444         }
8445 dodata:                         /* XXX */
8446         INP_WLOCK_ASSERT(tp->t_inpcb);
8447
8448         /*
8449          * Process the segment text, merging it into the TCP sequencing
8450          * queue, and arranging for acknowledgment of receipt if necessary.
8451          * This process logically involves adjusting tp->rcv_wnd as data is
8452          * presented to the user (this happens in tcp_usrreq.c, case
8453          * PRU_RCVD).  If a FIN has already been received on this connection
8454          * then we just ignore the text.
8455          */
8456         tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8457                    IS_FASTOPEN(tp->t_flags));
8458         if ((tlen || (thflags & TH_FIN) || tfo_syn) &&
8459             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8460                 tcp_seq save_start = th->th_seq;
8461                 tcp_seq save_rnxt  = tp->rcv_nxt;
8462                 int     save_tlen  = tlen;
8463
8464                 m_adj(m, drop_hdrlen);  /* delayed header drop */
8465                 /*
8466                  * Insert segment which includes th into TCP reassembly
8467                  * queue with control block tp.  Set thflags to whether
8468                  * reassembly now includes a segment with FIN.  This handles
8469                  * the common case inline (segment is the next to be
8470                  * received on an established connection, and the queue is
8471                  * empty), avoiding linkage into and removal from the queue
8472                  * and repetition of various conversions. Set DELACK for
8473                  * segments received in order, but ack immediately when
8474                  * segments are out of order (so fast retransmit can work).
8475                  */
8476                 if (th->th_seq == tp->rcv_nxt &&
8477                     SEGQ_EMPTY(tp) &&
8478                     (TCPS_HAVEESTABLISHED(tp->t_state) ||
8479                     tfo_syn)) {
8480 #ifdef NETFLIX_SB_LIMITS
8481                         u_int mcnt, appended;
8482
8483                         if (so->so_rcv.sb_shlim) {
8484                                 mcnt = m_memcnt(m);
8485                                 appended = 0;
8486                                 if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8487                                     CFO_NOSLEEP, NULL) == false) {
8488                                         counter_u64_add(tcp_sb_shlim_fails, 1);
8489                                         m_freem(m);
8490                                         return (0);
8491                                 }
8492                         }
8493
8494 #endif
8495                         if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8496                                 bbr->bbr_segs_rcvd += max(1, nsegs);
8497                                 tp->t_flags |= TF_DELACK;
8498                                 bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8499                         } else {
8500                                 bbr->r_wanted_output = 1;
8501                                 tp->t_flags |= TF_ACKNOW;
8502                         }
8503                         tp->rcv_nxt += tlen;
8504                         thflags = th->th_flags & TH_FIN;
8505                         TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8506                         TCPSTAT_ADD(tcps_rcvbyte, tlen);
8507                         SOCKBUF_LOCK(&so->so_rcv);
8508                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8509                                 m_freem(m);
8510                         else
8511 #ifdef NETFLIX_SB_LIMITS
8512                                 appended =
8513 #endif
8514                                         sbappendstream_locked(&so->so_rcv, m, 0);
8515                         /* NB: sorwakeup_locked() does an implicit unlock. */
8516                         sorwakeup_locked(so);
8517 #ifdef NETFLIX_SB_LIMITS
8518                         if (so->so_rcv.sb_shlim && appended != mcnt)
8519                                 counter_fo_release(so->so_rcv.sb_shlim,
8520                                     mcnt - appended);
8521 #endif
8522                 } else {
8523                         /*
8524                          * XXX: Due to the header drop above "th" is
8525                          * theoretically invalid by now.  Fortunately
8526                          * m_adj() doesn't actually frees any mbufs when
8527                          * trimming from the head.
8528                          */
8529                         tcp_seq temp = save_start;
8530                         thflags = tcp_reass(tp, th, &temp, &tlen, m);
8531                         tp->t_flags |= TF_ACKNOW;
8532                 }
8533                 if ((tp->t_flags & TF_SACK_PERMIT) && (save_tlen > 0)) {
8534                         if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8535                                 /*
8536                                  * DSACK actually handled in the fastpath
8537                                  * above.
8538                                  */
8539                                 tcp_update_sack_list(tp, save_start,
8540                                     save_start + save_tlen);
8541                         } else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8542                                 if ((tp->rcv_numsacks >= 1) &&
8543                                     (tp->sackblks[0].end == save_start)) {
8544                                         /*
8545                                          * Partial overlap, recorded at todrop
8546                                          * above.
8547                                          */
8548                                         tcp_update_sack_list(tp,
8549                                             tp->sackblks[0].start,
8550                                             tp->sackblks[0].end);
8551                                 } else {
8552                                         tcp_update_dsack_list(tp, save_start,
8553                                             save_start + save_tlen);
8554                                 }
8555                         } else if (tlen >= save_tlen) {
8556                                 /* Update of sackblks. */
8557                                 tcp_update_dsack_list(tp, save_start,
8558                                     save_start + save_tlen);
8559                         } else if (tlen > 0) {
8560                                 tcp_update_dsack_list(tp, save_start,
8561                                     save_start + tlen);
8562                         }
8563                 }
8564         } else {
8565                 m_freem(m);
8566                 thflags &= ~TH_FIN;
8567         }
8568
8569         /*
8570          * If FIN is received ACK the FIN and let the user know that the
8571          * connection is closing.
8572          */
8573         if (thflags & TH_FIN) {
8574                 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8575                         socantrcvmore(so);
8576                         /*
8577                          * If connection is half-synchronized (ie NEEDSYN
8578                          * flag on) then delay ACK, so it may be piggybacked
8579                          * when SYN is sent. Otherwise, since we received a
8580                          * FIN then no more input can be expected, send ACK
8581                          * now.
8582                          */
8583                         if (tp->t_flags & TF_NEEDSYN) {
8584                                 tp->t_flags |= TF_DELACK;
8585                                 bbr_timer_cancel(bbr,
8586                                     __LINE__, bbr->r_ctl.rc_rcvtime);
8587                         } else {
8588                                 tp->t_flags |= TF_ACKNOW;
8589                         }
8590                         tp->rcv_nxt++;
8591                 }
8592                 switch (tp->t_state) {
8593
8594                         /*
8595                          * In SYN_RECEIVED and ESTABLISHED STATES enter the
8596                          * CLOSE_WAIT state.
8597                          */
8598                 case TCPS_SYN_RECEIVED:
8599                         tp->t_starttime = ticks;
8600                         /* FALLTHROUGH */
8601                 case TCPS_ESTABLISHED:
8602                         tcp_state_change(tp, TCPS_CLOSE_WAIT);
8603                         break;
8604
8605                         /*
8606                          * If still in FIN_WAIT_1 STATE FIN has not been
8607                          * acked so enter the CLOSING state.
8608                          */
8609                 case TCPS_FIN_WAIT_1:
8610                         tcp_state_change(tp, TCPS_CLOSING);
8611                         break;
8612
8613                         /*
8614                          * In FIN_WAIT_2 state enter the TIME_WAIT state,
8615                          * starting the time-wait timer, turning off the
8616                          * other standard timers.
8617                          */
8618                 case TCPS_FIN_WAIT_2:
8619                         bbr->rc_timer_first = 1;
8620                         bbr_timer_cancel(bbr,
8621                             __LINE__, bbr->r_ctl.rc_rcvtime);
8622                         INP_WLOCK_ASSERT(tp->t_inpcb);
8623                         tcp_twstart(tp);
8624                         return (1);
8625                 }
8626         }
8627         /*
8628          * Return any desired output.
8629          */
8630         if ((tp->t_flags & TF_ACKNOW) ||
8631             (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8632                 bbr->r_wanted_output = 1;
8633         }
8634         INP_WLOCK_ASSERT(tp->t_inpcb);
8635         return (0);
8636 }
8637
8638 /*
8639  * Here nothing is really faster, its just that we
8640  * have broken out the fast-data path also just like
8641  * the fast-ack. Return 1 if we processed the packet
8642  * return 0 if you need to take the "slow-path".
8643  */
8644 static int
8645 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8646     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8647     uint32_t tiwin, int32_t nxt_pkt)
8648 {
8649         uint16_t nsegs;
8650         int32_t newsize = 0;    /* automatic sockbuf scaling */
8651         struct tcp_bbr *bbr;
8652 #ifdef NETFLIX_SB_LIMITS
8653         u_int mcnt, appended;
8654 #endif
8655 #ifdef TCPDEBUG
8656         /*
8657          * The size of tcp_saveipgen must be the size of the max ip header,
8658          * now IPv6.
8659          */
8660         u_char tcp_saveipgen[IP6_HDR_LEN];
8661         struct tcphdr tcp_savetcp;
8662         short ostate = 0;
8663
8664 #endif
8665         /* On the hpts and we would have called output */
8666         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8667
8668         /*
8669          * If last ACK falls within this segment's sequence numbers, record
8670          * the timestamp. NOTE that the test is modified according to the
8671          * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8672          */
8673         if (bbr->r_ctl.rc_resend != NULL) {
8674                 return (0);
8675         }
8676         if (tiwin && tiwin != tp->snd_wnd) {
8677                 return (0);
8678         }
8679         if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8680                 return (0);
8681         }
8682         if (__predict_false((to->to_flags & TOF_TS) &&
8683             (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8684                 return (0);
8685         }
8686         if (__predict_false((th->th_ack != tp->snd_una))) {
8687                 return (0);
8688         }
8689         if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8690                 return (0);
8691         }
8692         if ((to->to_flags & TOF_TS) != 0 &&
8693             SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8694                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8695                 tp->ts_recent = to->to_tsval;
8696         }
8697         /*
8698          * This is a pure, in-sequence data packet with nothing on the
8699          * reassembly queue and we have enough buffer space to take it.
8700          */
8701         nsegs = max(1, m->m_pkthdr.lro_nsegs);
8702
8703 #ifdef NETFLIX_SB_LIMITS
8704         if (so->so_rcv.sb_shlim) {
8705                 mcnt = m_memcnt(m);
8706                 appended = 0;
8707                 if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8708                     CFO_NOSLEEP, NULL) == false) {
8709                         counter_u64_add(tcp_sb_shlim_fails, 1);
8710                         m_freem(m);
8711                         return (1);
8712                 }
8713         }
8714 #endif
8715         /* Clean receiver SACK report if present */
8716         if (tp->rcv_numsacks)
8717                 tcp_clean_sackreport(tp);
8718         TCPSTAT_INC(tcps_preddat);
8719         tp->rcv_nxt += tlen;
8720         /*
8721          * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8722          */
8723         tp->snd_wl1 = th->th_seq;
8724         /*
8725          * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8726          */
8727         tp->rcv_up = tp->rcv_nxt;
8728         TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8729         TCPSTAT_ADD(tcps_rcvbyte, tlen);
8730 #ifdef TCPDEBUG
8731         if (so->so_options & SO_DEBUG)
8732                 tcp_trace(TA_INPUT, ostate, tp,
8733                     (void *)tcp_saveipgen, &tcp_savetcp, 0);
8734 #endif
8735         newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8736
8737         /* Add data to socket buffer. */
8738         SOCKBUF_LOCK(&so->so_rcv);
8739         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8740                 m_freem(m);
8741         } else {
8742                 /*
8743                  * Set new socket buffer size. Give up when limit is
8744                  * reached.
8745                  */
8746                 if (newsize)
8747                         if (!sbreserve_locked(&so->so_rcv,
8748                             newsize, so, NULL))
8749                                 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8750                 m_adj(m, drop_hdrlen);  /* delayed header drop */
8751
8752 #ifdef NETFLIX_SB_LIMITS
8753                 appended =
8754 #endif
8755                         sbappendstream_locked(&so->so_rcv, m, 0);
8756                 ctf_calc_rwin(so, tp);
8757         }
8758         /* NB: sorwakeup_locked() does an implicit unlock. */
8759         sorwakeup_locked(so);
8760 #ifdef NETFLIX_SB_LIMITS
8761         if (so->so_rcv.sb_shlim && mcnt != appended)
8762                 counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8763 #endif
8764         if (DELAY_ACK(tp, bbr, nsegs)) {
8765                 bbr->bbr_segs_rcvd += max(1, nsegs);
8766                 tp->t_flags |= TF_DELACK;
8767                 bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8768         } else {
8769                 bbr->r_wanted_output = 1;
8770                 tp->t_flags |= TF_ACKNOW;
8771         }
8772         return (1);
8773 }
8774
8775 /*
8776  * This subfunction is used to try to highly optimize the
8777  * fast path. We again allow window updates that are
8778  * in sequence to remain in the fast-path. We also add
8779  * in the __predict's to attempt to help the compiler.
8780  * Note that if we return a 0, then we can *not* process
8781  * it and the caller should push the packet into the
8782  * slow-path. If we return 1, then all is well and
8783  * the packet is fully processed.
8784  */
8785 static int
8786 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8787     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8788     uint32_t tiwin, int32_t nxt_pkt)
8789 {
8790         int32_t acked;
8791         uint16_t nsegs;
8792         uint32_t sack_changed;
8793 #ifdef TCPDEBUG
8794         /*
8795          * The size of tcp_saveipgen must be the size of the max ip header,
8796          * now IPv6.
8797          */
8798         u_char tcp_saveipgen[IP6_HDR_LEN];
8799         struct tcphdr tcp_savetcp;
8800         short ostate = 0;
8801
8802 #endif
8803         uint32_t prev_acked = 0;
8804         struct tcp_bbr *bbr;
8805
8806         if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8807                 /* Old ack, behind (or duplicate to) the last one rcv'd */
8808                 return (0);
8809         }
8810         if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8811                 /* Above what we have sent? */
8812                 return (0);
8813         }
8814         if (__predict_false(tiwin == 0)) {
8815                 /* zero window */
8816                 return (0);
8817         }
8818         if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8819                 /* We need a SYN or a FIN, unlikely.. */
8820                 return (0);
8821         }
8822         if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8823                 /* Timestamp is behind .. old ack with seq wrap? */
8824                 return (0);
8825         }
8826         if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8827                 /* Still recovering */
8828                 return (0);
8829         }
8830         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8831         if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8832                 /* We are retransmitting */
8833                 return (0);
8834         }
8835         if (__predict_false(bbr->rc_in_persist != 0)) {
8836                 /* In persist mode */
8837                 return (0);
8838         }
8839         if (bbr->r_ctl.rc_sacked) {
8840                 /* We have sack holes on our scoreboard */
8841                 return (0);
8842         }
8843         /* Ok if we reach here, we can process a fast-ack */
8844         nsegs = max(1, m->m_pkthdr.lro_nsegs);
8845         sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8846         /* 
8847          * We never detect loss in fast ack [we can't
8848          * have a sack and can't be in recovery so
8849          * we always pass 0 (nothing detected)].
8850          */
8851         bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8852         /* Did the window get updated? */
8853         if (tiwin != tp->snd_wnd) {
8854                 tp->snd_wnd = tiwin;
8855                 tp->snd_wl1 = th->th_seq;
8856                 if (tp->snd_wnd > tp->max_sndwnd)
8857                         tp->max_sndwnd = tp->snd_wnd;
8858         }
8859         /* Do we need to exit persists? */
8860         if ((bbr->rc_in_persist != 0) &&
8861             (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8862                                bbr_minseg(bbr)))) {
8863                 bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8864                 bbr->r_wanted_output = 1;
8865         }
8866         /* Do we need to enter persists? */
8867         if ((bbr->rc_in_persist == 0) &&
8868             (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8869             TCPS_HAVEESTABLISHED(tp->t_state) &&
8870             (tp->snd_max == tp->snd_una) &&
8871             sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
8872             (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
8873                 /* No send window.. we must enter persist */
8874                 bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8875         }
8876         /*
8877          * If last ACK falls within this segment's sequence numbers, record
8878          * the timestamp. NOTE that the test is modified according to the
8879          * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8880          */
8881         if ((to->to_flags & TOF_TS) != 0 &&
8882             SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8883                 tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8884                 tp->ts_recent = to->to_tsval;
8885         }
8886         /*
8887          * This is a pure ack for outstanding data.
8888          */
8889         TCPSTAT_INC(tcps_predack);
8890
8891         /*
8892          * "bad retransmit" recovery.
8893          */
8894         if (tp->t_flags & TF_PREVVALID) {
8895                 tp->t_flags &= ~TF_PREVVALID;
8896                 if (tp->t_rxtshift == 1 &&
8897                     (int)(ticks - tp->t_badrxtwin) < 0)
8898                         bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8899         }
8900         /*
8901          * Recalculate the transmit timer / rtt.
8902          *
8903          * Some boxes send broken timestamp replies during the SYN+ACK
8904          * phase, ignore timestamps of 0 or we could calculate a huge RTT
8905          * and blow up the retransmit timer.
8906          */
8907         acked = BYTES_THIS_ACK(tp, th);
8908
8909 #ifdef TCP_HHOOK
8910         /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8911         hhook_run_tcp_est_in(tp, th, to);
8912 #endif
8913
8914         TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8915         TCPSTAT_ADD(tcps_rcvackbyte, acked);
8916         sbdrop(&so->so_snd, acked);
8917
8918         if (SEQ_GT(th->th_ack, tp->snd_una))
8919                 bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8920         tp->snd_una = th->th_ack;
8921         if (tp->snd_wnd < ctf_outstanding(tp))
8922                 /* The peer collapsed its window on us */
8923                 bbr_collapsed_window(bbr);
8924         else if (bbr->rc_has_collapsed)
8925                 bbr_un_collapse_window(bbr);
8926
8927         if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8928                 tp->snd_recover = tp->snd_una;
8929         }
8930         bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8931         /*
8932          * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8933          */
8934         tp->snd_wl2 = th->th_ack;
8935         m_freem(m);
8936         /*
8937          * If all outstanding data are acked, stop retransmit timer,
8938          * otherwise restart timer using current (possibly backed-off)
8939          * value. If process is waiting for space, wakeup/selwakeup/signal.
8940          * If data are ready to send, let tcp_output decide between more
8941          * output or persist.
8942          */
8943 #ifdef TCPDEBUG
8944         if (so->so_options & SO_DEBUG)
8945                 tcp_trace(TA_INPUT, ostate, tp,
8946                     (void *)tcp_saveipgen,
8947                     &tcp_savetcp, 0);
8948 #endif
8949         /* Wake up the socket if we have room to write more */
8950         sowwakeup(so);
8951         if (tp->snd_una == tp->snd_max) {
8952                 /* Nothing left outstanding */
8953                 bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8954                 if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
8955                         bbr->rc_tp->t_acktime = 0;
8956                 bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8957                 if (bbr->rc_in_persist == 0) {
8958                         bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8959                 }
8960                 sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8961                 bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8962                 /* 
8963                  * We invalidate the last ack here since we
8964                  * don't want to transfer forward the time
8965                  * for our sum's calculations.
8966                  */
8967                 bbr->r_wanted_output = 1;
8968         }
8969         if (sbavail(&so->so_snd)) {
8970                 bbr->r_wanted_output = 1;
8971         }
8972         return (1);
8973 }
8974
8975 /*
8976  * Return value of 1, the TCB is unlocked and most
8977  * likely gone, return value of 0, the TCB is still
8978  * locked.
8979  */
8980 static int
8981 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8982     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8983     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8984 {
8985         int32_t todrop;
8986         int32_t ourfinisacked = 0;
8987         struct tcp_bbr *bbr;
8988         int32_t ret_val = 0;
8989
8990         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8991         ctf_calc_rwin(so, tp);
8992         /*
8993          * If the state is SYN_SENT: if seg contains an ACK, but not for our
8994          * SYN, drop the input. if seg contains a RST, then drop the
8995          * connection. if seg does not contain SYN, then drop it. Otherwise
8996          * this is an acceptable SYN segment initialize tp->rcv_nxt and
8997          * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8998          * not support ECN so we will not say we are capable. if SYN has
8999          * been acked change to ESTABLISHED else SYN_RCVD state arrange for
9000          * segment to be acked (eventually) continue processing rest of
9001          * data/controls, beginning with URG
9002          */
9003         if ((thflags & TH_ACK) &&
9004             (SEQ_LEQ(th->th_ack, tp->iss) ||
9005             SEQ_GT(th->th_ack, tp->snd_max))) {
9006                 ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9007                 return (1);
9008         }
9009         if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
9010                 TCP_PROBE5(connect__refused, NULL, tp,
9011                     mtod(m, const char *), tp, th);
9012                 tp = tcp_drop(tp, ECONNREFUSED);
9013                 ctf_do_drop(m, tp);
9014                 return (1);
9015         }
9016         if (thflags & TH_RST) {
9017                 ctf_do_drop(m, tp);
9018                 return (1);
9019         }
9020         if (!(thflags & TH_SYN)) {
9021                 ctf_do_drop(m, tp);
9022                 return (1);
9023         }
9024         tp->irs = th->th_seq;
9025         tcp_rcvseqinit(tp);
9026         if (thflags & TH_ACK) {
9027                 int tfo_partial = 0;
9028
9029                 TCPSTAT_INC(tcps_connects);
9030                 soisconnected(so);
9031 #ifdef MAC
9032                 mac_socketpeer_set_from_mbuf(m, so);
9033 #endif
9034                 /* Do window scaling on this connection? */
9035                 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9036                     (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9037                         tp->rcv_scale = tp->request_r_scale;
9038                 }
9039                 tp->rcv_adv += min(tp->rcv_wnd,
9040                     TCP_MAXWIN << tp->rcv_scale);
9041                 /*
9042                  * If not all the data that was sent in the TFO SYN
9043                  * has been acked, resend the remainder right away.
9044                  */
9045                 if (IS_FASTOPEN(tp->t_flags) &&
9046                     (tp->snd_una != tp->snd_max)) {
9047                         tp->snd_nxt = th->th_ack;
9048                         tfo_partial = 1;
9049                 }
9050                 /*
9051                  * If there's data, delay ACK; if there's also a FIN ACKNOW
9052                  * will be turned on later.
9053                  */
9054                 if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && (tfo_partial == 0)) {
9055                         bbr->bbr_segs_rcvd += 1;
9056                         tp->t_flags |= TF_DELACK;
9057                         bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
9058                 } else {
9059                         bbr->r_wanted_output = 1;
9060                         tp->t_flags |= TF_ACKNOW;
9061                 }
9062                 if (SEQ_GT(th->th_ack, tp->iss)) {
9063                         /* 
9064                          * The SYN is acked
9065                          * handle it specially.
9066                          */
9067                         bbr_log_syn(tp, to);
9068                 }
9069                 if (SEQ_GT(th->th_ack, tp->snd_una)) {
9070                         /* 
9071                          * We advance snd_una for the 
9072                          * fast open case. If th_ack is
9073                          * acknowledging data beyond 
9074                          * snd_una we can't just call
9075                          * ack-processing since the 
9076                          * data stream in our send-map
9077                          * will start at snd_una + 1 (one
9078                          * beyond the SYN). If its just
9079                          * equal we don't need to do that
9080                          * and there is no send_map.
9081                          */
9082                         tp->snd_una++;
9083                 }
9084                 /*
9085                  * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
9086                  * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
9087                  */
9088                 tp->t_starttime = ticks;
9089                 if (tp->t_flags & TF_NEEDFIN) {
9090                         tcp_state_change(tp, TCPS_FIN_WAIT_1);
9091                         tp->t_flags &= ~TF_NEEDFIN;
9092                         thflags &= ~TH_SYN;
9093                 } else {
9094                         tcp_state_change(tp, TCPS_ESTABLISHED);
9095                         TCP_PROBE5(connect__established, NULL, tp,
9096                             mtod(m, const char *), tp, th);
9097                         cc_conn_init(tp);
9098                 }
9099         } else {
9100                 /*
9101                  * Received initial SYN in SYN-SENT[*] state => simultaneous
9102                  * open.  If segment contains CC option and there is a
9103                  * cached CC, apply TAO test. If it succeeds, connection is *
9104                  * half-synchronized. Otherwise, do 3-way handshake:
9105                  * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
9106                  * there was no CC option, clear cached CC value.
9107                  */
9108                 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
9109                 tcp_state_change(tp, TCPS_SYN_RECEIVED);
9110         }
9111         INP_WLOCK_ASSERT(tp->t_inpcb);
9112         /*
9113          * Advance th->th_seq to correspond to first data byte. If data,
9114          * trim to stay within window, dropping FIN if necessary.
9115          */
9116         th->th_seq++;
9117         if (tlen > tp->rcv_wnd) {
9118                 todrop = tlen - tp->rcv_wnd;
9119                 m_adj(m, -todrop);
9120                 tlen = tp->rcv_wnd;
9121                 thflags &= ~TH_FIN;
9122                 TCPSTAT_INC(tcps_rcvpackafterwin);
9123                 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
9124         }
9125         tp->snd_wl1 = th->th_seq - 1;
9126         tp->rcv_up = th->th_seq;
9127         /*
9128          * Client side of transaction: already sent SYN and data. If the
9129          * remote host used T/TCP to validate the SYN, our data will be
9130          * ACK'd; if so, enter normal data segment processing in the middle
9131          * of step 5, ack processing. Otherwise, goto step 6.
9132          */
9133         if (thflags & TH_ACK) {
9134                 if ((to->to_flags & TOF_TS) != 0) {
9135                         uint32_t t, rtt;
9136                         
9137                         t = tcp_tv_to_mssectick(&bbr->rc_tv);
9138                         if (TSTMP_GEQ(t, to->to_tsecr)) {
9139                                 rtt = t - to->to_tsecr;
9140                                 if (rtt == 0) {
9141                                         rtt = 1;
9142                                 }
9143                                 rtt *= MS_IN_USEC;
9144                                 tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9145                                 apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
9146                                                        rtt, bbr->r_ctl.rc_rcvtime);
9147                         }
9148                 }
9149                 if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
9150                         return (ret_val);
9151                 /* We may have changed to FIN_WAIT_1 above */
9152                 if (tp->t_state == TCPS_FIN_WAIT_1) {
9153                         /*
9154                          * In FIN_WAIT_1 STATE in addition to the processing
9155                          * for the ESTABLISHED state if our FIN is now
9156                          * acknowledged then enter FIN_WAIT_2.
9157                          */
9158                         if (ourfinisacked) {
9159                                 /*
9160                                  * If we can't receive any more data, then
9161                                  * closing user can proceed. Starting the
9162                                  * timer is contrary to the specification,
9163                                  * but if we don't get a FIN we'll hang
9164                                  * forever.
9165                                  *
9166                                  * XXXjl: we should release the tp also, and
9167                                  * use a compressed state.
9168                                  */
9169                                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9170                                         soisdisconnected(so);
9171                                         tcp_timer_activate(tp, TT_2MSL,
9172                                             (tcp_fast_finwait2_recycle ?
9173                                             tcp_finwait2_timeout :
9174                                             TP_MAXIDLE(tp)));
9175                                 }
9176                                 tcp_state_change(tp, TCPS_FIN_WAIT_2);
9177                         }
9178                 }
9179         }
9180         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9181             tiwin, thflags, nxt_pkt));
9182 }
9183
9184 /*
9185  * Return value of 1, the TCB is unlocked and most
9186  * likely gone, return value of 0, the TCB is still
9187  * locked.
9188  */
9189 static int
9190 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
9191                 struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9192                 uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
9193 {
9194         int32_t ourfinisacked = 0;
9195         int32_t ret_val;
9196         struct tcp_bbr *bbr;
9197
9198         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9199         ctf_calc_rwin(so, tp);
9200         if ((thflags & TH_ACK) &&
9201             (SEQ_LEQ(th->th_ack, tp->snd_una) ||
9202              SEQ_GT(th->th_ack, tp->snd_max))) {
9203                 ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9204                 return (1);
9205         }
9206         if (IS_FASTOPEN(tp->t_flags)) {
9207                 /*
9208                  * When a TFO connection is in SYN_RECEIVED, the only valid
9209                  * packets are the initial SYN, a retransmit/copy of the
9210                  * initial SYN (possibly with a subset of the original
9211                  * data), a valid ACK, a FIN, or a RST.
9212                  */
9213                 if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
9214                         ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9215                         return (1);
9216                 } else if (thflags & TH_SYN) {
9217                         /* non-initial SYN is ignored */
9218                         if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
9219                             (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
9220                             (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
9221                                 ctf_do_drop(m, NULL);
9222                                 return (0);
9223                         }
9224                 } else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
9225                         ctf_do_drop(m, NULL);
9226                         return (0);
9227                 }
9228         }
9229         if ((thflags & TH_RST) ||
9230             (tp->t_fin_is_rst && (thflags & TH_FIN)))
9231                 return (ctf_process_rst(m, th, so, tp));
9232         /*
9233          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9234          * it's less than ts_recent, drop it.
9235          */
9236         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9237             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9238                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9239                         return (ret_val);
9240         }
9241         /*
9242          * In the SYN-RECEIVED state, validate that the packet belongs to
9243          * this connection before trimming the data to fit the receive
9244          * window.  Check the sequence number versus IRS since we know the
9245          * sequence numbers haven't wrapped.  This is a partial fix for the
9246          * "LAND" DoS attack.
9247          */
9248         if (SEQ_LT(th->th_seq, tp->irs)) {
9249                 ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9250                 return (1);
9251         }
9252         INP_WLOCK_ASSERT(tp->t_inpcb);
9253         if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9254                 return (ret_val);
9255         }
9256         /*
9257          * If last ACK falls within this segment's sequence numbers, record
9258          * its timestamp. NOTE: 1) That the test incorporates suggestions
9259          * from the latest proposal of the tcplw@cray.com list (Braden
9260          * 1993/04/26). 2) That updating only on newer timestamps interferes
9261          * with our earlier PAWS tests, so this check should be solely
9262          * predicated on the sequence space of this segment. 3) That we
9263          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9264          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9265          * SEG.Len, This modified check allows us to overcome RFC1323's
9266          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9267          * p.869. In such cases, we can still calculate the RTT correctly
9268          * when RCV.NXT == Last.ACK.Sent.
9269          */
9270         if ((to->to_flags & TOF_TS) != 0 &&
9271             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9272             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9273                     ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9274                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9275                 tp->ts_recent = to->to_tsval;
9276         }
9277         tp->snd_wnd = tiwin;
9278         /*
9279          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9280          * is on (half-synchronized state), then queue data for later
9281          * processing; else drop segment and return.
9282          */
9283         if ((thflags & TH_ACK) == 0) {
9284                 if (IS_FASTOPEN(tp->t_flags)) {
9285                         cc_conn_init(tp);
9286                 }
9287                 return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9288                                          tiwin, thflags, nxt_pkt));
9289         }
9290         TCPSTAT_INC(tcps_connects);
9291         soisconnected(so);
9292         /* Do window scaling? */
9293         if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9294             (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9295                 tp->rcv_scale = tp->request_r_scale;
9296         }
9297         /*
9298          * ok for the first time in lets see if we can use the ts to figure
9299          * out what the initial RTT was.
9300          */
9301         if ((to->to_flags & TOF_TS) != 0) {
9302                 uint32_t t, rtt;
9303
9304                 t = tcp_tv_to_mssectick(&bbr->rc_tv);
9305                 if (TSTMP_GEQ(t, to->to_tsecr)) {
9306                         rtt = t - to->to_tsecr;
9307                         if (rtt == 0) {
9308                                 rtt = 1;
9309                         }
9310                         rtt *= MS_IN_USEC;
9311                         tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9312                         apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9313                 }
9314         }
9315         /* Drop off any SYN in the send map (probably not there)  */
9316         if (thflags & TH_ACK)
9317                 bbr_log_syn(tp, to);
9318         if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
9319                 
9320                 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9321                 tp->t_tfo_pending = NULL;
9322                 /*
9323                  * Account for the ACK of our SYN prior to regular
9324                  * ACK processing below.
9325                  */
9326                 tp->snd_una++;
9327         }
9328         /*
9329          * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9330          * FIN-WAIT-1
9331          */
9332         tp->t_starttime = ticks;
9333         if (tp->t_flags & TF_NEEDFIN) {
9334                 tcp_state_change(tp, TCPS_FIN_WAIT_1);
9335                 tp->t_flags &= ~TF_NEEDFIN;
9336         } else {
9337                 tcp_state_change(tp, TCPS_ESTABLISHED);
9338                 TCP_PROBE5(accept__established, NULL, tp,
9339                            mtod(m, const char *), tp, th);
9340                 /*
9341                  * TFO connections call cc_conn_init() during SYN
9342                  * processing.  Calling it again here for such connections
9343                  * is not harmless as it would undo the snd_cwnd reduction
9344                  * that occurs when a TFO SYN|ACK is retransmitted.
9345                  */
9346                 if (!IS_FASTOPEN(tp->t_flags))
9347                         cc_conn_init(tp);
9348         }
9349         /*
9350          * If segment contains data or ACK, will call tcp_reass() later; if
9351          * not, do so now to pass queued data to user.
9352          */
9353         if (tlen == 0 && (thflags & TH_FIN) == 0)
9354                 (void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9355                         (struct mbuf *)0);
9356         tp->snd_wl1 = th->th_seq - 1;
9357         if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9358                 return (ret_val);
9359         }
9360         if (tp->t_state == TCPS_FIN_WAIT_1) {
9361                 /* We could have went to FIN_WAIT_1 (or EST) above */
9362                 /*
9363                  * In FIN_WAIT_1 STATE in addition to the processing for the
9364                  * ESTABLISHED state if our FIN is now acknowledged then
9365                  * enter FIN_WAIT_2.
9366                  */
9367                 if (ourfinisacked) {
9368                         /*
9369                          * If we can't receive any more data, then closing
9370                          * user can proceed. Starting the timer is contrary
9371                          * to the specification, but if we don't get a FIN
9372                          * we'll hang forever.
9373                          *
9374                          * XXXjl: we should release the tp also, and use a
9375                          * compressed state.
9376                          */
9377                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9378                                 soisdisconnected(so);
9379                                 tcp_timer_activate(tp, TT_2MSL,
9380                                                    (tcp_fast_finwait2_recycle ?
9381                                                     tcp_finwait2_timeout :
9382                                                     TP_MAXIDLE(tp)));
9383                         }
9384                         tcp_state_change(tp, TCPS_FIN_WAIT_2);
9385                 }
9386         }
9387         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9388                                  tiwin, thflags, nxt_pkt));
9389 }
9390
9391 /*
9392  * Return value of 1, the TCB is unlocked and most
9393  * likely gone, return value of 0, the TCB is still
9394  * locked.
9395  */
9396 static int
9397 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9398     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9399     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
9400 {
9401         struct tcp_bbr *bbr;
9402         int32_t ret_val;
9403
9404         /*
9405          * Header prediction: check for the two common cases of a
9406          * uni-directional data xfer.  If the packet has no control flags,
9407          * is in-sequence, the window didn't change and we're not
9408          * retransmitting, it's a candidate.  If the length is zero and the
9409          * ack moved forward, we're the sender side of the xfer.  Just free
9410          * the data acked & wake any higher level process that was blocked
9411          * waiting for space.  If the length is non-zero and the ack didn't
9412          * move, we're the receiver side.  If we're getting packets in-order
9413          * (the reassembly queue is empty), add the data toc The socket
9414          * buffer and note that we need a delayed ack. Make sure that the
9415          * hidden state-flags are also off. Since we check for
9416          * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9417          */
9418         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9419         if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9420                 /*
9421                  * If we have delived under 4 segments increase the initial
9422                  * window if raised by the peer. We use this to determine
9423                  * dynamic and static rwnd's at the end of a connection.
9424                  */
9425                 bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9426         }
9427         if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9428             __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9429             __predict_true(SEGQ_EMPTY(tp)) &&
9430             __predict_true(th->th_seq == tp->rcv_nxt)) {
9431                 if (tlen == 0) {
9432                         if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9433                             tiwin, nxt_pkt)) {
9434                                 return (0);
9435                         }
9436                 } else {
9437                         if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9438                             tiwin, nxt_pkt)) {
9439                                 return (0);
9440                         }
9441                 }
9442         }
9443         ctf_calc_rwin(so, tp);
9444
9445         if ((thflags & TH_RST) ||
9446             (tp->t_fin_is_rst && (thflags & TH_FIN)))
9447                 return (ctf_process_rst(m, th, so, tp));
9448         /*
9449          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9450          * synchronized state.
9451          */
9452         if (thflags & TH_SYN) {
9453                 ctf_challenge_ack(m, th, tp, &ret_val);
9454                 return (ret_val);
9455         }
9456         /*
9457          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9458          * it's less than ts_recent, drop it.
9459          */
9460         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9461             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9462                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9463                         return (ret_val);
9464         }
9465         INP_WLOCK_ASSERT(tp->t_inpcb);
9466         if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9467                 return (ret_val);
9468         }
9469         /*
9470          * If last ACK falls within this segment's sequence numbers, record
9471          * its timestamp. NOTE: 1) That the test incorporates suggestions
9472          * from the latest proposal of the tcplw@cray.com list (Braden
9473          * 1993/04/26). 2) That updating only on newer timestamps interferes
9474          * with our earlier PAWS tests, so this check should be solely
9475          * predicated on the sequence space of this segment. 3) That we
9476          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9477          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9478          * SEG.Len, This modified check allows us to overcome RFC1323's
9479          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9480          * p.869. In such cases, we can still calculate the RTT correctly
9481          * when RCV.NXT == Last.ACK.Sent.
9482          */
9483         if ((to->to_flags & TOF_TS) != 0 &&
9484             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9485             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9486             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9487                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9488                 tp->ts_recent = to->to_tsval;
9489         }
9490         /*
9491          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9492          * is on (half-synchronized state), then queue data for later
9493          * processing; else drop segment and return.
9494          */
9495         if ((thflags & TH_ACK) == 0) {
9496                 if (tp->t_flags & TF_NEEDSYN) {
9497                         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9498                             tiwin, thflags, nxt_pkt));
9499                 } else if (tp->t_flags & TF_ACKNOW) {
9500                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9501                         bbr->r_wanted_output = 1;
9502                         return (ret_val);
9503                 } else {
9504                         ctf_do_drop(m, NULL);
9505                         return (0);
9506                 }
9507         }
9508         /*
9509          * Ack processing.
9510          */
9511         if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9512                 return (ret_val);
9513         }
9514         if (sbavail(&so->so_snd)) {
9515                 if (bbr_progress_timeout_check(bbr)) {
9516                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9517                         return (1);
9518                 }
9519         }
9520         /* State changes only happen in bbr_process_data() */
9521         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9522             tiwin, thflags, nxt_pkt));
9523 }
9524
9525 /*
9526  * Return value of 1, the TCB is unlocked and most
9527  * likely gone, return value of 0, the TCB is still
9528  * locked.
9529  */
9530 static int
9531 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9532     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9533     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
9534 {
9535         struct tcp_bbr *bbr;
9536         int32_t ret_val;
9537
9538         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9539         ctf_calc_rwin(so, tp);
9540         if ((thflags & TH_RST) ||
9541             (tp->t_fin_is_rst && (thflags & TH_FIN)))
9542                 return (ctf_process_rst(m, th, so, tp));
9543         /*
9544          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9545          * synchronized state.
9546          */
9547         if (thflags & TH_SYN) {
9548                 ctf_challenge_ack(m, th, tp, &ret_val);
9549                 return (ret_val);
9550         }
9551         /*
9552          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9553          * it's less than ts_recent, drop it.
9554          */
9555         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9556             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9557                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9558                         return (ret_val);
9559         }
9560         INP_WLOCK_ASSERT(tp->t_inpcb);
9561         if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9562                 return (ret_val);
9563         }
9564         /*
9565          * If last ACK falls within this segment's sequence numbers, record
9566          * its timestamp. NOTE: 1) That the test incorporates suggestions
9567          * from the latest proposal of the tcplw@cray.com list (Braden
9568          * 1993/04/26). 2) That updating only on newer timestamps interferes
9569          * with our earlier PAWS tests, so this check should be solely
9570          * predicated on the sequence space of this segment. 3) That we
9571          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9572          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9573          * SEG.Len, This modified check allows us to overcome RFC1323's
9574          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9575          * p.869. In such cases, we can still calculate the RTT correctly
9576          * when RCV.NXT == Last.ACK.Sent.
9577          */
9578         if ((to->to_flags & TOF_TS) != 0 &&
9579             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9580             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9581             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9582                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9583                 tp->ts_recent = to->to_tsval;
9584         }
9585         /*
9586          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9587          * is on (half-synchronized state), then queue data for later
9588          * processing; else drop segment and return.
9589          */
9590         if ((thflags & TH_ACK) == 0) {
9591                 if (tp->t_flags & TF_NEEDSYN) {
9592                         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9593                             tiwin, thflags, nxt_pkt));
9594                 } else if (tp->t_flags & TF_ACKNOW) {
9595                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9596                         bbr->r_wanted_output = 1;
9597                         return (ret_val);
9598                 } else {
9599                         ctf_do_drop(m, NULL);
9600                         return (0);
9601                 }
9602         }
9603         /*
9604          * Ack processing.
9605          */
9606         if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9607                 return (ret_val);
9608         }
9609         if (sbavail(&so->so_snd)) {
9610                 if (bbr_progress_timeout_check(bbr)) {
9611                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9612                         return (1);
9613                 }
9614         }
9615         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9616             tiwin, thflags, nxt_pkt));
9617 }
9618
9619 static int
9620 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9621     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9622 {
9623
9624         if (bbr->rc_allow_data_af_clo == 0) {
9625 close_now:
9626                 tp = tcp_close(tp);
9627                 TCPSTAT_INC(tcps_rcvafterclose);
9628                 ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9629                 return (1);
9630         }
9631         if (sbavail(&so->so_snd) == 0)
9632                 goto close_now;
9633         /* Ok we allow data that is ignored and a followup reset */
9634         tp->rcv_nxt = th->th_seq + *tlen;
9635         tp->t_flags2 |= TF2_DROP_AF_DATA;
9636         bbr->r_wanted_output = 1;
9637         *tlen = 0;
9638         return (0);
9639 }
9640
9641 /*
9642  * Return value of 1, the TCB is unlocked and most
9643  * likely gone, return value of 0, the TCB is still
9644  * locked.
9645  */
9646 static int
9647 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9648     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9649     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
9650 {
9651         int32_t ourfinisacked = 0;
9652         int32_t ret_val;
9653         struct tcp_bbr *bbr;
9654
9655         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9656         ctf_calc_rwin(so, tp);
9657         if ((thflags & TH_RST) ||
9658             (tp->t_fin_is_rst && (thflags & TH_FIN)))
9659                 return (ctf_process_rst(m, th, so, tp));
9660         /*
9661          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9662          * synchronized state.
9663          */
9664         if (thflags & TH_SYN) {
9665                 ctf_challenge_ack(m, th, tp, &ret_val);
9666                 return (ret_val);
9667         }
9668         /*
9669          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9670          * it's less than ts_recent, drop it.
9671          */
9672         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9673             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9674                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9675                         return (ret_val);
9676         }
9677         INP_WLOCK_ASSERT(tp->t_inpcb);
9678         if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9679                 return (ret_val);
9680         }
9681         /*
9682          * If new data are received on a connection after the user processes
9683          * are gone, then RST the other end.
9684          */
9685         if ((so->so_state & SS_NOFDREF) && tlen) {
9686                 /*
9687                  * We call a new function now so we might continue and setup
9688                  * to reset at all data being ack'd.
9689                  */
9690                 if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9691                         return (1);
9692         }
9693         /*
9694          * If last ACK falls within this segment's sequence numbers, record
9695          * its timestamp. NOTE: 1) That the test incorporates suggestions
9696          * from the latest proposal of the tcplw@cray.com list (Braden
9697          * 1993/04/26). 2) That updating only on newer timestamps interferes
9698          * with our earlier PAWS tests, so this check should be solely
9699          * predicated on the sequence space of this segment. 3) That we
9700          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9701          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9702          * SEG.Len, This modified check allows us to overcome RFC1323's
9703          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9704          * p.869. In such cases, we can still calculate the RTT correctly
9705          * when RCV.NXT == Last.ACK.Sent.
9706          */
9707         if ((to->to_flags & TOF_TS) != 0 &&
9708             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9709             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9710             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9711                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9712                 tp->ts_recent = to->to_tsval;
9713         }
9714         /*
9715          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9716          * is on (half-synchronized state), then queue data for later
9717          * processing; else drop segment and return.
9718          */
9719         if ((thflags & TH_ACK) == 0) {
9720                 if (tp->t_flags & TF_NEEDSYN) {
9721                         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9722                             tiwin, thflags, nxt_pkt));
9723                 } else if (tp->t_flags & TF_ACKNOW) {
9724                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9725                         bbr->r_wanted_output = 1;
9726                         return (ret_val);
9727                 } else {
9728                         ctf_do_drop(m, NULL);
9729                         return (0);
9730                 }
9731         }
9732         /*
9733          * Ack processing.
9734          */
9735         if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9736                 return (ret_val);
9737         }
9738         if (ourfinisacked) {
9739                 /*
9740                  * If we can't receive any more data, then closing user can
9741                  * proceed. Starting the timer is contrary to the
9742                  * specification, but if we don't get a FIN we'll hang
9743                  * forever.
9744                  *
9745                  * XXXjl: we should release the tp also, and use a
9746                  * compressed state.
9747                  */
9748                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9749                         soisdisconnected(so);
9750                         tcp_timer_activate(tp, TT_2MSL,
9751                             (tcp_fast_finwait2_recycle ?
9752                             tcp_finwait2_timeout :
9753                             TP_MAXIDLE(tp)));
9754                 }
9755                 tcp_state_change(tp, TCPS_FIN_WAIT_2);
9756         }
9757         if (sbavail(&so->so_snd)) {
9758                 if (bbr_progress_timeout_check(bbr)) {
9759                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9760                         return (1);
9761                 }
9762         }
9763         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9764             tiwin, thflags, nxt_pkt));
9765 }
9766
9767 /*
9768  * Return value of 1, the TCB is unlocked and most
9769  * likely gone, return value of 0, the TCB is still
9770  * locked.
9771  */
9772 static int
9773 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9774     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9775     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
9776 {
9777         int32_t ourfinisacked = 0;
9778         int32_t ret_val;
9779         struct tcp_bbr *bbr;
9780
9781         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9782         ctf_calc_rwin(so, tp);
9783         if ((thflags & TH_RST) ||
9784             (tp->t_fin_is_rst && (thflags & TH_FIN)))
9785                 return (ctf_process_rst(m, th, so, tp));
9786         /*
9787          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9788          * synchronized state.
9789          */
9790         if (thflags & TH_SYN) {
9791                 ctf_challenge_ack(m, th, tp, &ret_val);
9792                 return (ret_val);
9793         }
9794         /*
9795          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9796          * it's less than ts_recent, drop it.
9797          */
9798         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9799             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9800                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9801                         return (ret_val);
9802         }
9803         INP_WLOCK_ASSERT(tp->t_inpcb);
9804         if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9805                 return (ret_val);
9806         }
9807         /*
9808          * If new data are received on a connection after the user processes
9809          * are gone, then RST the other end.
9810          */
9811         if ((so->so_state & SS_NOFDREF) && tlen) {
9812                 /*
9813                  * We call a new function now so we might continue and setup
9814                  * to reset at all data being ack'd.
9815                  */
9816                 if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9817                         return (1);
9818         }
9819         /*
9820          * If last ACK falls within this segment's sequence numbers, record
9821          * its timestamp. NOTE: 1) That the test incorporates suggestions
9822          * from the latest proposal of the tcplw@cray.com list (Braden
9823          * 1993/04/26). 2) That updating only on newer timestamps interferes
9824          * with our earlier PAWS tests, so this check should be solely
9825          * predicated on the sequence space of this segment. 3) That we
9826          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9827          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9828          * SEG.Len, This modified check allows us to overcome RFC1323's
9829          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9830          * p.869. In such cases, we can still calculate the RTT correctly
9831          * when RCV.NXT == Last.ACK.Sent.
9832          */
9833         if ((to->to_flags & TOF_TS) != 0 &&
9834             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9835             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9836             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9837                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9838                 tp->ts_recent = to->to_tsval;
9839         }
9840         /*
9841          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9842          * is on (half-synchronized state), then queue data for later
9843          * processing; else drop segment and return.
9844          */
9845         if ((thflags & TH_ACK) == 0) {
9846                 if (tp->t_flags & TF_NEEDSYN) {
9847                         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9848                             tiwin, thflags, nxt_pkt));
9849                 } else if (tp->t_flags & TF_ACKNOW) {
9850                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9851                         bbr->r_wanted_output = 1;
9852                         return (ret_val);
9853                 } else {
9854                         ctf_do_drop(m, NULL);
9855                         return (0);
9856                 }
9857         }
9858         /*
9859          * Ack processing.
9860          */
9861         if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9862                 return (ret_val);
9863         }
9864         if (ourfinisacked) {
9865                 tcp_twstart(tp);
9866                 m_freem(m);
9867                 return (1);
9868         }
9869         if (sbavail(&so->so_snd)) {
9870                 if (bbr_progress_timeout_check(bbr)) {
9871                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9872                         return (1);
9873                 }
9874         }
9875         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9876             tiwin, thflags, nxt_pkt));
9877 }
9878
9879 /*
9880  * Return value of 1, the TCB is unlocked and most
9881  * likely gone, return value of 0, the TCB is still
9882  * locked.
9883  */
9884 static int
9885 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9886     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9887     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
9888 {
9889         int32_t ourfinisacked = 0;
9890         int32_t ret_val;
9891         struct tcp_bbr *bbr;
9892
9893         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9894         ctf_calc_rwin(so, tp);
9895         if ((thflags & TH_RST) ||
9896             (tp->t_fin_is_rst && (thflags & TH_FIN)))
9897                 return (ctf_process_rst(m, th, so, tp));
9898         /*
9899          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9900          * synchronized state.
9901          */
9902         if (thflags & TH_SYN) {
9903                 ctf_challenge_ack(m, th, tp, &ret_val);
9904                 return (ret_val);
9905         }
9906         /*
9907          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9908          * it's less than ts_recent, drop it.
9909          */
9910         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9911             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9912                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9913                         return (ret_val);
9914         }
9915         INP_WLOCK_ASSERT(tp->t_inpcb);
9916         if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9917                 return (ret_val);
9918         }
9919         /*
9920          * If new data are received on a connection after the user processes
9921          * are gone, then RST the other end.
9922          */
9923         if ((so->so_state & SS_NOFDREF) && tlen) {
9924                 /*
9925                  * We call a new function now so we might continue and setup
9926                  * to reset at all data being ack'd.
9927                  */
9928                 if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9929                         return (1);
9930         }
9931         /*
9932          * If last ACK falls within this segment's sequence numbers, record
9933          * its timestamp. NOTE: 1) That the test incorporates suggestions
9934          * from the latest proposal of the tcplw@cray.com list (Braden
9935          * 1993/04/26). 2) That updating only on newer timestamps interferes
9936          * with our earlier PAWS tests, so this check should be solely
9937          * predicated on the sequence space of this segment. 3) That we
9938          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9939          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9940          * SEG.Len, This modified check allows us to overcome RFC1323's
9941          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9942          * p.869. In such cases, we can still calculate the RTT correctly
9943          * when RCV.NXT == Last.ACK.Sent.
9944          */
9945         if ((to->to_flags & TOF_TS) != 0 &&
9946             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9947             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9948             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9949                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9950                 tp->ts_recent = to->to_tsval;
9951         }
9952         /*
9953          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9954          * is on (half-synchronized state), then queue data for later
9955          * processing; else drop segment and return.
9956          */
9957         if ((thflags & TH_ACK) == 0) {
9958                 if (tp->t_flags & TF_NEEDSYN) {
9959                         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9960                             tiwin, thflags, nxt_pkt));
9961                 } else if (tp->t_flags & TF_ACKNOW) {
9962                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9963                         bbr->r_wanted_output = 1;
9964                         return (ret_val);
9965                 } else {
9966                         ctf_do_drop(m, NULL);
9967                         return (0);
9968                 }
9969         }
9970         /*
9971          * case TCPS_LAST_ACK: Ack processing.
9972          */
9973         if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9974                 return (ret_val);
9975         }
9976         if (ourfinisacked) {
9977                 tp = tcp_close(tp);
9978                 ctf_do_drop(m, tp);
9979                 return (1);
9980         }
9981         if (sbavail(&so->so_snd)) {
9982                 if (bbr_progress_timeout_check(bbr)) {
9983                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9984                         return (1);
9985                 }
9986         }
9987         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9988             tiwin, thflags, nxt_pkt));
9989 }
9990
9991
9992 /*
9993  * Return value of 1, the TCB is unlocked and most
9994  * likely gone, return value of 0, the TCB is still
9995  * locked.
9996  */
9997 static int
9998 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9999     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
10000     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
10001 {
10002         int32_t ourfinisacked = 0;
10003         int32_t ret_val;
10004         struct tcp_bbr *bbr;
10005
10006         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10007         ctf_calc_rwin(so, tp);
10008         /* Reset receive buffer auto scaling when not in bulk receive mode. */
10009         if ((thflags & TH_RST) ||
10010             (tp->t_fin_is_rst && (thflags & TH_FIN)))
10011                 return (ctf_process_rst(m, th, so, tp));
10012
10013         /*
10014          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
10015          * synchronized state.
10016          */
10017         if (thflags & TH_SYN) {
10018                 ctf_challenge_ack(m, th, tp, &ret_val);
10019                 return (ret_val);
10020         }
10021         INP_WLOCK_ASSERT(tp->t_inpcb);
10022         /*
10023          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
10024          * it's less than ts_recent, drop it.
10025          */
10026         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
10027             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
10028                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
10029                         return (ret_val);
10030         }
10031         INP_WLOCK_ASSERT(tp->t_inpcb);
10032         if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
10033                 return (ret_val);
10034         }
10035         /*
10036          * If new data are received on a connection after the user processes
10037          * are gone, then we may RST the other end depending on the outcome
10038          * of bbr_check_data_after_close.
10039          */
10040         if ((so->so_state & SS_NOFDREF) &&
10041             tlen) {
10042                 /*
10043                  * We call a new function now so we might continue and setup
10044                  * to reset at all data being ack'd.
10045                  */
10046                 if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
10047                         return (1);
10048         }
10049         INP_WLOCK_ASSERT(tp->t_inpcb);
10050         /*
10051          * If last ACK falls within this segment's sequence numbers, record
10052          * its timestamp. NOTE: 1) That the test incorporates suggestions
10053          * from the latest proposal of the tcplw@cray.com list (Braden
10054          * 1993/04/26). 2) That updating only on newer timestamps interferes
10055          * with our earlier PAWS tests, so this check should be solely
10056          * predicated on the sequence space of this segment. 3) That we
10057          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
10058          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
10059          * SEG.Len, This modified check allows us to overcome RFC1323's
10060          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
10061          * p.869. In such cases, we can still calculate the RTT correctly
10062          * when RCV.NXT == Last.ACK.Sent.
10063          */
10064         INP_WLOCK_ASSERT(tp->t_inpcb);
10065         if ((to->to_flags & TOF_TS) != 0 &&
10066             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
10067             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
10068             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
10069                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
10070                 tp->ts_recent = to->to_tsval;
10071         }
10072         /*
10073          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
10074          * is on (half-synchronized state), then queue data for later
10075          * processing; else drop segment and return.
10076          */
10077         if ((thflags & TH_ACK) == 0) {
10078                 if (tp->t_flags & TF_NEEDSYN) {
10079                         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
10080                             tiwin, thflags, nxt_pkt));
10081                 } else if (tp->t_flags & TF_ACKNOW) {
10082                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
10083                         bbr->r_wanted_output = 1;
10084                         return (ret_val);
10085                 } else {
10086                         ctf_do_drop(m, NULL);
10087                         return (0);
10088                 }
10089         }
10090         /*
10091          * Ack processing.
10092          */
10093         INP_WLOCK_ASSERT(tp->t_inpcb);
10094         if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
10095                 return (ret_val);
10096         }
10097         if (sbavail(&so->so_snd)) {
10098                 if (bbr_progress_timeout_check(bbr)) {
10099                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
10100                         return (1);
10101                 }
10102         }
10103         INP_WLOCK_ASSERT(tp->t_inpcb);
10104         return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
10105             tiwin, thflags, nxt_pkt));
10106 }
10107
10108 static void
10109 bbr_stop_all_timers(struct tcpcb *tp)
10110 {
10111         struct tcp_bbr *bbr;
10112
10113         /*
10114          * Assure no timers are running.
10115          */
10116         if (tcp_timer_active(tp, TT_PERSIST)) {
10117                 /* We enter in persists, set the flag appropriately */
10118                 bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10119                 bbr->rc_in_persist = 1;
10120         }
10121         tcp_timer_suspend(tp, TT_PERSIST);
10122         tcp_timer_suspend(tp, TT_REXMT);
10123         tcp_timer_suspend(tp, TT_KEEP);
10124         tcp_timer_suspend(tp, TT_DELACK);
10125 }
10126
10127 static void
10128 bbr_google_mode_on(struct tcp_bbr *bbr)
10129 {
10130         bbr->rc_use_google = 1;
10131         bbr->rc_no_pacing = 0;
10132         bbr->r_ctl.bbr_google_discount = bbr_google_discount;
10133         bbr->r_use_policer = bbr_policer_detection_enabled;
10134         bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10135         bbr->bbr_use_rack_cheat = 0;
10136         bbr->r_ctl.rc_incr_tmrs = 0;
10137         bbr->r_ctl.rc_inc_tcp_oh = 0;
10138         bbr->r_ctl.rc_inc_ip_oh = 0;
10139         bbr->r_ctl.rc_inc_enet_oh = 0;
10140         reset_time(&bbr->r_ctl.rc_delrate,
10141                    BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10142         reset_time_small(&bbr->r_ctl.rc_rttprop,
10143                          (11 * USECS_IN_SECOND));
10144         tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
10145 }
10146
10147 static void
10148 bbr_google_mode_off(struct tcp_bbr *bbr)
10149 {
10150         bbr->rc_use_google = 0;
10151         bbr->r_ctl.bbr_google_discount = 0;
10152         bbr->no_pacing_until = bbr_no_pacing_until;
10153         bbr->r_use_policer = 0;
10154         if (bbr->no_pacing_until)
10155                 bbr->rc_no_pacing = 1;
10156         else
10157                 bbr->rc_no_pacing = 0;
10158         if (bbr_use_rack_resend_cheat)
10159                 bbr->bbr_use_rack_cheat = 1;
10160         else
10161                 bbr->bbr_use_rack_cheat = 0;
10162         if (bbr_incr_timers)
10163                 bbr->r_ctl.rc_incr_tmrs = 1;
10164         else
10165                 bbr->r_ctl.rc_incr_tmrs = 0;
10166         if (bbr_include_tcp_oh)
10167                 bbr->r_ctl.rc_inc_tcp_oh = 1;
10168         else
10169                 bbr->r_ctl.rc_inc_tcp_oh = 0;
10170         if (bbr_include_ip_oh)
10171                 bbr->r_ctl.rc_inc_ip_oh = 1;
10172         else
10173                 bbr->r_ctl.rc_inc_ip_oh = 0;
10174         if (bbr_include_enet_oh)
10175                 bbr->r_ctl.rc_inc_enet_oh = 1;
10176         else
10177                 bbr->r_ctl.rc_inc_enet_oh = 0;
10178         bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10179         reset_time(&bbr->r_ctl.rc_delrate,
10180                    bbr_num_pktepo_for_del_limit);
10181         reset_time_small(&bbr->r_ctl.rc_rttprop,
10182                          (bbr_filter_len_sec * USECS_IN_SECOND));
10183         tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
10184 }
10185 /*
10186  * Return 0 on success, non-zero on failure
10187  * which indicates the error (usually no memory).
10188  */
10189 static int
10190 bbr_init(struct tcpcb *tp)
10191 {
10192         struct tcp_bbr *bbr = NULL;
10193         struct inpcb *inp;
10194         uint32_t cts;
10195
10196         tp->t_fb_ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
10197         if (tp->t_fb_ptr == NULL) {
10198                 /*
10199                  * We need to allocate memory but cant. The INP and INP_INFO
10200                  * locks and they are recusive (happens during setup. So a
10201                  * scheme to drop the locks fails :(
10202                  *
10203                  */
10204                 return (ENOMEM);
10205         }
10206         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10207         bbr->rtt_valid = 0;
10208         inp = tp->t_inpcb;
10209         inp->inp_flags2 |= INP_CANNOT_DO_ECN;
10210         inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
10211         TAILQ_INIT(&bbr->r_ctl.rc_map);
10212         TAILQ_INIT(&bbr->r_ctl.rc_free);
10213         TAILQ_INIT(&bbr->r_ctl.rc_tmap);
10214         bbr->rc_tp = tp;
10215         if (tp->t_inpcb) {
10216                 bbr->rc_inp = tp->t_inpcb;
10217         }
10218         cts = tcp_get_usecs(&bbr->rc_tv);
10219         tp->t_acktime = 0;
10220         bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
10221         bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
10222         bbr->rc_tlp_threshold = bbr_tlp_thresh;
10223         bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
10224         bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
10225         bbr->r_ctl.rc_min_to = bbr_min_to;
10226         bbr->rc_bbr_state = BBR_STATE_STARTUP;
10227         bbr->r_ctl.bbr_lost_at_state = 0;
10228         bbr->r_ctl.rc_lost_at_startup = 0;
10229         bbr->rc_all_timers_stopped = 0;
10230         bbr->r_ctl.rc_bbr_lastbtlbw = 0;
10231         bbr->r_ctl.rc_pkt_epoch_del = 0;
10232         bbr->r_ctl.rc_pkt_epoch = 0;
10233         bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
10234         bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
10235         bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
10236         bbr->r_ctl.rc_went_idle_time = cts;
10237         bbr->rc_pacer_started = cts;
10238         bbr->r_ctl.rc_pkt_epoch_time = cts;
10239         bbr->r_ctl.rc_rcvtime = cts;
10240         bbr->r_ctl.rc_bbr_state_time = cts;
10241         bbr->r_ctl.rc_del_time = cts;
10242         bbr->r_ctl.rc_tlp_rxt_last_time = cts;
10243         bbr->r_ctl.last_in_probertt = cts;
10244         bbr->skip_gain = 0;
10245         bbr->gain_is_limited = 0;
10246         bbr->no_pacing_until = bbr_no_pacing_until;
10247         if (bbr->no_pacing_until)
10248                 bbr->rc_no_pacing = 1;
10249         if (bbr_use_google_algo) {
10250                 bbr->rc_no_pacing = 0;
10251                 bbr->rc_use_google = 1;
10252                 bbr->r_ctl.bbr_google_discount = bbr_google_discount;
10253                 bbr->r_use_policer = bbr_policer_detection_enabled;
10254         } else {
10255                 bbr->rc_use_google = 0;
10256                 bbr->r_ctl.bbr_google_discount = 0;
10257                 bbr->r_use_policer = 0;
10258         }
10259         if (bbr_ts_limiting)
10260                 bbr->rc_use_ts_limit = 1;
10261         else
10262                 bbr->rc_use_ts_limit = 0;
10263         if (bbr_ts_can_raise) 
10264                 bbr->ts_can_raise = 1;
10265         else
10266                 bbr->ts_can_raise = 0;
10267         if (V_tcp_delack_enabled == 1)
10268                 tp->t_delayed_ack = 2;
10269         else if (V_tcp_delack_enabled == 0)
10270                 tp->t_delayed_ack = 0;
10271         else if (V_tcp_delack_enabled < 100)
10272                 tp->t_delayed_ack = V_tcp_delack_enabled;
10273         else
10274                 tp->t_delayed_ack = 2;
10275         if (bbr->rc_use_google == 0)
10276                 bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10277         else
10278                 bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10279         bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10280         bbr->rc_max_rto_sec = bbr_rto_max_sec;
10281         bbr->rc_init_win = bbr_def_init_win;
10282         if (tp->t_flags & TF_REQ_TSTMP)
10283                 bbr->rc_last_options = TCP_TS_OVERHEAD;
10284         bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10285         bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10286         bbr->r_init_rtt = 1;
10287
10288         counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10289         if (bbr_allow_hdwr_pacing)
10290                 bbr->bbr_hdw_pace_ena = 1;
10291         else
10292                 bbr->bbr_hdw_pace_ena = 0;
10293         if (bbr_sends_full_iwnd)
10294                 bbr->bbr_init_win_cheat = 1;
10295         else
10296                 bbr->bbr_init_win_cheat = 0;
10297         bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10298         bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10299         bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10300         bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10301         bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10302         bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10303         bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10304         bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10305         bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10306         bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10307         bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10308         bbr->r_ctl.rc_rtt_shrinks = cts;
10309         if (bbr->rc_use_google) {
10310                 setup_time_filter(&bbr->r_ctl.rc_delrate,
10311                                   FILTER_TYPE_MAX,
10312                                   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10313                 setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10314                                         FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10315         } else {
10316                 setup_time_filter(&bbr->r_ctl.rc_delrate,
10317                                   FILTER_TYPE_MAX,
10318                                   bbr_num_pktepo_for_del_limit);
10319                 setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10320                                         FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10321         }
10322         bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10323         if (bbr_uses_idle_restart)
10324                 bbr->rc_use_idle_restart = 1;
10325         else
10326                 bbr->rc_use_idle_restart = 0;
10327         bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10328         bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10329         if (bbr_resends_use_tso)
10330                 bbr->rc_resends_use_tso = 1;
10331 #ifdef NETFLIX_PEAKRATE
10332         tp->t_peakrate_thr = tp->t_maxpeakrate;
10333 #endif
10334         if (tp->snd_una != tp->snd_max) {
10335                 /* Create a send map for the current outstanding data */
10336                 struct bbr_sendmap *rsm;
10337
10338                 rsm = bbr_alloc(bbr);
10339                 if (rsm == NULL) {
10340                         uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10341                         tp->t_fb_ptr = NULL;
10342                         return (ENOMEM);
10343                 }
10344                 rsm->r_flags = BBR_OVERMAX;
10345                 rsm->r_tim_lastsent[0] = cts;
10346                 rsm->r_rtr_cnt = 1;
10347                 rsm->r_rtr_bytes = 0;
10348                 rsm->r_start = tp->snd_una;
10349                 rsm->r_end = tp->snd_max;
10350                 rsm->r_dupack = 0;
10351                 rsm->r_delivered = bbr->r_ctl.rc_delivered;
10352                 rsm->r_ts_valid = 0;
10353                 rsm->r_del_ack_ts = tp->ts_recent;
10354                 rsm->r_del_time = cts;
10355                 if (bbr->r_ctl.r_app_limited_until)
10356                         rsm->r_app_limited = 1;
10357                 else
10358                         rsm->r_app_limited = 0;
10359                 TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10360                 TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10361                 rsm->r_in_tmap = 1;
10362                 if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10363                         rsm->r_bbr_state = bbr_state_val(bbr);
10364                 else
10365                         rsm->r_bbr_state = 8;
10366         }
10367         if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10368                 bbr->bbr_use_rack_cheat = 1;
10369         if (bbr_incr_timers && (bbr->rc_use_google == 0))
10370                 bbr->r_ctl.rc_incr_tmrs = 1;
10371         if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10372                 bbr->r_ctl.rc_inc_tcp_oh = 1;
10373         if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10374                 bbr->r_ctl.rc_inc_ip_oh = 1;
10375         if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10376                 bbr->r_ctl.rc_inc_enet_oh = 1;
10377
10378         bbr_log_type_statechange(bbr, cts, __LINE__);
10379         if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10380             (tp->t_srtt)) {
10381                 uint32_t rtt;
10382
10383                 rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10384                 apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10385         }
10386         /* announce the settings and state */
10387         bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10388         tcp_bbr_tso_size_check(bbr, cts);
10389         /*
10390          * Now call the generic function to start a timer. This will place
10391          * the TCB on the hptsi wheel if a timer is needed with appropriate
10392          * flags.
10393          */
10394         bbr_stop_all_timers(tp);
10395         bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10396         return (0);
10397 }
10398
10399 /*
10400  * Return 0 if we can accept the connection. Return
10401  * non-zero if we can't handle the connection. A EAGAIN
10402  * means you need to wait until the connection is up.
10403  * a EADDRNOTAVAIL means we can never handle the connection
10404  * (no SACK).
10405  */
10406 static int
10407 bbr_handoff_ok(struct tcpcb *tp)
10408 {
10409         if ((tp->t_state == TCPS_CLOSED) ||
10410             (tp->t_state == TCPS_LISTEN)) {
10411                 /* Sure no problem though it may not stick */
10412                 return (0);
10413         }
10414         if ((tp->t_state == TCPS_SYN_SENT) ||
10415             (tp->t_state == TCPS_SYN_RECEIVED)) {
10416                 /*
10417                  * We really don't know you have to get to ESTAB or beyond
10418                  * to tell.
10419                  */
10420                 return (EAGAIN);
10421         }
10422         if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10423                 return (0);
10424         }
10425         /*
10426          * If we reach here we don't do SACK on this connection so we can
10427          * never do rack.
10428          */
10429         return (EINVAL);
10430 }
10431
10432 static void
10433 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10434 {
10435         if (tp->t_fb_ptr) {
10436                 uint32_t calc;
10437                 struct tcp_bbr *bbr;
10438                 struct bbr_sendmap *rsm;
10439
10440                 bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10441                 if (bbr->r_ctl.crte)
10442                         tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10443                 bbr_log_flowend(bbr);
10444                 bbr->rc_tp = NULL;
10445                 if (tp->t_inpcb) {
10446                         /* Backout any flags2 we applied */
10447                         tp->t_inpcb->inp_flags2 &= ~INP_CANNOT_DO_ECN;
10448                         tp->t_inpcb->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
10449                         tp->t_inpcb->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
10450                 }
10451                 if (bbr->bbr_hdrw_pacing)
10452                         counter_u64_add(bbr_flows_whdwr_pacing, -1);
10453                 else
10454                         counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10455                 rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10456                 while (rsm) {
10457                         TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10458                         uma_zfree(bbr_zone, rsm);
10459                         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10460                 }
10461                 rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10462                 while (rsm) {
10463                         TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10464                         uma_zfree(bbr_zone, rsm);
10465                         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10466                 }
10467                 calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10468                 if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10469                         BBR_STAT_INC(bbr_dynamic_rwnd);
10470                 else
10471                         BBR_STAT_INC(bbr_static_rwnd);
10472                 bbr->r_ctl.rc_free_cnt = 0;
10473                 uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10474                 tp->t_fb_ptr = NULL;
10475         }
10476         /* Make sure snd_nxt is correctly set */
10477         tp->snd_nxt = tp->snd_max;
10478 }
10479
10480 static void
10481 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10482 {
10483         switch (tp->t_state) {
10484         case TCPS_SYN_SENT:
10485                 bbr->r_state = TCPS_SYN_SENT;
10486                 bbr->r_substate = bbr_do_syn_sent;
10487                 break;
10488         case TCPS_SYN_RECEIVED:
10489                 bbr->r_state = TCPS_SYN_RECEIVED;
10490                 bbr->r_substate = bbr_do_syn_recv;
10491                 break;
10492         case TCPS_ESTABLISHED:
10493                 bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10494                 bbr->r_state = TCPS_ESTABLISHED;
10495                 bbr->r_substate = bbr_do_established;
10496                 break;
10497         case TCPS_CLOSE_WAIT:
10498                 bbr->r_state = TCPS_CLOSE_WAIT;
10499                 bbr->r_substate = bbr_do_close_wait;
10500                 break;
10501         case TCPS_FIN_WAIT_1:
10502                 bbr->r_state = TCPS_FIN_WAIT_1;
10503                 bbr->r_substate = bbr_do_fin_wait_1;
10504                 break;
10505         case TCPS_CLOSING:
10506                 bbr->r_state = TCPS_CLOSING;
10507                 bbr->r_substate = bbr_do_closing;
10508                 break;
10509         case TCPS_LAST_ACK:
10510                 bbr->r_state = TCPS_LAST_ACK;
10511                 bbr->r_substate = bbr_do_lastack;
10512                 break;
10513         case TCPS_FIN_WAIT_2:
10514                 bbr->r_state = TCPS_FIN_WAIT_2;
10515                 bbr->r_substate = bbr_do_fin_wait_2;
10516                 break;
10517         case TCPS_LISTEN:
10518         case TCPS_CLOSED:
10519         case TCPS_TIME_WAIT:
10520         default:
10521                 break;
10522         };
10523 }
10524
10525 static void
10526 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10527 {
10528         /*
10529          * Now what state are we going into now? Is there adjustments
10530          * needed?
10531          */
10532         int32_t old_state, old_gain;
10533
10534         
10535         old_state = bbr_state_val(bbr);
10536         old_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
10537         if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10538                 /* Save the lowest srtt we saw in our end of the sub-state */
10539                 bbr->rc_hit_state_1 = 0;
10540                 if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10541                         bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10542         }
10543         bbr->rc_bbr_substate++;
10544         if (bbr->rc_bbr_substate >= BBR_SUBSTATE_COUNT) {
10545                 /* Cycle back to first state-> gain */
10546                 bbr->rc_bbr_substate = 0;
10547         }
10548         if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10549                 /*
10550                  * We enter the gain(5/4) cycle (possibly less if
10551                  * shallow buffer detection is enabled)
10552                  */
10553                 if (bbr->skip_gain) {
10554                         /* 
10555                          * Hardware pacing has set our rate to
10556                          * the max and limited our b/w just
10557                          * do level i.e. no gain.
10558                          */
10559                         bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10560                 } else if (bbr->gain_is_limited &&
10561                            bbr->bbr_hdrw_pacing &&
10562                            bbr->r_ctl.crte) {
10563                         /* 
10564                          * We can't gain above the hardware pacing
10565                          * rate which is less than our rate + the gain
10566                          * calculate the gain needed to reach the hardware
10567                          * pacing rate..
10568                          */
10569                         uint64_t bw, rate, gain_calc;
10570
10571                         bw = bbr_get_bw(bbr);
10572                         rate = bbr->r_ctl.crte->rate;
10573                         if ((rate > bw) &&
10574                             (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10575                                 gain_calc = (rate * BBR_UNIT) / bw;
10576                                 if (gain_calc < BBR_UNIT)
10577                                         gain_calc = BBR_UNIT;
10578                                 bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10579                         } else {
10580                                 bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10581                         }
10582                 } else
10583                         bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10584                 if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10585                         bbr->r_ctl.rc_bbr_state_atflight = cts;
10586                 } else 
10587                         bbr->r_ctl.rc_bbr_state_atflight = 0;
10588         } else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10589                 bbr->rc_hit_state_1 = 1;
10590                 bbr->r_ctl.rc_exta_time_gd = 0;
10591                 bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10592                                                      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10593                 if (bbr_state_drain_2_tar) {
10594                         bbr->r_ctl.rc_bbr_state_atflight = 0;
10595                 } else
10596                         bbr->r_ctl.rc_bbr_state_atflight = cts;
10597                 bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10598         } else {
10599                 /* All other cycles hit here 2-7 */
10600                 if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10601                         if (bbr_sub_drain_slam_cwnd &&
10602                             (bbr->rc_use_google == 0) &&
10603                             (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10604                                 bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10605                                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10606                         }
10607                         if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10608                                 bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10609                                                                bbr_get_rtt(bbr, BBR_RTT_PROP));
10610                         else
10611                                 bbr->r_ctl.rc_exta_time_gd = 0;
10612                         if (bbr->r_ctl.rc_exta_time_gd) {
10613                                 bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10614                                 /* Now chop up the time for each state (div by 7) */
10615                                 bbr->r_ctl.rc_level_state_extra /= 7;
10616                                 if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10617                                         /* Add a randomization */
10618                                         bbr_randomize_extra_state_time(bbr);
10619                                 }
10620                         }
10621                 }
10622                 bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10623                 bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10624         }
10625         if (bbr->rc_use_google) {
10626                 bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10627         }
10628         bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10629         bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10630         if (dolog)
10631                 bbr_log_type_statechange(bbr, cts, line);
10632
10633         if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10634                 uint32_t time_in;
10635
10636                 time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10637                 if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10638                         counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10639                 } else {
10640                         counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10641                 }
10642         }
10643         bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10644         bbr_set_state_target(bbr, __LINE__);
10645         if (bbr_sub_drain_slam_cwnd &&
10646             (bbr->rc_use_google == 0) &&
10647             (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10648                 /* Slam down the cwnd */
10649                 bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10650                 bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10651                 if (bbr_sub_drain_app_limit) {
10652                         /* Go app limited if we are on a long drain */
10653                         bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10654                                                           ctf_flight_size(bbr->rc_tp,
10655                                                               (bbr->r_ctl.rc_sacked +
10656                                                                bbr->r_ctl.rc_lost_bytes)));
10657                 }
10658                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10659         }
10660         if (bbr->rc_lt_use_bw) {
10661                 /* In policed mode we clamp pacing_gain to BBR_UNIT */
10662                 bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10663         }
10664         /* Google changes TSO size every cycle */
10665         if (bbr->rc_use_google)
10666                 tcp_bbr_tso_size_check(bbr, cts);
10667         bbr->r_ctl.gain_epoch = cts;
10668         bbr->r_ctl.rc_bbr_state_time = cts;
10669         bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10670 }
10671
10672 static void
10673 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10674 {
10675         if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10676             (google_allow_early_out == 1) &&
10677             (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10678                 /* We have reached out target flight size possibly early */
10679                 goto change_state;
10680         }
10681         if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10682                 return;
10683         }
10684         if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10685                 /* 
10686                  * Must be a rttProp movement forward before
10687                  * we can change states.
10688                  */
10689                 return;
10690         }
10691         if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10692                 /* 
10693                  * The needed time has passed but for
10694                  * the gain cycle extra rules apply:
10695                  * 1) If we have seen loss, we exit
10696                  * 2) If we have not reached the target
10697                  *    we stay in GAIN (gain-to-target).
10698                  */
10699                 if (google_consider_lost && losses)
10700                         goto change_state;
10701                 if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10702                         return;
10703                 }
10704         }
10705 change_state:
10706         /* For gain we must reach our target, all others last 1 rttProp */
10707         bbr_substate_change(bbr, cts, __LINE__, 1);
10708 }
10709
10710 static void
10711 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10712 {
10713         uint32_t flight, bbr_cur_cycle_time;
10714         
10715         if (bbr->rc_use_google) {
10716                 bbr_set_probebw_google_gains(bbr, cts, losses);
10717                 return;
10718         }
10719         if (cts == 0) {
10720                 /* 
10721                  * Never alow cts to be 0 we
10722                  * do this so we can judge if
10723                  * we have set a timestamp.
10724                  */
10725                 cts = 1;
10726         }
10727         if (bbr_state_is_pkt_epoch)
10728                 bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10729         else
10730                 bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10731         
10732         if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10733                 if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10734                         flight = ctf_flight_size(bbr->rc_tp,
10735                                      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10736                         if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10737                                 /* Keep it slam down */ 
10738                                 if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10739                                         bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10740                                         bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10741                                 }
10742                                 if (bbr_sub_drain_app_limit) {
10743                                         /* Go app limited if we are on a long drain */
10744                                         bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10745                                 }
10746                         }
10747                         if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10748                             (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10749                              (flight >= bbr->r_ctl.flightsize_at_drain))) {
10750                                 /*
10751                                  * Still here after the same time as
10752                                  * the gain. We need to drain harder
10753                                  * for the next srtt. Reduce by a set amount
10754                                  * the gain drop is capped at DRAIN states
10755                                  * value (88).
10756                                  */
10757                                 bbr->r_ctl.flightsize_at_drain = flight;
10758                                 if (bbr_drain_drop_mul &&
10759                                     bbr_drain_drop_div &&
10760                                     (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10761                                         /* Use your specific drop value (def 4/5 = 20%) */
10762                                         bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10763                                         bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10764                                 } else {
10765                                         /* You get drop of 20% */
10766                                         bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10767                                         bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10768                                 }
10769                                 if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10770                                         /* Reduce our gain again to the bottom  */
10771                                         bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10772                                 }
10773                                 bbr_log_exit_gain(bbr, cts, 4);
10774                                 /*
10775                                  * Extend out so we wait another
10776                                  * epoch before dropping again.
10777                                  */
10778                                 bbr->r_ctl.gain_epoch = cts;
10779                         }
10780                         if (flight <= bbr->r_ctl.rc_target_at_state) {
10781                                 if (bbr_sub_drain_slam_cwnd &&
10782                                     (bbr->rc_use_google == 0) &&
10783                                     (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10784                                         bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10785                                         bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10786                                 }
10787                                 bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10788                                 bbr_log_exit_gain(bbr, cts, 3);
10789                         }
10790                 } else {
10791                         /* Its a gain  */
10792                         if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10793                                 bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10794                                 goto change_state;
10795                         }
10796                         if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10797                             ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10798                              bbr->rc_tp->snd_wnd)) {
10799                                 bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10800                                 bbr_log_exit_gain(bbr, cts, 2);
10801                         }
10802                 }
10803                 /**
10804                  * We fall through and return always one of two things has
10805                  * occured. 
10806                  * 1) We are still not at target 
10807                  *    <or> 
10808                  * 2) We reached the target and set rc_bbr_state_atflight 
10809                  *    which means we no longer hit this block 
10810                  *    next time we are called.
10811                  */
10812                 return;
10813         }
10814 change_state:
10815         if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10816                 return;
10817         if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10818                 /* Less than a full time-period has passed */
10819                 return;
10820         }
10821         if (bbr->r_ctl.rc_level_state_extra &&
10822             (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10823             ((cts - bbr->r_ctl.rc_bbr_state_time) <
10824              (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10825                 /* Less than a full time-period + extra has passed */
10826                 return;
10827         }
10828         if (bbr_gain_gets_extra_too &&
10829             bbr->r_ctl.rc_level_state_extra &&
10830             (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10831             ((cts - bbr->r_ctl.rc_bbr_state_time) <
10832              (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10833                 /* Less than a full time-period + extra has passed */
10834                 return;
10835         }
10836         bbr_substate_change(bbr, cts, __LINE__, 1);
10837 }
10838
10839 static uint32_t
10840 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10841 {
10842         uint32_t mss, tar;
10843
10844         if (bbr->rc_use_google) {
10845                 /* Google just uses the cwnd target */
10846                 tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10847         } else {
10848                 mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10849                           bbr->r_ctl.rc_pace_max_segs);
10850                 /* Get the base cwnd with gain rounded to a mss */
10851                 tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10852                                                       gain), mss);
10853                 /* Make sure it is within our min */
10854                 if (tar < get_min_cwnd(bbr))
10855                         return (get_min_cwnd(bbr));
10856         }
10857         return (tar);
10858 }
10859
10860 static void
10861 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10862 {
10863         uint32_t tar, meth;
10864         
10865         if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10866             ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10867                 /* Special case using old probe-rtt method */
10868                 tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10869                 meth = 1;
10870         } else {
10871                 /* Non-probe-rtt case and reduced probe-rtt  */
10872                 if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10873                     (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10874                         /* For gain cycle we use the hptsi gain */
10875                         tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10876                         meth = 2;
10877                 } else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10878                         /* 
10879                          * If configured, or for google all other states
10880                          * get BBR_UNIT.
10881                          */
10882                         tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10883                         meth = 3;
10884                 } else {
10885                         /* 
10886                          * Or we set a target based on the pacing gain 
10887                          * for non-google mode and default (non-configured).
10888                          * Note we don't set a target goal below drain (192).
10889                          */
10890                         if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10891                                 tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10892                                 meth = 4;
10893                         } else {
10894                                 tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10895                                 meth = 5;
10896                         }
10897                 }
10898         }
10899         bbr_log_set_of_state_target(bbr, tar, line, meth);
10900         bbr->r_ctl.rc_target_at_state = tar;
10901 }
10902
10903 static void
10904 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10905 {
10906         /* Change to probe_rtt */
10907         uint32_t time_in;
10908
10909         bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10910         bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10911                                              (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10912         bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10913                                           + bbr->r_ctl.rc_delivered);
10914         /* Setup so we force feed the filter */
10915         if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10916                 bbr->rc_prtt_set_ts = 1;
10917         if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10918                 time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10919                 counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10920         }
10921         bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10922         bbr->r_ctl.rc_rtt_shrinks = cts;
10923         bbr->r_ctl.last_in_probertt = cts;
10924         bbr->r_ctl.rc_probertt_srttchktim = cts;
10925         bbr->r_ctl.rc_bbr_state_time = cts;
10926         bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10927         /* We need to force the filter to update */
10928         
10929         if ((bbr_sub_drain_slam_cwnd) &&
10930             bbr->rc_hit_state_1 &&
10931             (bbr->rc_use_google == 0) &&
10932             (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10933                 if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10934                         bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10935         } else 
10936                 bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10937         /* Update the lost */
10938         bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10939         if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10940                 /* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10941                 bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10942                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10943                 bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10944                 bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10945                 bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10946                 bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10947         } else {
10948                 /*
10949                  * We bring it down slowly by using a hptsi gain that is
10950                  * probably 75%. This will slowly float down our outstanding
10951                  * without tampering with the cwnd.
10952                  */
10953                 bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10954                 bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10955                 bbr_set_state_target(bbr, __LINE__);
10956                 if (bbr_prtt_slam_cwnd &&
10957                     (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10958                         bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10959                         bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10960                 }
10961         }
10962         if (ctf_flight_size(bbr->rc_tp,
10963                 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10964             bbr->r_ctl.rc_target_at_state) {
10965                 /* We are at target */
10966                 bbr->r_ctl.rc_bbr_enters_probertt = cts;
10967         } else {
10968                 /* We need to come down to reach target before our time begins */
10969                 bbr->r_ctl.rc_bbr_enters_probertt = 0;
10970         }
10971         bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10972         BBR_STAT_INC(bbr_enter_probertt);
10973         bbr_log_exit_gain(bbr, cts, 0);
10974         bbr_log_type_statechange(bbr, cts, line);
10975 }
10976
10977 static void
10978 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10979 {
10980         /* 
10981          * Sanity check on probe-rtt intervals.
10982          * In crazy situations where we are competing
10983          * against new-reno flows with huge buffers
10984          * our rtt-prop interval could come to dominate
10985          * things if we can't get through a full set
10986          * of cycles, we need to adjust it.
10987          */
10988         if (bbr_can_adjust_probertt &&
10989             (bbr->rc_use_google == 0)) {
10990                 uint16_t val = 0;
10991                 uint32_t cur_rttp, fval, newval, baseval;
10992
10993                 /* Are we to small and go into probe-rtt to often? */
10994                 baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10995                 cur_rttp = roundup(baseval, USECS_IN_SECOND);
10996                 fval = bbr_filter_len_sec * USECS_IN_SECOND;
10997                 if (bbr_is_ratio == 0) {
10998                         if (fval > bbr_rtt_probe_limit) 
10999                                 newval = cur_rttp + (fval - bbr_rtt_probe_limit);
11000                         else
11001                                 newval = cur_rttp;
11002                 } else {
11003                         int mul;
11004
11005                         mul = fval / bbr_rtt_probe_limit;
11006                         newval = cur_rttp * mul;
11007                 }
11008                 if (cur_rttp >  bbr->r_ctl.rc_probertt_int) {
11009                         bbr->r_ctl.rc_probertt_int = cur_rttp;
11010                         reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
11011                         val = 1;
11012                 } else {
11013                         /* 
11014                          * No adjustments were made
11015                          * do we need to shrink it?
11016                          */
11017                         if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
11018                                 if (cur_rttp <= bbr_rtt_probe_limit) {
11019                                         /* 
11020                                          * Things have calmed down lets 
11021                                          * shrink all the way to default 
11022                                          */
11023                                         bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
11024                                         reset_time_small(&bbr->r_ctl.rc_rttprop,
11025                                                          (bbr_filter_len_sec * USECS_IN_SECOND));
11026                                         cur_rttp = bbr_rtt_probe_limit;
11027                                         newval = (bbr_filter_len_sec * USECS_IN_SECOND);
11028                                         val = 2;
11029                                 } else {
11030                                         /*
11031                                          * Well does some adjustment make sense?
11032                                          */
11033                                         if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
11034                                                 /* We can reduce interval time some */
11035                                                 bbr->r_ctl.rc_probertt_int = cur_rttp;
11036                                                 reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
11037                                                 val = 3;
11038                                         }
11039                                 }
11040                         }
11041                 }
11042                 if (val)
11043                         bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
11044         }
11045 }
11046
11047 static void
11048 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
11049 {
11050         /* Exit probe-rtt */
11051
11052         if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
11053                 tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11054                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11055         }
11056         bbr_log_exit_gain(bbr, cts, 1);
11057         bbr->rc_hit_state_1 = 0;
11058         bbr->r_ctl.rc_rtt_shrinks = cts;
11059         bbr->r_ctl.last_in_probertt = cts;
11060         bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
11061         bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11062         bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
11063                                               (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11064                                           bbr->r_ctl.rc_delivered);
11065         if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11066                 uint32_t time_in;
11067
11068                 time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11069                 counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11070         }
11071         if (bbr->rc_filled_pipe) {
11072                 /* Switch to probe_bw */
11073                 bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11074                 bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11075                 bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
11076                 bbr_substate_change(bbr, cts, __LINE__, 0);
11077                 bbr_log_type_statechange(bbr, cts, __LINE__);
11078         } else {
11079                 /* Back to startup */
11080                 bbr->rc_bbr_state = BBR_STATE_STARTUP;
11081                 bbr->r_ctl.rc_bbr_state_time = cts;
11082                 /* 
11083                  * We don't want to give a complete free 3 
11084                  * measurements until we exit, so we use
11085                  * the number of pe's we were in probe-rtt
11086                  * to add to the startup_epoch. That way
11087                  * we will still retain the old state.
11088                  */
11089                 bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
11090                 bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11091                 /* Make sure to use the lower pg when shifting back in */
11092                 if (bbr->r_ctl.rc_lost &&
11093                     bbr_use_lower_gain_in_startup &&
11094                     (bbr->rc_use_google == 0))
11095                         bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
11096                 else
11097                         bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
11098                 bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
11099                 /* Probably not needed but set it anyway */
11100                 bbr_set_state_target(bbr, __LINE__);
11101                 bbr_log_type_statechange(bbr, cts, __LINE__);
11102                 bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11103                     bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 0);
11104         }
11105         bbr_check_probe_rtt_limits(bbr, cts);
11106 }
11107
11108 static int32_t inline
11109 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
11110 {
11111         if ((bbr->rc_past_init_win == 1) &&
11112             (bbr->rc_in_persist == 0) &&
11113             (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
11114                 return (1);
11115         }
11116         if (bbr_can_force_probertt &&
11117             (bbr->rc_in_persist == 0) &&
11118             (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
11119             ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
11120                 return (1);
11121         }
11122         return (0);
11123 }
11124
11125
11126 static int32_t 
11127 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
11128 {
11129         uint64_t btlbw, gain;
11130         if (pkt_epoch == 0) {
11131                 /*
11132                  * Need to be on a pkt-epoch to continue.
11133                  */
11134                 return (0);
11135         }
11136         btlbw = bbr_get_full_bw(bbr);
11137         gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11138                  (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11139         if (btlbw >= gain) {
11140                 bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
11141                 bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11142                                       bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
11143                 bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
11144         }
11145         if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
11146                 return (1);
11147         bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11148                               bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11149         return(0);
11150 }
11151
11152 static int32_t inline
11153 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
11154 {
11155         /* Have we gained 25% in the last 3 packet based epoch's? */
11156         uint64_t btlbw, gain;
11157         int do_exit;
11158         int delta, rtt_gain;
11159
11160         if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11161             (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11162                 /*
11163                  * This qualifies as a RTT_PROBE session since we drop the
11164                  * data outstanding to nothing and waited more than
11165                  * bbr_rtt_probe_time.
11166                  */
11167                 bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11168                 bbr_set_reduced_rtt(bbr, cts, __LINE__);
11169         }
11170         if (bbr_should_enter_probe_rtt(bbr, cts)) {
11171                 bbr_enter_probe_rtt(bbr, cts, __LINE__);
11172                 return (0);
11173         }
11174         if (bbr->rc_use_google)
11175                 return (bbr_google_startup(bbr, cts,  pkt_epoch));
11176
11177         if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11178             (bbr_use_lower_gain_in_startup)) {
11179                 /* Drop to a lower gain 1.5 x since we saw loss */
11180                 bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
11181         }
11182         if (pkt_epoch == 0) {
11183                 /*
11184                  * Need to be on a pkt-epoch to continue.
11185                  */
11186                 return (0);
11187         }
11188         if (bbr_rtt_gain_thresh) {
11189                 /*
11190                  * Do we allow a flow to stay
11191                  * in startup with no loss and no
11192                  * gain in rtt over a set threshold?
11193                  */
11194                 if (bbr->r_ctl.rc_pkt_epoch_rtt &&
11195                     bbr->r_ctl.startup_last_srtt &&
11196                     (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
11197                         delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
11198                         rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
11199                 } else
11200                         rtt_gain = 0;
11201                 if ((bbr->r_ctl.startup_last_srtt == 0)  ||
11202                     (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
11203                         /* First time or new lower value */
11204                         bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
11205
11206                 if ((bbr->r_ctl.rc_lost == 0) &&
11207                     (rtt_gain < bbr_rtt_gain_thresh)) {
11208                         /*
11209                          * No loss, and we are under
11210                          * our gain threhold for
11211                          * increasing RTT.
11212                          */
11213                         if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11214                                 bbr->r_ctl.rc_bbr_last_startup_epoch++;
11215                         bbr_log_startup_event(bbr, cts, rtt_gain,
11216                                               delta, bbr->r_ctl.startup_last_srtt, 10);
11217                         return (0);
11218                 }
11219         }
11220         if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
11221             (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
11222             (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
11223                 /*
11224                  * We only assess if we have a new measurment when
11225                  * we have no loss and are not in recovery.
11226                  * Drag up by one our last_startup epoch so we will hold 
11227                  * the number of non-gain we have already accumulated.
11228                  */
11229                 if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11230                         bbr->r_ctl.rc_bbr_last_startup_epoch++;
11231                 bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11232                                       bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 9);
11233                 return (0);
11234         }
11235         /* Case where we reduced the lost (bad retransmit) */
11236         if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
11237                 bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11238         bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
11239         btlbw = bbr_get_full_bw(bbr);
11240         if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
11241                 gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11242                          (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11243         else
11244                 gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11245                          (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11246         do_exit = 0;
11247         if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
11248                 bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
11249         if (btlbw >= gain) {
11250                 bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
11251                 /* Update the lost so we won't exit in next set of tests */
11252                 bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11253                 bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11254                                       bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
11255         }
11256         if ((bbr->rc_loss_exit &&
11257              (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11258              (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
11259             ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
11260                 /*
11261                  * If we had no gain,  we had loss and that loss was above
11262                  * our threshould, the rwnd is not constrained, and we have
11263                  * had at least 3 packet epochs exit. Note that this is
11264                  * switched off by sysctl. Google does not do this by the
11265                  * way.
11266                  */
11267                 if ((ctf_flight_size(bbr->rc_tp,
11268                          (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11269                      (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11270                         do_exit = 1;
11271                         bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11272                                               bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11273                 } else {
11274                         /* Just record an updated loss value */
11275                         bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11276                         bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11277                                               bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11278                 }
11279         } else
11280                 bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11281         if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11282             do_exit) {
11283                 /* Return 1 to exit the startup state. */
11284                 return (1);
11285         }
11286         /* Stay in startup */
11287         bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11288                               bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11289         return (0);
11290 }
11291
11292 static void
11293 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11294 {
11295         /*
11296          * A tick occured in the rtt epoch do we need to do anything?
11297          */
11298 #ifdef BBR_INVARIANTS
11299         if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11300             (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11301             (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11302             (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11303             (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11304                 /* Debug code? */
11305                 panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11306         }
11307 #endif
11308         if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11309                 /* Do we exit the startup state? */
11310                 if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11311                         uint32_t time_in;
11312
11313                         bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11314                                               bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11315                         bbr->rc_filled_pipe = 1;
11316                         bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11317                         if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11318
11319                                 time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11320                                 counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11321                         } else
11322                                 time_in = 0;
11323                         if (bbr->rc_no_pacing)
11324                                 bbr->rc_no_pacing = 0;
11325                         bbr->r_ctl.rc_bbr_state_time = cts;
11326                         bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11327                         bbr->rc_bbr_state = BBR_STATE_DRAIN;
11328                         bbr_set_state_target(bbr, __LINE__);
11329                         if ((bbr->rc_use_google == 0) &&
11330                             bbr_slam_cwnd_in_main_drain) {
11331                                 /* Here we don't have to worry about probe-rtt */
11332                                 bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;                                
11333                                 bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11334                                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11335                         }
11336                         bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11337                         bbr_log_type_statechange(bbr, cts, __LINE__);
11338                         if (ctf_flight_size(bbr->rc_tp,
11339                                 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11340                             bbr->r_ctl.rc_target_at_state) {
11341                                 /*
11342                                  * Switch to probe_bw if we are already
11343                                  * there
11344                                  */
11345                                 bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11346                                 bbr_substate_change(bbr, cts, __LINE__, 0);
11347                                 bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11348                                 bbr_log_type_statechange(bbr, cts, __LINE__);
11349                         }
11350                 }
11351         } else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11352                 uint32_t inflight;
11353                 struct tcpcb *tp;
11354
11355                 tp = bbr->rc_tp;
11356                 inflight = ctf_flight_size(tp,
11357                               (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11358                 if (inflight >= bbr->r_ctl.rc_target_at_state) {
11359                         /* We have reached a flight of the cwnd target */
11360                         bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11361                         bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11362                         bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11363                         bbr_set_state_target(bbr, __LINE__);
11364                         /* 
11365                          * Rig it so we don't do anything crazy and
11366                          * start fresh with a new randomization.
11367                          */
11368                         bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11369                         bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11370                         bbr_substate_change(bbr, cts, __LINE__, 1);
11371                 }
11372         } else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11373                 /* Has in-flight reached the bdp (or less)? */
11374                 uint32_t inflight;
11375                 struct tcpcb *tp;
11376
11377                 tp = bbr->rc_tp;
11378                 inflight = ctf_flight_size(tp,
11379                               (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11380                 if ((bbr->rc_use_google == 0) &&
11381                     bbr_slam_cwnd_in_main_drain &&
11382                     (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11383                         /* 
11384                          * Here we don't have to worry about probe-rtt 
11385                          * re-slam it, but keep it slammed down.
11386                          */
11387                         bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11388                         bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11389                 }
11390                 if (inflight <= bbr->r_ctl.rc_target_at_state) {
11391                         /* We have drained */
11392                         bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11393                         bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11394                         if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11395                                 uint32_t time_in;
11396
11397                                 time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11398                                 counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11399                         }
11400                         if ((bbr->rc_use_google == 0) &&
11401                             bbr_slam_cwnd_in_main_drain &&
11402                             (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11403                                 /* Restore the cwnd */
11404                                 tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11405                                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11406                         }
11407                         /* Setup probe-rtt has being done now RRS-HERE */
11408                         bbr->r_ctl.rc_rtt_shrinks = cts;
11409                         bbr->r_ctl.last_in_probertt = cts;
11410                         bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11411                         /* Randomly pick a sub-state */
11412                         bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11413                         bbr_substate_change(bbr, cts, __LINE__, 0);
11414                         bbr_log_type_statechange(bbr, cts, __LINE__);
11415                 }
11416         } else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11417                 uint32_t flight;
11418
11419                 flight = ctf_flight_size(bbr->rc_tp,
11420                              (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11421                 bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11422                 if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11423                     (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11424                         /*
11425                          * We must keep cwnd at the desired MSS.
11426                          */
11427                         bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11428                         bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11429                 } else if ((bbr_prtt_slam_cwnd) && 
11430                            (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11431                         /* Re-slam it */
11432                         bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11433                         bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11434                 }
11435                 if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11436                         /* Has outstanding reached our target? */
11437                         if (flight <= bbr->r_ctl.rc_target_at_state) {
11438                                 bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11439                                 bbr->r_ctl.rc_bbr_enters_probertt = cts;
11440                                 /* If time is exactly 0, be 1usec off */
11441                                 if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11442                                         bbr->r_ctl.rc_bbr_enters_probertt = 1;
11443                                 if (bbr->rc_use_google == 0) {
11444                                         /*
11445                                          * Restore any lowering that as occured to
11446                                          * reach here
11447                                          */
11448                                         if (bbr->r_ctl.bbr_rttprobe_gain_val)
11449                                                 bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11450                                         else
11451                                                 bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11452                                 }
11453                         }
11454                         if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11455                             (bbr->rc_use_google == 0) &&
11456                             bbr->r_ctl.bbr_rttprobe_gain_val &&
11457                             (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11458                              (flight >= bbr->r_ctl.flightsize_at_drain))) {
11459                                 /*
11460                                  * We have doddled with our current hptsi
11461                                  * gain an srtt and have still not made it
11462                                  * to target, or we have increased our flight.
11463                                  * Lets reduce the gain by xx%
11464                                  * flooring the reduce at DRAIN (based on
11465                                  * mul/div)
11466                                  */
11467                                 int red;
11468
11469                                 bbr->r_ctl.flightsize_at_drain = flight;
11470                                 bbr->r_ctl.rc_probertt_srttchktim = cts;
11471                                 red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11472                                 if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11473                                         /* Reduce our gain again */
11474                                         bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11475                                         bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11476                                 } else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11477                                         /* one more chance before we give up */
11478                                         bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11479                                         bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11480                                 } else {
11481                                         /* At the very bottom */
11482                                         bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11483                                 }
11484                         }
11485                 }
11486                 if (bbr->r_ctl.rc_bbr_enters_probertt &&
11487                     (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11488                     ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11489                         /* Time to exit probe RTT normally */
11490                         bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11491                 }
11492         } else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11493                 if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11494                     (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11495                         /*
11496                          * This qualifies as a RTT_PROBE session since we
11497                          * drop the data outstanding to nothing and waited
11498                          * more than bbr_rtt_probe_time.
11499                          */
11500                         bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11501                         bbr_set_reduced_rtt(bbr, cts, __LINE__);
11502                 }
11503                 if (bbr_should_enter_probe_rtt(bbr, cts)) {
11504                         bbr_enter_probe_rtt(bbr, cts, __LINE__);
11505                 } else {
11506                         bbr_set_probebw_gains(bbr, cts, losses);
11507                 }
11508         }
11509 }
11510
11511 static void
11512 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11513 {
11514         int32_t epoch = 0;
11515
11516         if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11517                 bbr_set_epoch(bbr, cts, line);
11518                 /* At each epoch doe lt bw sampling */
11519                 epoch = 1;
11520         }
11521         bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11522 }
11523
11524 static int
11525 bbr_do_segment_nounlock(struct mbuf *m, struct tcphdr *th, struct socket *so,
11526     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos,
11527     int32_t nxt_pkt, struct timeval *tv)
11528 {
11529         int32_t thflags, retval;
11530         uint32_t cts, lcts;
11531         uint32_t tiwin;
11532         struct tcpopt to;
11533         struct tcp_bbr *bbr;
11534         struct bbr_sendmap *rsm;
11535         struct timeval ltv;
11536         int32_t did_out = 0;
11537         int32_t in_recovery;
11538         uint16_t nsegs;
11539         int32_t prev_state;
11540         uint32_t lost;
11541
11542         nsegs = max(1, m->m_pkthdr.lro_nsegs);
11543         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11544         /* add in our stats */
11545         kern_prefetch(bbr, &prev_state);
11546         prev_state = 0;
11547         thflags = th->th_flags;
11548         /*
11549          * If this is either a state-changing packet or current state isn't
11550          * established, we require a write lock on tcbinfo.  Otherwise, we
11551          * allow the tcbinfo to be in either alocked or unlocked, as the
11552          * caller may have unnecessarily acquired a write lock due to a
11553          * race.
11554          */
11555         INP_WLOCK_ASSERT(tp->t_inpcb);
11556         KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11557             __func__));
11558         KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11559             __func__));
11560
11561         tp->t_rcvtime = ticks;
11562         /*
11563          * Unscale the window into a 32-bit value. For the SYN_SENT state
11564          * the scale is zero.
11565          */
11566         tiwin = th->th_win << tp->snd_scale;
11567 #ifdef STATS
11568         stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11569 #endif
11570         /*
11571          * Parse options on any incoming segment.
11572          */
11573         tcp_dooptions(&to, (u_char *)(th + 1),
11574             (th->th_off << 2) - sizeof(struct tcphdr),
11575             (thflags & TH_SYN) ? TO_SYN : 0);
11576
11577         if (m->m_flags & M_TSTMP) {
11578                 /* Prefer the hardware timestamp if present */
11579                 struct timespec ts;
11580                 
11581                 mbuf_tstmp2timespec(m, &ts);
11582                 bbr->rc_tv.tv_sec = ts.tv_sec;
11583                 bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11584                 bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11585         } else if (m->m_flags & M_TSTMP_LRO) {
11586                 /* Next the arrival timestamp */
11587                 struct timespec ts;
11588
11589                 mbuf_tstmp2timespec(m, &ts);
11590                 bbr->rc_tv.tv_sec = ts.tv_sec;
11591                 bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11592                 bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11593         } else {
11594                 /* 
11595                  * Ok just get the current time.
11596                  */
11597                 bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11598         }
11599         /*
11600          * If echoed timestamp is later than the current time, fall back to
11601          * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
11602          * were used when this connection was established.
11603          */
11604         if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
11605                 to.to_tsecr -= tp->ts_offset;
11606                 if (TSTMP_GT(to.to_tsecr, tcp_tv_to_mssectick(&bbr->rc_tv)))
11607                         to.to_tsecr = 0;
11608         }
11609         /*
11610          * If its the first time in we need to take care of options and
11611          * verify we can do SACK for rack!
11612          */
11613         if (bbr->r_state == 0) {
11614                 /*
11615                  * Process options only when we get SYN/ACK back. The SYN
11616                  * case for incoming connections is handled in tcp_syncache.
11617                  * According to RFC1323 the window field in a SYN (i.e., a
11618                  * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
11619                  * this is traditional behavior, may need to be cleaned up.
11620                  */
11621                 if (bbr->rc_inp == NULL) {
11622                         bbr->rc_inp = tp->t_inpcb;
11623                 }
11624                 /*
11625                  * We need to init rc_inp here since its not init'd when
11626                  * bbr_init is called
11627                  */
11628                 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
11629                         if ((to.to_flags & TOF_SCALE) &&
11630                             (tp->t_flags & TF_REQ_SCALE)) {
11631                                 tp->t_flags |= TF_RCVD_SCALE;
11632                                 tp->snd_scale = to.to_wscale;
11633                         }
11634                         /*
11635                          * Initial send window.  It will be updated with the
11636                          * next incoming segment to the scaled value.
11637                          */
11638                         tp->snd_wnd = th->th_win;
11639                         if (to.to_flags & TOF_TS) {
11640                                 tp->t_flags |= TF_RCVD_TSTMP;
11641                                 tp->ts_recent = to.to_tsval;
11642                                 tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
11643                         }
11644                         if (to.to_flags & TOF_MSS)
11645                                 tcp_mss(tp, to.to_mss);
11646                         if ((tp->t_flags & TF_SACK_PERMIT) &&
11647                             (to.to_flags & TOF_SACKPERM) == 0)
11648                                 tp->t_flags &= ~TF_SACK_PERMIT;
11649                         if (IS_FASTOPEN(tp->t_flags)) {
11650                                 if (to.to_flags & TOF_FASTOPEN) {
11651                                         uint16_t mss;
11652
11653                                         if (to.to_flags & TOF_MSS)
11654                                                 mss = to.to_mss;
11655                                         else
11656                                                 if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
11657                                                         mss = TCP6_MSS;
11658                                                 else
11659                                                         mss = TCP_MSS;
11660                                         tcp_fastopen_update_cache(tp, mss,
11661                                             to.to_tfo_len, to.to_tfo_cookie);
11662                                 } else
11663                                         tcp_fastopen_disable_path(tp);
11664                         }
11665                 }
11666                 /*
11667                  * At this point we are at the initial call. Here we decide
11668                  * if we are doing RACK or not. We do this by seeing if
11669                  * TF_SACK_PERMIT is set, if not rack is *not* possible and
11670                  * we switch to the default code.
11671                  */
11672                 if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
11673                         /* Bail */
11674                         tcp_switch_back_to_default(tp);
11675                         (*tp->t_fb->tfb_tcp_do_segment) (m, th, so, tp, drop_hdrlen,
11676                             tlen, iptos);
11677                         return (1);
11678                 }
11679                 /* Set the flag */
11680                 bbr->r_is_v6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
11681                 tcp_set_hpts(tp->t_inpcb);
11682                 sack_filter_clear(&bbr->r_ctl.bbr_sf, th->th_ack);
11683         }
11684         if (thflags & TH_ACK) {
11685                 /* Track ack types */
11686                 if (to.to_flags & TOF_SACK)
11687                         BBR_STAT_INC(bbr_acks_with_sacks);
11688                 else
11689                         BBR_STAT_INC(bbr_plain_acks);
11690         }
11691         /*
11692          * This is the one exception case where we set the rack state
11693          * always. All other times (timers etc) we must have a rack-state
11694          * set (so we assure we have done the checks above for SACK).
11695          */
11696         if (bbr->r_state != tp->t_state)
11697                 bbr_set_state(tp, bbr, tiwin);
11698
11699         if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map)) != NULL)
11700                 kern_prefetch(rsm, &prev_state);
11701         prev_state = bbr->r_state;
11702         bbr->rc_ack_was_delayed = 0;
11703         lost = bbr->r_ctl.rc_lost;
11704         bbr->rc_is_pkt_epoch_now = 0;
11705         if (m->m_flags & (M_TSTMP|M_TSTMP_LRO)) {
11706                 /* Get the real time into lcts and figure the real delay */
11707                 lcts = tcp_get_usecs(&ltv);
11708                 if (TSTMP_GT(lcts, cts)) {
11709                         bbr->r_ctl.rc_ack_hdwr_delay = lcts - cts;
11710                         bbr->rc_ack_was_delayed = 1;
11711                         if (TSTMP_GT(bbr->r_ctl.rc_ack_hdwr_delay,
11712                                      bbr->r_ctl.highest_hdwr_delay)) 
11713                                 bbr->r_ctl.highest_hdwr_delay = bbr->r_ctl.rc_ack_hdwr_delay;
11714                 } else {
11715                         bbr->r_ctl.rc_ack_hdwr_delay = 0;
11716                         bbr->rc_ack_was_delayed = 0;
11717                 }
11718         } else {
11719                 bbr->r_ctl.rc_ack_hdwr_delay = 0;
11720                 bbr->rc_ack_was_delayed = 0;
11721         }
11722         bbr_log_ack_event(bbr, th, &to, tlen, nsegs, cts, nxt_pkt, m);
11723         if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
11724                 retval = 0;
11725                 m_freem(m);
11726                 goto done_with_input;
11727         }
11728         /*
11729          * If a segment with the ACK-bit set arrives in the SYN-SENT state
11730          * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
11731          */
11732         if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
11733             (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
11734                 ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11735                 return (1);
11736         }
11737         in_recovery = IN_RECOVERY(tp->t_flags);
11738         if (tiwin > bbr->r_ctl.rc_high_rwnd)
11739                 bbr->r_ctl.rc_high_rwnd = tiwin;
11740 #ifdef BBR_INVARIANTS
11741         if ((tp->t_inpcb->inp_flags & INP_DROPPED) ||
11742             (tp->t_inpcb->inp_flags2 & INP_FREED)) {
11743                 panic("tp:%p bbr:%p given a dropped inp:%p",
11744                     tp, bbr, tp->t_inpcb);
11745         }
11746 #endif
11747         bbr->r_ctl.rc_flight_at_input = ctf_flight_size(tp,
11748                                             (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11749         bbr->rtt_valid = 0;
11750         if (to.to_flags & TOF_TS) {
11751                 bbr->rc_ts_valid = 1;
11752                 bbr->r_ctl.last_inbound_ts = to.to_tsval;
11753         } else {
11754                 bbr->rc_ts_valid = 0;
11755                 bbr->r_ctl.last_inbound_ts = 0;
11756         }
11757         retval = (*bbr->r_substate) (m, th, so,
11758             tp, &to, drop_hdrlen,
11759             tlen, tiwin, thflags, nxt_pkt);
11760 #ifdef BBR_INVARIANTS
11761         if ((retval == 0) &&
11762             (tp->t_inpcb == NULL)) {
11763                 panic("retval:%d tp:%p t_inpcb:NULL state:%d",
11764                     retval, tp, prev_state);
11765         }
11766 #endif
11767         if (nxt_pkt == 0)
11768                 BBR_STAT_INC(bbr_rlock_left_ret0);
11769         else
11770                 BBR_STAT_INC(bbr_rlock_left_ret1);
11771         if (retval == 0) {
11772                 /*
11773                  * If retval is 1 the tcb is unlocked and most likely the tp
11774                  * is gone.
11775                  */
11776                 INP_WLOCK_ASSERT(tp->t_inpcb);
11777                 tcp_bbr_xmit_timer_commit(bbr, tp, cts);
11778                 if (bbr->rc_is_pkt_epoch_now)
11779                         bbr_set_pktepoch(bbr, cts, __LINE__);
11780                 bbr_check_bbr_for_state(bbr, cts, __LINE__, (bbr->r_ctl.rc_lost - lost));
11781                 if (nxt_pkt == 0) {
11782                         if (bbr->r_wanted_output != 0) {
11783                                 bbr->rc_output_starts_timer = 0;
11784                                 did_out = 1;
11785                                 (void)tp->t_fb->tfb_tcp_output(tp);
11786                         } else
11787                                 bbr_start_hpts_timer(bbr, tp, cts, 6, 0, 0);
11788                 }
11789                 if ((nxt_pkt == 0) &&
11790                     ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
11791                     (SEQ_GT(tp->snd_max, tp->snd_una) ||
11792                      (tp->t_flags & TF_DELACK) ||
11793                      ((V_tcp_always_keepalive || bbr->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
11794                       (tp->t_state <= TCPS_CLOSING)))) {
11795                         /*
11796                          * We could not send (probably in the hpts but
11797                          * stopped the timer)?
11798                          */
11799                         if ((tp->snd_max == tp->snd_una) &&
11800                             ((tp->t_flags & TF_DELACK) == 0) &&
11801                             (bbr->rc_inp->inp_in_hpts) &&
11802                             (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11803                                 /*
11804                                  * keep alive not needed if we are hptsi
11805                                  * output yet
11806                                  */
11807                                 ;
11808                         } else {
11809                                 if (bbr->rc_inp->inp_in_hpts) {
11810                                         tcp_hpts_remove(bbr->rc_inp, HPTS_REMOVE_OUTPUT);
11811                                         if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11812                                             (TSTMP_GT(lcts, bbr->rc_pacer_started))) {
11813                                                 uint32_t del;
11814
11815                                                 del = lcts - bbr->rc_pacer_started;
11816                                                 if (bbr->r_ctl.rc_last_delay_val > del) {
11817                                                         BBR_STAT_INC(bbr_force_timer_start);
11818                                                         bbr->r_ctl.rc_last_delay_val -= del;
11819                                                         bbr->rc_pacer_started = lcts;
11820                                                 } else {
11821                                                         /* We are late */
11822                                                         bbr->r_ctl.rc_last_delay_val = 0;
11823                                                         BBR_STAT_INC(bbr_force_output);
11824                                                         (void)tp->t_fb->tfb_tcp_output(tp);
11825                                                 }
11826                                         }
11827                                 }
11828                                 bbr_start_hpts_timer(bbr, tp, cts, 8, bbr->r_ctl.rc_last_delay_val,
11829                                     0);
11830                         }
11831                 } else if ((bbr->rc_output_starts_timer == 0) && (nxt_pkt == 0)) {
11832                         /* Do we have the correct timer running? */
11833                         bbr_timer_audit(tp, bbr, lcts, &so->so_snd);
11834                 }
11835                 /* Do we have a new state */
11836                 if (bbr->r_state != tp->t_state)
11837                         bbr_set_state(tp, bbr, tiwin);
11838 done_with_input:
11839                 bbr_log_doseg_done(bbr, cts, nxt_pkt, did_out);
11840                 if (did_out)
11841                         bbr->r_wanted_output = 0;
11842 #ifdef BBR_INVARIANTS
11843                 if (tp->t_inpcb == NULL) {
11844                         panic("OP:%d retval:%d tp:%p t_inpcb:NULL state:%d",
11845                             did_out,
11846                             retval, tp, prev_state);
11847                 }
11848 #endif
11849         }
11850         return (retval);
11851 }
11852
11853 static void
11854 bbr_log_type_hrdwtso(struct tcpcb *tp, struct tcp_bbr *bbr, int len, int mod, int what_we_can_send)
11855 {
11856         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
11857                 union tcp_log_stackspecific log;
11858                 struct timeval tv;
11859                 uint32_t cts;
11860
11861                 cts = tcp_get_usecs(&tv);
11862                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
11863                 log.u_bbr.flex1 = bbr->r_ctl.rc_pace_min_segs;
11864                 log.u_bbr.flex2 = what_we_can_send;
11865                 log.u_bbr.flex3 = bbr->r_ctl.rc_pace_max_segs;
11866                 log.u_bbr.flex4 = len;
11867                 log.u_bbr.flex5 = 0;
11868                 log.u_bbr.flex7 = mod;
11869                 log.u_bbr.flex8 = 1;
11870                 TCP_LOG_EVENTP(tp, NULL,
11871                     &tp->t_inpcb->inp_socket->so_rcv,
11872                     &tp->t_inpcb->inp_socket->so_snd,
11873                     TCP_HDWR_TLS, 0,
11874                     0, &log, false, &tv);
11875         }
11876 }
11877
11878 static void
11879 bbr_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
11880     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
11881 {
11882         struct timeval tv;
11883         int retval;
11884         
11885         /* First lets see if we have old packets */
11886         if (tp->t_in_pkt) {
11887                 if (ctf_do_queued_segments(so, tp, 1)) {
11888                         m_freem(m);
11889                         return;
11890                 }
11891         }
11892         if (m->m_flags & M_TSTMP_LRO) {
11893                 tv.tv_sec = m->m_pkthdr.rcv_tstmp /1000000000;
11894                 tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000)/1000;
11895         } else {
11896                 /* Should not be should we kassert instead? */
11897                 tcp_get_usecs(&tv);
11898         }
11899         retval = bbr_do_segment_nounlock(m, th, so, tp,
11900                                          drop_hdrlen, tlen, iptos, 0, &tv);
11901         if (retval == 0)
11902                 INP_WUNLOCK(tp->t_inpcb);
11903 }
11904
11905 /*
11906  * Return how much data can be sent without violating the
11907  * cwnd or rwnd.
11908  */
11909
11910 static inline uint32_t
11911 bbr_what_can_we_send(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t sendwin,
11912     uint32_t avail, int32_t sb_offset, uint32_t cts)
11913 {
11914         uint32_t len;
11915
11916         if (ctf_outstanding(tp) >= tp->snd_wnd) {
11917                 /* We never want to go over our peers rcv-window */
11918                 len = 0;
11919         } else {
11920                 uint32_t flight;
11921
11922                 flight = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11923                 if (flight >= sendwin) {
11924                         /*
11925                          * We have in flight what we are allowed by cwnd (if
11926                          * it was rwnd blocking it would have hit above out
11927                          * >= tp->snd_wnd).
11928                          */
11929                         return (0);
11930                 }
11931                 len = sendwin - flight;
11932                 if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
11933                         /* We would send too much (beyond the rwnd) */
11934                         len = tp->snd_wnd - ctf_outstanding(tp);
11935                 }
11936                 if ((len + sb_offset) > avail) {
11937                         /*
11938                          * We don't have that much in the SB, how much is
11939                          * there?
11940                          */
11941                         len = avail - sb_offset;
11942                 }
11943         }
11944         return (len);
11945 }
11946
11947 static inline void
11948 bbr_do_error_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11949 {
11950 #ifdef NETFLIX_STATS
11951         TCPSTAT_INC(tcps_sndpack_error);
11952         TCPSTAT_ADD(tcps_sndbyte_error, len);
11953 #endif
11954 }
11955
11956 static inline void
11957 bbr_do_send_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11958 {
11959         if (error) {
11960                 bbr_do_error_accounting(tp, bbr, rsm, len, error);
11961                 return;
11962         }
11963         if ((tp->t_flags & TF_FORCEDATA) && len == 1) {
11964                 /* Window probe */
11965                 TCPSTAT_INC(tcps_sndprobe);
11966 #ifdef STATS
11967                 stats_voi_update_abs_u32(tp->t_stats,
11968                     VOI_TCP_RETXPB, len);
11969 #endif
11970         } else if (rsm) {
11971                 if (rsm->r_flags & BBR_TLP) {
11972                         /*
11973                          * TLP should not count in retran count, but in its
11974                          * own bin
11975                          */
11976 #ifdef NETFLIX_STATS
11977                         tp->t_sndtlppack++;
11978                         tp->t_sndtlpbyte += len;
11979                         TCPSTAT_INC(tcps_tlpresends);
11980                         TCPSTAT_ADD(tcps_tlpresend_bytes, len);
11981 #endif
11982                 } else {
11983                         /* Retransmit */
11984                         tp->t_sndrexmitpack++;
11985                         TCPSTAT_INC(tcps_sndrexmitpack);
11986                         TCPSTAT_ADD(tcps_sndrexmitbyte, len);
11987 #ifdef STATS
11988                         stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
11989                             len);
11990 #endif
11991                 }
11992                 /*
11993                  * Logs in 0 - 8, 8 is all non probe_bw states 0-7 is
11994                  * sub-state
11995                  */
11996                 counter_u64_add(bbr_state_lost[rsm->r_bbr_state], len);
11997                 if (bbr->rc_bbr_state != BBR_STATE_PROBE_BW) {
11998                         /* Non probe_bw log in 1, 2, or 4. */
11999                         counter_u64_add(bbr_state_resend[bbr->rc_bbr_state], len);
12000                 } else {
12001                         /*
12002                          * Log our probe state 3, and log also 5-13 to show
12003                          * us the recovery sub-state for the send. This
12004                          * means that 3 == (5+6+7+8+9+10+11+12+13)
12005                          */
12006                         counter_u64_add(bbr_state_resend[BBR_STATE_PROBE_BW], len);
12007                         counter_u64_add(bbr_state_resend[(bbr_state_val(bbr) + 5)], len);
12008                 }
12009                 /* Place in both 16's the totals of retransmitted */
12010                 counter_u64_add(bbr_state_lost[16], len);
12011                 counter_u64_add(bbr_state_resend[16], len);
12012                 /* Place in 17's the total sent */
12013                 counter_u64_add(bbr_state_resend[17], len);
12014                 counter_u64_add(bbr_state_lost[17], len);
12015
12016         } else {
12017                 /* New sends */
12018                 TCPSTAT_INC(tcps_sndpack);
12019                 TCPSTAT_ADD(tcps_sndbyte, len);
12020                 /* Place in 17's the total sent */
12021                 counter_u64_add(bbr_state_resend[17], len);
12022                 counter_u64_add(bbr_state_lost[17], len);
12023 #ifdef STATS
12024                 stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
12025                     len);
12026 #endif
12027         }
12028 }
12029
12030 static void
12031 bbr_cwnd_limiting(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t in_level)
12032 {
12033         if (bbr->rc_filled_pipe && bbr_target_cwnd_mult_limit && (bbr->rc_use_google == 0)) {
12034                 /*
12035                  * Limit the cwnd to not be above N x the target plus whats
12036                  * is outstanding. The target is based on the current b/w
12037                  * estimate.
12038                  */
12039                 uint32_t target;
12040
12041                 target = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), BBR_UNIT);
12042                 target += ctf_outstanding(tp);
12043                 target *= bbr_target_cwnd_mult_limit;
12044                 if (tp->snd_cwnd > target)
12045                         tp->snd_cwnd = target;
12046                 bbr_log_type_cwndupd(bbr, 0, 0, 0, 10, 0, 0, __LINE__);
12047         }
12048 }
12049
12050 static int
12051 bbr_window_update_needed(struct tcpcb *tp, struct socket *so, uint32_t recwin, int32_t maxseg)
12052 {
12053         /*
12054          * "adv" is the amount we could increase the window, taking into
12055          * account that we are limited by TCP_MAXWIN << tp->rcv_scale.
12056          */
12057         uint32_t adv;
12058         int32_t oldwin;
12059
12060         adv = min(recwin, TCP_MAXWIN << tp->rcv_scale);
12061         if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
12062                 oldwin = (tp->rcv_adv - tp->rcv_nxt);
12063                 adv -= oldwin;
12064         } else
12065                 oldwin = 0;
12066
12067         /*
12068          * If the new window size ends up being the same as the old size
12069          * when it is scaled, then don't force a window update.
12070          */
12071         if (oldwin >> tp->rcv_scale == (adv + oldwin) >> tp->rcv_scale)
12072                 return (0);
12073
12074         if (adv >= (2 * maxseg) &&
12075             (adv >= (so->so_rcv.sb_hiwat / 4) ||
12076             recwin <= (so->so_rcv.sb_hiwat / 8) ||
12077             so->so_rcv.sb_hiwat <= 8 * maxseg)) {
12078                 return (1);
12079         }
12080         if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
12081                 return (1);
12082         return (0);
12083 }
12084
12085 /*
12086  * Return 0 on success and a errno on failure to send.
12087  * Note that a 0 return may not mean we sent anything
12088  * if the TCB was on the hpts. A non-zero return
12089  * does indicate the error we got from ip[6]_output.
12090  */
12091 static int
12092 bbr_output_wtime(struct tcpcb *tp, const struct timeval *tv)
12093 {
12094         struct socket *so;
12095         int32_t len;
12096         uint32_t cts;
12097         uint32_t recwin, sendwin;
12098         int32_t sb_offset;
12099         int32_t flags, abandon, error = 0;
12100         struct tcp_log_buffer *lgb = NULL;
12101         struct mbuf *m;
12102         struct mbuf *mb;
12103         uint32_t if_hw_tsomaxsegcount = 0;
12104         uint32_t if_hw_tsomaxsegsize = 0;
12105         uint32_t if_hw_tsomax = 0;
12106         struct ip *ip = NULL;
12107 #ifdef TCPDEBUG
12108         struct ipovly *ipov = NULL;
12109 #endif
12110         struct tcp_bbr *bbr;
12111         struct tcphdr *th;
12112 #ifdef NETFLIX_TCPOUDP
12113         struct udphdr *udp = NULL;
12114 #endif
12115         u_char opt[TCP_MAXOLEN];
12116         unsigned ipoptlen, optlen, hdrlen;
12117 #ifdef NETFLIX_TCPOUDP
12118         unsigned ulen;
12119 #endif
12120         uint32_t bbr_seq;
12121         uint32_t delay_calc=0;
12122         uint8_t doing_tlp = 0;
12123         uint8_t local_options;
12124 #ifdef BBR_INVARIANTS
12125         uint8_t doing_retran_from = 0;
12126         uint8_t picked_up_retran = 0;
12127 #endif
12128         uint8_t wanted_cookie = 0;
12129         uint8_t more_to_rxt=0;
12130         int32_t prefetch_so_done = 0;
12131         int32_t prefetch_rsm = 0;
12132         uint32_t what_we_can = 0;
12133         uint32_t tot_len = 0;
12134         uint32_t rtr_cnt = 0;
12135         uint32_t maxseg, pace_max_segs, p_maxseg;
12136         int32_t csum_flags;
12137         int32_t hw_tls;
12138 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12139         unsigned ipsec_optlen = 0;
12140
12141 #endif
12142         volatile int32_t sack_rxmit;
12143         struct bbr_sendmap *rsm = NULL;
12144         int32_t tso, mtu;
12145         int force_tso = 0;
12146         struct tcpopt to;
12147         int32_t slot = 0;
12148         struct inpcb *inp;
12149         struct sockbuf *sb;
12150         uint32_t hpts_calling;
12151 #ifdef INET6
12152         struct ip6_hdr *ip6 = NULL;
12153         int32_t isipv6;
12154 #endif
12155         uint8_t app_limited = BBR_JR_SENT_DATA;
12156         uint8_t filled_all = 0;
12157         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
12158         /* We take a cache hit here */
12159         memcpy(&bbr->rc_tv, tv, sizeof(struct timeval));
12160         cts = tcp_tv_to_usectick(&bbr->rc_tv);
12161         inp = bbr->rc_inp;
12162         so = inp->inp_socket;
12163         sb = &so->so_snd;
12164 #ifdef KERN_TLS
12165         if (sb->sb_flags & SB_TLS_IFNET)
12166                 hw_tls = 1;
12167         else
12168 #endif
12169                 hw_tls = 0;
12170         kern_prefetch(sb, &maxseg);
12171         maxseg = tp->t_maxseg - bbr->rc_last_options;
12172         if (bbr_minseg(bbr) < maxseg) {
12173                 tcp_bbr_tso_size_check(bbr, cts);
12174         }
12175         /* Remove any flags that indicate we are pacing on the inp  */
12176         pace_max_segs = bbr->r_ctl.rc_pace_max_segs;
12177         p_maxseg = min(maxseg, pace_max_segs);
12178         INP_WLOCK_ASSERT(inp);
12179 #ifdef TCP_OFFLOAD
12180         if (tp->t_flags & TF_TOE)
12181                 return (tcp_offload_output(tp));
12182 #endif
12183
12184 #ifdef INET6
12185         if (bbr->r_state) {
12186                 /* Use the cache line loaded if possible */
12187                 isipv6 = bbr->r_is_v6;
12188         } else {
12189                 isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
12190         }
12191 #endif
12192         if (((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
12193             inp->inp_in_hpts) {
12194                 /*
12195                  * We are on the hpts for some timer but not hptsi output.
12196                  * Possibly remove from the hpts so we can send/recv etc.
12197                  */
12198                 if ((tp->t_flags & TF_ACKNOW) == 0) {
12199                         /*
12200                          * No immediate demand right now to send an ack, but
12201                          * the user may have read, making room for new data
12202                          * (a window update). If so we may want to cancel
12203                          * whatever timer is running (KEEP/DEL-ACK?) and
12204                          * continue to send out a window update. Or we may
12205                          * have gotten more data into the socket buffer to
12206                          * send.
12207                          */
12208                         recwin = min(max(sbspace(&so->so_rcv), 0),
12209                             TCP_MAXWIN << tp->rcv_scale);
12210                         if ((bbr_window_update_needed(tp, so, recwin, maxseg) == 0) &&
12211                             ((sbavail(sb) + ((tcp_outflags[tp->t_state] & TH_FIN) ? 1 : 0)) <=
12212                             (tp->snd_max - tp->snd_una))) {
12213                                 /*
12214                                  * Nothing new to send and no window update
12215                                  * is needed to send. Lets just return and
12216                                  * let the timer-run off.
12217                                  */
12218                                 return (0);
12219                         }
12220                 }
12221                 tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12222                 bbr_timer_cancel(bbr, __LINE__, cts);
12223         }
12224         if (bbr->r_ctl.rc_last_delay_val) {
12225                 /* Calculate a rough delay for early escape to sending  */
12226                 if (SEQ_GT(cts, bbr->rc_pacer_started))
12227                         delay_calc = cts - bbr->rc_pacer_started;
12228                 if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12229                         delay_calc -= bbr->r_ctl.rc_last_delay_val;
12230                 else
12231                         delay_calc = 0;
12232         }
12233         /* Mark that we have called bbr_output(). */
12234         if ((bbr->r_timer_override) ||
12235             (tp->t_flags & TF_FORCEDATA) ||
12236             (tp->t_state < TCPS_ESTABLISHED)) {
12237                 /* Timeouts or early states are exempt */
12238                 if (inp->inp_in_hpts)
12239                         tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12240         } else if (inp->inp_in_hpts) {
12241                 if ((bbr->r_ctl.rc_last_delay_val) &&
12242                     (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
12243                     delay_calc) {
12244                         /*
12245                          * We were being paced for output and the delay has
12246                          * already exceeded when we were supposed to be
12247                          * called, lets go ahead and pull out of the hpts
12248                          * and call output.
12249                          */
12250                         counter_u64_add(bbr_out_size[TCP_MSS_ACCT_LATE], 1);
12251                         bbr->r_ctl.rc_last_delay_val = 0;
12252                         tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12253                 } else if (tp->t_state == TCPS_CLOSED) {
12254                         bbr->r_ctl.rc_last_delay_val = 0;
12255                         tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12256                 } else {
12257                         /*
12258                          * On the hpts, you shall not pass! even if ACKNOW
12259                          * is on, we will when the hpts fires, unless of
12260                          * course we are overdue.
12261                          */
12262                         counter_u64_add(bbr_out_size[TCP_MSS_ACCT_INPACE], 1);
12263                         return (0);
12264                 }
12265         }
12266         bbr->rc_cwnd_limited = 0;
12267         if (bbr->r_ctl.rc_last_delay_val) {
12268                 /* recalculate the real delay and deal with over/under  */
12269                 if (SEQ_GT(cts, bbr->rc_pacer_started))
12270                         delay_calc = cts - bbr->rc_pacer_started;
12271                 else
12272                         delay_calc = 0;
12273                 if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12274                         /* Setup the delay which will be added in */
12275                         delay_calc -= bbr->r_ctl.rc_last_delay_val;
12276                 else {
12277                         /* 
12278                          * We are early setup to adjust 
12279                          * our slot time.
12280                          */
12281                         uint64_t merged_val;
12282                         
12283                         bbr->r_ctl.rc_agg_early += (bbr->r_ctl.rc_last_delay_val - delay_calc);
12284                         bbr->r_agg_early_set = 1;
12285                         if (bbr->r_ctl.rc_hptsi_agg_delay) {
12286                                 if (bbr->r_ctl.rc_hptsi_agg_delay >= bbr->r_ctl.rc_agg_early) {
12287                                         /* Nope our previous late cancels out the early */
12288                                         bbr->r_ctl.rc_hptsi_agg_delay -= bbr->r_ctl.rc_agg_early;
12289                                         bbr->r_agg_early_set = 0;
12290                                         bbr->r_ctl.rc_agg_early = 0;
12291                                 } else {
12292                                         bbr->r_ctl.rc_agg_early -= bbr->r_ctl.rc_hptsi_agg_delay;
12293                                         bbr->r_ctl.rc_hptsi_agg_delay = 0;
12294                                 }
12295                         }
12296                         merged_val = bbr->rc_pacer_started;
12297                         merged_val <<= 32;
12298                         merged_val |= bbr->r_ctl.rc_last_delay_val;
12299                         bbr_log_pacing_delay_calc(bbr, inp->inp_hpts_calls,
12300                                                  bbr->r_ctl.rc_agg_early, cts, delay_calc, merged_val,
12301                                                  bbr->r_agg_early_set, 3);
12302                         bbr->r_ctl.rc_last_delay_val = 0;
12303                         BBR_STAT_INC(bbr_early);
12304                         delay_calc = 0;
12305                 }
12306         } else {
12307                 /* We were not delayed due to hptsi */
12308                 if (bbr->r_agg_early_set)
12309                         bbr->r_ctl.rc_agg_early = 0;
12310                 bbr->r_agg_early_set = 0;
12311                 delay_calc = 0;
12312         }
12313         if (delay_calc) {
12314                 /*
12315                  * We had a hptsi delay which means we are falling behind on
12316                  * sending at the expected rate. Calculate an extra amount
12317                  * of data we can send, if any, to put us back on track.
12318                  */
12319                 if ((bbr->r_ctl.rc_hptsi_agg_delay + delay_calc) < bbr->r_ctl.rc_hptsi_agg_delay)
12320                         bbr->r_ctl.rc_hptsi_agg_delay = 0xffffffff;
12321                 else
12322                         bbr->r_ctl.rc_hptsi_agg_delay += delay_calc;
12323         }
12324         sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12325         if ((tp->snd_una == tp->snd_max) &&
12326             (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
12327             (sbavail(sb))) {
12328                 /* 
12329                  * Ok we have been idle with nothing outstanding
12330                  * we possibly need to start fresh with either a new
12331                  * suite of states or a fast-ramp up.
12332                  */
12333                 bbr_restart_after_idle(bbr,
12334                                        cts, bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time));
12335         }
12336         /*
12337          * Now was there a hptsi delay where we are behind? We only count
12338          * being behind if: a) We are not in recovery. b) There was a delay.
12339          * <and> c) We had room to send something.
12340          *
12341          */
12342         hpts_calling = inp->inp_hpts_calls;
12343         inp->inp_hpts_calls = 0;
12344         if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
12345                 if (bbr_process_timers(tp, bbr, cts, hpts_calling)) {
12346                         counter_u64_add(bbr_out_size[TCP_MSS_ACCT_ATIMER], 1);
12347                         return (0);
12348                 }
12349         }
12350         bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
12351         if (hpts_calling &&
12352             (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
12353                 bbr->r_ctl.rc_last_delay_val = 0;
12354         }
12355         bbr->r_timer_override = 0;
12356         bbr->r_wanted_output = 0;
12357         /*
12358          * For TFO connections in SYN_RECEIVED, only allow the initial
12359          * SYN|ACK and those sent by the retransmit timer.
12360          */
12361         if (IS_FASTOPEN(tp->t_flags) &&
12362             ((tp->t_state == TCPS_SYN_RECEIVED) ||
12363              (tp->t_state == TCPS_SYN_SENT)) &&
12364             SEQ_GT(tp->snd_max, tp->snd_una) && /* inital SYN or SYN|ACK sent */
12365             (tp->t_rxtshift == 0)) {    /* not a retransmit */
12366                 return (0);
12367         }
12368         /*
12369          * Before sending anything check for a state update. For hpts
12370          * calling without input this is important. If its input calling
12371          * then this was already done.
12372          */
12373         if (bbr->rc_use_google == 0)
12374                 bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12375 again:
12376         /*
12377          * If we've recently taken a timeout, snd_max will be greater than
12378          * snd_max. BBR in general does not pay much attention to snd_nxt
12379          * for historic reasons the persist timer still uses it. This means
12380          * we have to look at it. All retransmissions that are not persits
12381          * use the rsm that needs to be sent so snd_nxt is ignored. At the
12382          * end of this routine we pull snd_nxt always up to snd_max.
12383          */
12384         doing_tlp = 0;
12385 #ifdef BBR_INVARIANTS
12386         doing_retran_from = picked_up_retran = 0;
12387 #endif
12388         error = 0;
12389         tso = 0;
12390         slot = 0;
12391         mtu = 0;
12392         sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12393         sb_offset = tp->snd_max - tp->snd_una;
12394         flags = tcp_outflags[tp->t_state];
12395         sack_rxmit = 0;
12396         len = 0;
12397         rsm = NULL;
12398         if (flags & TH_RST) {
12399                 SOCKBUF_LOCK(sb);
12400                 goto send;
12401         }
12402 recheck_resend:
12403         while (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
12404                 /* We need to always have one in reserve */
12405                 rsm = bbr_alloc(bbr);
12406                 if (rsm == NULL) {
12407                         error = ENOMEM;
12408                         /* Lie to get on the hpts */
12409                         tot_len = tp->t_maxseg;
12410                         if (hpts_calling)
12411                                 /* Retry in a ms */
12412                                 slot = 1001;
12413                         goto just_return_nolock;
12414                 }
12415                 TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
12416                 bbr->r_ctl.rc_free_cnt++;
12417                 rsm = NULL;
12418         }
12419         /* What do we send, a resend? */
12420         if (bbr->r_ctl.rc_resend == NULL) {
12421                 /* Check for rack timeout */
12422                 bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
12423                 if (bbr->r_ctl.rc_resend) {
12424 #ifdef BBR_INVARIANTS
12425                         picked_up_retran = 1;
12426 #endif
12427                         bbr_cong_signal(tp, NULL, CC_NDUPACK, bbr->r_ctl.rc_resend);
12428                 }
12429         }
12430         if (bbr->r_ctl.rc_resend) {
12431                 rsm = bbr->r_ctl.rc_resend;
12432 #ifdef BBR_INVARIANTS
12433                 doing_retran_from = 1;
12434 #endif
12435                 /* Remove any TLP flags its a RACK or T-O */
12436                 rsm->r_flags &= ~BBR_TLP;
12437                 bbr->r_ctl.rc_resend = NULL;
12438                 if (SEQ_LT(rsm->r_start, tp->snd_una)) {
12439 #ifdef BBR_INVARIANTS
12440                         panic("Huh, tp:%p bbr:%p rsm:%p start:%u < snd_una:%u\n",
12441                             tp, bbr, rsm, rsm->r_start, tp->snd_una);
12442                         goto recheck_resend;
12443 #else
12444                         /* TSNH */
12445                         rsm = NULL;
12446                         goto recheck_resend;
12447 #endif
12448                 }
12449                 rtr_cnt++;
12450                 if (rsm->r_flags & BBR_HAS_SYN) {
12451                         /* Only retransmit a SYN by itself */
12452                         len = 0;
12453                         if ((flags & TH_SYN) == 0) {
12454                                 /* Huh something is wrong */
12455                                 rsm->r_start++;
12456                                 if (rsm->r_start == rsm->r_end) {
12457                                         /* Clean it up, somehow we missed the ack? */
12458                                         bbr_log_syn(tp, NULL);
12459                                 } else {
12460                                         /* TFO with data? */
12461                                         rsm->r_flags &= ~BBR_HAS_SYN;
12462                                         len = rsm->r_end - rsm->r_start;
12463                                 }
12464                         } else {
12465                                 /* Retransmitting SYN */
12466                                 rsm = NULL;
12467                                 SOCKBUF_LOCK(sb);
12468                                 goto send;
12469                         }
12470                 } else
12471                         len = rsm->r_end - rsm->r_start;
12472                 if ((bbr->rc_resends_use_tso == 0) &&
12473 #ifdef KERN_TLS
12474                     ((sb->sb_flags & SB_TLS_IFNET) == 0) &&
12475 #endif
12476                     (len > maxseg)) {
12477                         len = maxseg;
12478                         more_to_rxt = 1;
12479                 }
12480                 sb_offset = rsm->r_start - tp->snd_una;
12481                 if (len > 0) {
12482                         sack_rxmit = 1;
12483                         TCPSTAT_INC(tcps_sack_rexmits);
12484                         TCPSTAT_ADD(tcps_sack_rexmit_bytes,
12485                             min(len, maxseg));
12486                 } else {
12487                         /* I dont think this can happen */
12488                         rsm = NULL;
12489                         goto recheck_resend;
12490                 }
12491                 BBR_STAT_INC(bbr_resends_set);
12492         } else if (bbr->r_ctl.rc_tlp_send) {
12493                 /*
12494                  * Tail loss probe
12495                  */
12496                 doing_tlp = 1;
12497                 rsm = bbr->r_ctl.rc_tlp_send;
12498                 bbr->r_ctl.rc_tlp_send = NULL;
12499                 sack_rxmit = 1;
12500                 len = rsm->r_end - rsm->r_start;
12501                 rtr_cnt++;
12502                 if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12503                         len = maxseg;
12504
12505                 if (SEQ_GT(tp->snd_una, rsm->r_start)) {
12506 #ifdef BBR_INVARIANTS
12507                         panic("tp:%p bbc:%p snd_una:%u rsm:%p r_start:%u",
12508                             tp, bbr, tp->snd_una, rsm, rsm->r_start);
12509 #else
12510                         /* TSNH */
12511                         rsm = NULL;
12512                         goto recheck_resend;
12513 #endif
12514                 }
12515                 sb_offset = rsm->r_start - tp->snd_una;
12516                 BBR_STAT_INC(bbr_tlp_set);
12517         }
12518         /* 
12519          * Enforce a connection sendmap count limit if set 
12520          * as long as we are not retransmiting.
12521          */
12522         if ((rsm == NULL) &&
12523             (V_tcp_map_entries_limit > 0) &&
12524             (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
12525                 BBR_STAT_INC(bbr_alloc_limited);
12526                 if (!bbr->alloc_limit_reported) {
12527                         bbr->alloc_limit_reported = 1;
12528                         BBR_STAT_INC(bbr_alloc_limited_conns);
12529                 }
12530                 goto just_return_nolock;
12531         }
12532 #ifdef BBR_INVARIANTS
12533         if (rsm && SEQ_LT(rsm->r_start, tp->snd_una)) {
12534                 panic("tp:%p bbr:%p rsm:%p sb_offset:%u len:%u",
12535                     tp, bbr, rsm, sb_offset, len);
12536         }
12537 #endif
12538         /*
12539          * Get standard flags, and add SYN or FIN if requested by 'hidden'
12540          * state flags.
12541          */
12542         if (tp->t_flags & TF_NEEDFIN && (rsm == NULL))
12543                 flags |= TH_FIN;
12544         if (tp->t_flags & TF_NEEDSYN)
12545                 flags |= TH_SYN;
12546
12547         if (rsm && (rsm->r_flags & BBR_HAS_FIN)) {
12548                 /* we are retransmitting the fin */
12549                 len--;
12550                 if (len) {
12551                         /*
12552                          * When retransmitting data do *not* include the
12553                          * FIN. This could happen from a TLP probe if we
12554                          * allowed data with a FIN.
12555                          */
12556                         flags &= ~TH_FIN;
12557                 }
12558         } else if (rsm) {
12559                 if (flags & TH_FIN)
12560                         flags &= ~TH_FIN;
12561         }
12562         if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
12563                 void *end_rsm;
12564
12565                 end_rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
12566                 if (end_rsm)
12567                         kern_prefetch(end_rsm, &prefetch_rsm);
12568                 prefetch_rsm = 1;
12569         }
12570         SOCKBUF_LOCK(sb);
12571         /*
12572          * If in persist timeout with window of 0, send 1 byte. Otherwise,
12573          * if window is small but nonzero and time TF_SENTFIN expired, we
12574          * will send what we can and go to transmit state.
12575          */
12576         if (tp->t_flags & TF_FORCEDATA) {
12577                 if ((sendwin == 0) || (sendwin <= (tp->snd_max - tp->snd_una))) {
12578                         /*
12579                          * If we still have some data to send, then clear
12580                          * the FIN bit.  Usually this would happen below
12581                          * when it realizes that we aren't sending all the
12582                          * data.  However, if we have exactly 1 byte of
12583                          * unsent data, then it won't clear the FIN bit
12584                          * below, and if we are in persist state, we wind up
12585                          * sending the packet without recording that we sent
12586                          * the FIN bit.
12587                          *
12588                          * We can't just blindly clear the FIN bit, because
12589                          * if we don't have any more data to send then the
12590                          * probe will be the FIN itself.
12591                          */
12592                         if (sb_offset < sbused(sb))
12593                                 flags &= ~TH_FIN;
12594                         sendwin = 1;
12595                 } else {
12596                         if ((bbr->rc_in_persist != 0) &&
12597                             (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
12598                                                bbr_minseg(bbr)))) {
12599                                 /* Exit persists if there is space */
12600                                 bbr_exit_persist(tp, bbr, cts, __LINE__);
12601                         }
12602                         if (rsm == NULL) {
12603                                 /*
12604                                  * If we are dropping persist mode then we
12605                                  * need to correct sb_offset if not a
12606                                  * retransmit.
12607                                  */
12608                                 sb_offset = tp->snd_max - tp->snd_una;
12609                         }
12610                 }
12611         }
12612         /*
12613          * If snd_nxt == snd_max and we have transmitted a FIN, the
12614          * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
12615          * negative length.  This can also occur when TCP opens up its
12616          * congestion window while receiving additional duplicate acks after
12617          * fast-retransmit because TCP will reset snd_nxt to snd_max after
12618          * the fast-retransmit.
12619          *
12620          * In the normal retransmit-FIN-only case, however, snd_nxt will be
12621          * set to snd_una, the sb_offset will be 0, and the length may wind
12622          * up 0.
12623          *
12624          * If sack_rxmit is true we are retransmitting from the scoreboard
12625          * in which case len is already set.
12626          */
12627         if (sack_rxmit == 0) {
12628                 uint32_t avail;
12629
12630                 avail = sbavail(sb);
12631                 if (SEQ_GT(tp->snd_max, tp->snd_una))
12632                         sb_offset = tp->snd_max - tp->snd_una;
12633                 else
12634                         sb_offset = 0;
12635                 if (bbr->rc_tlp_new_data) {
12636                         /* TLP is forcing out new data */
12637                         uint32_t tlplen;
12638
12639                         doing_tlp = 1;
12640                         tlplen = maxseg;
12641
12642                         if (tlplen > (uint32_t)(avail - sb_offset)) {
12643                                 tlplen = (uint32_t)(avail - sb_offset);
12644                         }
12645                         if (tlplen > tp->snd_wnd) {
12646                                 len = tp->snd_wnd;
12647                         } else {
12648                                 len = tlplen;
12649                         }
12650                         bbr->rc_tlp_new_data = 0;
12651                 } else {
12652                         what_we_can = len = bbr_what_can_we_send(tp, bbr, sendwin, avail, sb_offset, cts);
12653                         if ((len < p_maxseg) &&
12654                             (bbr->rc_in_persist == 0) &&
12655                             (ctf_outstanding(tp) >= (2 * p_maxseg)) &&
12656                             ((avail - sb_offset) >= p_maxseg)) {
12657                                 /*
12658                                  * We are not completing whats in the socket
12659                                  * buffer (i.e. there is at least a segment
12660                                  * waiting to send) and we have 2 or more
12661                                  * segments outstanding. There is no sense
12662                                  * of sending a little piece. Lets defer and
12663                                  * and wait until we can send a whole
12664                                  * segment.
12665                                  */
12666                                 len = 0;
12667                         }
12668                         if ((tp->t_flags & TF_FORCEDATA) && (bbr->rc_in_persist)) {
12669                                 /*
12670                                  * We are in persists, figure out if
12671                                  * a retransmit is available (maybe the previous
12672                                  * persists we sent) or if we have to send new
12673                                  * data.
12674                                  */
12675                                 rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
12676                                 if (rsm) {
12677                                         len = rsm->r_end - rsm->r_start;
12678                                         if (rsm->r_flags & BBR_HAS_FIN)
12679                                                 len--;
12680                                         if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12681                                                 len = maxseg;
12682                                         if (len > 1)
12683                                                 BBR_STAT_INC(bbr_persist_reneg);
12684                                         /*
12685                                          * XXXrrs we could force the len to
12686                                          * 1 byte here to cause the chunk to
12687                                          * split apart.. but that would then
12688                                          * mean we always retransmit it as
12689                                          * one byte even after the window
12690                                          * opens.
12691                                          */
12692                                         sack_rxmit = 1;
12693                                         sb_offset = rsm->r_start - tp->snd_una;
12694                                 } else {
12695                                         /*
12696                                          * First time through in persists or peer
12697                                          * acked our one byte. Though we do have
12698                                          * to have something in the sb.
12699                                          */
12700                                         len = 1;
12701                                         sb_offset = 0;  
12702                                         if (avail == 0)
12703                                             len = 0;
12704                                 }
12705                         }
12706                 }
12707         }
12708         if (prefetch_so_done == 0) {
12709                 kern_prefetch(so, &prefetch_so_done);
12710                 prefetch_so_done = 1;
12711         }
12712         /*
12713          * Lop off SYN bit if it has already been sent.  However, if this is
12714          * SYN-SENT state and if segment contains data and if we don't know
12715          * that foreign host supports TAO, suppress sending segment.
12716          */
12717         if ((flags & TH_SYN) && (rsm == NULL) &&
12718             SEQ_GT(tp->snd_max, tp->snd_una)) {
12719                 if (tp->t_state != TCPS_SYN_RECEIVED)
12720                         flags &= ~TH_SYN;
12721                 /*
12722                  * When sending additional segments following a TFO SYN|ACK,
12723                  * do not include the SYN bit.
12724                  */
12725                 if (IS_FASTOPEN(tp->t_flags) &&
12726                     (tp->t_state == TCPS_SYN_RECEIVED))
12727                         flags &= ~TH_SYN;
12728                 sb_offset--, len++;
12729                 if (sbavail(sb) == 0)
12730                         len = 0;
12731         } else if ((flags & TH_SYN) && rsm) {
12732                 /*
12733                  * Subtract one from the len for the SYN being
12734                  * retransmitted.
12735                  */
12736                 len--;
12737         }
12738         /*
12739          * Be careful not to send data and/or FIN on SYN segments. This
12740          * measure is needed to prevent interoperability problems with not
12741          * fully conformant TCP implementations.
12742          */
12743         if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
12744                 len = 0;
12745                 flags &= ~TH_FIN;
12746         }
12747         /*
12748          * On TFO sockets, ensure no data is sent in the following cases:
12749          *
12750          *  - When retransmitting SYN|ACK on a passively-created socket
12751          *  - When retransmitting SYN on an actively created socket
12752          *  - When sending a zero-length cookie (cookie request) on an
12753          *    actively created socket
12754          *  - When the socket is in the CLOSED state (RST is being sent)
12755          */
12756         if (IS_FASTOPEN(tp->t_flags) &&
12757             (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
12758              ((tp->t_state == TCPS_SYN_SENT) &&
12759               (tp->t_tfo_client_cookie_len == 0)) ||
12760              (flags & TH_RST))) {
12761                 len = 0;
12762                 sack_rxmit = 0;
12763                 rsm = NULL;
12764         }
12765         /* Without fast-open there should never be data sent on a SYN */
12766         if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags)))
12767                 len = 0;
12768         if (len <= 0) {
12769                 /*
12770                  * If FIN has been sent but not acked, but we haven't been
12771                  * called to retransmit, len will be < 0.  Otherwise, window
12772                  * shrank after we sent into it.  If window shrank to 0,
12773                  * cancel pending retransmit, pull snd_nxt back to (closed)
12774                  * window, and set the persist timer if it isn't already
12775                  * going.  If the window didn't close completely, just wait
12776                  * for an ACK.
12777                  *
12778                  * We also do a general check here to ensure that we will
12779                  * set the persist timer when we have data to send, but a
12780                  * 0-byte window. This makes sure the persist timer is set
12781                  * even if the packet hits one of the "goto send" lines
12782                  * below.
12783                  */
12784                 len = 0;
12785                 if ((tp->snd_wnd == 0) &&
12786                     (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12787                     (tp->snd_una == tp->snd_max) &&
12788                     (sb_offset < (int)sbavail(sb))) {
12789                         /*
12790                          * Not enough room in the rwnd to send
12791                          * a paced segment out.
12792                          */
12793                         bbr_enter_persist(tp, bbr, cts, __LINE__);
12794                 }
12795         } else if ((rsm == NULL) &&
12796                    (doing_tlp == 0) &&
12797                    (len < bbr->r_ctl.rc_pace_max_segs)) {
12798                 /* 
12799                  * We are not sending a full segment for
12800                  * some reason. Should we not send anything (think
12801                  * sws or persists)?
12802                  */
12803                 if ((tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12804                     (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12805                     (len < (int)(sbavail(sb) - sb_offset))) {
12806                         /*
12807                          * Here the rwnd is less than
12808                          * the pacing size, this is not a retransmit,
12809                          * we are established and
12810                          * the send is not the last in the socket buffer
12811                          * lets not send, and possibly enter persists.
12812                          */
12813                         len = 0;
12814                         if (tp->snd_max == tp->snd_una) 
12815                                 bbr_enter_persist(tp, bbr, cts, __LINE__);
12816                 } else if ((tp->snd_cwnd >= bbr->r_ctl.rc_pace_max_segs) &&
12817                            (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12818                                                  bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12819                            (len < (int)(sbavail(sb) - sb_offset)) &&
12820                            (len < bbr_minseg(bbr))) {
12821                         /*
12822                          * Here we are not retransmitting, and
12823                          * the cwnd is not so small that we could
12824                          * not send at least a min size (rxt timer
12825                          * not having gone off), We have 2 segments or
12826                          * more already in flight, its not the tail end
12827                          * of the socket buffer  and the cwnd is blocking
12828                          * us from sending out minimum pacing segment size. 
12829                          * Lets not send anything.
12830                          */
12831                         bbr->rc_cwnd_limited = 1;
12832                         len = 0;
12833                 } else if (((tp->snd_wnd - ctf_outstanding(tp)) <
12834                             min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12835                            (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12836                                                  bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12837                            (len < (int)(sbavail(sb) - sb_offset)) &&
12838                            (TCPS_HAVEESTABLISHED(tp->t_state))) {
12839                         /* 
12840                          * Here we have a send window but we have
12841                          * filled it up and we can't send another pacing segment.
12842                          * We also have in flight more than 2 segments 
12843                          * and we are not completing the sb i.e. we allow
12844                          * the last bytes of the sb to go out even if
12845                          * its not a full pacing segment.
12846                          */
12847                         len = 0;
12848                 }
12849         }
12850         /* len will be >= 0 after this point. */
12851         KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
12852         tcp_sndbuf_autoscale(tp, so, sendwin);
12853         /*
12854          *
12855          */
12856         if (bbr->rc_in_persist &&
12857             len &&
12858             (rsm == NULL) &&
12859             (len < min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs))) {
12860                 /* 
12861                  * We are in persist, not doing a retransmit and don't have enough space
12862                  * yet to send a full TSO. So is it at the end of the sb
12863                  * if so we need to send else nuke to 0 and don't send.
12864                  */
12865                 int sbleft;
12866                 if (sbavail(sb) > sb_offset)
12867                         sbleft = sbavail(sb) - sb_offset;
12868                 else
12869                         sbleft = 0;
12870                 if (sbleft >= min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs)) {
12871                         /* not at end of sb lets not send */
12872                         len = 0;
12873                 }
12874         }
12875         /*
12876          * Decide if we can use TCP Segmentation Offloading (if supported by
12877          * hardware).
12878          *
12879          * TSO may only be used if we are in a pure bulk sending state.  The
12880          * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
12881          * options prevent using TSO.  With TSO the TCP header is the same
12882          * (except for the sequence number) for all generated packets.  This
12883          * makes it impossible to transmit any options which vary per
12884          * generated segment or packet.
12885          *
12886          * IPv4 handling has a clear separation of ip options and ip header
12887          * flags while IPv6 combines both in in6p_outputopts. ip6_optlen()
12888          * does the right thing below to provide length of just ip options
12889          * and thus checking for ipoptlen is enough to decide if ip options
12890          * are present.
12891          */
12892 #ifdef INET6
12893         if (isipv6)
12894                 ipoptlen = ip6_optlen(inp);
12895         else
12896 #endif
12897         if (inp->inp_options)
12898                 ipoptlen = inp->inp_options->m_len -
12899                     offsetof(struct ipoption, ipopt_list);
12900         else
12901                 ipoptlen = 0;
12902 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12903         /*
12904          * Pre-calculate here as we save another lookup into the darknesses
12905          * of IPsec that way and can actually decide if TSO is ok.
12906          */
12907 #ifdef INET6
12908         if (isipv6 && IPSEC_ENABLED(ipv6))
12909                 ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
12910 #ifdef INET
12911         else
12912 #endif
12913 #endif                          /* INET6 */
12914 #ifdef INET
12915         if (IPSEC_ENABLED(ipv4))
12916                 ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
12917 #endif                          /* INET */
12918 #endif                          /* IPSEC */
12919 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12920         ipoptlen += ipsec_optlen;
12921 #endif
12922         if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
12923             (len > maxseg) &&
12924             (tp->t_port == 0) &&
12925             ((tp->t_flags & TF_SIGNATURE) == 0) &&
12926             tp->rcv_numsacks == 0 &&
12927             ipoptlen == 0)
12928                 tso = 1;
12929
12930         recwin = min(max(sbspace(&so->so_rcv), 0),
12931             TCP_MAXWIN << tp->rcv_scale);
12932         /*
12933          * Sender silly window avoidance.   We transmit under the following
12934          * conditions when len is non-zero:
12935          *
12936          * - We have a full segment (or more with TSO) - This is the last
12937          * buffer in a write()/send() and we are either idle or running
12938          * NODELAY - we've timed out (e.g. persist timer) - we have more
12939          * then 1/2 the maximum send window's worth of data (receiver may be
12940          * limited the window size) - we need to retransmit
12941          */
12942         if (rsm)
12943                 goto send;
12944         if (len) {
12945                 if (sack_rxmit)
12946                         goto send;
12947                 if (len >= p_maxseg)
12948                         goto send;
12949                 /*
12950                  * NOTE! on localhost connections an 'ack' from the remote
12951                  * end may occur synchronously with the output and cause us
12952                  * to flush a buffer queued with moretocome.  XXX
12953                  *
12954                  */
12955                 if (((tp->t_flags & TF_MORETOCOME) == 0) &&     /* normal case */
12956                     ((tp->t_flags & TF_NODELAY) ||
12957                     ((uint32_t)len + (uint32_t)sb_offset) >= sbavail(&so->so_snd)) &&
12958                     (tp->t_flags & TF_NOPUSH) == 0) {
12959                         goto send;
12960                 }
12961                 if ((tp->snd_una == tp->snd_max) && len) {      /* Nothing outstanding */
12962                         goto send;
12963                 }
12964                 if (tp->t_flags & TF_FORCEDATA) {       /* typ. timeout case */
12965                         goto send;
12966                 }
12967                 if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
12968                         goto send;
12969                 }
12970         }
12971         /*
12972          * Sending of standalone window updates.
12973          *
12974          * Window updates are important when we close our window due to a
12975          * full socket buffer and are opening it again after the application
12976          * reads data from it.  Once the window has opened again and the
12977          * remote end starts to send again the ACK clock takes over and
12978          * provides the most current window information.
12979          *
12980          * We must avoid the silly window syndrome whereas every read from
12981          * the receive buffer, no matter how small, causes a window update
12982          * to be sent.  We also should avoid sending a flurry of window
12983          * updates when the socket buffer had queued a lot of data and the
12984          * application is doing small reads.
12985          *
12986          * Prevent a flurry of pointless window updates by only sending an
12987          * update when we can increase the advertized window by more than
12988          * 1/4th of the socket buffer capacity.  When the buffer is getting
12989          * full or is very small be more aggressive and send an update
12990          * whenever we can increase by two mss sized segments. In all other
12991          * situations the ACK's to new incoming data will carry further
12992          * window increases.
12993          *
12994          * Don't send an independent window update if a delayed ACK is
12995          * pending (it will get piggy-backed on it) or the remote side
12996          * already has done a half-close and won't send more data.  Skip
12997          * this if the connection is in T/TCP half-open state.
12998          */
12999         if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
13000             !(tp->t_flags & TF_DELACK) &&
13001             !TCPS_HAVERCVDFIN(tp->t_state)) {
13002                 /* Check to see if we should do a window update */
13003                 if (bbr_window_update_needed(tp, so, recwin, maxseg))
13004                         goto send;
13005         }
13006         /*
13007          * Send if we owe the peer an ACK, RST, SYN, or urgent data.  ACKNOW
13008          * is also a catch-all for the retransmit timer timeout case.
13009          */
13010         if (tp->t_flags & TF_ACKNOW) {
13011                 goto send;
13012         }
13013         if (((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0)) {
13014                 goto send;
13015         }
13016         if (SEQ_GT(tp->snd_up, tp->snd_una)) {
13017                 goto send;
13018         }
13019         /*
13020          * If our state indicates that FIN should be sent and we have not
13021          * yet done so, then we need to send.
13022          */
13023         if (flags & TH_FIN &&
13024             ((tp->t_flags & TF_SENTFIN) == 0)) {
13025                 goto send;
13026         }
13027         /*
13028          * No reason to send a segment, just return.
13029          */
13030 just_return:
13031         SOCKBUF_UNLOCK(sb);
13032 just_return_nolock:
13033         if (tot_len)
13034                 slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
13035         if (bbr->rc_no_pacing)
13036                 slot = 0;
13037         if (tot_len == 0) {
13038                 if ((ctf_outstanding(tp) + min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) >=
13039                     tp->snd_wnd) {
13040                         BBR_STAT_INC(bbr_rwnd_limited);
13041                         app_limited = BBR_JR_RWND_LIMITED;
13042                         bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
13043                         if ((bbr->rc_in_persist == 0) &&
13044                             TCPS_HAVEESTABLISHED(tp->t_state) &&
13045                             (tp->snd_max == tp->snd_una) &&
13046                             sbavail(&tp->t_inpcb->inp_socket->so_snd)) {
13047                                 /* No send window.. we must enter persist */
13048                                 bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
13049                         }
13050                 } else if (ctf_outstanding(tp) >= sbavail(sb)) {
13051                         BBR_STAT_INC(bbr_app_limited);
13052                         app_limited = BBR_JR_APP_LIMITED;
13053                         bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
13054                 } else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13055                                                  bbr->r_ctl.rc_lost_bytes)) + p_maxseg) >= tp->snd_cwnd) {
13056                         BBR_STAT_INC(bbr_cwnd_limited);
13057                         app_limited = BBR_JR_CWND_LIMITED;
13058                         bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13059                                                                         bbr->r_ctl.rc_lost_bytes)));
13060                         bbr->rc_cwnd_limited = 1;
13061                 } else {
13062                         BBR_STAT_INC(bbr_app_limited);
13063                         app_limited = BBR_JR_APP_LIMITED;
13064                         bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
13065                 }
13066                 bbr->r_ctl.rc_hptsi_agg_delay = 0;
13067                 bbr->r_agg_early_set = 0;
13068                 bbr->r_ctl.rc_agg_early = 0;
13069                 bbr->r_ctl.rc_last_delay_val = 0;
13070         } else if (bbr->rc_use_google == 0)
13071                 bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
13072         /* Are we app limited? */
13073         if ((app_limited == BBR_JR_APP_LIMITED) ||
13074             (app_limited == BBR_JR_RWND_LIMITED)) {
13075                 /**
13076                  * We are application limited.
13077                  */
13078                 bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13079                                                                        bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_delivered);
13080         } 
13081         if (tot_len == 0)
13082                 counter_u64_add(bbr_out_size[TCP_MSS_ACCT_JUSTRET], 1);
13083         tp->t_flags &= ~TF_FORCEDATA;
13084         /* Dont update the time if we did not send */
13085         bbr->r_ctl.rc_last_delay_val = 0;
13086         bbr->rc_output_starts_timer = 1;
13087         bbr_start_hpts_timer(bbr, tp, cts, 9, slot, tot_len);
13088         bbr_log_type_just_return(bbr, cts, tot_len, hpts_calling, app_limited, p_maxseg, len);
13089         if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
13090                 /* Make sure snd_nxt is drug up */
13091                 tp->snd_nxt = tp->snd_max;
13092         }
13093         return (error);
13094
13095 send:
13096         if (doing_tlp == 0) {
13097                 /*
13098                  * Data not a TLP, and its not the rxt firing. If it is the
13099                  * rxt firing, we want to leave the tlp_in_progress flag on
13100                  * so we don't send another TLP. It has to be a rack timer
13101                  * or normal send (response to acked data) to clear the tlp
13102                  * in progress flag.
13103                  */
13104                 bbr->rc_tlp_in_progress = 0;
13105                 bbr->rc_tlp_rtx_out = 0;
13106         } else {
13107                 /*
13108                  * Its a TLP.
13109                  */
13110                 bbr->rc_tlp_in_progress = 1;
13111         }
13112         bbr_timer_cancel(bbr, __LINE__, cts);
13113         if (rsm == NULL) {
13114                 if (sbused(sb) > 0) {
13115                         /*
13116                          * This is sub-optimal. We only send a stand alone
13117                          * FIN on its own segment.
13118                          */
13119                         if (flags & TH_FIN) {
13120                                 flags &= ~TH_FIN;
13121                                 if ((len == 0) && ((tp->t_flags & TF_ACKNOW) == 0)) {
13122                                         /* Lets not send this */
13123                                         slot = 0;
13124                                         goto just_return;
13125                                 }
13126                         }
13127                 }
13128         } else {
13129                 /*
13130                  * We do *not* send a FIN on a retransmit if it has data.
13131                  * The if clause here where len > 1 should never come true.
13132                  */
13133                 if ((len > 0) &&
13134                     (((rsm->r_flags & BBR_HAS_FIN) == 0) &&
13135                     (flags & TH_FIN))) {
13136                         flags &= ~TH_FIN;
13137                         len--;
13138                 }
13139         }
13140         SOCKBUF_LOCK_ASSERT(sb);
13141         if (len > 0) {
13142                 if ((tp->snd_una == tp->snd_max) &&
13143                     (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
13144                         /*
13145                          * This qualifies as a RTT_PROBE session since we
13146                          * drop the data outstanding to nothing and waited
13147                          * more than bbr_rtt_probe_time.
13148                          */
13149                         bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
13150                         bbr_set_reduced_rtt(bbr, cts, __LINE__);
13151                 }
13152                 if (len >= maxseg)
13153                         tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
13154                 else
13155                         tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
13156         }
13157         /*
13158          * Before ESTABLISHED, force sending of initial options unless TCP
13159          * set not to do any options. NOTE: we assume that the IP/TCP header
13160          * plus TCP options always fit in a single mbuf, leaving room for a
13161          * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
13162          * + optlen <= MCLBYTES
13163          */
13164         optlen = 0;
13165 #ifdef INET6
13166         if (isipv6)
13167                 hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
13168         else
13169 #endif
13170                 hdrlen = sizeof(struct tcpiphdr);
13171
13172         /*
13173          * Compute options for segment. We only have to care about SYN and
13174          * established connection segments.  Options for SYN-ACK segments
13175          * are handled in TCP syncache.
13176          */
13177         to.to_flags = 0;
13178         local_options = 0;
13179         if ((tp->t_flags & TF_NOOPT) == 0) {
13180                 /* Maximum segment size. */
13181                 if (flags & TH_SYN) {
13182                         to.to_mss = tcp_mssopt(&inp->inp_inc);
13183 #ifdef NETFLIX_TCPOUDP
13184                         if (tp->t_port)
13185                                 to.to_mss -= V_tcp_udp_tunneling_overhead;
13186 #endif
13187                         to.to_flags |= TOF_MSS;
13188                         /*
13189                          * On SYN or SYN|ACK transmits on TFO connections,
13190                          * only include the TFO option if it is not a
13191                          * retransmit, as the presence of the TFO option may
13192                          * have caused the original SYN or SYN|ACK to have
13193                          * been dropped by a middlebox.
13194                          */
13195                         if (IS_FASTOPEN(tp->t_flags) &&
13196                             (tp->t_rxtshift == 0)) {
13197                                 if (tp->t_state == TCPS_SYN_RECEIVED) {
13198                                         to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
13199                                         to.to_tfo_cookie =
13200                                             (u_int8_t *)&tp->t_tfo_cookie.server;
13201                                         to.to_flags |= TOF_FASTOPEN;
13202                                         wanted_cookie = 1;
13203                                 } else if (tp->t_state == TCPS_SYN_SENT) {
13204                                         to.to_tfo_len =
13205                                             tp->t_tfo_client_cookie_len;
13206                                         to.to_tfo_cookie =
13207                                             tp->t_tfo_cookie.client;
13208                                         to.to_flags |= TOF_FASTOPEN;
13209                                         wanted_cookie = 1;
13210                                 }
13211                         }
13212                 }
13213                 /* Window scaling. */
13214                 if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
13215                         to.to_wscale = tp->request_r_scale;
13216                         to.to_flags |= TOF_SCALE;
13217                 }
13218                 /* Timestamps. */
13219                 if ((tp->t_flags & TF_RCVD_TSTMP) ||
13220                     ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
13221                         to.to_tsval =   tcp_tv_to_mssectick(&bbr->rc_tv) + tp->ts_offset;
13222                         to.to_tsecr = tp->ts_recent;
13223                         to.to_flags |= TOF_TS;
13224                         local_options += TCPOLEN_TIMESTAMP + 2;
13225                 }
13226                 /* Set receive buffer autosizing timestamp. */
13227                 if (tp->rfbuf_ts == 0 &&
13228                     (so->so_rcv.sb_flags & SB_AUTOSIZE))
13229                         tp->rfbuf_ts =  tcp_tv_to_mssectick(&bbr->rc_tv);
13230                 /* Selective ACK's. */
13231                 if (flags & TH_SYN)
13232                         to.to_flags |= TOF_SACKPERM;
13233                 else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13234                     tp->rcv_numsacks > 0) {
13235                         to.to_flags |= TOF_SACK;
13236                         to.to_nsacks = tp->rcv_numsacks;
13237                         to.to_sacks = (u_char *)tp->sackblks;
13238                 }
13239 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13240                 /* TCP-MD5 (RFC2385). */
13241                 if (tp->t_flags & TF_SIGNATURE)
13242                         to.to_flags |= TOF_SIGNATURE;
13243 #endif                          /* TCP_SIGNATURE */
13244
13245                 /* Processing the options. */
13246                 hdrlen += (optlen = tcp_addoptions(&to, opt));
13247                 /*
13248                  * If we wanted a TFO option to be added, but it was unable
13249                  * to fit, ensure no data is sent.
13250                  */
13251                 if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
13252                     !(to.to_flags & TOF_FASTOPEN))
13253                         len = 0;
13254         }
13255 #ifdef NETFLIX_TCPOUDP
13256         if (tp->t_port) {
13257                 if (V_tcp_udp_tunneling_port == 0) {
13258                         /* The port was removed?? */
13259                         SOCKBUF_UNLOCK(&so->so_snd);
13260                         return (EHOSTUNREACH);
13261                 }
13262                 hdrlen += sizeof(struct udphdr);
13263         }
13264 #endif
13265 #ifdef INET6
13266         if (isipv6)
13267                 ipoptlen = ip6_optlen(tp->t_inpcb);
13268         else
13269 #endif
13270         if (tp->t_inpcb->inp_options)
13271                 ipoptlen = tp->t_inpcb->inp_options->m_len -
13272                     offsetof(struct ipoption, ipopt_list);
13273         else
13274                 ipoptlen = 0;
13275         ipoptlen = 0;
13276 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
13277         ipoptlen += ipsec_optlen;
13278 #endif
13279         if (bbr->rc_last_options != local_options) {
13280                 /*
13281                  * Cache the options length this generally does not change
13282                  * on a connection. We use this to calculate TSO.
13283                  */
13284                 bbr->rc_last_options = local_options;
13285         }
13286         maxseg = tp->t_maxseg - (ipoptlen + optlen);
13287         p_maxseg = min(maxseg, pace_max_segs);
13288         /*
13289          * Adjust data length if insertion of options will bump the packet
13290          * length beyond the t_maxseg length. Clear the FIN bit because we
13291          * cut off the tail of the segment.
13292          */
13293 #ifdef KERN_TLS
13294         /* force TSO for so TLS offload can get mss */
13295         if (sb->sb_flags & SB_TLS_IFNET) {
13296                 force_tso = 1;
13297         }
13298 #endif
13299
13300         if (len > maxseg) {
13301                 if (len != 0 && (flags & TH_FIN)) {
13302                         flags &= ~TH_FIN;
13303                 }
13304                 if (tso) {
13305                         uint32_t moff;
13306                         int32_t max_len;
13307
13308                         /* extract TSO information */
13309                         if_hw_tsomax = tp->t_tsomax;
13310                         if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
13311                         if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
13312                         KASSERT(ipoptlen == 0,
13313                             ("%s: TSO can't do IP options", __func__));
13314
13315                         /*
13316                          * Check if we should limit by maximum payload
13317                          * length:
13318                          */
13319                         if (if_hw_tsomax != 0) {
13320                                 /* compute maximum TSO length */
13321                                 max_len = (if_hw_tsomax - hdrlen -
13322                                     max_linkhdr);
13323                                 if (max_len <= 0) {
13324                                         len = 0;
13325                                 } else if (len > max_len) {
13326                                         len = max_len;
13327                                 }
13328                         }
13329                         /*
13330                          * Prevent the last segment from being fractional
13331                          * unless the send sockbuf can be emptied:
13332                          */
13333                         if (((sb_offset + len) < sbavail(sb)) &&
13334                             (hw_tls == 0)) {
13335                                 moff = len % (uint32_t)maxseg;
13336                                 if (moff != 0) {
13337                                         len -= moff;
13338                                 }
13339                         }
13340                         /*
13341                          * In case there are too many small fragments don't
13342                          * use TSO:
13343                          */
13344                         if (len <= maxseg) {
13345                                 len = maxseg;
13346                                 tso = 0;
13347                         }
13348                 } else {
13349                         /* Not doing TSO */
13350                         if (optlen + ipoptlen >= tp->t_maxseg) {
13351                                 /*
13352                                  * Since we don't have enough space to put
13353                                  * the IP header chain and the TCP header in
13354                                  * one packet as required by RFC 7112, don't
13355                                  * send it. Also ensure that at least one
13356                                  * byte of the payload can be put into the
13357                                  * TCP segment.
13358                                  */
13359                                 SOCKBUF_UNLOCK(&so->so_snd);
13360                                 error = EMSGSIZE;
13361                                 sack_rxmit = 0;
13362                                 goto out;
13363                         }
13364                         len = maxseg;
13365                 }
13366         } else {
13367                 /* Not doing TSO */
13368                 if_hw_tsomaxsegcount = 0;
13369                 tso = 0;
13370         }
13371         KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
13372             ("%s: len > IP_MAXPACKET", __func__));
13373 #ifdef DIAGNOSTIC
13374 #ifdef INET6
13375         if (max_linkhdr + hdrlen > MCLBYTES)
13376 #else
13377         if (max_linkhdr + hdrlen > MHLEN)
13378 #endif
13379                 panic("tcphdr too big");
13380 #endif
13381         /*
13382          * This KASSERT is here to catch edge cases at a well defined place.
13383          * Before, those had triggered (random) panic conditions further
13384          * down.
13385          */
13386 #ifdef BBR_INVARIANTS
13387         if (sack_rxmit) {
13388                 if (SEQ_LT(rsm->r_start, tp->snd_una)) {
13389                         panic("RSM:%p TP:%p bbr:%p start:%u is < snd_una:%u",
13390                             rsm, tp, bbr, rsm->r_start, tp->snd_una);
13391                 }
13392         }
13393 #endif
13394         KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
13395         if ((len == 0) &&
13396             (flags & TH_FIN) &&
13397             (sbused(sb))) {
13398                 /*
13399                  * We have outstanding data, don't send a fin by itself!.
13400                  */
13401                 slot = 0;
13402                 goto just_return;
13403         }
13404         /*
13405          * Grab a header mbuf, attaching a copy of data to be transmitted,
13406          * and initialize the header from the template for sends on this
13407          * connection.
13408          */
13409         if (len) {
13410                 uint32_t moff;
13411                 uint32_t orig_len;
13412
13413                 /*
13414                  * We place a limit on sending with hptsi.
13415                  */
13416                 if ((rsm == NULL) && len > pace_max_segs)
13417                         len = pace_max_segs;
13418                 if (len <= maxseg)
13419                         tso = 0;
13420 #ifdef INET6
13421                 if (MHLEN < hdrlen + max_linkhdr)
13422                         m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
13423                 else
13424 #endif
13425                         m = m_gethdr(M_NOWAIT, MT_DATA);
13426
13427                 if (m == NULL) {
13428                         BBR_STAT_INC(bbr_failed_mbuf_aloc);
13429                         bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13430                         SOCKBUF_UNLOCK(sb);
13431                         error = ENOBUFS;
13432                         sack_rxmit = 0;
13433                         goto out;
13434                 }
13435                 m->m_data += max_linkhdr;
13436                 m->m_len = hdrlen;
13437                 /*
13438                  * Start the m_copy functions from the closest mbuf to the
13439                  * sb_offset in the socket buffer chain.
13440                  */
13441                 if ((sb_offset > sbavail(sb)) || ((len + sb_offset) > sbavail(sb))) {
13442 #ifdef BBR_INVARIANTS
13443                         if ((len + sb_offset) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0)))
13444                                 panic("tp:%p bbr:%p len:%u sb_offset:%u sbavail:%u rsm:%p %u:%u:%u",
13445                                     tp, bbr, len, sb_offset, sbavail(sb), rsm,
13446                                     doing_retran_from,
13447                                     picked_up_retran,
13448                                     doing_tlp);
13449
13450 #endif
13451                         /*
13452                          * In this messed up situation we have two choices,
13453                          * a) pretend the send worked, and just start timers
13454                          * and what not (not good since that may lead us
13455                          * back here a lot). <or> b) Send the lowest segment
13456                          * in the map. <or> c) Drop the connection. Lets do
13457                          * <b> which if it continues to happen will lead to
13458                          * <c> via timeouts.
13459                          */
13460                         BBR_STAT_INC(bbr_offset_recovery);
13461                         rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
13462                         sb_offset = 0;
13463                         if (rsm == NULL) {
13464                                 sack_rxmit = 0;
13465                                 len = sbavail(sb);
13466                         } else {
13467                                 sack_rxmit = 1;
13468                                 if (rsm->r_start != tp->snd_una) {
13469                                         /*
13470                                          * Things are really messed up, <c>
13471                                          * is the only thing to do.
13472                                          */
13473                                         BBR_STAT_INC(bbr_offset_drop);
13474                                         tcp_set_inp_to_drop(inp, EFAULT);
13475                                         return (0);
13476                                 }
13477                                 len = rsm->r_end - rsm->r_start;
13478                         }
13479                         if (len > sbavail(sb))
13480                                 len = sbavail(sb);
13481                         if (len > maxseg)
13482                                 len = maxseg;
13483                 }
13484                 mb = sbsndptr_noadv(sb, sb_offset, &moff);
13485                 if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
13486                         m_copydata(mb, moff, (int)len,
13487                             mtod(m, caddr_t)+hdrlen);
13488                         if (rsm == NULL)
13489                                 sbsndptr_adv(sb, mb, len);
13490                         m->m_len += len;
13491                 } else {
13492                         struct sockbuf *msb;
13493
13494                         if (rsm)
13495                                 msb = NULL;
13496                         else
13497                                 msb = sb;
13498 #ifdef BBR_INVARIANTS
13499                         if ((len + moff) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0))) {
13500                                 if (rsm) {
13501                                         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 ",
13502                                             tp, bbr, len, moff,
13503                                             sbavail(sb), rsm,
13504                                             tp->snd_una, rsm->r_flags, rsm->r_start,
13505                                             doing_retran_from,
13506                                             picked_up_retran,
13507                                             doing_tlp, sack_rxmit);
13508                                 } else {
13509                                         panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u sb_offset:%u snd_una:%u",
13510                                             tp, bbr, len, moff, sbavail(sb), sb_offset, tp->snd_una);
13511                                 }
13512                         }
13513 #endif
13514                         orig_len = len;
13515                         m->m_next = tcp_m_copym(
13516 #ifdef NETFLIX_COPY_ARGS
13517                                 tp,
13518 #endif
13519                                 mb, moff, &len,
13520                                 if_hw_tsomaxsegcount,
13521                                 if_hw_tsomaxsegsize, msb, 
13522                                 ((rsm == NULL) ? hw_tls : 0) 
13523 #ifdef NETFLIX_COPY_ARGS
13524                                 , &filled_all
13525 #endif
13526                                 );
13527                         if (len <= maxseg && !force_tso) {
13528                                 /*
13529                                  * Must have ran out of mbufs for the copy
13530                                  * shorten it to no longer need tso. Lets
13531                                  * not put on sendalot since we are low on
13532                                  * mbufs.
13533                                  */
13534                                 tso = 0;
13535                         }
13536                         if (m->m_next == NULL) {
13537                                 SOCKBUF_UNLOCK(sb);
13538                                 (void)m_free(m);
13539                                 error = ENOBUFS;
13540                                 sack_rxmit = 0;
13541                                 goto out;
13542                         }
13543                 }
13544 #ifdef BBR_INVARIANTS
13545                 if (tso && len < maxseg) {
13546                         panic("tp:%p tso on, but len:%d < maxseg:%d",
13547                             tp, len, maxseg);
13548                 }
13549                 if (tso && if_hw_tsomaxsegcount) {
13550                         int32_t seg_cnt = 0;
13551                         struct mbuf *foo;
13552
13553                         foo = m;
13554                         while (foo) {
13555                                 seg_cnt++;
13556                                 foo = foo->m_next;
13557                         }
13558                         if (seg_cnt > if_hw_tsomaxsegcount) {
13559                                 panic("seg_cnt:%d > max:%d", seg_cnt, if_hw_tsomaxsegcount);
13560                         }
13561                 }
13562 #endif
13563                 /*
13564                  * If we're sending everything we've got, set PUSH. (This
13565                  * will keep happy those implementations which only give
13566                  * data to the user when a buffer fills or a PUSH comes in.)
13567                  */
13568                 if (sb_offset + len == sbused(sb) &&
13569                     sbused(sb) &&
13570                     !(flags & TH_SYN)) {
13571                         flags |= TH_PUSH;
13572                 }
13573                 SOCKBUF_UNLOCK(sb);
13574         } else {
13575                 SOCKBUF_UNLOCK(sb);
13576                 if (tp->t_flags & TF_ACKNOW)
13577                         TCPSTAT_INC(tcps_sndacks);
13578                 else if (flags & (TH_SYN | TH_FIN | TH_RST))
13579                         TCPSTAT_INC(tcps_sndctrl);
13580                 else if (SEQ_GT(tp->snd_up, tp->snd_una))
13581                         TCPSTAT_INC(tcps_sndurg);
13582                 else
13583                         TCPSTAT_INC(tcps_sndwinup);
13584
13585                 m = m_gethdr(M_NOWAIT, MT_DATA);
13586                 if (m == NULL) {
13587                         BBR_STAT_INC(bbr_failed_mbuf_aloc);
13588                         bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13589                         error = ENOBUFS;
13590                         /* Fudge the send time since we could not send */
13591                         sack_rxmit = 0;
13592                         goto out;
13593                 }
13594 #ifdef INET6
13595                 if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
13596                     MHLEN >= hdrlen) {
13597                         M_ALIGN(m, hdrlen);
13598                 } else
13599 #endif
13600                         m->m_data += max_linkhdr;
13601                 m->m_len = hdrlen;
13602         }
13603         SOCKBUF_UNLOCK_ASSERT(sb);
13604         m->m_pkthdr.rcvif = (struct ifnet *)0;
13605 #ifdef MAC
13606         mac_inpcb_create_mbuf(inp, m);
13607 #endif
13608 #ifdef INET6
13609         if (isipv6) {
13610                 ip6 = mtod(m, struct ip6_hdr *);
13611 #ifdef NETFLIX_TCPOUDP
13612                 if (tp->t_port) {
13613                         udp = (struct udphdr *)((caddr_t)ip6 + ipoptlen + sizeof(struct ip6_hdr));
13614                         udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13615                         udp->uh_dport = tp->t_port;
13616                         ulen = hdrlen + len - sizeof(struct ip6_hdr);
13617                         udp->uh_ulen = htons(ulen);
13618                         th = (struct tcphdr *)(udp + 1);
13619                 } else {
13620 #endif
13621                         th = (struct tcphdr *)(ip6 + 1);
13622
13623 #ifdef NETFLIX_TCPOUDP
13624                 }
13625 #endif
13626                 tcpip_fillheaders(inp,
13627 #ifdef NETFLIX_TCPOUDP
13628                                   tp->t_port,
13629 #endif
13630                                   ip6, th);
13631         } else
13632 #endif                          /* INET6 */
13633         {
13634                 ip = mtod(m, struct ip *);
13635 #ifdef TCPDEBUG
13636                 ipov = (struct ipovly *)ip;
13637 #endif
13638 #ifdef NETFLIX_TCPOUDP
13639                 if (tp->t_port) {
13640                         udp = (struct udphdr *)((caddr_t)ip + ipoptlen + sizeof(struct ip));
13641                         udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13642                         udp->uh_dport = tp->t_port;
13643                         ulen = hdrlen + len - sizeof(struct ip);
13644                         udp->uh_ulen = htons(ulen);
13645                         th = (struct tcphdr *)(udp + 1);
13646                 } else
13647 #endif
13648                         th = (struct tcphdr *)(ip + 1);
13649                 tcpip_fillheaders(inp,
13650 #ifdef NETFLIX_TCPOUDP
13651                                   tp->t_port,
13652 #endif
13653                                   ip, th);
13654         }
13655         /*
13656          * If we are doing retransmissions, then snd_nxt will not reflect
13657          * the first unsent octet.  For ACK only packets, we do not want the
13658          * sequence number of the retransmitted packet, we want the sequence
13659          * number of the next unsent octet.  So, if there is no data (and no
13660          * SYN or FIN), use snd_max instead of snd_nxt when filling in
13661          * ti_seq.  But if we are in persist state, snd_max might reflect
13662          * one byte beyond the right edge of the window, so use snd_nxt in
13663          * that case, since we know we aren't doing a retransmission.
13664          * (retransmit and persist are mutually exclusive...)
13665          */
13666         if (sack_rxmit == 0) {
13667                 if (len && ((flags & (TH_FIN | TH_SYN | TH_RST)) == 0)) {
13668                         /* New data (including new persists) */
13669                         th->th_seq = htonl(tp->snd_max);
13670                         bbr_seq = tp->snd_max;
13671                 } else if (flags & TH_SYN) {
13672                         /* Syn's always send from iss */
13673                         th->th_seq = htonl(tp->iss);
13674                         bbr_seq = tp->iss;
13675                 } else if (flags & TH_FIN) {
13676                         if (flags & TH_FIN && tp->t_flags & TF_SENTFIN) {
13677                                 /*
13678                                  * If we sent the fin already its 1 minus
13679                                  * snd_max
13680                                  */
13681                                 th->th_seq = (htonl(tp->snd_max - 1));
13682                                 bbr_seq = (tp->snd_max - 1);
13683                         } else {
13684                                 /* First time FIN use snd_max */
13685                                 th->th_seq = htonl(tp->snd_max);
13686                                 bbr_seq = tp->snd_max;
13687                         }
13688                 } else if (flags & TH_RST) {
13689                         /*
13690                          * For a Reset send the last cum ack in sequence
13691                          * (this like any other choice may still generate a
13692                          * challenge ack, if a ack-update packet is in
13693                          * flight).
13694                          */
13695                         th->th_seq = htonl(tp->snd_una);
13696                         bbr_seq = tp->snd_una;
13697                 } else {
13698                         /*
13699                          * len == 0 and not persist we use snd_max, sending
13700                          * an ack unless we have sent the fin then its 1
13701                          * minus.
13702                          */
13703                         /*
13704                          * XXXRRS Question if we are in persists and we have
13705                          * nothing outstanding to send and we have not sent
13706                          * a FIN, we will send an ACK. In such a case it
13707                          * might be better to send (tp->snd_una - 1) which
13708                          * would force the peer to ack.
13709                          */
13710                         if (tp->t_flags & TF_SENTFIN) {
13711                                 th->th_seq = htonl(tp->snd_max - 1);
13712                                 bbr_seq = (tp->snd_max - 1);
13713                         } else {
13714                                 th->th_seq = htonl(tp->snd_max);
13715                                 bbr_seq = tp->snd_max;
13716                         }
13717                 }
13718         } else {
13719                 /* All retransmits use the rsm to guide the send */
13720                 th->th_seq = htonl(rsm->r_start);
13721                 bbr_seq = rsm->r_start;
13722         }
13723         th->th_ack = htonl(tp->rcv_nxt);
13724         if (optlen) {
13725                 bcopy(opt, th + 1, optlen);
13726                 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
13727         }
13728         th->th_flags = flags;
13729         /*
13730          * Calculate receive window.  Don't shrink window, but avoid silly
13731          * window syndrome.
13732          */
13733         if ((flags & TH_RST) || ((recwin < (so->so_rcv.sb_hiwat / 4) &&
13734                                   recwin < maxseg)))
13735                 recwin = 0;
13736         if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
13737             recwin < (tp->rcv_adv - tp->rcv_nxt))
13738                 recwin = (tp->rcv_adv - tp->rcv_nxt);
13739         if (recwin > TCP_MAXWIN << tp->rcv_scale)
13740                 recwin = TCP_MAXWIN << tp->rcv_scale;
13741
13742         /*
13743          * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
13744          * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
13745          * handled in syncache.
13746          */
13747         if (flags & TH_SYN)
13748                 th->th_win = htons((u_short)
13749                     (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
13750         else
13751                 th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
13752         /*
13753          * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
13754          * window.  This may cause the remote transmitter to stall.  This
13755          * flag tells soreceive() to disable delayed acknowledgements when
13756          * draining the buffer.  This can occur if the receiver is
13757          * attempting to read more data than can be buffered prior to
13758          * transmitting on the connection.
13759          */
13760         if (th->th_win == 0) {
13761                 tp->t_sndzerowin++;
13762                 tp->t_flags |= TF_RXWIN0SENT;
13763         } else
13764                 tp->t_flags &= ~TF_RXWIN0SENT;
13765         if (SEQ_GT(tp->snd_up, tp->snd_max)) {
13766                 th->th_urp = htons((u_short)(tp->snd_up - tp->snd_max));
13767                 th->th_flags |= TH_URG;
13768         } else
13769                 /*
13770                  * If no urgent pointer to send, then we pull the urgent
13771                  * pointer to the left edge of the send window so that it
13772                  * doesn't drift into the send window on sequence number
13773                  * wraparound.
13774                  */
13775                 tp->snd_up = tp->snd_una;       /* drag it along */
13776
13777 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13778         if (to.to_flags & TOF_SIGNATURE) {
13779                 /*
13780                  * Calculate MD5 signature and put it into the place
13781                  * determined before. NOTE: since TCP options buffer doesn't
13782                  * point into mbuf's data, calculate offset and use it.
13783                  */
13784                 if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
13785                     (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
13786                         /*
13787                          * Do not send segment if the calculation of MD5
13788                          * digest has failed.
13789                          */
13790                         goto out;
13791                 }
13792         }
13793 #endif
13794
13795         /*
13796          * Put TCP length in extended header, and then checksum extended
13797          * header and data.
13798          */
13799         m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
13800 #ifdef INET6
13801         if (isipv6) {
13802                 /*
13803                  * ip6_plen is not need to be filled now, and will be filled
13804                  * in ip6_output.
13805                  */
13806 #ifdef NETFLIX_TCPOUDP
13807                 if (tp->t_port) {
13808                         m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
13809                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13810                         udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
13811                         th->th_sum = htons(0);
13812                         UDPSTAT_INC(udps_opackets);
13813                 } else {
13814 #endif
13815                         csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
13816                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13817                         th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
13818                             optlen + len, IPPROTO_TCP, 0);
13819 #ifdef NETFLIX_TCPOUDP
13820                 }
13821 #endif
13822         }
13823 #endif
13824 #if defined(INET6) && defined(INET)
13825         else
13826 #endif
13827 #ifdef INET
13828         {
13829 #ifdef NETFLIX_TCPOUDP
13830                 if (tp->t_port) {
13831                         m->m_pkthdr.csum_flags = CSUM_UDP;
13832                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13833                         udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
13834                             ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
13835                         th->th_sum = htons(0);
13836                         UDPSTAT_INC(udps_opackets);
13837                 } else {
13838 #endif
13839                         csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP;
13840                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13841                         th->th_sum = in_pseudo(ip->ip_src.s_addr,
13842                             ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
13843                             IPPROTO_TCP + len + optlen));
13844 #ifdef NETFLIX_TCPOUDP
13845                 }
13846 #endif
13847                 /* IP version must be set here for ipv4/ipv6 checking later */
13848                 KASSERT(ip->ip_v == IPVERSION,
13849                     ("%s: IP version incorrect: %d", __func__, ip->ip_v));
13850         }
13851 #endif
13852
13853         /*
13854          * Enable TSO and specify the size of the segments. The TCP pseudo
13855          * header checksum is always provided. XXX: Fixme: This is currently
13856          * not the case for IPv6.
13857          */
13858         if (tso || force_tso) {
13859                 KASSERT(force_tso || len > maxseg,
13860                     ("%s: len:%d <= tso_segsz:%d", __func__, len, maxseg));
13861                 m->m_pkthdr.csum_flags |= CSUM_TSO;
13862                 csum_flags |= CSUM_TSO;
13863                 m->m_pkthdr.tso_segsz = maxseg;
13864         }
13865         KASSERT(len + hdrlen == m_length(m, NULL),
13866             ("%s: mbuf chain different than expected: %d + %u != %u",
13867             __func__, len, hdrlen, m_length(m, NULL)));
13868
13869 #ifdef TCP_HHOOK
13870         /* Run HHOOK_TC_ESTABLISHED_OUT helper hooks. */
13871         hhook_run_tcp_est_out(tp, th, &to, len, tso);
13872 #endif
13873 #ifdef TCPDEBUG
13874         /*
13875          * Trace.
13876          */
13877         if (so->so_options & SO_DEBUG) {
13878                 u_short save = 0;
13879
13880 #ifdef INET6
13881                 if (!isipv6)
13882 #endif
13883                 {
13884                         save = ipov->ih_len;
13885                         ipov->ih_len = htons(m->m_pkthdr.len    /* - hdrlen +
13886                               * (th->th_off << 2) */ );
13887                 }
13888                 tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
13889 #ifdef INET6
13890                 if (!isipv6)
13891 #endif
13892                         ipov->ih_len = save;
13893         }
13894 #endif                          /* TCPDEBUG */
13895
13896         /* Log to the black box */
13897         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
13898                 union tcp_log_stackspecific log;
13899                 
13900                 bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
13901                 /* Record info on type of transmission */
13902                 log.u_bbr.flex1 = bbr->r_ctl.rc_hptsi_agg_delay;
13903                 log.u_bbr.flex2 = (bbr->r_recovery_bw << 3);
13904                 log.u_bbr.flex3 = maxseg;
13905                 log.u_bbr.flex4 = delay_calc;
13906                 /* Encode filled_all into the upper flex5 bit */
13907                 log.u_bbr.flex5 = bbr->rc_past_init_win;
13908                 log.u_bbr.flex5 <<= 1;
13909                 log.u_bbr.flex5 |= bbr->rc_no_pacing;
13910                 log.u_bbr.flex5 <<= 29;
13911                 if (filled_all)
13912                         log.u_bbr.flex5 |= 0x80000000;
13913                 log.u_bbr.flex5 |= tp->t_maxseg;
13914                 log.u_bbr.flex6 = bbr->r_ctl.rc_pace_max_segs;
13915                 log.u_bbr.flex7 = (bbr->rc_bbr_state << 8) | bbr_state_val(bbr);
13916                 /* lets poke in the low and the high here for debugging */
13917                 log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
13918                 if (rsm || sack_rxmit) {
13919                         if (doing_tlp)
13920                                 log.u_bbr.flex8 = 2;
13921                         else
13922                                 log.u_bbr.flex8 = 1;
13923                 } else {
13924                         log.u_bbr.flex8 = 0;
13925                 }
13926                 lgb = tcp_log_event_(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
13927                     len, &log, false, NULL, NULL, 0, tv);
13928         } else {
13929                 lgb = NULL;
13930         }
13931         /*
13932          * Fill in IP length and desired time to live and send to IP level.
13933          * There should be a better way to handle ttl and tos; we could keep
13934          * them in the template, but need a way to checksum without them.
13935          */
13936         /*
13937          * m->m_pkthdr.len should have been set before cksum calcuration,
13938          * because in6_cksum() need it.
13939          */
13940 #ifdef INET6
13941         if (isipv6) {
13942                 /*
13943                  * we separately set hoplimit for every segment, since the
13944                  * user might want to change the value via setsockopt. Also,
13945                  * desired default hop limit might be changed via Neighbor
13946                  * Discovery.
13947                  */
13948                 ip6->ip6_hlim = in6_selecthlim(inp, NULL);
13949
13950                 /*
13951                  * Set the packet size here for the benefit of DTrace
13952                  * probes. ip6_output() will set it properly; it's supposed
13953                  * to include the option header lengths as well.
13954                  */
13955                 ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
13956
13957                 if (V_path_mtu_discovery && maxseg > V_tcp_minmss)
13958                         tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13959                 else
13960                         tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13961
13962                 if (tp->t_state == TCPS_SYN_SENT)
13963                         TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
13964
13965                 TCP_PROBE5(send, NULL, tp, ip6, tp, th);
13966                 /* TODO: IPv6 IP6TOS_ECT bit on */
13967                 error = ip6_output(m, inp->in6p_outputopts,
13968                     &inp->inp_route6,
13969                     ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
13970                     NULL, NULL, inp);
13971
13972                 if (error == EMSGSIZE && inp->inp_route6.ro_rt != NULL)
13973                         mtu = inp->inp_route6.ro_rt->rt_mtu;
13974         }
13975 #endif                          /* INET6 */
13976 #if defined(INET) && defined(INET6)
13977         else
13978 #endif
13979 #ifdef INET
13980         {
13981                 ip->ip_len = htons(m->m_pkthdr.len);
13982 #ifdef INET6
13983                 if (isipv6)
13984                         ip->ip_ttl = in6_selecthlim(inp, NULL);
13985 #endif                          /* INET6 */
13986                 /*
13987                  * If we do path MTU discovery, then we set DF on every
13988                  * packet. This might not be the best thing to do according
13989                  * to RFC3390 Section 2. However the tcp hostcache migitates
13990                  * the problem so it affects only the first tcp connection
13991                  * with a host.
13992                  *
13993                  * NB: Don't set DF on small MTU/MSS to have a safe
13994                  * fallback.
13995                  */
13996                 if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
13997                         tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13998                         if (tp->t_port == 0 || len < V_tcp_minmss) {
13999                                 ip->ip_off |= htons(IP_DF);
14000                         }
14001                 } else {
14002                         tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
14003                 }
14004
14005                 if (tp->t_state == TCPS_SYN_SENT)
14006                         TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
14007
14008                 TCP_PROBE5(send, NULL, tp, ip, tp, th);
14009
14010                 error = ip_output(m, inp->inp_options, &inp->inp_route,
14011                     ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
14012                     inp);
14013                 if (error == EMSGSIZE && inp->inp_route.ro_rt != NULL)
14014                         mtu = inp->inp_route.ro_rt->rt_mtu;
14015         }
14016 #endif                          /* INET */
14017 out:
14018
14019         if (lgb) {
14020                 lgb->tlb_errno = error;
14021                 lgb = NULL;
14022         }
14023         /*
14024          * In transmit state, time the transmission and arrange for the
14025          * retransmit.  In persist state, just set snd_max.
14026          */
14027         if (error == 0) {
14028                 if (TCPS_HAVEESTABLISHED(tp->t_state) &&
14029                     (tp->t_flags & TF_SACK_PERMIT) &&
14030                     tp->rcv_numsacks > 0)
14031                         tcp_clean_dsack_blocks(tp);
14032                 /* We sent an ack clear the bbr_segs_rcvd count */
14033                 bbr->output_error_seen = 0;
14034                 bbr->oerror_cnt = 0;
14035                 bbr->bbr_segs_rcvd = 0;
14036                 if (len == 0)
14037                         counter_u64_add(bbr_out_size[TCP_MSS_ACCT_SNDACK], 1);
14038                 else if (hw_tls) {
14039                         if (filled_all ||
14040                             (len >= bbr->r_ctl.rc_pace_max_segs))
14041                                 BBR_STAT_INC(bbr_meets_tso_thresh);
14042                         else {
14043                                 if (doing_tlp) {
14044                                         BBR_STAT_INC(bbr_miss_tlp);
14045                                         bbr_log_type_hrdwtso(tp, bbr, len, 1, what_we_can);
14046                                         
14047
14048                                 } else if (rsm) {
14049                                         BBR_STAT_INC(bbr_miss_retran);
14050                                         bbr_log_type_hrdwtso(tp, bbr, len, 2, what_we_can);
14051                                 } else if ((ctf_outstanding(tp) + bbr->r_ctl.rc_pace_max_segs) > sbavail(sb)) {
14052                                         BBR_STAT_INC(bbr_miss_tso_app);
14053                                         bbr_log_type_hrdwtso(tp, bbr, len, 3, what_we_can);
14054                                 } else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
14055                                                                  bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_pace_max_segs) > tp->snd_cwnd) {
14056                                         BBR_STAT_INC(bbr_miss_tso_cwnd);
14057                                         bbr_log_type_hrdwtso(tp, bbr, len, 4, what_we_can);
14058                                 } else if ((ctf_outstanding(tp) + bbr->r_ctl.rc_pace_max_segs) > tp->snd_wnd) {
14059                                         BBR_STAT_INC(bbr_miss_tso_rwnd);
14060                                         bbr_log_type_hrdwtso(tp, bbr, len, 5, what_we_can);
14061                                 } else {
14062                                         BBR_STAT_INC(bbr_miss_unknown);
14063                                         bbr_log_type_hrdwtso(tp, bbr, len, 6, what_we_can);
14064                                 }
14065                         }
14066                 }
14067                 /* Do accounting for new sends */
14068                 if ((len > 0) && (rsm == NULL)) {
14069                         int idx;
14070                         if (tp->snd_una == tp->snd_max) {
14071                                 /*
14072                                  * Special case to match google, when
14073                                  * nothing is in flight the delivered
14074                                  * time does get updated to the current
14075                                  * time (see tcp_rate_bsd.c).
14076                                  */
14077                                 bbr->r_ctl.rc_del_time = cts;
14078                         }
14079                         if (len >= maxseg) {
14080                                 idx = (len / maxseg) + 3;
14081                                 if (idx >= TCP_MSS_ACCT_ATIMER)
14082                                         counter_u64_add(bbr_out_size[(TCP_MSS_ACCT_ATIMER - 1)], 1);
14083                                 else
14084                                         counter_u64_add(bbr_out_size[idx], 1);
14085                         } else {
14086                                 /* smaller than a MSS */
14087                                 idx = len / (bbr_hptsi_bytes_min - bbr->rc_last_options);
14088                                 if (idx >= TCP_MSS_SMALL_MAX_SIZE_DIV)
14089                                         idx = (TCP_MSS_SMALL_MAX_SIZE_DIV - 1);
14090                                 counter_u64_add(bbr_out_size[(idx + TCP_MSS_SMALL_SIZE_OFF)], 1);
14091                         }
14092                 }
14093         }
14094         abandon = 0;
14095         /*
14096          * We must do the send accounting before we log the output,
14097          * otherwise the state of the rsm could change and we account to the
14098          * wrong bucket.
14099          */
14100         if (len > 0) {
14101                 bbr_do_send_accounting(tp, bbr, rsm, len, error);
14102                 if (error == 0) {
14103                         if (tp->snd_una == tp->snd_max)
14104                                 bbr->r_ctl.rc_tlp_rxt_last_time = cts;
14105                 }
14106         }
14107         bbr_log_output(bbr, tp, &to, len, bbr_seq, (uint8_t) flags, error,
14108             cts, mb, &abandon, rsm, 0, sb);
14109         if (abandon) {
14110                 /*
14111                  * If bbr_log_output destroys the TCB or sees a TH_RST being
14112                  * sent we should hit this condition.
14113                  */
14114                 return (0);
14115         }
14116         if (((tp->t_flags & TF_FORCEDATA) == 0) ||
14117             (bbr->rc_in_persist == 0)) {
14118                 /*
14119                  * Advance snd_nxt over sequence space of this segment.
14120                  */
14121                 if (error)
14122                         /* We don't log or do anything with errors */
14123                         goto skip_upd;
14124
14125                 if (tp->snd_una == tp->snd_max &&
14126                     (len || (flags & (TH_SYN | TH_FIN)))) {
14127                         /*
14128                          * Update the time we just added data since none was
14129                          * outstanding.
14130                          */
14131                         bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
14132                         bbr->rc_tp->t_acktime  = ticks;
14133                 }
14134                 if (flags & (TH_SYN | TH_FIN) && (rsm == NULL)) {
14135                         if (flags & TH_SYN) {
14136                                 tp->snd_max++;
14137                         }
14138                         if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
14139                                 tp->snd_max++;
14140                                 tp->t_flags |= TF_SENTFIN;
14141                         }
14142                 }
14143                 if (sack_rxmit == 0)
14144                         tp->snd_max += len;
14145 skip_upd:
14146                 if ((error == 0) && len)
14147                         tot_len += len;
14148         } else {
14149                 /* Persists case */
14150                 int32_t xlen = len;
14151
14152                 if (error)
14153                         goto nomore;
14154
14155                 if (flags & TH_SYN)
14156                         ++xlen;
14157                 if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
14158                         ++xlen;
14159                         tp->t_flags |= TF_SENTFIN;
14160                 }
14161                 if (xlen && (tp->snd_una == tp->snd_max)) {
14162                         /*
14163                          * Update the time we just added data since none was
14164                          * outstanding.
14165                          */
14166                         bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
14167                         bbr->rc_tp->t_acktime = ticks;
14168                 }
14169                 if (sack_rxmit == 0)
14170                         tp->snd_max += xlen;
14171                 tot_len += (len + optlen + ipoptlen);
14172         }
14173 nomore:
14174         if (error) {
14175                 /*
14176                  * Failures do not advance the seq counter above. For the
14177                  * case of ENOBUFS we will fall out and become ack-clocked.
14178                  * capping the cwnd at the current flight. 
14179                  * Everything else will just have to retransmit with the timer 
14180                  * (no pacer).
14181                  */
14182                 SOCKBUF_UNLOCK_ASSERT(sb);
14183                 BBR_STAT_INC(bbr_saw_oerr);
14184                 /* Clear all delay/early tracks */
14185                 bbr->r_ctl.rc_hptsi_agg_delay = 0;
14186                 bbr->r_ctl.rc_agg_early = 0;
14187                 bbr->r_agg_early_set = 0;
14188                 bbr->output_error_seen = 1;
14189                 if (bbr->oerror_cnt < 0xf)
14190                         bbr->oerror_cnt++;
14191                 if (bbr_max_net_error_cnt && (bbr->oerror_cnt >= bbr_max_net_error_cnt)) {
14192                         /* drop the session */
14193                         tcp_set_inp_to_drop(inp, ENETDOWN);
14194                 }
14195                 switch (error) {
14196                 case ENOBUFS:
14197                         /*
14198                          * Make this guy have to get ack's to send
14199                          * more but lets make sure we don't
14200                          * slam him below a T-O (1MSS).
14201                          */
14202                         if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
14203                                 tp->snd_cwnd = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
14204                                                                     bbr->r_ctl.rc_lost_bytes)) - maxseg;
14205                                 if (tp->snd_cwnd < maxseg)
14206                                         tp->snd_cwnd = maxseg;
14207                         }
14208                         slot = (bbr_error_base_paceout + 1) << bbr->oerror_cnt;
14209                         BBR_STAT_INC(bbr_saw_enobuf);
14210                         if (bbr->bbr_hdrw_pacing)
14211                                 counter_u64_add(bbr_hdwr_pacing_enobuf, 1);
14212                         else
14213                                 counter_u64_add(bbr_nohdwr_pacing_enobuf, 1);
14214                         /*
14215                          * Here even in the enobuf's case we want to do our
14216                          * state update. The reason being we may have been
14217                          * called by the input function. If so we have had
14218                          * things change.
14219                          */
14220                         error = 0;
14221                         goto enobufs;
14222                 case EMSGSIZE:
14223                         /*
14224                          * For some reason the interface we used initially
14225                          * to send segments changed to another or lowered
14226                          * its MTU. If TSO was active we either got an
14227                          * interface without TSO capabilits or TSO was
14228                          * turned off. If we obtained mtu from ip_output()
14229                          * then update it and try again.
14230                          */
14231                         /* Turn on tracing (or try to) */
14232                         {
14233                                 int old_maxseg;
14234
14235                                 old_maxseg = tp->t_maxseg;
14236                                 BBR_STAT_INC(bbr_saw_emsgsiz);
14237                                 bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, csum_flags, tso, cts);
14238                                 if (mtu != 0)
14239                                         tcp_mss_update(tp, -1, mtu, NULL, NULL);
14240                                 if (old_maxseg <= tp->t_maxseg) {
14241                                         /* Huh it did not shrink? */
14242                                         tp->t_maxseg = old_maxseg - 40;
14243                                         bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
14244                                 }
14245                                 tp->t_flags &= ~TF_FORCEDATA;
14246                                 /*
14247                                  * Nuke all other things that can interfere
14248                                  * with slot
14249                                  */
14250                                 if ((tot_len + len) && (len >= tp->t_maxseg)) {
14251                                         slot = bbr_get_pacing_delay(bbr,
14252                                             bbr->r_ctl.rc_bbr_hptsi_gain,
14253                                             (tot_len + len), cts, 0);
14254                                         if (slot < bbr_error_base_paceout)
14255                                                 slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
14256                                 } else
14257                                         slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
14258                                 bbr->rc_output_starts_timer = 1;
14259                                 bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
14260                                     tot_len);
14261                                 return (error);
14262                         }
14263                 case EPERM:
14264                         tp->t_softerror = error;
14265                         /* Fall through */
14266                 case EHOSTDOWN:
14267                 case EHOSTUNREACH:
14268                 case ENETDOWN:
14269                 case ENETUNREACH:
14270                         if (TCPS_HAVERCVDSYN(tp->t_state)) {
14271                                 tp->t_softerror = error;
14272                         }
14273                         /* FALLTHROUGH */
14274                 default:
14275                         tp->t_flags &= ~TF_FORCEDATA;
14276                         slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
14277                         bbr->rc_output_starts_timer = 1;
14278                         bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
14279                         return (error);
14280                 }
14281 #ifdef STATS
14282         } else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
14283                     len &&
14284                     (rsm == NULL) &&
14285             (bbr->rc_in_persist == 0)) {
14286                 tp->gput_seq = bbr_seq;
14287                 tp->gput_ack = bbr_seq +
14288                     min(sbavail(&so->so_snd) - sb_offset, sendwin);
14289                 tp->gput_ts = cts;
14290                 tp->t_flags |= TF_GPUTINPROG;
14291 #endif
14292         }
14293         TCPSTAT_INC(tcps_sndtotal);
14294         if ((bbr->bbr_hdw_pace_ena) &&
14295             (bbr->bbr_attempt_hdwr_pace == 0) &&
14296             (bbr->rc_past_init_win) &&
14297             (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
14298             (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
14299             (inp->inp_route.ro_rt &&
14300              inp->inp_route.ro_rt->rt_ifp)) {
14301                 /*
14302                  * We are past the initial window and
14303                  * have at least one measurement so we
14304                  * could use hardware pacing if its available.
14305                  * We have an interface and we have not attempted
14306                  * to setup hardware pacing, lets try to now.
14307                  */
14308                 uint64_t rate_wanted;
14309                 int err = 0;
14310
14311                 rate_wanted = bbr_get_hardware_rate(bbr);
14312                 bbr->bbr_attempt_hdwr_pace = 1;
14313                 bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp, 
14314                                                       inp->inp_route.ro_rt->rt_ifp,
14315                                                       rate_wanted,
14316                                                       (RS_PACING_GEQ|RS_PACING_SUB_OK),
14317                                                       &err);
14318                 if (bbr->r_ctl.crte) {
14319                         bbr_type_log_hdwr_pacing(bbr,
14320                                                  bbr->r_ctl.crte->ptbl->rs_ifp,
14321                                                  rate_wanted,
14322                                                  bbr->r_ctl.crte->rate,
14323                                                  __LINE__, cts, err);
14324                         BBR_STAT_INC(bbr_hdwr_rl_add_ok);
14325                         counter_u64_add(bbr_flows_nohdwr_pacing, -1);
14326                         counter_u64_add(bbr_flows_whdwr_pacing, 1);
14327                         bbr->bbr_hdrw_pacing = 1;
14328                         /* Now what is our gain status? */
14329                         if (bbr->r_ctl.crte->rate < rate_wanted) {
14330                                 /* We have a problem */
14331                                 bbr_setup_less_of_rate(bbr, cts,
14332                                                        bbr->r_ctl.crte->rate, rate_wanted);
14333                         } else {
14334                                 /* We are good */
14335                                 bbr->gain_is_limited = 0;
14336                                 bbr->skip_gain = 0;
14337                         }
14338                         tcp_bbr_tso_size_check(bbr, cts);
14339                 } else {
14340                         bbr_type_log_hdwr_pacing(bbr,
14341                                                  inp->inp_route.ro_rt->rt_ifp,
14342                                                  rate_wanted,
14343                                                  0,
14344                                                  __LINE__, cts, err);
14345                         BBR_STAT_INC(bbr_hdwr_rl_add_fail);
14346                 }
14347         }
14348         if (bbr->bbr_hdrw_pacing) {
14349                 /*
14350                  * Worry about cases where the route
14351                  * changes or something happened that we
14352                  * lost our hardware pacing possibly during
14353                  * the last ip_output call.
14354                  */
14355                 if (inp->inp_snd_tag == NULL) {
14356                         /* A change during ip output disabled hw pacing? */
14357                         bbr->bbr_hdrw_pacing = 0;
14358                 } else if ((inp->inp_route.ro_rt == NULL) ||
14359                     (inp->inp_route.ro_rt->rt_ifp != inp->inp_snd_tag->ifp)) {
14360                         /* 
14361                          * We had an interface or route change,
14362                          * detach from the current hdwr pacing 
14363                          * and setup to re-attempt next go
14364                          * round.
14365                          */
14366                         bbr->bbr_hdrw_pacing = 0;
14367                         bbr->bbr_attempt_hdwr_pace = 0;
14368                         tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
14369                         tcp_bbr_tso_size_check(bbr, cts);
14370                 }
14371         }
14372         /*
14373          * Data sent (as far as we can tell). If this advertises a larger
14374          * window than any other segment, then remember the size of the
14375          * advertised window. Any pending ACK has now been sent.
14376          */
14377         if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
14378                 tp->rcv_adv = tp->rcv_nxt + recwin;
14379
14380         tp->last_ack_sent = tp->rcv_nxt;
14381         if ((error == 0) &&
14382             (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
14383             (doing_tlp == 0) &&
14384             (tso == 0) &&
14385             (hw_tls == 0) &&
14386             (len > 0) &&
14387             ((flags & TH_RST) == 0) &&
14388             (IN_RECOVERY(tp->t_flags) == 0) &&
14389             (bbr->rc_in_persist == 0) &&
14390             ((tp->t_flags & TF_FORCEDATA) == 0) &&
14391             (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
14392                 /*
14393                  * For non-tso we need to goto again until we have sent out
14394                  * enough data to match what we are hptsi out every hptsi
14395                  * interval.
14396                  */
14397                 if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14398                         /* Make sure snd_nxt is drug up */
14399                         tp->snd_nxt = tp->snd_max;
14400                 }
14401                 if (rsm != NULL) {
14402                         rsm = NULL;
14403                         goto skip_again;
14404                 }
14405                 rsm = NULL;
14406                 sack_rxmit = 0;
14407                 tp->t_flags &= ~(TF_ACKNOW | TF_DELACK | TF_FORCEDATA);
14408                 goto again;
14409         }
14410 skip_again:
14411         if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
14412                 /*
14413                  * Calculate/Re-Calculate the hptsi slot in usecs based on
14414                  * what we have sent so far
14415                  */
14416                 slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
14417                 if (bbr->rc_no_pacing)
14418                         slot = 0;
14419         }
14420         tp->t_flags &= ~(TF_ACKNOW | TF_DELACK | TF_FORCEDATA);
14421 enobufs:
14422         if (bbr->rc_use_google == 0)
14423                 bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
14424         bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
14425                                                         bbr->r_ctl.rc_lost_bytes)));
14426         bbr->rc_output_starts_timer = 1;
14427         if (bbr->bbr_use_rack_cheat &&
14428             (more_to_rxt ||
14429              ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
14430                 /* Rack cheats and shotguns out all rxt's 1ms apart */
14431                 if (slot > 1000)
14432                         slot = 1000;
14433         }
14434         if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
14435                 /* 
14436                  * We don't change the tso size until some number of sends 
14437                  * to give the hardware commands time to get down
14438                  * to the interface.
14439                  */
14440                 bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
14441                 if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
14442                         bbr->hw_pacing_set = 1;
14443                         tcp_bbr_tso_size_check(bbr, cts);
14444                 }
14445         }
14446         bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
14447         if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14448                 /* Make sure snd_nxt is drug up */
14449                 tp->snd_nxt = tp->snd_max;
14450         }
14451         return (error);
14452
14453 }
14454
14455 /*
14456  * See bbr_output_wtime() for return values.
14457  */
14458 static int
14459 bbr_output(struct tcpcb *tp)
14460 {
14461         int32_t ret;
14462         struct timeval tv;
14463         struct tcp_bbr *bbr;
14464
14465         NET_EPOCH_ASSERT();
14466
14467         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14468         INP_WLOCK_ASSERT(tp->t_inpcb);
14469         (void)tcp_get_usecs(&tv);
14470         ret = bbr_output_wtime(tp, &tv);
14471         return (ret);
14472 }
14473
14474 static void
14475 bbr_mtu_chg(struct tcpcb *tp)
14476 {
14477         struct tcp_bbr *bbr;
14478         struct bbr_sendmap *rsm, *frsm = NULL;
14479         uint32_t maxseg;
14480
14481         /*
14482          * The MTU has changed. a) Clear the sack filter. b) Mark everything
14483          * over the current size as SACK_PASS so a retransmit will occur.
14484          */
14485
14486         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14487         maxseg = tp->t_maxseg - bbr->rc_last_options;
14488         sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14489         TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14490                 /* Don't mess with ones acked (by sack?) */
14491                 if (rsm->r_flags & BBR_ACKED)
14492                         continue;
14493                 if ((rsm->r_end - rsm->r_start) > maxseg) {
14494                         /*
14495                          * We mark sack-passed on all the previous large
14496                          * sends we did. This will force them to retransmit.
14497                          */
14498                         rsm->r_flags |= BBR_SACK_PASSED;
14499                         if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14500                             bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14501                                 bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14502                                 bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14503                                 rsm->r_flags |= BBR_MARKED_LOST;
14504                         }
14505                         if (frsm == NULL)
14506                                 frsm = rsm;
14507                 }
14508         }
14509         if (frsm) {
14510                 bbr->r_ctl.rc_resend = frsm;
14511         }
14512 }
14513
14514 /*
14515  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14516  * socket option arguments.  When it re-acquires the lock after the copy, it
14517  * has to revalidate that the connection is still valid for the socket
14518  * option.
14519  */
14520 static int
14521 bbr_set_sockopt(struct socket *so, struct sockopt *sopt,
14522                 struct inpcb *inp, struct tcpcb *tp, struct tcp_bbr *bbr)
14523 {
14524         int32_t error = 0, optval;
14525
14526         switch (sopt->sopt_name) {
14527         case TCP_RACK_PACE_MAX_SEG:
14528         case TCP_RACK_MIN_TO:
14529         case TCP_RACK_REORD_THRESH:
14530         case TCP_RACK_REORD_FADE:
14531         case TCP_RACK_TLP_THRESH:
14532         case TCP_RACK_PKT_DELAY:
14533         case TCP_BBR_ALGORITHM:
14534         case TCP_BBR_TSLIMITS:
14535         case TCP_BBR_IWINTSO:
14536         case TCP_BBR_RECFORCE:
14537         case TCP_BBR_STARTUP_PG:
14538         case TCP_BBR_DRAIN_PG:
14539         case TCP_BBR_RWND_IS_APP:
14540         case TCP_BBR_PROBE_RTT_INT:
14541         case TCP_BBR_PROBE_RTT_GAIN:
14542         case TCP_BBR_PROBE_RTT_LEN:
14543         case TCP_BBR_STARTUP_LOSS_EXIT:
14544         case TCP_BBR_USEDEL_RATE:
14545         case TCP_BBR_MIN_RTO:
14546         case TCP_BBR_MAX_RTO:
14547         case TCP_BBR_PACE_PER_SEC:
14548         case TCP_DELACK:
14549         case TCP_BBR_PACE_DEL_TAR:
14550         case TCP_BBR_SEND_IWND_IN_TSO:
14551         case TCP_BBR_EXTRA_STATE:
14552         case TCP_BBR_UTTER_MAX_TSO:
14553         case TCP_BBR_MIN_TOPACEOUT:
14554         case TCP_BBR_FLOOR_MIN_TSO:
14555         case TCP_BBR_TSTMP_RAISES:
14556         case TCP_BBR_POLICER_DETECT:
14557         case TCP_BBR_USE_RACK_CHEAT:
14558         case TCP_DATA_AFTER_CLOSE:
14559         case TCP_BBR_HDWR_PACE:
14560         case TCP_BBR_PACE_SEG_MAX:
14561         case TCP_BBR_PACE_SEG_MIN:
14562         case TCP_BBR_PACE_CROSS:
14563         case TCP_BBR_PACE_OH:
14564 #ifdef NETFLIX_PEAKRATE
14565         case TCP_MAXPEAKRATE:
14566 #endif
14567         case TCP_BBR_TMR_PACE_OH:
14568         case TCP_BBR_RACK_RTT_USE:
14569         case TCP_BBR_RETRAN_WTSO:
14570                 break;
14571         default:
14572                 return (tcp_default_ctloutput(so, sopt, inp, tp));
14573                 break;
14574         }
14575         INP_WUNLOCK(inp);
14576         error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14577         if (error)
14578                 return (error);
14579         INP_WLOCK(inp);
14580         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
14581                 INP_WUNLOCK(inp);
14582                 return (ECONNRESET);
14583         }
14584         tp = intotcpcb(inp);
14585         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14586         switch (sopt->sopt_name) {
14587         case TCP_BBR_PACE_PER_SEC:
14588                 BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14589                 bbr->r_ctl.bbr_hptsi_per_second = optval;
14590                 break;
14591         case TCP_BBR_PACE_DEL_TAR:
14592                 BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14593                 bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14594                 break;
14595         case TCP_BBR_PACE_SEG_MAX:
14596                 BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14597                 bbr->r_ctl.bbr_hptsi_segments_max = optval;
14598                 break;
14599         case TCP_BBR_PACE_SEG_MIN:
14600                 BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14601                 bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14602                 break;
14603         case TCP_BBR_PACE_CROSS:
14604                 BBR_OPTS_INC(tcp_bbr_pace_cross);
14605                 bbr->r_ctl.bbr_cross_over = optval;
14606                 break;
14607         case TCP_BBR_ALGORITHM:
14608                 BBR_OPTS_INC(tcp_bbr_algorithm);
14609                 if (optval && (bbr->rc_use_google == 0)) {
14610                         /* Turn on the google mode */
14611                         bbr_google_mode_on(bbr);
14612                         if ((optval > 3) && (optval < 500)) {
14613                                 /* 
14614                                  * Must be at least greater than .3% 
14615                                  * and must be less than 50.0%. 
14616                                  */
14617                                 bbr->r_ctl.bbr_google_discount = optval;
14618                         }
14619                 } else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14620                         /* Turn off the google mode */
14621                         bbr_google_mode_off(bbr);
14622                 }
14623                 break;
14624         case TCP_BBR_TSLIMITS:
14625                 BBR_OPTS_INC(tcp_bbr_tslimits);
14626                 if (optval == 1) 
14627                         bbr->rc_use_ts_limit = 1;
14628                 else if (optval == 0)
14629                         bbr->rc_use_ts_limit = 0;
14630                 else
14631                         error = EINVAL;
14632                 break;
14633
14634         case TCP_BBR_IWINTSO:
14635                 BBR_OPTS_INC(tcp_bbr_iwintso);
14636                 if ((optval >= 0) && (optval < 128)) {
14637                         uint32_t twin;
14638
14639                         bbr->rc_init_win = optval;
14640                         twin = bbr_initial_cwnd(bbr, tp);
14641                         if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14642                                 tp->snd_cwnd = twin;
14643                         else
14644                                 error = EBUSY;
14645                 } else
14646                         error = EINVAL;
14647                 break;
14648         case TCP_BBR_STARTUP_PG:
14649                 BBR_OPTS_INC(tcp_bbr_startup_pg);
14650                 if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14651                         bbr->r_ctl.rc_startup_pg = optval;
14652                         if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14653                                 bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14654                         }
14655                 } else
14656                         error = EINVAL;
14657                 break;
14658         case TCP_BBR_DRAIN_PG:
14659                 BBR_OPTS_INC(tcp_bbr_drain_pg);
14660                 if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14661                         bbr->r_ctl.rc_drain_pg = optval;
14662                 else
14663                         error = EINVAL;
14664                 break;
14665         case TCP_BBR_PROBE_RTT_LEN:
14666                 BBR_OPTS_INC(tcp_bbr_probertt_len);
14667                 if (optval <= 1)
14668                         reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14669                 else
14670                         error = EINVAL;
14671                 break;
14672         case TCP_BBR_PROBE_RTT_GAIN:
14673                 BBR_OPTS_INC(tcp_bbr_probertt_gain);
14674                 if (optval <= BBR_UNIT)
14675                         bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14676                 else
14677                         error = EINVAL;
14678                 break;
14679         case TCP_BBR_PROBE_RTT_INT:
14680                 BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14681                 if (optval > 1000)
14682                         bbr->r_ctl.rc_probertt_int = optval;
14683                 else
14684                         error = EINVAL;
14685                 break;
14686         case TCP_BBR_MIN_TOPACEOUT:
14687                 BBR_OPTS_INC(tcp_bbr_topaceout);
14688                 if (optval == 0) {
14689                         bbr->no_pacing_until = 0;
14690                         bbr->rc_no_pacing = 0;
14691                 } else if (optval <= 0x00ff) {
14692                         bbr->no_pacing_until = optval;
14693                         if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14694                             (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14695                                 /* Turn on no pacing */
14696                                 bbr->rc_no_pacing = 1;
14697                         }
14698                 } else
14699                         error = EINVAL;
14700                 break;
14701         case TCP_BBR_STARTUP_LOSS_EXIT:
14702                 BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14703                 bbr->rc_loss_exit = optval;
14704                 break;
14705         case TCP_BBR_USEDEL_RATE:
14706                 error = EINVAL;
14707                 break;
14708         case TCP_BBR_MIN_RTO:
14709                 BBR_OPTS_INC(tcp_bbr_min_rto);
14710                 bbr->r_ctl.rc_min_rto_ms = optval;
14711                 break;
14712         case TCP_BBR_MAX_RTO:
14713                 BBR_OPTS_INC(tcp_bbr_max_rto);
14714                 bbr->rc_max_rto_sec = optval;
14715                 break;
14716         case TCP_RACK_MIN_TO:
14717                 /* Minimum time between rack t-o's in ms */
14718                 BBR_OPTS_INC(tcp_rack_min_to);
14719                 bbr->r_ctl.rc_min_to = optval;
14720                 break;
14721         case TCP_RACK_REORD_THRESH:
14722                 /* RACK reorder threshold (shift amount) */
14723                 BBR_OPTS_INC(tcp_rack_reord_thresh);
14724                 if ((optval > 0) && (optval < 31))
14725                         bbr->r_ctl.rc_reorder_shift = optval;
14726                 else
14727                         error = EINVAL;
14728                 break;
14729         case TCP_RACK_REORD_FADE:
14730                 /* Does reordering fade after ms time */
14731                 BBR_OPTS_INC(tcp_rack_reord_fade);
14732                 bbr->r_ctl.rc_reorder_fade = optval;
14733                 break;
14734         case TCP_RACK_TLP_THRESH:
14735                 /* RACK TLP theshold i.e. srtt+(srtt/N) */
14736                 BBR_OPTS_INC(tcp_rack_tlp_thresh);
14737                 if (optval)
14738                         bbr->rc_tlp_threshold = optval;
14739                 else
14740                         error = EINVAL;
14741                 break;
14742         case TCP_BBR_USE_RACK_CHEAT:
14743                 BBR_OPTS_INC(tcp_use_rackcheat);
14744                 if (bbr->rc_use_google) {
14745                         error = EINVAL;
14746                         break;
14747                 }
14748                 BBR_OPTS_INC(tcp_rack_cheat);
14749                 if (optval)
14750                         bbr->bbr_use_rack_cheat = 1;
14751                 else
14752                         bbr->bbr_use_rack_cheat = 0;
14753                 break;
14754         case TCP_BBR_FLOOR_MIN_TSO:
14755                 BBR_OPTS_INC(tcp_utter_max_tso);
14756                 if ((optval >= 0) && (optval < 40)) 
14757                         bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14758                 else
14759                         error = EINVAL;
14760                 break;
14761         case TCP_BBR_UTTER_MAX_TSO:
14762                 BBR_OPTS_INC(tcp_utter_max_tso);
14763                 if ((optval >= 0) && (optval < 0xffff))
14764                         bbr->r_ctl.bbr_utter_max = optval;
14765                 else
14766                         error = EINVAL;
14767                 break;
14768
14769         case TCP_BBR_EXTRA_STATE:
14770                 BBR_OPTS_INC(tcp_extra_state);
14771                 if (optval)
14772                         bbr->rc_use_idle_restart = 1;
14773                 else
14774                         bbr->rc_use_idle_restart = 0;
14775                 break;
14776         case TCP_BBR_SEND_IWND_IN_TSO:
14777                 BBR_OPTS_INC(tcp_iwnd_tso);
14778                 if (optval) {
14779                         bbr->bbr_init_win_cheat = 1;
14780                         if (bbr->rc_past_init_win == 0) {
14781                                 uint32_t cts;
14782                                 cts = tcp_get_usecs(&bbr->rc_tv);
14783                                 tcp_bbr_tso_size_check(bbr, cts);
14784                         }
14785                 } else
14786                         bbr->bbr_init_win_cheat = 0;
14787                 break;
14788         case TCP_BBR_HDWR_PACE:
14789                 BBR_OPTS_INC(tcp_hdwr_pacing);
14790                 if (optval){
14791                         bbr->bbr_hdw_pace_ena = 1;
14792                         bbr->bbr_attempt_hdwr_pace = 0;
14793                 } else {
14794                         bbr->bbr_hdw_pace_ena = 0;
14795 #ifdef RATELIMIT
14796                         if (bbr->bbr_hdrw_pacing) {
14797                                 bbr->bbr_hdrw_pacing = 0;
14798                                 in_pcbdetach_txrtlmt(bbr->rc_inp);
14799                         }
14800 #endif
14801                 }
14802                 break;
14803
14804         case TCP_DELACK:
14805                 BBR_OPTS_INC(tcp_delack);
14806                 if (optval < 100) {
14807                         if (optval == 0) /* off */
14808                                 tp->t_delayed_ack = 0;
14809                         else if (optval == 1) /* on which is 2 */
14810                                 tp->t_delayed_ack = 2;
14811                         else /* higher than 2 and less than 100 */
14812                                 tp->t_delayed_ack = optval;
14813                         if (tp->t_flags & TF_DELACK) {
14814                                 tp->t_flags &= ~TF_DELACK;
14815                                 tp->t_flags |= TF_ACKNOW;
14816                                 bbr_output(tp);
14817                         }
14818                 } else
14819                         error = EINVAL;
14820                 break;
14821         case TCP_RACK_PKT_DELAY:
14822                 /* RACK added ms i.e. rack-rtt + reord + N */
14823                 BBR_OPTS_INC(tcp_rack_pkt_delay);
14824                 bbr->r_ctl.rc_pkt_delay = optval;
14825                 break;
14826 #ifdef NETFLIX_PEAKRATE
14827         case TCP_MAXPEAKRATE:
14828                 BBR_OPTS_INC(tcp_maxpeak);
14829                 error = tcp_set_maxpeakrate(tp, optval);
14830                 if (!error)
14831                         tp->t_peakrate_thr = tp->t_maxpeakrate;
14832                 break;
14833 #endif
14834         case TCP_BBR_RETRAN_WTSO:
14835                 BBR_OPTS_INC(tcp_retran_wtso);
14836                 if (optval)
14837                         bbr->rc_resends_use_tso = 1;
14838                 else
14839                         bbr->rc_resends_use_tso = 0;
14840                 break;
14841         case TCP_DATA_AFTER_CLOSE:
14842                 BBR_OPTS_INC(tcp_data_ac);
14843                 if (optval)
14844                         bbr->rc_allow_data_af_clo = 1;
14845                 else
14846                         bbr->rc_allow_data_af_clo = 0;
14847                 break;
14848         case TCP_BBR_POLICER_DETECT:
14849                 BBR_OPTS_INC(tcp_policer_det);
14850                 if (bbr->rc_use_google == 0)
14851                         error = EINVAL;
14852                 else if (optval)
14853                         bbr->r_use_policer = 1;
14854                 else
14855                         bbr->r_use_policer = 0;
14856                 break;
14857
14858         case TCP_BBR_TSTMP_RAISES:
14859                 BBR_OPTS_INC(tcp_ts_raises);
14860                 if (optval)
14861                         bbr->ts_can_raise = 1;
14862                 else
14863                         bbr->ts_can_raise = 0;
14864                 break;
14865         case TCP_BBR_TMR_PACE_OH:
14866                 BBR_OPTS_INC(tcp_pacing_oh_tmr);
14867                 if (bbr->rc_use_google) {
14868                         error = EINVAL;
14869                 } else {
14870                         if (optval)
14871                                 bbr->r_ctl.rc_incr_tmrs = 1;
14872                         else
14873                                 bbr->r_ctl.rc_incr_tmrs = 0;
14874                 }
14875                 break;
14876         case TCP_BBR_PACE_OH:
14877                 BBR_OPTS_INC(tcp_pacing_oh);
14878                 if (bbr->rc_use_google) {
14879                         error = EINVAL;
14880                 } else {
14881                         if (optval > (BBR_INCL_TCP_OH|
14882                                       BBR_INCL_IP_OH|
14883                                       BBR_INCL_ENET_OH)) {
14884                                 error = EINVAL;
14885                                 break;
14886                         }
14887                         if (optval & BBR_INCL_TCP_OH)
14888                                 bbr->r_ctl.rc_inc_tcp_oh = 1;
14889                         else
14890                                 bbr->r_ctl.rc_inc_tcp_oh = 0;
14891                         if (optval & BBR_INCL_IP_OH)
14892                                 bbr->r_ctl.rc_inc_ip_oh = 1;
14893                         else
14894                                 bbr->r_ctl.rc_inc_ip_oh = 0;
14895                         if (optval & BBR_INCL_ENET_OH)
14896                                 bbr->r_ctl.rc_inc_enet_oh = 1;
14897                         else
14898                                 bbr->r_ctl.rc_inc_enet_oh = 0;
14899                 }
14900                 break;
14901         default:
14902                 return (tcp_default_ctloutput(so, sopt, inp, tp));
14903                 break;
14904         }
14905 #ifdef NETFLIX_STATS
14906         tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14907 #endif
14908         INP_WUNLOCK(inp);
14909         return (error);
14910 }
14911
14912 /*
14913  * return 0 on success, error-num on failure
14914  */
14915 static int
14916 bbr_get_sockopt(struct socket *so, struct sockopt *sopt,
14917     struct inpcb *inp, struct tcpcb *tp, struct tcp_bbr *bbr)
14918 {
14919         int32_t error, optval;
14920
14921         /*
14922          * Because all our options are either boolean or an int, we can just
14923          * pull everything into optval and then unlock and copy. If we ever
14924          * add a option that is not a int, then this will have quite an
14925          * impact to this routine.
14926          */
14927         switch (sopt->sopt_name) {
14928         case TCP_BBR_PACE_PER_SEC:
14929                 optval = bbr->r_ctl.bbr_hptsi_per_second;
14930                 break;
14931         case TCP_BBR_PACE_DEL_TAR:
14932                 optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14933                 break;
14934         case TCP_BBR_PACE_SEG_MAX:
14935                 optval = bbr->r_ctl.bbr_hptsi_segments_max;
14936                 break;
14937         case TCP_BBR_MIN_TOPACEOUT:
14938                 optval = bbr->no_pacing_until;
14939                 break;
14940         case TCP_BBR_PACE_SEG_MIN:
14941                 optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14942                 break;
14943         case TCP_BBR_PACE_CROSS:
14944                 optval = bbr->r_ctl.bbr_cross_over;
14945                 break;
14946         case TCP_BBR_ALGORITHM:
14947                 optval = bbr->rc_use_google;
14948                 break;
14949         case TCP_BBR_TSLIMITS:
14950                 optval = bbr->rc_use_ts_limit;
14951                 break;
14952         case TCP_BBR_IWINTSO:
14953                 optval = bbr->rc_init_win;
14954                 break;
14955         case TCP_BBR_STARTUP_PG:
14956                 optval = bbr->r_ctl.rc_startup_pg;
14957                 break;
14958         case TCP_BBR_DRAIN_PG:
14959                 optval = bbr->r_ctl.rc_drain_pg;
14960                 break;
14961         case TCP_BBR_PROBE_RTT_INT:
14962                 optval = bbr->r_ctl.rc_probertt_int;
14963                 break;
14964         case TCP_BBR_PROBE_RTT_LEN:
14965                 optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14966                 break;
14967         case TCP_BBR_PROBE_RTT_GAIN:
14968                 optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14969                 break;
14970         case TCP_BBR_STARTUP_LOSS_EXIT:
14971                 optval = bbr->rc_loss_exit;
14972                 break;
14973         case TCP_BBR_USEDEL_RATE:
14974                 error = EINVAL;
14975                 break;
14976         case TCP_BBR_MIN_RTO:
14977                 optval = bbr->r_ctl.rc_min_rto_ms;
14978                 break;
14979         case TCP_BBR_MAX_RTO:
14980                 optval = bbr->rc_max_rto_sec;
14981                 break;
14982         case TCP_RACK_PACE_MAX_SEG:
14983                 /* Max segments in a pace */
14984                 optval = bbr->r_ctl.rc_pace_max_segs;
14985                 break;
14986         case TCP_RACK_MIN_TO:
14987                 /* Minimum time between rack t-o's in ms */
14988                 optval = bbr->r_ctl.rc_min_to;
14989                 break;
14990         case TCP_RACK_REORD_THRESH:
14991                 /* RACK reorder threshold (shift amount) */
14992                 optval = bbr->r_ctl.rc_reorder_shift;
14993                 break;
14994         case TCP_RACK_REORD_FADE:
14995                 /* Does reordering fade after ms time */
14996                 optval = bbr->r_ctl.rc_reorder_fade;
14997                 break;
14998         case TCP_BBR_USE_RACK_CHEAT:
14999                 /* Do we use the rack cheat for rxt */
15000                 optval = bbr->bbr_use_rack_cheat;
15001                 break;
15002         case TCP_BBR_FLOOR_MIN_TSO:
15003                 optval = bbr->r_ctl.bbr_hptsi_segments_floor;
15004                 break;
15005         case TCP_BBR_UTTER_MAX_TSO:
15006                 optval = bbr->r_ctl.bbr_utter_max;
15007                 break;
15008         case TCP_BBR_SEND_IWND_IN_TSO:
15009                 /* Do we send TSO size segments initially */
15010                 optval = bbr->bbr_init_win_cheat;
15011                 break;
15012         case TCP_BBR_EXTRA_STATE:
15013                 optval = bbr->rc_use_idle_restart;
15014                 break;
15015         case TCP_RACK_TLP_THRESH:
15016                 /* RACK TLP theshold i.e. srtt+(srtt/N) */
15017                 optval = bbr->rc_tlp_threshold;
15018                 break;
15019         case TCP_RACK_PKT_DELAY:
15020                 /* RACK added ms i.e. rack-rtt + reord + N */
15021                 optval = bbr->r_ctl.rc_pkt_delay;
15022                 break;
15023         case TCP_BBR_RETRAN_WTSO:
15024                 optval = bbr->rc_resends_use_tso;
15025                 break;
15026         case TCP_DATA_AFTER_CLOSE:
15027                 optval = bbr->rc_allow_data_af_clo;
15028                 break;
15029         case TCP_DELACK:
15030                 optval = tp->t_delayed_ack;
15031                 break;
15032         case TCP_BBR_HDWR_PACE:
15033                 optval = bbr->bbr_hdw_pace_ena;
15034                 break;
15035         case TCP_BBR_POLICER_DETECT:
15036                 optval = bbr->r_use_policer;
15037                 break;
15038         case TCP_BBR_TSTMP_RAISES:
15039                 optval = bbr->ts_can_raise;
15040                 break;
15041         case TCP_BBR_TMR_PACE_OH:
15042                 optval = bbr->r_ctl.rc_incr_tmrs;
15043                 break;
15044         case TCP_BBR_PACE_OH:
15045                 optval = 0;
15046                 if (bbr->r_ctl.rc_inc_tcp_oh)
15047                         optval |= BBR_INCL_TCP_OH;
15048                 if (bbr->r_ctl.rc_inc_ip_oh)
15049                         optval |= BBR_INCL_IP_OH;
15050                 if (bbr->r_ctl.rc_inc_enet_oh)
15051                         optval |= BBR_INCL_ENET_OH;
15052                 break;
15053         default:
15054                 return (tcp_default_ctloutput(so, sopt, inp, tp));
15055                 break;
15056         }
15057         INP_WUNLOCK(inp);
15058         error = sooptcopyout(sopt, &optval, sizeof optval);
15059         return (error);
15060 }
15061
15062 /*
15063  * return 0 on success, error-num on failure
15064  */
15065 static int
15066 bbr_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp, struct tcpcb *tp)
15067 {
15068         int32_t error = EINVAL;
15069         struct tcp_bbr *bbr;
15070
15071         bbr = (struct tcp_bbr *)tp->t_fb_ptr;
15072         if (bbr == NULL) {
15073                 /* Huh? */
15074                 goto out;
15075         }
15076         if (sopt->sopt_dir == SOPT_SET) {
15077                 return (bbr_set_sockopt(so, sopt, inp, tp, bbr));
15078         } else if (sopt->sopt_dir == SOPT_GET) {
15079                 return (bbr_get_sockopt(so, sopt, inp, tp, bbr));
15080         }
15081 out:
15082         INP_WUNLOCK(inp);
15083         return (error);
15084 }
15085
15086
15087 struct tcp_function_block __tcp_bbr = {
15088         .tfb_tcp_block_name = __XSTRING(STACKNAME),
15089         .tfb_tcp_output = bbr_output,
15090         .tfb_do_queued_segments = ctf_do_queued_segments,
15091         .tfb_do_segment_nounlock = bbr_do_segment_nounlock,
15092         .tfb_tcp_do_segment = bbr_do_segment,
15093         .tfb_tcp_ctloutput = bbr_ctloutput,
15094         .tfb_tcp_fb_init = bbr_init,
15095         .tfb_tcp_fb_fini = bbr_fini,
15096         .tfb_tcp_timer_stop_all = bbr_stopall,
15097         .tfb_tcp_timer_activate = bbr_timer_activate,
15098         .tfb_tcp_timer_active = bbr_timer_active,
15099         .tfb_tcp_timer_stop = bbr_timer_stop,
15100         .tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
15101         .tfb_tcp_handoff_ok = bbr_handoff_ok,
15102         .tfb_tcp_mtu_chg = bbr_mtu_chg
15103 };
15104
15105 static const char *bbr_stack_names[] = {
15106         __XSTRING(STACKNAME),
15107 #ifdef STACKALIAS
15108         __XSTRING(STACKALIAS),
15109 #endif
15110 };
15111
15112 static bool bbr_mod_inited = false;
15113
15114 static int
15115 tcp_addbbr(module_t mod, int32_t type, void *data)
15116 {
15117         int32_t err = 0;
15118         int num_stacks;
15119
15120         switch (type) {
15121         case MOD_LOAD:
15122                 printf("Attempting to load " __XSTRING(MODNAME) "\n");
15123                 bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
15124                     sizeof(struct bbr_sendmap),
15125                     NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
15126                 bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
15127                     sizeof(struct tcp_bbr),
15128                     NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
15129                 sysctl_ctx_init(&bbr_sysctl_ctx);
15130                 bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
15131                     SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
15132                     OID_AUTO,
15133 #ifdef STACKALIAS
15134                     __XSTRING(STACKALIAS),
15135 #else
15136                     __XSTRING(STACKNAME),
15137 #endif
15138                     CTLFLAG_RW, 0,
15139                     "");
15140                 if (bbr_sysctl_root == NULL) {
15141                         printf("Failed to add sysctl node\n");
15142                         err = EFAULT;
15143                         goto free_uma;
15144                 }
15145                 bbr_init_sysctls();
15146                 num_stacks = nitems(bbr_stack_names);
15147                 err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
15148                     bbr_stack_names, &num_stacks);
15149                 if (err) {
15150                         printf("Failed to register %s stack name for "
15151                             "%s module\n", bbr_stack_names[num_stacks],
15152                             __XSTRING(MODNAME));
15153                         sysctl_ctx_free(&bbr_sysctl_ctx);
15154         free_uma:
15155                         uma_zdestroy(bbr_zone);
15156                         uma_zdestroy(bbr_pcb_zone);
15157                         bbr_counter_destroy();
15158                         printf("Failed to register " __XSTRING(MODNAME)
15159                             " module err:%d\n", err);
15160                         return (err);
15161                 }
15162                 tcp_lro_reg_mbufq();
15163                 bbr_mod_inited = true;
15164                 printf(__XSTRING(MODNAME) " is now available\n");
15165                 break;
15166         case MOD_QUIESCE:
15167                 err = deregister_tcp_functions(&__tcp_bbr, true, false);
15168                 break;
15169         case MOD_UNLOAD:
15170                 err = deregister_tcp_functions(&__tcp_bbr, false, true);
15171                 if (err == EBUSY)
15172                         break;
15173                 if (bbr_mod_inited) {
15174                         uma_zdestroy(bbr_zone);
15175                         uma_zdestroy(bbr_pcb_zone);
15176                         sysctl_ctx_free(&bbr_sysctl_ctx);
15177                         bbr_counter_destroy();
15178                         printf(__XSTRING(MODNAME)
15179                             " is now no longer available\n");
15180                         bbr_mod_inited = false;
15181                 }
15182                 tcp_lro_dereg_mbufq();
15183                 err = 0;
15184                 break;
15185         default:
15186                 return (EOPNOTSUPP);
15187         }
15188         return (err);
15189 }
15190
15191 static moduledata_t tcp_bbr = {
15192         .name = __XSTRING(MODNAME),
15193             .evhand = tcp_addbbr,
15194             .priv = 0
15195 };
15196
15197 MODULE_VERSION(MODNAME, 1);
15198 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
15199 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);