]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/tcp_stacks/rack.c
MFV: expat 2.5.0
[FreeBSD/FreeBSD.git] / sys / netinet / tcp_stacks / rack.c
1 /*-
2  * Copyright (c) 2016-2020 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include "opt_inet.h"
31 #include "opt_inet6.h"
32 #include "opt_ipsec.h"
33 #include "opt_tcpdebug.h"
34 #include "opt_ratelimit.h"
35 #include "opt_kern_tls.h"
36 #include <sys/param.h>
37 #include <sys/arb.h>
38 #include <sys/module.h>
39 #include <sys/kernel.h>
40 #ifdef TCP_HHOOK
41 #include <sys/hhook.h>
42 #endif
43 #include <sys/lock.h>
44 #include <sys/malloc.h>
45 #include <sys/lock.h>
46 #include <sys/mutex.h>
47 #include <sys/mbuf.h>
48 #include <sys/proc.h>           /* for proc0 declaration */
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/systm.h>
53 #ifdef STATS
54 #include <sys/qmath.h>
55 #include <sys/tree.h>
56 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
57 #else
58 #include <sys/tree.h>
59 #endif
60 #include <sys/refcount.h>
61 #include <sys/queue.h>
62 #include <sys/tim_filter.h>
63 #include <sys/smp.h>
64 #include <sys/kthread.h>
65 #include <sys/kern_prefetch.h>
66 #include <sys/protosw.h>
67 #ifdef TCP_ACCOUNTING
68 #include <sys/sched.h>
69 #include <machine/cpu.h>
70 #endif
71 #include <vm/uma.h>
72
73 #include <net/route.h>
74 #include <net/route/nhop.h>
75 #include <net/vnet.h>
76
77 #define TCPSTATES               /* for logging */
78
79 #include <netinet/in.h>
80 #include <netinet/in_kdtrace.h>
81 #include <netinet/in_pcb.h>
82 #include <netinet/ip.h>
83 #include <netinet/ip_icmp.h>    /* required for icmp_var.h */
84 #include <netinet/icmp_var.h>   /* for ICMP_BANDLIM */
85 #include <netinet/ip_var.h>
86 #include <netinet/ip6.h>
87 #include <netinet6/in6_pcb.h>
88 #include <netinet6/ip6_var.h>
89 #include <netinet/tcp.h>
90 #define TCPOUTFLAGS
91 #include <netinet/tcp_fsm.h>
92 #include <netinet/tcp_log_buf.h>
93 #include <netinet/tcp_seq.h>
94 #include <netinet/tcp_timer.h>
95 #include <netinet/tcp_var.h>
96 #include <netinet/tcp_syncache.h>
97 #include <netinet/tcp_hpts.h>
98 #include <netinet/tcp_ratelimit.h>
99 #include <netinet/tcp_accounting.h>
100 #include <netinet/tcpip.h>
101 #include <netinet/cc/cc.h>
102 #include <netinet/cc/cc_newreno.h>
103 #include <netinet/tcp_fastopen.h>
104 #include <netinet/tcp_lro.h>
105 #ifdef NETFLIX_SHARED_CWND
106 #include <netinet/tcp_shared_cwnd.h>
107 #endif
108 #ifdef TCPDEBUG
109 #include <netinet/tcp_debug.h>
110 #endif                          /* TCPDEBUG */
111 #ifdef TCP_OFFLOAD
112 #include <netinet/tcp_offload.h>
113 #endif
114 #ifdef INET6
115 #include <netinet6/tcp6_var.h>
116 #endif
117 #include <netinet/tcp_ecn.h>
118
119 #include <netipsec/ipsec_support.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 #include "sack_filter.h"
134 #include "tcp_rack.h"
135 #include "rack_bbr_common.h"
136
137 uma_zone_t rack_zone;
138 uma_zone_t rack_pcb_zone;
139
140 #ifndef TICKS2SBT
141 #define TICKS2SBT(__t)  (tick_sbt * ((sbintime_t)(__t)))
142 #endif
143
144 VNET_DECLARE(uint32_t, newreno_beta);
145 VNET_DECLARE(uint32_t, newreno_beta_ecn);
146 #define V_newreno_beta VNET(newreno_beta)
147 #define V_newreno_beta_ecn VNET(newreno_beta_ecn)
148
149
150 MALLOC_DEFINE(M_TCPFSB, "tcp_fsb", "TCP fast send block");
151 MALLOC_DEFINE(M_TCPDO, "tcp_do", "TCP deferred options");
152
153 struct sysctl_ctx_list rack_sysctl_ctx;
154 struct sysctl_oid *rack_sysctl_root;
155
156 #define CUM_ACKED 1
157 #define SACKED 2
158
159 /*
160  * The RACK module incorporates a number of
161  * TCP ideas that have been put out into the IETF
162  * over the last few years:
163  * - Matt Mathis's Rate Halving which slowly drops
164  *    the congestion window so that the ack clock can
165  *    be maintained during a recovery.
166  * - Yuchung Cheng's RACK TCP (for which its named) that
167  *    will stop us using the number of dup acks and instead
168  *    use time as the gage of when we retransmit.
169  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
170  *    of Dukkipati et.al.
171  * RACK depends on SACK, so if an endpoint arrives that
172  * cannot do SACK the state machine below will shuttle the
173  * connection back to using the "default" TCP stack that is
174  * in FreeBSD.
175  *
176  * To implement RACK the original TCP stack was first decomposed
177  * into a functional state machine with individual states
178  * for each of the possible TCP connection states. The do_segment
179  * functions role in life is to mandate the connection supports SACK
180  * initially and then assure that the RACK state matches the conenction
181  * state before calling the states do_segment function. Each
182  * state is simplified due to the fact that the original do_segment
183  * has been decomposed and we *know* what state we are in (no
184  * switches on the state) and all tests for SACK are gone. This
185  * greatly simplifies what each state does.
186  *
187  * TCP output is also over-written with a new version since it
188  * must maintain the new rack scoreboard.
189  *
190  */
191 static int32_t rack_tlp_thresh = 1;
192 static int32_t rack_tlp_limit = 2;      /* No more than 2 TLPs w-out new data */
193 static int32_t rack_tlp_use_greater = 1;
194 static int32_t rack_reorder_thresh = 2;
195 static int32_t rack_reorder_fade = 60000000;    /* 0 - never fade, def 60,000,000
196                                                  * - 60 seconds */
197 static uint8_t rack_req_measurements = 1;
198 /* Attack threshold detections */
199 static uint32_t rack_highest_sack_thresh_seen = 0;
200 static uint32_t rack_highest_move_thresh_seen = 0;
201 static int32_t rack_enable_hw_pacing = 0; /* Due to CCSP keep it off by default */
202 static int32_t rack_hw_pace_extra_slots = 2;    /* 2 extra MSS time betweens */
203 static int32_t rack_hw_rate_caps = 1; /* 1; */
204 static int32_t rack_hw_rate_min = 0; /* 1500000;*/
205 static int32_t rack_hw_rate_to_low = 0; /* 1200000; */
206 static int32_t rack_hw_up_only = 1;
207 static int32_t rack_stats_gets_ms_rtt = 1;
208 static int32_t rack_prr_addbackmax = 2;
209 static int32_t rack_do_hystart = 0;
210 static int32_t rack_apply_rtt_with_reduced_conf = 0;
211
212 static int32_t rack_pkt_delay = 1000;
213 static int32_t rack_send_a_lot_in_prr = 1;
214 static int32_t rack_min_to = 1000;      /* Number of microsecond  min timeout */
215 static int32_t rack_verbose_logging = 0;
216 static int32_t rack_ignore_data_after_close = 1;
217 static int32_t rack_enable_shared_cwnd = 1;
218 static int32_t rack_use_cmp_acks = 1;
219 static int32_t rack_use_fsb = 1;
220 static int32_t rack_use_rfo = 1;
221 static int32_t rack_use_rsm_rfo = 1;
222 static int32_t rack_max_abc_post_recovery = 2;
223 static int32_t rack_client_low_buf = 0;
224 static int32_t rack_dsack_std_based = 0x3;      /* bit field bit 1 sets rc_rack_tmr_std_based and bit 2 sets rc_rack_use_dsack */
225 #ifdef TCP_ACCOUNTING
226 static int32_t rack_tcp_accounting = 0;
227 #endif
228 static int32_t rack_limits_scwnd = 1;
229 static int32_t rack_enable_mqueue_for_nonpaced = 0;
230 static int32_t rack_disable_prr = 0;
231 static int32_t use_rack_rr = 1;
232 static int32_t rack_non_rxt_use_cr = 0; /* does a non-rxt in recovery use the configured rate (ss/ca)? */
233 static int32_t rack_persist_min = 250000;       /* 250usec */
234 static int32_t rack_persist_max = 2000000;      /* 2 Second in usec's */
235 static int32_t rack_sack_not_required = 1;      /* set to one to allow non-sack to use rack */
236 static int32_t rack_default_init_window = 0;    /* Use system default */
237 static int32_t rack_limit_time_with_srtt = 0;
238 static int32_t rack_autosndbuf_inc = 20;        /* In percentage form */
239 static int32_t rack_enobuf_hw_boost_mult = 2;   /* How many times the hw rate we boost slot using time_between */
240 static int32_t rack_enobuf_hw_max = 12000;      /* 12 ms in usecs */
241 static int32_t rack_enobuf_hw_min = 10000;      /* 10 ms in usecs */
242 static int32_t rack_hw_rwnd_factor = 2;         /* How many max_segs the rwnd must be before we hold off sending */
243
244 /*
245  * Currently regular tcp has a rto_min of 30ms
246  * the backoff goes 12 times so that ends up
247  * being a total of 122.850 seconds before a
248  * connection is killed.
249  */
250 static uint32_t rack_def_data_window = 20;
251 static uint32_t rack_goal_bdp = 2;
252 static uint32_t rack_min_srtts = 1;
253 static uint32_t rack_min_measure_usec = 0;
254 static int32_t rack_tlp_min = 10000;    /* 10ms */
255 static int32_t rack_rto_min = 30000;    /* 30,000 usec same as main freebsd */
256 static int32_t rack_rto_max = 4000000;  /* 4 seconds in usec's */
257 static const int32_t rack_free_cache = 2;
258 static int32_t rack_hptsi_segments = 40;
259 static int32_t rack_rate_sample_method = USE_RTT_LOW;
260 static int32_t rack_pace_every_seg = 0;
261 static int32_t rack_delayed_ack_time = 40000;   /* 40ms in usecs */
262 static int32_t rack_slot_reduction = 4;
263 static int32_t rack_wma_divisor = 8;            /* For WMA calculation */
264 static int32_t rack_cwnd_block_ends_measure = 0;
265 static int32_t rack_rwnd_block_ends_measure = 0;
266 static int32_t rack_def_profile = 0;
267
268 static int32_t rack_lower_cwnd_at_tlp = 0;
269 static int32_t rack_limited_retran = 0;
270 static int32_t rack_always_send_oldest = 0;
271 static int32_t rack_tlp_threshold_use = TLP_USE_TWO_ONE;
272
273 static uint16_t rack_per_of_gp_ss = 250;        /* 250 % slow-start */
274 static uint16_t rack_per_of_gp_ca = 200;        /* 200 % congestion-avoidance */
275 static uint16_t rack_per_of_gp_rec = 200;       /* 200 % of bw */
276
277 /* Probertt */
278 static uint16_t rack_per_of_gp_probertt = 60;   /* 60% of bw */
279 static uint16_t rack_per_of_gp_lowthresh = 40;  /* 40% is bottom */
280 static uint16_t rack_per_of_gp_probertt_reduce = 10; /* 10% reduction */
281 static uint16_t rack_atexit_prtt_hbp = 130;     /* Clamp to 130% on exit prtt if highly buffered path */
282 static uint16_t rack_atexit_prtt = 130; /* Clamp to 100% on exit prtt if non highly buffered path */
283
284 static uint32_t rack_max_drain_wait = 2;        /* How man gp srtt's before we give up draining */
285 static uint32_t rack_must_drain = 1;            /* How many GP srtt's we *must* wait */
286 static uint32_t rack_probertt_use_min_rtt_entry = 1;    /* Use the min to calculate the goal else gp_srtt */
287 static uint32_t rack_probertt_use_min_rtt_exit = 0;
288 static uint32_t rack_probe_rtt_sets_cwnd = 0;
289 static uint32_t rack_probe_rtt_safety_val = 2000000;    /* No more than 2 sec in probe-rtt */
290 static uint32_t rack_time_between_probertt = 9600000;   /* 9.6 sec in usecs */
291 static uint32_t rack_probertt_gpsrtt_cnt_mul = 0;       /* How many srtt periods does probe-rtt last top fraction */
292 static uint32_t rack_probertt_gpsrtt_cnt_div = 0;       /* How many srtt periods does probe-rtt last bottom fraction */
293 static uint32_t rack_min_probertt_hold = 40000;         /* Equal to delayed ack time */
294 static uint32_t rack_probertt_filter_life = 10000000;
295 static uint32_t rack_probertt_lower_within = 10;
296 static uint32_t rack_min_rtt_movement = 250000; /* Must move at least 250ms (in microseconds)  to count as a lowering */
297 static int32_t rack_pace_one_seg = 0;           /* Shall we pace for less than 1.4Meg 1MSS at a time */
298 static int32_t rack_probertt_clear_is = 1;
299 static int32_t rack_max_drain_hbp = 1;          /* Extra drain times gpsrtt for highly buffered paths */
300 static int32_t rack_hbp_thresh = 3;             /* what is the divisor max_rtt/min_rtt to decided a hbp */
301
302 /* Part of pacing */
303 static int32_t rack_max_per_above = 30;         /* When we go to increment stop if above 100+this% */
304
305 /* Timely information */
306 /* Combine these two gives the range of 'no change' to bw */
307 /* ie the up/down provide the upper and lower bound */
308 static int32_t rack_gp_per_bw_mul_up = 2;       /* 2% */
309 static int32_t rack_gp_per_bw_mul_down = 4;     /* 4% */
310 static int32_t rack_gp_rtt_maxmul = 3;          /* 3 x maxmin */
311 static int32_t rack_gp_rtt_minmul = 1;          /* minrtt + (minrtt/mindiv) is lower rtt */
312 static int32_t rack_gp_rtt_mindiv = 4;          /* minrtt + (minrtt * minmul/mindiv) is lower rtt */
313 static int32_t rack_gp_decrease_per = 20;       /* 20% decrease in multiplier */
314 static int32_t rack_gp_increase_per = 2;        /* 2% increase in multiplier */
315 static int32_t rack_per_lower_bound = 50;       /* Don't allow to drop below this multiplier */
316 static int32_t rack_per_upper_bound_ss = 0;     /* Don't allow SS to grow above this */
317 static int32_t rack_per_upper_bound_ca = 0;     /* Don't allow CA to grow above this */
318 static int32_t rack_do_dyn_mul = 0;             /* Are the rack gp multipliers dynamic */
319 static int32_t rack_gp_no_rec_chg = 1;          /* Prohibit recovery from reducing it's multiplier */
320 static int32_t rack_timely_dec_clear = 6;       /* Do we clear decrement count at a value (6)? */
321 static int32_t rack_timely_max_push_rise = 3;   /* One round of pushing */
322 static int32_t rack_timely_max_push_drop = 3;   /* Three round of pushing */
323 static int32_t rack_timely_min_segs = 4;        /* 4 segment minimum */
324 static int32_t rack_use_max_for_nobackoff = 0;
325 static int32_t rack_timely_int_timely_only = 0; /* do interim timely's only use the timely algo (no b/w changes)? */
326 static int32_t rack_timely_no_stopping = 0;
327 static int32_t rack_down_raise_thresh = 100;
328 static int32_t rack_req_segs = 1;
329 static uint64_t rack_bw_rate_cap = 0;
330 static uint32_t rack_trace_point_config = 0;
331 static uint32_t rack_trace_point_bb_mode = 4;
332 static int32_t rack_trace_point_count = 0;
333
334
335 /* Weird delayed ack mode */
336 static int32_t rack_use_imac_dack = 0;
337 /* Rack specific counters */
338 counter_u64_t rack_saw_enobuf;
339 counter_u64_t rack_saw_enobuf_hw;
340 counter_u64_t rack_saw_enetunreach;
341 counter_u64_t rack_persists_sends;
342 counter_u64_t rack_persists_acks;
343 counter_u64_t rack_persists_loss;
344 counter_u64_t rack_persists_lost_ends;
345 #ifdef INVARIANTS
346 counter_u64_t rack_adjust_map_bw;
347 #endif
348 /* Tail loss probe counters */
349 counter_u64_t rack_tlp_tot;
350 counter_u64_t rack_tlp_newdata;
351 counter_u64_t rack_tlp_retran;
352 counter_u64_t rack_tlp_retran_bytes;
353 counter_u64_t rack_to_tot;
354 counter_u64_t rack_hot_alloc;
355 counter_u64_t rack_to_alloc;
356 counter_u64_t rack_to_alloc_hard;
357 counter_u64_t rack_to_alloc_emerg;
358 counter_u64_t rack_to_alloc_limited;
359 counter_u64_t rack_alloc_limited_conns;
360 counter_u64_t rack_split_limited;
361
362 counter_u64_t rack_multi_single_eq;
363 counter_u64_t rack_proc_non_comp_ack;
364
365 counter_u64_t rack_fto_send;
366 counter_u64_t rack_fto_rsm_send;
367 counter_u64_t rack_nfto_resend;
368 counter_u64_t rack_non_fto_send;
369 counter_u64_t rack_extended_rfo;
370
371 counter_u64_t rack_sack_proc_all;
372 counter_u64_t rack_sack_proc_short;
373 counter_u64_t rack_sack_proc_restart;
374 counter_u64_t rack_sack_attacks_detected;
375 counter_u64_t rack_sack_attacks_reversed;
376 counter_u64_t rack_sack_used_next_merge;
377 counter_u64_t rack_sack_splits;
378 counter_u64_t rack_sack_used_prev_merge;
379 counter_u64_t rack_sack_skipped_acked;
380 counter_u64_t rack_ack_total;
381 counter_u64_t rack_express_sack;
382 counter_u64_t rack_sack_total;
383 counter_u64_t rack_move_none;
384 counter_u64_t rack_move_some;
385
386 counter_u64_t rack_input_idle_reduces;
387 counter_u64_t rack_collapsed_win;
388 counter_u64_t rack_collapsed_win_seen;
389 counter_u64_t rack_collapsed_win_rxt;
390 counter_u64_t rack_collapsed_win_rxt_bytes;
391 counter_u64_t rack_try_scwnd;
392 counter_u64_t rack_hw_pace_init_fail;
393 counter_u64_t rack_hw_pace_lost;
394
395 counter_u64_t rack_out_size[TCP_MSS_ACCT_SIZE];
396 counter_u64_t rack_opts_arry[RACK_OPTS_SIZE];
397
398
399 #define RACK_REXMTVAL(tp) max(rack_rto_min, ((tp)->t_srtt + ((tp)->t_rttvar << 2)))
400
401 #define RACK_TCPT_RANGESET(tv, value, tvmin, tvmax, slop) do {  \
402         (tv) = (value) + slop;   \
403         if ((u_long)(tv) < (u_long)(tvmin)) \
404                 (tv) = (tvmin); \
405         if ((u_long)(tv) > (u_long)(tvmax)) \
406                 (tv) = (tvmax); \
407 } while (0)
408
409 static void
410 rack_log_progress_event(struct tcp_rack *rack, struct tcpcb *tp, uint32_t tick,  int event, int line);
411
412 static int
413 rack_process_ack(struct mbuf *m, struct tcphdr *th,
414     struct socket *so, struct tcpcb *tp, struct tcpopt *to,
415     uint32_t tiwin, int32_t tlen, int32_t * ofia, int32_t thflags, int32_t * ret_val);
416 static int
417 rack_process_data(struct mbuf *m, struct tcphdr *th,
418     struct socket *so, struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
419     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
420 static void
421 rack_ack_received(struct tcpcb *tp, struct tcp_rack *rack,
422    uint32_t th_ack, uint16_t nsegs, uint16_t type, int32_t recovery);
423 static struct rack_sendmap *rack_alloc(struct tcp_rack *rack);
424 static struct rack_sendmap *rack_alloc_limit(struct tcp_rack *rack,
425     uint8_t limit_type);
426 static struct rack_sendmap *
427 rack_check_recovery_mode(struct tcpcb *tp,
428     uint32_t tsused);
429 static void
430 rack_cong_signal(struct tcpcb *tp,
431                  uint32_t type, uint32_t ack, int );
432 static void rack_counter_destroy(void);
433 static int
434 rack_ctloutput(struct inpcb *inp, struct sockopt *sopt);
435 static int32_t rack_ctor(void *mem, int32_t size, void *arg, int32_t how);
436 static void
437 rack_set_pace_segments(struct tcpcb *tp, struct tcp_rack *rack, uint32_t line, uint64_t *fill_override);
438 static void
439 rack_do_segment(struct mbuf *m, struct tcphdr *th,
440     struct socket *so, struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
441     uint8_t iptos);
442 static void rack_dtor(void *mem, int32_t size, void *arg);
443 static void
444 rack_log_alt_to_to_cancel(struct tcp_rack *rack,
445     uint32_t flex1, uint32_t flex2,
446     uint32_t flex3, uint32_t flex4,
447     uint32_t flex5, uint32_t flex6,
448     uint16_t flex7, uint8_t mod);
449
450 static void
451 rack_log_pacing_delay_calc(struct tcp_rack *rack, uint32_t len, uint32_t slot,
452    uint64_t bw_est, uint64_t bw, uint64_t len_time, int method, int line,
453    struct rack_sendmap *rsm, uint8_t quality);
454 static struct rack_sendmap *
455 rack_find_high_nonack(struct tcp_rack *rack,
456     struct rack_sendmap *rsm);
457 static struct rack_sendmap *rack_find_lowest_rsm(struct tcp_rack *rack);
458 static void rack_free(struct tcp_rack *rack, struct rack_sendmap *rsm);
459 static void rack_fini(struct tcpcb *tp, int32_t tcb_is_purged);
460 static int rack_get_sockopt(struct inpcb *inp, struct sockopt *sopt);
461 static void
462 rack_do_goodput_measurement(struct tcpcb *tp, struct tcp_rack *rack,
463                             tcp_seq th_ack, int line, uint8_t quality);
464 static uint32_t
465 rack_get_pacing_len(struct tcp_rack *rack, uint64_t bw, uint32_t mss);
466 static int32_t rack_handoff_ok(struct tcpcb *tp);
467 static int32_t rack_init(struct tcpcb *tp);
468 static void rack_init_sysctls(void);
469 static void
470 rack_log_ack(struct tcpcb *tp, struct tcpopt *to,
471     struct tcphdr *th, int entered_rec, int dup_ack_struck);
472 static void
473 rack_log_output(struct tcpcb *tp, struct tcpopt *to, int32_t len,
474     uint32_t seq_out, uint16_t th_flags, int32_t err, uint64_t ts,
475     struct rack_sendmap *hintrsm, uint16_t add_flags, struct mbuf *s_mb, uint32_t s_moff, int hw_tls);
476
477 static void
478 rack_log_sack_passed(struct tcpcb *tp, struct tcp_rack *rack,
479     struct rack_sendmap *rsm);
480 static void rack_log_to_event(struct tcp_rack *rack, int32_t to_num, struct rack_sendmap *rsm);
481 static int32_t rack_output(struct tcpcb *tp);
482
483 static uint32_t
484 rack_proc_sack_blk(struct tcpcb *tp, struct tcp_rack *rack,
485     struct sackblk *sack, struct tcpopt *to, struct rack_sendmap **prsm,
486     uint32_t cts, int *moved_two);
487 static void rack_post_recovery(struct tcpcb *tp, uint32_t th_seq);
488 static void rack_remxt_tmr(struct tcpcb *tp);
489 static int rack_set_sockopt(struct inpcb *inp, struct sockopt *sopt);
490 static void rack_set_state(struct tcpcb *tp, struct tcp_rack *rack);
491 static int32_t rack_stopall(struct tcpcb *tp);
492 static void
493 rack_timer_activate(struct tcpcb *tp, uint32_t timer_type,
494     uint32_t delta);
495 static int32_t rack_timer_active(struct tcpcb *tp, uint32_t timer_type);
496 static void rack_timer_cancel(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, int line);
497 static void rack_timer_stop(struct tcpcb *tp, uint32_t timer_type);
498 static uint32_t
499 rack_update_entry(struct tcpcb *tp, struct tcp_rack *rack,
500     struct rack_sendmap *rsm, uint64_t ts, int32_t * lenp, uint16_t add_flag);
501 static void
502 rack_update_rsm(struct tcpcb *tp, struct tcp_rack *rack,
503     struct rack_sendmap *rsm, uint64_t ts, uint16_t add_flag);
504 static int
505 rack_update_rtt(struct tcpcb *tp, struct tcp_rack *rack,
506     struct rack_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, tcp_seq th_ack);
507 static int32_t tcp_addrack(module_t mod, int32_t type, void *data);
508 static int
509 rack_do_close_wait(struct mbuf *m, struct tcphdr *th,
510     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
511     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
512 static int
513 rack_do_closing(struct mbuf *m, struct tcphdr *th,
514     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
515     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
516 static int
517 rack_do_established(struct mbuf *m, struct tcphdr *th,
518     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
519     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
520 static int
521 rack_do_fastnewdata(struct mbuf *m, struct tcphdr *th,
522     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
523     int32_t tlen, uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos);
524 static int
525 rack_do_fin_wait_1(struct mbuf *m, struct tcphdr *th,
526     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
527     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
528 static int
529 rack_do_fin_wait_2(struct mbuf *m, struct tcphdr *th,
530     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
531     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
532 static int
533 rack_do_lastack(struct mbuf *m, struct tcphdr *th,
534     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
535     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
536 static int
537 rack_do_syn_recv(struct mbuf *m, struct tcphdr *th,
538     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
539     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
540 static int
541 rack_do_syn_sent(struct mbuf *m, struct tcphdr *th,
542     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
543     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
544 struct rack_sendmap *
545 tcp_rack_output(struct tcpcb *tp, struct tcp_rack *rack,
546     uint32_t tsused);
547 static void tcp_rack_xmit_timer(struct tcp_rack *rack, int32_t rtt,
548     uint32_t len, uint32_t us_tim, int confidence, struct rack_sendmap *rsm, uint16_t rtrcnt);
549 static void
550      tcp_rack_partialack(struct tcpcb *tp);
551 static int
552 rack_set_profile(struct tcp_rack *rack, int prof);
553 static void
554 rack_apply_deferred_options(struct tcp_rack *rack);
555
556 int32_t rack_clear_counter=0;
557
558 static inline void
559 rack_trace_point(struct tcp_rack *rack, int num)
560 {
561         if (((rack_trace_point_config == num)  ||
562              (rack_trace_point_config = 0xffffffff)) &&
563             (rack_trace_point_bb_mode != 0) &&
564             (rack_trace_point_count > 0) &&
565             (rack->rc_tp->t_logstate == 0)) {
566                 int res;
567                 res = atomic_fetchadd_int(&rack_trace_point_count, -1);
568                 if (res > 0) {
569                         rack->rc_tp->t_logstate = rack_trace_point_bb_mode;
570                 } else {
571                         /* Loss a race assure its zero now */
572                         rack_trace_point_count = 0;
573                 }
574         }
575 }
576
577 static void
578 rack_set_cc_pacing(struct tcp_rack *rack)
579 {
580         struct sockopt sopt;
581         struct cc_newreno_opts opt;
582         struct newreno old, *ptr;
583         struct tcpcb *tp;
584         int error;
585
586         if (rack->rc_pacing_cc_set)
587                 return;
588
589         tp = rack->rc_tp;
590         if (tp->cc_algo == NULL) {
591                 /* Tcb is leaving */
592                 return;
593         }
594         rack->rc_pacing_cc_set = 1;
595         if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0) {
596                 /* Not new-reno we can't play games with beta! */
597                 goto out;
598         }
599         ptr = ((struct newreno *)tp->ccv->cc_data);
600         if (CC_ALGO(tp)->ctl_output == NULL)  {
601                 /* Huh, why does new_reno no longer have a set function? */
602                 goto out;
603         }
604         if (ptr == NULL) {
605                 /* Just the default values */
606                 old.beta = V_newreno_beta_ecn;
607                 old.beta_ecn = V_newreno_beta_ecn;
608                 old.newreno_flags = 0;
609         } else {
610                 old.beta = ptr->beta;
611                 old.beta_ecn = ptr->beta_ecn;
612                 old.newreno_flags = ptr->newreno_flags;
613         }
614         sopt.sopt_valsize = sizeof(struct cc_newreno_opts);
615         sopt.sopt_dir = SOPT_SET;
616         opt.name = CC_NEWRENO_BETA;
617         opt.val = rack->r_ctl.rc_saved_beta.beta;
618         error = CC_ALGO(tp)->ctl_output(tp->ccv, &sopt, &opt);
619         if (error)  {
620                 goto out;
621         }
622         /*
623          * Hack alert we need to set in our newreno_flags
624          * so that Abe behavior is also applied.
625          */
626         ((struct newreno *)tp->ccv->cc_data)->newreno_flags |= CC_NEWRENO_BETA_ECN_ENABLED;
627         opt.name = CC_NEWRENO_BETA_ECN;
628         opt.val = rack->r_ctl.rc_saved_beta.beta_ecn;
629         error = CC_ALGO(tp)->ctl_output(tp->ccv, &sopt, &opt);
630         if (error) {
631                 goto out;
632         }
633         /* Save off the original values for restoral */
634         memcpy(&rack->r_ctl.rc_saved_beta, &old, sizeof(struct newreno));
635 out:
636         if (rack_verbose_logging && (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
637                 union tcp_log_stackspecific log;
638                 struct timeval tv;
639
640                 ptr = ((struct newreno *)tp->ccv->cc_data);
641                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
642                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
643                 if (ptr) {
644                         log.u_bbr.flex1 = ptr->beta;
645                         log.u_bbr.flex2 = ptr->beta_ecn;
646                         log.u_bbr.flex3 = ptr->newreno_flags;
647                 }
648                 log.u_bbr.flex4 = rack->r_ctl.rc_saved_beta.beta;
649                 log.u_bbr.flex5 = rack->r_ctl.rc_saved_beta.beta_ecn;
650                 log.u_bbr.flex6 = rack->r_ctl.rc_saved_beta.newreno_flags;
651                 log.u_bbr.flex7 = rack->gp_ready;
652                 log.u_bbr.flex7 <<= 1;
653                 log.u_bbr.flex7 |= rack->use_fixed_rate;
654                 log.u_bbr.flex7 <<= 1;
655                 log.u_bbr.flex7 |= rack->rc_pacing_cc_set;
656                 log.u_bbr.pkts_out = rack->r_ctl.rc_prr_sndcnt;
657                 log.u_bbr.flex8 = 3;
658                 tcp_log_event_(tp, NULL, NULL, NULL, BBR_LOG_CWND, error,
659                                0, &log, false, NULL, NULL, 0, &tv);
660         }
661 }
662
663 static void
664 rack_undo_cc_pacing(struct tcp_rack *rack)
665 {
666         struct newreno old, *ptr;
667         struct tcpcb *tp;
668
669         if (rack->rc_pacing_cc_set == 0)
670                 return;
671         tp = rack->rc_tp;
672         rack->rc_pacing_cc_set = 0;
673         if (tp->cc_algo == NULL)
674                 /* Tcb is leaving */
675                 return;
676         if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0) {
677                 /* Not new-reno nothing to do! */
678                 return;
679         }
680         ptr = ((struct newreno *)tp->ccv->cc_data);
681         if (ptr == NULL) {
682                 /*
683                  * This happens at rack_fini() if the
684                  * cc module gets freed on us. In that
685                  * case we loose our "new" settings but
686                  * thats ok, since the tcb is going away anyway.
687                  */
688                 return;
689         }
690         /* Grab out our set values */
691         memcpy(&old, ptr, sizeof(struct newreno));
692         /* Copy back in the original values */
693         memcpy(ptr, &rack->r_ctl.rc_saved_beta, sizeof(struct newreno));
694         /* Now save back the values we had set in (for when pacing is restored) */
695         memcpy(&rack->r_ctl.rc_saved_beta, &old, sizeof(struct newreno));
696         if (rack_verbose_logging && (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
697                 union tcp_log_stackspecific log;
698                 struct timeval tv;
699
700                 ptr = ((struct newreno *)tp->ccv->cc_data);
701                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
702                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
703                 log.u_bbr.flex1 = ptr->beta;
704                 log.u_bbr.flex2 = ptr->beta_ecn;
705                 log.u_bbr.flex3 = ptr->newreno_flags;
706                 log.u_bbr.flex4 = rack->r_ctl.rc_saved_beta.beta;
707                 log.u_bbr.flex5 = rack->r_ctl.rc_saved_beta.beta_ecn;
708                 log.u_bbr.flex6 = rack->r_ctl.rc_saved_beta.newreno_flags;
709                 log.u_bbr.flex7 = rack->gp_ready;
710                 log.u_bbr.flex7 <<= 1;
711                 log.u_bbr.flex7 |= rack->use_fixed_rate;
712                 log.u_bbr.flex7 <<= 1;
713                 log.u_bbr.flex7 |= rack->rc_pacing_cc_set;
714                 log.u_bbr.pkts_out = rack->r_ctl.rc_prr_sndcnt;
715                 log.u_bbr.flex8 = 4;
716                 tcp_log_event_(tp, NULL, NULL, NULL, BBR_LOG_CWND, 0,
717                                0, &log, false, NULL, NULL, 0, &tv);
718         }
719 }
720
721 #ifdef NETFLIX_PEAKRATE
722 static inline void
723 rack_update_peakrate_thr(struct tcpcb *tp)
724 {
725         /* Keep in mind that t_maxpeakrate is in B/s. */
726         uint64_t peak;
727         peak = uqmax((tp->t_maxseg * 2),
728                      (((uint64_t)tp->t_maxpeakrate * (uint64_t)(tp->t_srtt)) / (uint64_t)HPTS_USEC_IN_SEC));
729         tp->t_peakrate_thr = (uint32_t)uqmin(peak, UINT32_MAX);
730 }
731 #endif
732
733 static int
734 sysctl_rack_clear(SYSCTL_HANDLER_ARGS)
735 {
736         uint32_t stat;
737         int32_t error;
738
739         error = SYSCTL_OUT(req, &rack_clear_counter, sizeof(uint32_t));
740         if (error || req->newptr == NULL)
741                 return error;
742
743         error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
744         if (error)
745                 return (error);
746         if (stat == 1) {
747 #ifdef INVARIANTS
748                 printf("Clearing RACK counters\n");
749 #endif
750                 counter_u64_zero(rack_tlp_tot);
751                 counter_u64_zero(rack_tlp_newdata);
752                 counter_u64_zero(rack_tlp_retran);
753                 counter_u64_zero(rack_tlp_retran_bytes);
754                 counter_u64_zero(rack_to_tot);
755                 counter_u64_zero(rack_saw_enobuf);
756                 counter_u64_zero(rack_saw_enobuf_hw);
757                 counter_u64_zero(rack_saw_enetunreach);
758                 counter_u64_zero(rack_persists_sends);
759                 counter_u64_zero(rack_persists_acks);
760                 counter_u64_zero(rack_persists_loss);
761                 counter_u64_zero(rack_persists_lost_ends);
762 #ifdef INVARIANTS
763                 counter_u64_zero(rack_adjust_map_bw);
764 #endif
765                 counter_u64_zero(rack_to_alloc_hard);
766                 counter_u64_zero(rack_to_alloc_emerg);
767                 counter_u64_zero(rack_sack_proc_all);
768                 counter_u64_zero(rack_fto_send);
769                 counter_u64_zero(rack_fto_rsm_send);
770                 counter_u64_zero(rack_extended_rfo);
771                 counter_u64_zero(rack_hw_pace_init_fail);
772                 counter_u64_zero(rack_hw_pace_lost);
773                 counter_u64_zero(rack_non_fto_send);
774                 counter_u64_zero(rack_nfto_resend);
775                 counter_u64_zero(rack_sack_proc_short);
776                 counter_u64_zero(rack_sack_proc_restart);
777                 counter_u64_zero(rack_to_alloc);
778                 counter_u64_zero(rack_to_alloc_limited);
779                 counter_u64_zero(rack_alloc_limited_conns);
780                 counter_u64_zero(rack_split_limited);
781                 counter_u64_zero(rack_multi_single_eq);
782                 counter_u64_zero(rack_proc_non_comp_ack);
783                 counter_u64_zero(rack_sack_attacks_detected);
784                 counter_u64_zero(rack_sack_attacks_reversed);
785                 counter_u64_zero(rack_sack_used_next_merge);
786                 counter_u64_zero(rack_sack_used_prev_merge);
787                 counter_u64_zero(rack_sack_splits);
788                 counter_u64_zero(rack_sack_skipped_acked);
789                 counter_u64_zero(rack_ack_total);
790                 counter_u64_zero(rack_express_sack);
791                 counter_u64_zero(rack_sack_total);
792                 counter_u64_zero(rack_move_none);
793                 counter_u64_zero(rack_move_some);
794                 counter_u64_zero(rack_try_scwnd);
795                 counter_u64_zero(rack_collapsed_win);
796                 counter_u64_zero(rack_collapsed_win_rxt);
797                 counter_u64_zero(rack_collapsed_win_seen);
798                 counter_u64_zero(rack_collapsed_win_rxt_bytes);
799         }
800         rack_clear_counter = 0;
801         return (0);
802 }
803
804 static void
805 rack_init_sysctls(void)
806 {
807         struct sysctl_oid *rack_counters;
808         struct sysctl_oid *rack_attack;
809         struct sysctl_oid *rack_pacing;
810         struct sysctl_oid *rack_timely;
811         struct sysctl_oid *rack_timers;
812         struct sysctl_oid *rack_tlp;
813         struct sysctl_oid *rack_misc;
814         struct sysctl_oid *rack_features;
815         struct sysctl_oid *rack_measure;
816         struct sysctl_oid *rack_probertt;
817         struct sysctl_oid *rack_hw_pacing;
818         struct sysctl_oid *rack_tracepoint;
819
820         rack_attack = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
821             SYSCTL_CHILDREN(rack_sysctl_root),
822             OID_AUTO,
823             "sack_attack",
824             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
825             "Rack Sack Attack Counters and Controls");
826         rack_counters = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
827             SYSCTL_CHILDREN(rack_sysctl_root),
828             OID_AUTO,
829             "stats",
830             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
831             "Rack Counters");
832         SYSCTL_ADD_S32(&rack_sysctl_ctx,
833             SYSCTL_CHILDREN(rack_sysctl_root),
834             OID_AUTO, "rate_sample_method", CTLFLAG_RW,
835             &rack_rate_sample_method , USE_RTT_LOW,
836             "What method should we use for rate sampling 0=high, 1=low ");
837         /* Probe rtt related controls */
838         rack_probertt = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
839             SYSCTL_CHILDREN(rack_sysctl_root),
840             OID_AUTO,
841             "probertt",
842             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
843             "ProbeRTT related Controls");
844         SYSCTL_ADD_U16(&rack_sysctl_ctx,
845             SYSCTL_CHILDREN(rack_probertt),
846             OID_AUTO, "exit_per_hpb", CTLFLAG_RW,
847             &rack_atexit_prtt_hbp, 130,
848             "What percentage above goodput do we clamp CA/SS to at exit on high-BDP path 110%");
849         SYSCTL_ADD_U16(&rack_sysctl_ctx,
850             SYSCTL_CHILDREN(rack_probertt),
851             OID_AUTO, "exit_per_nonhpb", CTLFLAG_RW,
852             &rack_atexit_prtt, 130,
853             "What percentage above goodput do we clamp CA/SS to at exit on a non high-BDP path 100%");
854         SYSCTL_ADD_U16(&rack_sysctl_ctx,
855             SYSCTL_CHILDREN(rack_probertt),
856             OID_AUTO, "gp_per_mul", CTLFLAG_RW,
857             &rack_per_of_gp_probertt, 60,
858             "What percentage of goodput do we pace at in probertt");
859         SYSCTL_ADD_U16(&rack_sysctl_ctx,
860             SYSCTL_CHILDREN(rack_probertt),
861             OID_AUTO, "gp_per_reduce", CTLFLAG_RW,
862             &rack_per_of_gp_probertt_reduce, 10,
863             "What percentage of goodput do we reduce every gp_srtt");
864         SYSCTL_ADD_U16(&rack_sysctl_ctx,
865             SYSCTL_CHILDREN(rack_probertt),
866             OID_AUTO, "gp_per_low", CTLFLAG_RW,
867             &rack_per_of_gp_lowthresh, 40,
868             "What percentage of goodput do we allow the multiplier to fall to");
869         SYSCTL_ADD_U32(&rack_sysctl_ctx,
870             SYSCTL_CHILDREN(rack_probertt),
871             OID_AUTO, "time_between", CTLFLAG_RW,
872             & rack_time_between_probertt, 96000000,
873             "How many useconds between the lowest rtt falling must past before we enter probertt");
874         SYSCTL_ADD_U32(&rack_sysctl_ctx,
875             SYSCTL_CHILDREN(rack_probertt),
876             OID_AUTO, "safety", CTLFLAG_RW,
877             &rack_probe_rtt_safety_val, 2000000,
878             "If not zero, provides a maximum usecond that you can stay in probertt (2sec = 2000000)");
879         SYSCTL_ADD_U32(&rack_sysctl_ctx,
880             SYSCTL_CHILDREN(rack_probertt),
881             OID_AUTO, "sets_cwnd", CTLFLAG_RW,
882             &rack_probe_rtt_sets_cwnd, 0,
883             "Do we set the cwnd too (if always_lower is on)");
884         SYSCTL_ADD_U32(&rack_sysctl_ctx,
885             SYSCTL_CHILDREN(rack_probertt),
886             OID_AUTO, "maxdrainsrtts", CTLFLAG_RW,
887             &rack_max_drain_wait, 2,
888             "Maximum number of gp_srtt's to hold in drain waiting for flight to reach goal");
889         SYSCTL_ADD_U32(&rack_sysctl_ctx,
890             SYSCTL_CHILDREN(rack_probertt),
891             OID_AUTO, "mustdrainsrtts", CTLFLAG_RW,
892             &rack_must_drain, 1,
893             "We must drain this many gp_srtt's waiting for flight to reach goal");
894         SYSCTL_ADD_U32(&rack_sysctl_ctx,
895             SYSCTL_CHILDREN(rack_probertt),
896             OID_AUTO, "goal_use_min_entry", CTLFLAG_RW,
897             &rack_probertt_use_min_rtt_entry, 1,
898             "Should we use the min-rtt to calculate the goal rtt (else gp_srtt) at entry");
899         SYSCTL_ADD_U32(&rack_sysctl_ctx,
900             SYSCTL_CHILDREN(rack_probertt),
901             OID_AUTO, "goal_use_min_exit", CTLFLAG_RW,
902             &rack_probertt_use_min_rtt_exit, 0,
903             "How to set cwnd at exit, 0 - dynamic, 1 - use min-rtt, 2 - use curgprtt, 3 - entry gp-rtt");
904         SYSCTL_ADD_U32(&rack_sysctl_ctx,
905             SYSCTL_CHILDREN(rack_probertt),
906             OID_AUTO, "length_div", CTLFLAG_RW,
907             &rack_probertt_gpsrtt_cnt_div, 0,
908             "How many recent goodput srtt periods plus hold tim does probertt last (bottom of fraction)");
909         SYSCTL_ADD_U32(&rack_sysctl_ctx,
910             SYSCTL_CHILDREN(rack_probertt),
911             OID_AUTO, "length_mul", CTLFLAG_RW,
912             &rack_probertt_gpsrtt_cnt_mul, 0,
913             "How many recent goodput srtt periods plus hold tim does probertt last (top of fraction)");
914         SYSCTL_ADD_U32(&rack_sysctl_ctx,
915             SYSCTL_CHILDREN(rack_probertt),
916             OID_AUTO, "holdtim_at_target", CTLFLAG_RW,
917             &rack_min_probertt_hold, 200000,
918             "What is the minimum time we hold probertt at target");
919         SYSCTL_ADD_U32(&rack_sysctl_ctx,
920             SYSCTL_CHILDREN(rack_probertt),
921             OID_AUTO, "filter_life", CTLFLAG_RW,
922             &rack_probertt_filter_life, 10000000,
923             "What is the time for the filters life in useconds");
924         SYSCTL_ADD_U32(&rack_sysctl_ctx,
925             SYSCTL_CHILDREN(rack_probertt),
926             OID_AUTO, "lower_within", CTLFLAG_RW,
927             &rack_probertt_lower_within, 10,
928             "If the rtt goes lower within this percentage of the time, go into probe-rtt");
929         SYSCTL_ADD_U32(&rack_sysctl_ctx,
930             SYSCTL_CHILDREN(rack_probertt),
931             OID_AUTO, "must_move", CTLFLAG_RW,
932             &rack_min_rtt_movement, 250,
933             "How much is the minimum movement in rtt to count as a drop for probertt purposes");
934         SYSCTL_ADD_U32(&rack_sysctl_ctx,
935             SYSCTL_CHILDREN(rack_probertt),
936             OID_AUTO, "clear_is_cnts", CTLFLAG_RW,
937             &rack_probertt_clear_is, 1,
938             "Do we clear I/S counts on exiting probe-rtt");
939         SYSCTL_ADD_S32(&rack_sysctl_ctx,
940             SYSCTL_CHILDREN(rack_probertt),
941             OID_AUTO, "hbp_extra_drain", CTLFLAG_RW,
942             &rack_max_drain_hbp, 1,
943             "How many extra drain gpsrtt's do we get in highly buffered paths");
944         SYSCTL_ADD_S32(&rack_sysctl_ctx,
945             SYSCTL_CHILDREN(rack_probertt),
946             OID_AUTO, "hbp_threshold", CTLFLAG_RW,
947             &rack_hbp_thresh, 3,
948             "We are highly buffered if min_rtt_seen / max_rtt_seen > this-threshold");
949
950         rack_tracepoint = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
951             SYSCTL_CHILDREN(rack_sysctl_root),
952             OID_AUTO,
953             "tp",
954             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
955             "Rack tracepoint facility");
956         SYSCTL_ADD_U32(&rack_sysctl_ctx,
957             SYSCTL_CHILDREN(rack_tracepoint),
958             OID_AUTO, "number", CTLFLAG_RW,
959             &rack_trace_point_config, 0,
960             "What is the trace point number to activate (0=none, 0xffffffff = all)?");
961         SYSCTL_ADD_U32(&rack_sysctl_ctx,
962             SYSCTL_CHILDREN(rack_tracepoint),
963             OID_AUTO, "bbmode", CTLFLAG_RW,
964             &rack_trace_point_bb_mode, 4,
965             "What is BB logging mode that is activated?");
966         SYSCTL_ADD_S32(&rack_sysctl_ctx,
967             SYSCTL_CHILDREN(rack_tracepoint),
968             OID_AUTO, "count", CTLFLAG_RW,
969             &rack_trace_point_count, 0,
970             "How many connections will have BB logging turned on that hit the tracepoint?");
971         /* Pacing related sysctls */
972         rack_pacing = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
973             SYSCTL_CHILDREN(rack_sysctl_root),
974             OID_AUTO,
975             "pacing",
976             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
977             "Pacing related Controls");
978         SYSCTL_ADD_S32(&rack_sysctl_ctx,
979             SYSCTL_CHILDREN(rack_pacing),
980             OID_AUTO, "max_pace_over", CTLFLAG_RW,
981             &rack_max_per_above, 30,
982             "What is the maximum allowable percentage that we can pace above (so 30 = 130% of our goal)");
983         SYSCTL_ADD_S32(&rack_sysctl_ctx,
984             SYSCTL_CHILDREN(rack_pacing),
985             OID_AUTO, "pace_to_one", CTLFLAG_RW,
986             &rack_pace_one_seg, 0,
987             "Do we allow low b/w pacing of 1MSS instead of two");
988         SYSCTL_ADD_S32(&rack_sysctl_ctx,
989             SYSCTL_CHILDREN(rack_pacing),
990             OID_AUTO, "limit_wsrtt", CTLFLAG_RW,
991             &rack_limit_time_with_srtt, 0,
992             "Do we limit pacing time based on srtt");
993         SYSCTL_ADD_S32(&rack_sysctl_ctx,
994             SYSCTL_CHILDREN(rack_pacing),
995             OID_AUTO, "init_win", CTLFLAG_RW,
996             &rack_default_init_window, 0,
997             "Do we have a rack initial window 0 = system default");
998         SYSCTL_ADD_U16(&rack_sysctl_ctx,
999             SYSCTL_CHILDREN(rack_pacing),
1000             OID_AUTO, "gp_per_ss", CTLFLAG_RW,
1001             &rack_per_of_gp_ss, 250,
1002             "If non zero, what percentage of goodput to pace at in slow start");
1003         SYSCTL_ADD_U16(&rack_sysctl_ctx,
1004             SYSCTL_CHILDREN(rack_pacing),
1005             OID_AUTO, "gp_per_ca", CTLFLAG_RW,
1006             &rack_per_of_gp_ca, 150,
1007             "If non zero, what percentage of goodput to pace at in congestion avoidance");
1008         SYSCTL_ADD_U16(&rack_sysctl_ctx,
1009             SYSCTL_CHILDREN(rack_pacing),
1010             OID_AUTO, "gp_per_rec", CTLFLAG_RW,
1011             &rack_per_of_gp_rec, 200,
1012             "If non zero, what percentage of goodput to pace at in recovery");
1013         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1014             SYSCTL_CHILDREN(rack_pacing),
1015             OID_AUTO, "pace_max_seg", CTLFLAG_RW,
1016             &rack_hptsi_segments, 40,
1017             "What size is the max for TSO segments in pacing and burst mitigation");
1018         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1019             SYSCTL_CHILDREN(rack_pacing),
1020             OID_AUTO, "burst_reduces", CTLFLAG_RW,
1021             &rack_slot_reduction, 4,
1022             "When doing only burst mitigation what is the reduce divisor");
1023         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1024             SYSCTL_CHILDREN(rack_sysctl_root),
1025             OID_AUTO, "use_pacing", CTLFLAG_RW,
1026             &rack_pace_every_seg, 0,
1027             "If set we use pacing, if clear we use only the original burst mitigation");
1028         SYSCTL_ADD_U64(&rack_sysctl_ctx,
1029             SYSCTL_CHILDREN(rack_pacing),
1030             OID_AUTO, "rate_cap", CTLFLAG_RW,
1031             &rack_bw_rate_cap, 0,
1032             "If set we apply this value to the absolute rate cap used by pacing");
1033         SYSCTL_ADD_U8(&rack_sysctl_ctx,
1034             SYSCTL_CHILDREN(rack_sysctl_root),
1035             OID_AUTO, "req_measure_cnt", CTLFLAG_RW,
1036             &rack_req_measurements, 1,
1037             "If doing dynamic pacing, how many measurements must be in before we start pacing?");
1038         /* Hardware pacing */
1039         rack_hw_pacing = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1040             SYSCTL_CHILDREN(rack_sysctl_root),
1041             OID_AUTO,
1042             "hdwr_pacing",
1043             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1044             "Pacing related Controls");
1045         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1046             SYSCTL_CHILDREN(rack_hw_pacing),
1047             OID_AUTO, "rwnd_factor", CTLFLAG_RW,
1048             &rack_hw_rwnd_factor, 2,
1049             "How many times does snd_wnd need to be bigger than pace_max_seg so we will hold off and get more acks?");
1050         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1051             SYSCTL_CHILDREN(rack_hw_pacing),
1052             OID_AUTO, "pace_enobuf_mult", CTLFLAG_RW,
1053             &rack_enobuf_hw_boost_mult, 2,
1054             "By how many time_betweens should we boost the pacing time if we see a ENOBUFS?");
1055         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1056             SYSCTL_CHILDREN(rack_hw_pacing),
1057             OID_AUTO, "pace_enobuf_max", CTLFLAG_RW,
1058             &rack_enobuf_hw_max, 2,
1059             "What is the max boost the pacing time if we see a ENOBUFS?");
1060         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1061             SYSCTL_CHILDREN(rack_hw_pacing),
1062             OID_AUTO, "pace_enobuf_min", CTLFLAG_RW,
1063             &rack_enobuf_hw_min, 2,
1064             "What is the min boost the pacing time if we see a ENOBUFS?");
1065         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1066             SYSCTL_CHILDREN(rack_hw_pacing),
1067             OID_AUTO, "enable", CTLFLAG_RW,
1068             &rack_enable_hw_pacing, 0,
1069             "Should RACK attempt to use hw pacing?");
1070         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1071             SYSCTL_CHILDREN(rack_hw_pacing),
1072             OID_AUTO, "rate_cap", CTLFLAG_RW,
1073             &rack_hw_rate_caps, 1,
1074             "Does the highest hardware pacing rate cap the rate we will send at??");
1075         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1076             SYSCTL_CHILDREN(rack_hw_pacing),
1077             OID_AUTO, "rate_min", CTLFLAG_RW,
1078             &rack_hw_rate_min, 0,
1079             "Do we need a minimum estimate of this many bytes per second in order to engage hw pacing?");
1080         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1081             SYSCTL_CHILDREN(rack_hw_pacing),
1082             OID_AUTO, "rate_to_low", CTLFLAG_RW,
1083             &rack_hw_rate_to_low, 0,
1084             "If we fall below this rate, dis-engage hw pacing?");
1085         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1086             SYSCTL_CHILDREN(rack_hw_pacing),
1087             OID_AUTO, "up_only", CTLFLAG_RW,
1088             &rack_hw_up_only, 1,
1089             "Do we allow hw pacing to lower the rate selected?");
1090         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1091             SYSCTL_CHILDREN(rack_hw_pacing),
1092             OID_AUTO, "extra_mss_precise", CTLFLAG_RW,
1093             &rack_hw_pace_extra_slots, 2,
1094             "If the rates between software and hardware match precisely how many extra time_betweens do we get?");
1095         rack_timely = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1096             SYSCTL_CHILDREN(rack_sysctl_root),
1097             OID_AUTO,
1098             "timely",
1099             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1100             "Rack Timely RTT Controls");
1101         /* Timely based GP dynmics */
1102         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1103             SYSCTL_CHILDREN(rack_timely),
1104             OID_AUTO, "upper", CTLFLAG_RW,
1105             &rack_gp_per_bw_mul_up, 2,
1106             "Rack timely upper range for equal b/w (in percentage)");
1107         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1108             SYSCTL_CHILDREN(rack_timely),
1109             OID_AUTO, "lower", CTLFLAG_RW,
1110             &rack_gp_per_bw_mul_down, 4,
1111             "Rack timely lower range for equal b/w (in percentage)");
1112         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1113             SYSCTL_CHILDREN(rack_timely),
1114             OID_AUTO, "rtt_max_mul", CTLFLAG_RW,
1115             &rack_gp_rtt_maxmul, 3,
1116             "Rack timely multiplier of lowest rtt for rtt_max");
1117         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1118             SYSCTL_CHILDREN(rack_timely),
1119             OID_AUTO, "rtt_min_div", CTLFLAG_RW,
1120             &rack_gp_rtt_mindiv, 4,
1121             "Rack timely divisor used for rtt + (rtt * mul/divisor) for check for lower rtt");
1122         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1123             SYSCTL_CHILDREN(rack_timely),
1124             OID_AUTO, "rtt_min_mul", CTLFLAG_RW,
1125             &rack_gp_rtt_minmul, 1,
1126             "Rack timely multiplier used for rtt + (rtt * mul/divisor) for check for lower rtt");
1127         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1128             SYSCTL_CHILDREN(rack_timely),
1129             OID_AUTO, "decrease", CTLFLAG_RW,
1130             &rack_gp_decrease_per, 20,
1131             "Rack timely decrease percentage of our GP multiplication factor");
1132         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1133             SYSCTL_CHILDREN(rack_timely),
1134             OID_AUTO, "increase", CTLFLAG_RW,
1135             &rack_gp_increase_per, 2,
1136             "Rack timely increase perentage of our GP multiplication factor");
1137         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1138             SYSCTL_CHILDREN(rack_timely),
1139             OID_AUTO, "lowerbound", CTLFLAG_RW,
1140             &rack_per_lower_bound, 50,
1141             "Rack timely lowest percentage we allow GP multiplier to fall to");
1142         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1143             SYSCTL_CHILDREN(rack_timely),
1144             OID_AUTO, "upperboundss", CTLFLAG_RW,
1145             &rack_per_upper_bound_ss, 0,
1146             "Rack timely highest percentage we allow GP multiplier in SS to raise to (0 is no upperbound)");
1147         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1148             SYSCTL_CHILDREN(rack_timely),
1149             OID_AUTO, "upperboundca", CTLFLAG_RW,
1150             &rack_per_upper_bound_ca, 0,
1151             "Rack timely highest percentage we allow GP multiplier to CA raise to (0 is no upperbound)");
1152         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1153             SYSCTL_CHILDREN(rack_timely),
1154             OID_AUTO, "dynamicgp", CTLFLAG_RW,
1155             &rack_do_dyn_mul, 0,
1156             "Rack timely do we enable dynmaic timely goodput by default");
1157         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1158             SYSCTL_CHILDREN(rack_timely),
1159             OID_AUTO, "no_rec_red", CTLFLAG_RW,
1160             &rack_gp_no_rec_chg, 1,
1161             "Rack timely do we prohibit the recovery multiplier from being lowered");
1162         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1163             SYSCTL_CHILDREN(rack_timely),
1164             OID_AUTO, "red_clear_cnt", CTLFLAG_RW,
1165             &rack_timely_dec_clear, 6,
1166             "Rack timely what threshold do we count to before another boost during b/w decent");
1167         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1168             SYSCTL_CHILDREN(rack_timely),
1169             OID_AUTO, "max_push_rise", CTLFLAG_RW,
1170             &rack_timely_max_push_rise, 3,
1171             "Rack timely how many times do we push up with b/w increase");
1172         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1173             SYSCTL_CHILDREN(rack_timely),
1174             OID_AUTO, "max_push_drop", CTLFLAG_RW,
1175             &rack_timely_max_push_drop, 3,
1176             "Rack timely how many times do we push back on b/w decent");
1177         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1178             SYSCTL_CHILDREN(rack_timely),
1179             OID_AUTO, "min_segs", CTLFLAG_RW,
1180             &rack_timely_min_segs, 4,
1181             "Rack timely when setting the cwnd what is the min num segments");
1182         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1183             SYSCTL_CHILDREN(rack_timely),
1184             OID_AUTO, "noback_max", CTLFLAG_RW,
1185             &rack_use_max_for_nobackoff, 0,
1186             "Rack timely when deciding if to backoff on a loss, do we use under max rtt else min");
1187         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1188             SYSCTL_CHILDREN(rack_timely),
1189             OID_AUTO, "interim_timely_only", CTLFLAG_RW,
1190             &rack_timely_int_timely_only, 0,
1191             "Rack timely when doing interim timely's do we only do timely (no b/w consideration)");
1192         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1193             SYSCTL_CHILDREN(rack_timely),
1194             OID_AUTO, "nonstop", CTLFLAG_RW,
1195             &rack_timely_no_stopping, 0,
1196             "Rack timely don't stop increase");
1197         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1198             SYSCTL_CHILDREN(rack_timely),
1199             OID_AUTO, "dec_raise_thresh", CTLFLAG_RW,
1200             &rack_down_raise_thresh, 100,
1201             "If the CA or SS is below this threshold raise on the first 3 b/w lowers (0=always)");
1202         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1203             SYSCTL_CHILDREN(rack_timely),
1204             OID_AUTO, "bottom_drag_segs", CTLFLAG_RW,
1205             &rack_req_segs, 1,
1206             "Bottom dragging if not these many segments outstanding and room");
1207
1208         /* TLP and Rack related parameters */
1209         rack_tlp = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1210             SYSCTL_CHILDREN(rack_sysctl_root),
1211             OID_AUTO,
1212             "tlp",
1213             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1214             "TLP and Rack related Controls");
1215         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1216             SYSCTL_CHILDREN(rack_tlp),
1217             OID_AUTO, "use_rrr", CTLFLAG_RW,
1218             &use_rack_rr, 1,
1219             "Do we use Rack Rapid Recovery");
1220         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1221             SYSCTL_CHILDREN(rack_tlp),
1222             OID_AUTO, "post_rec_labc", CTLFLAG_RW,
1223             &rack_max_abc_post_recovery, 2,
1224             "Since we do early recovery, do we override the l_abc to a value, if so what?");
1225         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1226             SYSCTL_CHILDREN(rack_tlp),
1227             OID_AUTO, "nonrxt_use_cr", CTLFLAG_RW,
1228             &rack_non_rxt_use_cr, 0,
1229             "Do we use ss/ca rate if in recovery we are transmitting a new data chunk");
1230         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1231             SYSCTL_CHILDREN(rack_tlp),
1232             OID_AUTO, "tlpmethod", CTLFLAG_RW,
1233             &rack_tlp_threshold_use, TLP_USE_TWO_ONE,
1234             "What method do we do for TLP time calc 0=no-de-ack-comp, 1=ID, 2=2.1, 3=2.2");
1235         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1236             SYSCTL_CHILDREN(rack_tlp),
1237             OID_AUTO, "limit", CTLFLAG_RW,
1238             &rack_tlp_limit, 2,
1239             "How many TLP's can be sent without sending new data");
1240         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1241             SYSCTL_CHILDREN(rack_tlp),
1242             OID_AUTO, "use_greater", CTLFLAG_RW,
1243             &rack_tlp_use_greater, 1,
1244             "Should we use the rack_rtt time if its greater than srtt");
1245         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1246             SYSCTL_CHILDREN(rack_tlp),
1247             OID_AUTO, "tlpminto", CTLFLAG_RW,
1248             &rack_tlp_min, 10000,
1249             "TLP minimum timeout per the specification (in microseconds)");
1250         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1251             SYSCTL_CHILDREN(rack_tlp),
1252             OID_AUTO, "send_oldest", CTLFLAG_RW,
1253             &rack_always_send_oldest, 0,
1254             "Should we always send the oldest TLP and RACK-TLP");
1255         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1256             SYSCTL_CHILDREN(rack_tlp),
1257             OID_AUTO, "rack_tlimit", CTLFLAG_RW,
1258             &rack_limited_retran, 0,
1259             "How many times can a rack timeout drive out sends");
1260         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1261             SYSCTL_CHILDREN(rack_tlp),
1262             OID_AUTO, "tlp_cwnd_flag", CTLFLAG_RW,
1263             &rack_lower_cwnd_at_tlp, 0,
1264             "When a TLP completes a retran should we enter recovery");
1265         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1266             SYSCTL_CHILDREN(rack_tlp),
1267             OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1268             &rack_reorder_thresh, 2,
1269             "What factor for rack will be added when seeing reordering (shift right)");
1270         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1271             SYSCTL_CHILDREN(rack_tlp),
1272             OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1273             &rack_tlp_thresh, 1,
1274             "What divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1275         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1276             SYSCTL_CHILDREN(rack_tlp),
1277             OID_AUTO, "reorder_fade", CTLFLAG_RW,
1278             &rack_reorder_fade, 60000000,
1279             "Does reorder detection fade, if so how many microseconds (0 means never)");
1280         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1281             SYSCTL_CHILDREN(rack_tlp),
1282             OID_AUTO, "pktdelay", CTLFLAG_RW,
1283             &rack_pkt_delay, 1000,
1284             "Extra RACK time (in microseconds) besides reordering thresh");
1285
1286         /* Timer related controls */
1287         rack_timers = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1288             SYSCTL_CHILDREN(rack_sysctl_root),
1289             OID_AUTO,
1290             "timers",
1291             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1292             "Timer related controls");
1293         SYSCTL_ADD_U32(&rack_sysctl_ctx,
1294             SYSCTL_CHILDREN(rack_timers),
1295             OID_AUTO, "persmin", CTLFLAG_RW,
1296             &rack_persist_min, 250000,
1297             "What is the minimum time in microseconds between persists");
1298         SYSCTL_ADD_U32(&rack_sysctl_ctx,
1299             SYSCTL_CHILDREN(rack_timers),
1300             OID_AUTO, "persmax", CTLFLAG_RW,
1301             &rack_persist_max, 2000000,
1302             "What is the largest delay in microseconds between persists");
1303         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1304             SYSCTL_CHILDREN(rack_timers),
1305             OID_AUTO, "delayed_ack", CTLFLAG_RW,
1306             &rack_delayed_ack_time, 40000,
1307             "Delayed ack time (40ms in microseconds)");
1308         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1309             SYSCTL_CHILDREN(rack_timers),
1310             OID_AUTO, "minrto", CTLFLAG_RW,
1311             &rack_rto_min, 30000,
1312             "Minimum RTO in microseconds -- set with caution below 1000 due to TLP");
1313         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1314             SYSCTL_CHILDREN(rack_timers),
1315             OID_AUTO, "maxrto", CTLFLAG_RW,
1316             &rack_rto_max, 4000000,
1317             "Maximum RTO in microseconds -- should be at least as large as min_rto");
1318         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1319             SYSCTL_CHILDREN(rack_timers),
1320             OID_AUTO, "minto", CTLFLAG_RW,
1321             &rack_min_to, 1000,
1322             "Minimum rack timeout in microseconds");
1323         /* Measure controls */
1324         rack_measure = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1325             SYSCTL_CHILDREN(rack_sysctl_root),
1326             OID_AUTO,
1327             "measure",
1328             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1329             "Measure related controls");
1330         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1331             SYSCTL_CHILDREN(rack_measure),
1332             OID_AUTO, "wma_divisor", CTLFLAG_RW,
1333             &rack_wma_divisor, 8,
1334             "When doing b/w calculation what is the  divisor for the WMA");
1335         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1336             SYSCTL_CHILDREN(rack_measure),
1337             OID_AUTO, "end_cwnd", CTLFLAG_RW,
1338             &rack_cwnd_block_ends_measure, 0,
1339             "Does a cwnd just-return end the measurement window (app limited)");
1340         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1341             SYSCTL_CHILDREN(rack_measure),
1342             OID_AUTO, "end_rwnd", CTLFLAG_RW,
1343             &rack_rwnd_block_ends_measure, 0,
1344             "Does an rwnd just-return end the measurement window (app limited -- not persists)");
1345         SYSCTL_ADD_U32(&rack_sysctl_ctx,
1346             SYSCTL_CHILDREN(rack_measure),
1347             OID_AUTO, "min_target", CTLFLAG_RW,
1348             &rack_def_data_window, 20,
1349             "What is the minimum target window (in mss) for a GP measurements");
1350         SYSCTL_ADD_U32(&rack_sysctl_ctx,
1351             SYSCTL_CHILDREN(rack_measure),
1352             OID_AUTO, "goal_bdp", CTLFLAG_RW,
1353             &rack_goal_bdp, 2,
1354             "What is the goal BDP to measure");
1355         SYSCTL_ADD_U32(&rack_sysctl_ctx,
1356             SYSCTL_CHILDREN(rack_measure),
1357             OID_AUTO, "min_srtts", CTLFLAG_RW,
1358             &rack_min_srtts, 1,
1359             "What is the goal BDP to measure");
1360         SYSCTL_ADD_U32(&rack_sysctl_ctx,
1361             SYSCTL_CHILDREN(rack_measure),
1362             OID_AUTO, "min_measure_tim", CTLFLAG_RW,
1363             &rack_min_measure_usec, 0,
1364             "What is the Minimum time time for a measurement if 0, this is off");
1365         /* Features */
1366         rack_features = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1367             SYSCTL_CHILDREN(rack_sysctl_root),
1368             OID_AUTO,
1369             "features",
1370             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1371             "Feature controls");
1372         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1373             SYSCTL_CHILDREN(rack_features),
1374             OID_AUTO, "cmpack", CTLFLAG_RW,
1375             &rack_use_cmp_acks, 1,
1376             "Should RACK have LRO send compressed acks");
1377         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1378             SYSCTL_CHILDREN(rack_features),
1379             OID_AUTO, "fsb", CTLFLAG_RW,
1380             &rack_use_fsb, 1,
1381             "Should RACK use the fast send block?");
1382         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1383             SYSCTL_CHILDREN(rack_features),
1384             OID_AUTO, "rfo", CTLFLAG_RW,
1385             &rack_use_rfo, 1,
1386             "Should RACK use rack_fast_output()?");
1387         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1388             SYSCTL_CHILDREN(rack_features),
1389             OID_AUTO, "rsmrfo", CTLFLAG_RW,
1390             &rack_use_rsm_rfo, 1,
1391             "Should RACK use rack_fast_rsm_output()?");
1392         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1393             SYSCTL_CHILDREN(rack_features),
1394             OID_AUTO, "non_paced_lro_queue", CTLFLAG_RW,
1395             &rack_enable_mqueue_for_nonpaced, 0,
1396             "Should RACK use mbuf queuing for non-paced connections");
1397         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1398             SYSCTL_CHILDREN(rack_features),
1399             OID_AUTO, "hystartplusplus", CTLFLAG_RW,
1400             &rack_do_hystart, 0,
1401             "Should RACK enable HyStart++ on connections?");
1402         /* Misc rack controls */
1403         rack_misc = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1404             SYSCTL_CHILDREN(rack_sysctl_root),
1405             OID_AUTO,
1406             "misc",
1407             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1408             "Misc related controls");
1409 #ifdef TCP_ACCOUNTING
1410         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1411             SYSCTL_CHILDREN(rack_misc),
1412             OID_AUTO, "tcp_acct", CTLFLAG_RW,
1413             &rack_tcp_accounting, 0,
1414             "Should we turn on TCP accounting for all rack sessions?");
1415 #endif
1416         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1417             SYSCTL_CHILDREN(rack_misc),
1418             OID_AUTO, "apply_rtt_with_low_conf", CTLFLAG_RW,
1419             &rack_apply_rtt_with_reduced_conf, 0,
1420             "When a persist or keep-alive probe is not answered do we calculate rtt on subsequent answers?");
1421         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1422             SYSCTL_CHILDREN(rack_misc),
1423             OID_AUTO, "rack_dsack_ctl", CTLFLAG_RW,
1424             &rack_dsack_std_based, 3,
1425             "How do we process dsack with respect to rack timers, bit field, 3 is standards based?");
1426         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1427             SYSCTL_CHILDREN(rack_misc),
1428             OID_AUTO, "prr_addback_max", CTLFLAG_RW,
1429             &rack_prr_addbackmax, 2,
1430             "What is the maximum number of MSS we allow to be added back if prr can't send all its data?");
1431         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1432             SYSCTL_CHILDREN(rack_misc),
1433             OID_AUTO, "stats_gets_ms", CTLFLAG_RW,
1434             &rack_stats_gets_ms_rtt, 1,
1435             "What do we feed the stats framework (1 = ms_rtt, 0 = us_rtt, 2 = ms_rtt from hdwr, > 2 usec rtt from hdwr)?");
1436         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1437             SYSCTL_CHILDREN(rack_misc),
1438             OID_AUTO, "clientlowbuf", CTLFLAG_RW,
1439             &rack_client_low_buf, 0,
1440             "Client low buffer level (below this we are more aggressive in DGP exiting recovery (0 = off)?");
1441         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1442             SYSCTL_CHILDREN(rack_misc),
1443             OID_AUTO, "defprofile", CTLFLAG_RW,
1444             &rack_def_profile, 0,
1445             "Should RACK use a default profile (0=no, num == profile num)?");
1446         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1447             SYSCTL_CHILDREN(rack_misc),
1448             OID_AUTO, "shared_cwnd", CTLFLAG_RW,
1449             &rack_enable_shared_cwnd, 1,
1450             "Should RACK try to use the shared cwnd on connections where allowed");
1451         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1452             SYSCTL_CHILDREN(rack_misc),
1453             OID_AUTO, "limits_on_scwnd", CTLFLAG_RW,
1454             &rack_limits_scwnd, 1,
1455             "Should RACK place low end time limits on the shared cwnd feature");
1456         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1457             SYSCTL_CHILDREN(rack_misc),
1458             OID_AUTO, "iMac_dack", CTLFLAG_RW,
1459             &rack_use_imac_dack, 0,
1460             "Should RACK try to emulate iMac delayed ack");
1461         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1462             SYSCTL_CHILDREN(rack_misc),
1463             OID_AUTO, "no_prr", CTLFLAG_RW,
1464             &rack_disable_prr, 0,
1465             "Should RACK not use prr and only pace (must have pacing on)");
1466         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1467             SYSCTL_CHILDREN(rack_misc),
1468             OID_AUTO, "bb_verbose", CTLFLAG_RW,
1469             &rack_verbose_logging, 0,
1470             "Should RACK black box logging be verbose");
1471         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1472             SYSCTL_CHILDREN(rack_misc),
1473             OID_AUTO, "data_after_close", CTLFLAG_RW,
1474             &rack_ignore_data_after_close, 1,
1475             "Do we hold off sending a RST until all pending data is ack'd");
1476         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1477             SYSCTL_CHILDREN(rack_misc),
1478             OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1479             &rack_sack_not_required, 1,
1480             "Do we allow rack to run on connections not supporting SACK");
1481         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1482             SYSCTL_CHILDREN(rack_misc),
1483             OID_AUTO, "prr_sendalot", CTLFLAG_RW,
1484             &rack_send_a_lot_in_prr, 1,
1485             "Send a lot in prr");
1486         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1487             SYSCTL_CHILDREN(rack_misc),
1488             OID_AUTO, "autoscale", CTLFLAG_RW,
1489             &rack_autosndbuf_inc, 20,
1490             "What percentage should rack scale up its snd buffer by?");
1491         /* Sack Attacker detection stuff */
1492         SYSCTL_ADD_U32(&rack_sysctl_ctx,
1493             SYSCTL_CHILDREN(rack_attack),
1494             OID_AUTO, "detect_highsackratio", CTLFLAG_RW,
1495             &rack_highest_sack_thresh_seen, 0,
1496             "Highest sack to ack ratio seen");
1497         SYSCTL_ADD_U32(&rack_sysctl_ctx,
1498             SYSCTL_CHILDREN(rack_attack),
1499             OID_AUTO, "detect_highmoveratio", CTLFLAG_RW,
1500             &rack_highest_move_thresh_seen, 0,
1501             "Highest move to non-move ratio seen");
1502         rack_ack_total = counter_u64_alloc(M_WAITOK);
1503         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1504             SYSCTL_CHILDREN(rack_attack),
1505             OID_AUTO, "acktotal", CTLFLAG_RD,
1506             &rack_ack_total,
1507             "Total number of Ack's");
1508         rack_express_sack = counter_u64_alloc(M_WAITOK);
1509         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1510             SYSCTL_CHILDREN(rack_attack),
1511             OID_AUTO, "exp_sacktotal", CTLFLAG_RD,
1512             &rack_express_sack,
1513             "Total expresss number of Sack's");
1514         rack_sack_total = counter_u64_alloc(M_WAITOK);
1515         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1516             SYSCTL_CHILDREN(rack_attack),
1517             OID_AUTO, "sacktotal", CTLFLAG_RD,
1518             &rack_sack_total,
1519             "Total number of SACKs");
1520         rack_move_none = counter_u64_alloc(M_WAITOK);
1521         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1522             SYSCTL_CHILDREN(rack_attack),
1523             OID_AUTO, "move_none", CTLFLAG_RD,
1524             &rack_move_none,
1525             "Total number of SACK index reuse of positions under threshold");
1526         rack_move_some = counter_u64_alloc(M_WAITOK);
1527         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1528             SYSCTL_CHILDREN(rack_attack),
1529             OID_AUTO, "move_some", CTLFLAG_RD,
1530             &rack_move_some,
1531             "Total number of SACK index reuse of positions over threshold");
1532         rack_sack_attacks_detected = counter_u64_alloc(M_WAITOK);
1533         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1534             SYSCTL_CHILDREN(rack_attack),
1535             OID_AUTO, "attacks", CTLFLAG_RD,
1536             &rack_sack_attacks_detected,
1537             "Total number of SACK attackers that had sack disabled");
1538         rack_sack_attacks_reversed = counter_u64_alloc(M_WAITOK);
1539         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1540             SYSCTL_CHILDREN(rack_attack),
1541             OID_AUTO, "reversed", CTLFLAG_RD,
1542             &rack_sack_attacks_reversed,
1543             "Total number of SACK attackers that were later determined false positive");
1544         rack_sack_used_next_merge = counter_u64_alloc(M_WAITOK);
1545         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1546             SYSCTL_CHILDREN(rack_attack),
1547             OID_AUTO, "nextmerge", CTLFLAG_RD,
1548             &rack_sack_used_next_merge,
1549             "Total number of times we used the next merge");
1550         rack_sack_used_prev_merge = counter_u64_alloc(M_WAITOK);
1551         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1552             SYSCTL_CHILDREN(rack_attack),
1553             OID_AUTO, "prevmerge", CTLFLAG_RD,
1554             &rack_sack_used_prev_merge,
1555             "Total number of times we used the prev merge");
1556         /* Counters */
1557         rack_fto_send = counter_u64_alloc(M_WAITOK);
1558         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1559             SYSCTL_CHILDREN(rack_counters),
1560             OID_AUTO, "fto_send", CTLFLAG_RD,
1561             &rack_fto_send, "Total number of rack_fast_output sends");
1562         rack_fto_rsm_send = counter_u64_alloc(M_WAITOK);
1563         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1564             SYSCTL_CHILDREN(rack_counters),
1565             OID_AUTO, "fto_rsm_send", CTLFLAG_RD,
1566             &rack_fto_rsm_send, "Total number of rack_fast_rsm_output sends");
1567         rack_nfto_resend = counter_u64_alloc(M_WAITOK);
1568         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1569             SYSCTL_CHILDREN(rack_counters),
1570             OID_AUTO, "nfto_resend", CTLFLAG_RD,
1571             &rack_nfto_resend, "Total number of rack_output retransmissions");
1572         rack_non_fto_send = counter_u64_alloc(M_WAITOK);
1573         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1574             SYSCTL_CHILDREN(rack_counters),
1575             OID_AUTO, "nfto_send", CTLFLAG_RD,
1576             &rack_non_fto_send, "Total number of rack_output first sends");
1577         rack_extended_rfo = counter_u64_alloc(M_WAITOK);
1578         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1579             SYSCTL_CHILDREN(rack_counters),
1580             OID_AUTO, "rfo_extended", CTLFLAG_RD,
1581             &rack_extended_rfo, "Total number of times we extended rfo");
1582
1583         rack_hw_pace_init_fail = counter_u64_alloc(M_WAITOK);
1584         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1585             SYSCTL_CHILDREN(rack_counters),
1586             OID_AUTO, "hwpace_init_fail", CTLFLAG_RD,
1587             &rack_hw_pace_init_fail, "Total number of times we failed to initialize hw pacing");
1588         rack_hw_pace_lost = counter_u64_alloc(M_WAITOK);
1589
1590         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1591             SYSCTL_CHILDREN(rack_counters),
1592             OID_AUTO, "hwpace_lost", CTLFLAG_RD,
1593             &rack_hw_pace_lost, "Total number of times we failed to initialize hw pacing");
1594         rack_tlp_tot = counter_u64_alloc(M_WAITOK);
1595         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1596             SYSCTL_CHILDREN(rack_counters),
1597             OID_AUTO, "tlp_to_total", CTLFLAG_RD,
1598             &rack_tlp_tot,
1599             "Total number of tail loss probe expirations");
1600         rack_tlp_newdata = counter_u64_alloc(M_WAITOK);
1601         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1602             SYSCTL_CHILDREN(rack_counters),
1603             OID_AUTO, "tlp_new", CTLFLAG_RD,
1604             &rack_tlp_newdata,
1605             "Total number of tail loss probe sending new data");
1606         rack_tlp_retran = counter_u64_alloc(M_WAITOK);
1607         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1608             SYSCTL_CHILDREN(rack_counters),
1609             OID_AUTO, "tlp_retran", CTLFLAG_RD,
1610             &rack_tlp_retran,
1611             "Total number of tail loss probe sending retransmitted data");
1612         rack_tlp_retran_bytes = counter_u64_alloc(M_WAITOK);
1613         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1614             SYSCTL_CHILDREN(rack_counters),
1615             OID_AUTO, "tlp_retran_bytes", CTLFLAG_RD,
1616             &rack_tlp_retran_bytes,
1617             "Total bytes of tail loss probe sending retransmitted data");
1618         rack_to_tot = counter_u64_alloc(M_WAITOK);
1619         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1620             SYSCTL_CHILDREN(rack_counters),
1621             OID_AUTO, "rack_to_tot", CTLFLAG_RD,
1622             &rack_to_tot,
1623             "Total number of times the rack to expired");
1624         rack_saw_enobuf = counter_u64_alloc(M_WAITOK);
1625         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1626             SYSCTL_CHILDREN(rack_counters),
1627             OID_AUTO, "saw_enobufs", CTLFLAG_RD,
1628             &rack_saw_enobuf,
1629             "Total number of times a sends returned enobuf for non-hdwr paced connections");
1630         rack_saw_enobuf_hw = counter_u64_alloc(M_WAITOK);
1631         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1632             SYSCTL_CHILDREN(rack_counters),
1633             OID_AUTO, "saw_enobufs_hw", CTLFLAG_RD,
1634             &rack_saw_enobuf_hw,
1635             "Total number of times a send returned enobuf for hdwr paced connections");
1636         rack_saw_enetunreach = counter_u64_alloc(M_WAITOK);
1637         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1638             SYSCTL_CHILDREN(rack_counters),
1639             OID_AUTO, "saw_enetunreach", CTLFLAG_RD,
1640             &rack_saw_enetunreach,
1641             "Total number of times a send received a enetunreachable");
1642         rack_hot_alloc = counter_u64_alloc(M_WAITOK);
1643         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1644             SYSCTL_CHILDREN(rack_counters),
1645             OID_AUTO, "alloc_hot", CTLFLAG_RD,
1646             &rack_hot_alloc,
1647             "Total allocations from the top of our list");
1648         rack_to_alloc = counter_u64_alloc(M_WAITOK);
1649         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1650             SYSCTL_CHILDREN(rack_counters),
1651             OID_AUTO, "allocs", CTLFLAG_RD,
1652             &rack_to_alloc,
1653             "Total allocations of tracking structures");
1654         rack_to_alloc_hard = counter_u64_alloc(M_WAITOK);
1655         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1656             SYSCTL_CHILDREN(rack_counters),
1657             OID_AUTO, "allochard", CTLFLAG_RD,
1658             &rack_to_alloc_hard,
1659             "Total allocations done with sleeping the hard way");
1660         rack_to_alloc_emerg = counter_u64_alloc(M_WAITOK);
1661         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1662             SYSCTL_CHILDREN(rack_counters),
1663             OID_AUTO, "allocemerg", CTLFLAG_RD,
1664             &rack_to_alloc_emerg,
1665             "Total allocations done from emergency cache");
1666         rack_to_alloc_limited = counter_u64_alloc(M_WAITOK);
1667         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1668             SYSCTL_CHILDREN(rack_counters),
1669             OID_AUTO, "alloc_limited", CTLFLAG_RD,
1670             &rack_to_alloc_limited,
1671             "Total allocations dropped due to limit");
1672         rack_alloc_limited_conns = counter_u64_alloc(M_WAITOK);
1673         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1674             SYSCTL_CHILDREN(rack_counters),
1675             OID_AUTO, "alloc_limited_conns", CTLFLAG_RD,
1676             &rack_alloc_limited_conns,
1677             "Connections with allocations dropped due to limit");
1678         rack_split_limited = counter_u64_alloc(M_WAITOK);
1679         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1680             SYSCTL_CHILDREN(rack_counters),
1681             OID_AUTO, "split_limited", CTLFLAG_RD,
1682             &rack_split_limited,
1683             "Split allocations dropped due to limit");
1684         rack_persists_sends = counter_u64_alloc(M_WAITOK);
1685         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1686             SYSCTL_CHILDREN(rack_counters),
1687             OID_AUTO, "persist_sends", CTLFLAG_RD,
1688             &rack_persists_sends,
1689             "Number of times we sent a persist probe");
1690         rack_persists_acks = counter_u64_alloc(M_WAITOK);
1691         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1692             SYSCTL_CHILDREN(rack_counters),
1693             OID_AUTO, "persist_acks", CTLFLAG_RD,
1694             &rack_persists_acks,
1695             "Number of times a persist probe was acked");
1696         rack_persists_loss = counter_u64_alloc(M_WAITOK);
1697         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1698             SYSCTL_CHILDREN(rack_counters),
1699             OID_AUTO, "persist_loss", CTLFLAG_RD,
1700             &rack_persists_loss,
1701             "Number of times we detected a lost persist probe (no ack)");
1702         rack_persists_lost_ends = counter_u64_alloc(M_WAITOK);
1703         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1704             SYSCTL_CHILDREN(rack_counters),
1705             OID_AUTO, "persist_loss_ends", CTLFLAG_RD,
1706             &rack_persists_lost_ends,
1707             "Number of lost persist probe (no ack) that the run ended with a PERSIST abort");
1708 #ifdef INVARIANTS
1709         rack_adjust_map_bw = counter_u64_alloc(M_WAITOK);
1710         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1711             SYSCTL_CHILDREN(rack_counters),
1712             OID_AUTO, "map_adjust_req", CTLFLAG_RD,
1713             &rack_adjust_map_bw,
1714             "Number of times we hit the case where the sb went up and down on a sendmap entry");
1715 #endif
1716         rack_multi_single_eq = counter_u64_alloc(M_WAITOK);
1717         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1718             SYSCTL_CHILDREN(rack_counters),
1719             OID_AUTO, "cmp_ack_equiv", CTLFLAG_RD,
1720             &rack_multi_single_eq,
1721             "Number of compressed acks total represented");
1722         rack_proc_non_comp_ack = counter_u64_alloc(M_WAITOK);
1723         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1724             SYSCTL_CHILDREN(rack_counters),
1725             OID_AUTO, "cmp_ack_not", CTLFLAG_RD,
1726             &rack_proc_non_comp_ack,
1727             "Number of non compresseds acks that we processed");
1728
1729
1730         rack_sack_proc_all = counter_u64_alloc(M_WAITOK);
1731         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1732             SYSCTL_CHILDREN(rack_counters),
1733             OID_AUTO, "sack_long", CTLFLAG_RD,
1734             &rack_sack_proc_all,
1735             "Total times we had to walk whole list for sack processing");
1736         rack_sack_proc_restart = counter_u64_alloc(M_WAITOK);
1737         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1738             SYSCTL_CHILDREN(rack_counters),
1739             OID_AUTO, "sack_restart", CTLFLAG_RD,
1740             &rack_sack_proc_restart,
1741             "Total times we had to walk whole list due to a restart");
1742         rack_sack_proc_short = counter_u64_alloc(M_WAITOK);
1743         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1744             SYSCTL_CHILDREN(rack_counters),
1745             OID_AUTO, "sack_short", CTLFLAG_RD,
1746             &rack_sack_proc_short,
1747             "Total times we took shortcut for sack processing");
1748         rack_sack_skipped_acked = counter_u64_alloc(M_WAITOK);
1749         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1750             SYSCTL_CHILDREN(rack_attack),
1751             OID_AUTO, "skipacked", CTLFLAG_RD,
1752             &rack_sack_skipped_acked,
1753             "Total number of times we skipped previously sacked");
1754         rack_sack_splits = counter_u64_alloc(M_WAITOK);
1755         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1756             SYSCTL_CHILDREN(rack_attack),
1757             OID_AUTO, "ofsplit", CTLFLAG_RD,
1758             &rack_sack_splits,
1759             "Total number of times we did the old fashion tree split");
1760         rack_input_idle_reduces = counter_u64_alloc(M_WAITOK);
1761         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1762             SYSCTL_CHILDREN(rack_counters),
1763             OID_AUTO, "idle_reduce_oninput", CTLFLAG_RD,
1764             &rack_input_idle_reduces,
1765             "Total number of idle reductions on input");
1766         rack_collapsed_win_seen = counter_u64_alloc(M_WAITOK);
1767         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1768             SYSCTL_CHILDREN(rack_counters),
1769             OID_AUTO, "collapsed_win_seen", CTLFLAG_RD,
1770             &rack_collapsed_win_seen,
1771             "Total number of collapsed window events seen (where our window shrinks)");
1772
1773         rack_collapsed_win = counter_u64_alloc(M_WAITOK);
1774         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1775             SYSCTL_CHILDREN(rack_counters),
1776             OID_AUTO, "collapsed_win", CTLFLAG_RD,
1777             &rack_collapsed_win,
1778             "Total number of collapsed window events where we mark packets");
1779         rack_collapsed_win_rxt = counter_u64_alloc(M_WAITOK);
1780         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1781             SYSCTL_CHILDREN(rack_counters),
1782             OID_AUTO, "collapsed_win_rxt", CTLFLAG_RD,
1783             &rack_collapsed_win_rxt,
1784             "Total number of packets that were retransmitted");
1785         rack_collapsed_win_rxt_bytes = counter_u64_alloc(M_WAITOK);
1786         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1787             SYSCTL_CHILDREN(rack_counters),
1788             OID_AUTO, "collapsed_win_bytes", CTLFLAG_RD,
1789             &rack_collapsed_win_rxt_bytes,
1790             "Total number of bytes that were retransmitted");
1791         rack_try_scwnd = counter_u64_alloc(M_WAITOK);
1792         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1793             SYSCTL_CHILDREN(rack_counters),
1794             OID_AUTO, "tried_scwnd", CTLFLAG_RD,
1795             &rack_try_scwnd,
1796             "Total number of scwnd attempts");
1797         COUNTER_ARRAY_ALLOC(rack_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1798         SYSCTL_ADD_COUNTER_U64_ARRAY(&rack_sysctl_ctx, SYSCTL_CHILDREN(rack_sysctl_root),
1799             OID_AUTO, "outsize", CTLFLAG_RD,
1800             rack_out_size, TCP_MSS_ACCT_SIZE, "MSS send sizes");
1801         COUNTER_ARRAY_ALLOC(rack_opts_arry, RACK_OPTS_SIZE, M_WAITOK);
1802         SYSCTL_ADD_COUNTER_U64_ARRAY(&rack_sysctl_ctx, SYSCTL_CHILDREN(rack_sysctl_root),
1803             OID_AUTO, "opts", CTLFLAG_RD,
1804             rack_opts_arry, RACK_OPTS_SIZE, "RACK Option Stats");
1805         SYSCTL_ADD_PROC(&rack_sysctl_ctx,
1806             SYSCTL_CHILDREN(rack_sysctl_root),
1807             OID_AUTO, "clear", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1808             &rack_clear_counter, 0, sysctl_rack_clear, "IU", "Clear counters");
1809 }
1810
1811 static __inline int
1812 rb_map_cmp(struct rack_sendmap *b, struct rack_sendmap *a)
1813 {
1814         if (SEQ_GEQ(b->r_start, a->r_start) &&
1815             SEQ_LT(b->r_start, a->r_end)) {
1816                 /*
1817                  * The entry b is within the
1818                  * block a. i.e.:
1819                  * a --   |-------------|
1820                  * b --   |----|
1821                  * <or>
1822                  * b --       |------|
1823                  * <or>
1824                  * b --       |-----------|
1825                  */
1826                 return (0);
1827         } else if (SEQ_GEQ(b->r_start, a->r_end)) {
1828                 /*
1829                  * b falls as either the next
1830                  * sequence block after a so a
1831                  * is said to be smaller than b.
1832                  * i.e:
1833                  * a --   |------|
1834                  * b --          |--------|
1835                  * or
1836                  * b --              |-----|
1837                  */
1838                 return (1);
1839         }
1840         /*
1841          * Whats left is where a is
1842          * larger than b. i.e:
1843          * a --         |-------|
1844          * b --  |---|
1845          * or even possibly
1846          * b --   |--------------|
1847          */
1848         return (-1);
1849 }
1850
1851 RB_PROTOTYPE(rack_rb_tree_head, rack_sendmap, r_next, rb_map_cmp);
1852 RB_GENERATE(rack_rb_tree_head, rack_sendmap, r_next, rb_map_cmp);
1853
1854 static uint32_t
1855 rc_init_window(struct tcp_rack *rack)
1856 {
1857         uint32_t win;
1858
1859         if (rack->rc_init_win == 0) {
1860                 /*
1861                  * Nothing set by the user, use the system stack
1862                  * default.
1863                  */
1864                 return (tcp_compute_initwnd(tcp_maxseg(rack->rc_tp)));
1865         }
1866         win = ctf_fixed_maxseg(rack->rc_tp) * rack->rc_init_win;
1867         return (win);
1868 }
1869
1870 static uint64_t
1871 rack_get_fixed_pacing_bw(struct tcp_rack *rack)
1872 {
1873         if (IN_FASTRECOVERY(rack->rc_tp->t_flags))
1874                 return (rack->r_ctl.rc_fixed_pacing_rate_rec);
1875         else if (rack->r_ctl.cwnd_to_use < rack->rc_tp->snd_ssthresh)
1876                 return (rack->r_ctl.rc_fixed_pacing_rate_ss);
1877         else
1878                 return (rack->r_ctl.rc_fixed_pacing_rate_ca);
1879 }
1880
1881 static uint64_t
1882 rack_get_bw(struct tcp_rack *rack)
1883 {
1884         if (rack->use_fixed_rate) {
1885                 /* Return the fixed pacing rate */
1886                 return (rack_get_fixed_pacing_bw(rack));
1887         }
1888         if (rack->r_ctl.gp_bw == 0) {
1889                 /*
1890                  * We have yet no b/w measurement,
1891                  * if we have a user set initial bw
1892                  * return it. If we don't have that and
1893                  * we have an srtt, use the tcp IW (10) to
1894                  * calculate a fictional b/w over the SRTT
1895                  * which is more or less a guess. Note
1896                  * we don't use our IW from rack on purpose
1897                  * so if we have like IW=30, we are not
1898                  * calculating a "huge" b/w.
1899                  */
1900                 uint64_t bw, srtt;
1901                 if (rack->r_ctl.init_rate)
1902                         return (rack->r_ctl.init_rate);
1903
1904                 /* Has the user set a max peak rate? */
1905 #ifdef NETFLIX_PEAKRATE
1906                 if (rack->rc_tp->t_maxpeakrate)
1907                         return (rack->rc_tp->t_maxpeakrate);
1908 #endif
1909                 /* Ok lets come up with the IW guess, if we have a srtt */
1910                 if (rack->rc_tp->t_srtt == 0) {
1911                         /*
1912                          * Go with old pacing method
1913                          * i.e. burst mitigation only.
1914                          */
1915                         return (0);
1916                 }
1917                 /* Ok lets get the initial TCP win (not racks) */
1918                 bw = tcp_compute_initwnd(tcp_maxseg(rack->rc_tp));
1919                 srtt = (uint64_t)rack->rc_tp->t_srtt;
1920                 bw *= (uint64_t)USECS_IN_SECOND;
1921                 bw /= srtt;
1922                 if (rack->r_ctl.bw_rate_cap && (bw > rack->r_ctl.bw_rate_cap))
1923                         bw = rack->r_ctl.bw_rate_cap;
1924                 return (bw);
1925         } else {
1926                 uint64_t bw;
1927
1928                 if (rack->r_ctl.num_measurements >= RACK_REQ_AVG) {
1929                         /* Averaging is done, we can return the value */
1930                         bw = rack->r_ctl.gp_bw;
1931                 } else {
1932                         /* Still doing initial average must calculate */
1933                         bw = rack->r_ctl.gp_bw / rack->r_ctl.num_measurements;
1934                 }
1935 #ifdef NETFLIX_PEAKRATE
1936                 if ((rack->rc_tp->t_maxpeakrate) &&
1937                     (bw > rack->rc_tp->t_maxpeakrate)) {
1938                         /* The user has set a peak rate to pace at
1939                          * don't allow us to pace faster than that.
1940                          */
1941                         return (rack->rc_tp->t_maxpeakrate);
1942                 }
1943 #endif
1944                 if (rack->r_ctl.bw_rate_cap && (bw > rack->r_ctl.bw_rate_cap))
1945                         bw = rack->r_ctl.bw_rate_cap;
1946                 return (bw);
1947         }
1948 }
1949
1950 static uint16_t
1951 rack_get_output_gain(struct tcp_rack *rack, struct rack_sendmap *rsm)
1952 {
1953         if (rack->use_fixed_rate) {
1954                 return (100);
1955         } else if (rack->in_probe_rtt && (rsm == NULL))
1956                 return (rack->r_ctl.rack_per_of_gp_probertt);
1957         else if ((IN_FASTRECOVERY(rack->rc_tp->t_flags) &&
1958                   rack->r_ctl.rack_per_of_gp_rec)) {
1959                 if (rsm) {
1960                         /* a retransmission always use the recovery rate */
1961                         return (rack->r_ctl.rack_per_of_gp_rec);
1962                 } else if (rack->rack_rec_nonrxt_use_cr) {
1963                         /* Directed to use the configured rate */
1964                         goto configured_rate;
1965                 } else if (rack->rack_no_prr &&
1966                            (rack->r_ctl.rack_per_of_gp_rec > 100)) {
1967                         /* No PRR, lets just use the b/w estimate only */
1968                         return (100);
1969                 } else {
1970                         /*
1971                          * Here we may have a non-retransmit but we
1972                          * have no overrides, so just use the recovery
1973                          * rate (prr is in effect).
1974                          */
1975                         return (rack->r_ctl.rack_per_of_gp_rec);
1976                 }
1977         }
1978 configured_rate:
1979         /* For the configured rate we look at our cwnd vs the ssthresh */
1980         if (rack->r_ctl.cwnd_to_use < rack->rc_tp->snd_ssthresh)
1981                 return (rack->r_ctl.rack_per_of_gp_ss);
1982         else
1983                 return (rack->r_ctl.rack_per_of_gp_ca);
1984 }
1985
1986 static void
1987 rack_log_dsack_event(struct tcp_rack *rack, uint8_t mod, uint32_t flex4, uint32_t flex5, uint32_t flex6)
1988 {
1989         /*
1990          * Types of logs (mod value)
1991          * 1 = dsack_persists reduced by 1 via T-O or fast recovery exit.
1992          * 2 = a dsack round begins, persist is reset to 16.
1993          * 3 = a dsack round ends
1994          * 4 = Dsack option increases rack rtt flex5 is the srtt input, flex6 is thresh
1995          * 5 = Socket option set changing the control flags rc_rack_tmr_std_based, rc_rack_use_dsack
1996          * 6 = Final rack rtt, flex4 is srtt and flex6 is final limited thresh.
1997          */
1998         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1999                 union tcp_log_stackspecific log;
2000                 struct timeval tv;
2001
2002                 memset(&log, 0, sizeof(log));
2003                 log.u_bbr.flex1 = rack->rc_rack_tmr_std_based;
2004                 log.u_bbr.flex1 <<= 1;
2005                 log.u_bbr.flex1 |= rack->rc_rack_use_dsack;
2006                 log.u_bbr.flex1 <<= 1;
2007                 log.u_bbr.flex1 |= rack->rc_dsack_round_seen;
2008                 log.u_bbr.flex2 = rack->r_ctl.dsack_round_end;
2009                 log.u_bbr.flex3 = rack->r_ctl.num_dsack;
2010                 log.u_bbr.flex4 = flex4;
2011                 log.u_bbr.flex5 = flex5;
2012                 log.u_bbr.flex6 = flex6;
2013                 log.u_bbr.flex7 = rack->r_ctl.dsack_persist;
2014                 log.u_bbr.flex8 = mod;
2015                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2016                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2017                     &rack->rc_inp->inp_socket->so_rcv,
2018                     &rack->rc_inp->inp_socket->so_snd,
2019                     RACK_DSACK_HANDLING, 0,
2020                     0, &log, false, &tv);
2021         }
2022 }
2023
2024 static void
2025 rack_log_hdwr_pacing(struct tcp_rack *rack,
2026                      uint64_t rate, uint64_t hw_rate, int line,
2027                      int error, uint16_t mod)
2028 {
2029         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2030                 union tcp_log_stackspecific log;
2031                 struct timeval tv;
2032                 const struct ifnet *ifp;
2033
2034                 memset(&log, 0, sizeof(log));
2035                 log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2036                 log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2037                 if (rack->r_ctl.crte) {
2038                         ifp = rack->r_ctl.crte->ptbl->rs_ifp;
2039                 } else if (rack->rc_inp->inp_route.ro_nh &&
2040                            rack->rc_inp->inp_route.ro_nh->nh_ifp) {
2041                         ifp = rack->rc_inp->inp_route.ro_nh->nh_ifp;
2042                 } else
2043                         ifp = NULL;
2044                 if (ifp) {
2045                         log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2046                         log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2047                 }
2048                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2049                 log.u_bbr.bw_inuse = rate;
2050                 log.u_bbr.flex5 = line;
2051                 log.u_bbr.flex6 = error;
2052                 log.u_bbr.flex7 = mod;
2053                 log.u_bbr.applimited = rack->r_ctl.rc_pace_max_segs;
2054                 log.u_bbr.flex8 = rack->use_fixed_rate;
2055                 log.u_bbr.flex8 <<= 1;
2056                 log.u_bbr.flex8 |= rack->rack_hdrw_pacing;
2057                 log.u_bbr.pkts_out = rack->rc_tp->t_maxseg;
2058                 log.u_bbr.delRate = rack->r_ctl.crte_prev_rate;
2059                 if (rack->r_ctl.crte)
2060                         log.u_bbr.cur_del_rate = rack->r_ctl.crte->rate;
2061                 else
2062                         log.u_bbr.cur_del_rate = 0;
2063                 log.u_bbr.rttProp = rack->r_ctl.last_hw_bw_req;
2064                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2065                     &rack->rc_inp->inp_socket->so_rcv,
2066                     &rack->rc_inp->inp_socket->so_snd,
2067                     BBR_LOG_HDWR_PACE, 0,
2068                     0, &log, false, &tv);
2069         }
2070 }
2071
2072 static uint64_t
2073 rack_get_output_bw(struct tcp_rack *rack, uint64_t bw, struct rack_sendmap *rsm, int *capped)
2074 {
2075         /*
2076          * We allow rack_per_of_gp_xx to dictate our bw rate we want.
2077          */
2078         uint64_t bw_est, high_rate;
2079         uint64_t gain;
2080
2081         gain = (uint64_t)rack_get_output_gain(rack, rsm);
2082         bw_est = bw * gain;
2083         bw_est /= (uint64_t)100;
2084         /* Never fall below the minimum (def 64kbps) */
2085         if (bw_est < RACK_MIN_BW)
2086                 bw_est = RACK_MIN_BW;
2087         if (rack->r_rack_hw_rate_caps) {
2088                 /* Rate caps are in place */
2089                 if (rack->r_ctl.crte != NULL) {
2090                         /* We have a hdwr rate already */
2091                         high_rate = tcp_hw_highest_rate(rack->r_ctl.crte);
2092                         if (bw_est >= high_rate) {
2093                                 /* We are capping bw at the highest rate table entry */
2094                                 rack_log_hdwr_pacing(rack,
2095                                                      bw_est, high_rate, __LINE__,
2096                                                      0, 3);
2097                                 bw_est = high_rate;
2098                                 if (capped)
2099                                         *capped = 1;
2100                         }
2101                 } else if ((rack->rack_hdrw_pacing == 0) &&
2102                            (rack->rack_hdw_pace_ena) &&
2103                            (rack->rack_attempt_hdwr_pace == 0) &&
2104                            (rack->rc_inp->inp_route.ro_nh != NULL) &&
2105                            (rack->rc_inp->inp_route.ro_nh->nh_ifp != NULL)) {
2106                         /*
2107                          * Special case, we have not yet attempted hardware
2108                          * pacing, and yet we may, when we do, find out if we are
2109                          * above the highest rate. We need to know the maxbw for the interface
2110                          * in question (if it supports ratelimiting). We get back
2111                          * a 0, if the interface is not found in the RL lists.
2112                          */
2113                         high_rate = tcp_hw_highest_rate_ifp(rack->rc_inp->inp_route.ro_nh->nh_ifp, rack->rc_inp);
2114                         if (high_rate) {
2115                                 /* Yep, we have a rate is it above this rate? */
2116                                 if (bw_est > high_rate) {
2117                                         bw_est = high_rate;
2118                                         if (capped)
2119                                                 *capped = 1;
2120                                 }
2121                         }
2122                 }
2123         }
2124         return (bw_est);
2125 }
2126
2127 static void
2128 rack_log_retran_reason(struct tcp_rack *rack, struct rack_sendmap *rsm, uint32_t tsused, uint32_t thresh, int mod)
2129 {
2130         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2131                 union tcp_log_stackspecific log;
2132                 struct timeval tv;
2133
2134                 if ((mod != 1) && (rack_verbose_logging == 0)) {
2135                         /*
2136                          * We get 3 values currently for mod
2137                          * 1 - We are retransmitting and this tells the reason.
2138                          * 2 - We are clearing a dup-ack count.
2139                          * 3 - We are incrementing a dup-ack count.
2140                          *
2141                          * The clear/increment are only logged
2142                          * if you have BBverbose on.
2143                          */
2144                         return;
2145                 }
2146                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2147                 log.u_bbr.flex1 = tsused;
2148                 log.u_bbr.flex2 = thresh;
2149                 log.u_bbr.flex3 = rsm->r_flags;
2150                 log.u_bbr.flex4 = rsm->r_dupack;
2151                 log.u_bbr.flex5 = rsm->r_start;
2152                 log.u_bbr.flex6 = rsm->r_end;
2153                 log.u_bbr.flex8 = mod;
2154                 log.u_bbr.inhpts = tcp_in_hpts(rack->rc_inp);
2155                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2156                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2157                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2158                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2159                 log.u_bbr.pacing_gain = rack->r_must_retran;
2160                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2161                     &rack->rc_inp->inp_socket->so_rcv,
2162                     &rack->rc_inp->inp_socket->so_snd,
2163                     BBR_LOG_SETTINGS_CHG, 0,
2164                     0, &log, false, &tv);
2165         }
2166 }
2167
2168 static void
2169 rack_log_to_start(struct tcp_rack *rack, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2170 {
2171         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2172                 union tcp_log_stackspecific log;
2173                 struct timeval tv;
2174
2175                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2176                 log.u_bbr.flex1 = rack->rc_tp->t_srtt;
2177                 log.u_bbr.flex2 = to;
2178                 log.u_bbr.flex3 = rack->r_ctl.rc_hpts_flags;
2179                 log.u_bbr.flex4 = slot;
2180                 log.u_bbr.flex5 = rack->rc_inp->inp_hptsslot;
2181                 log.u_bbr.flex6 = rack->rc_tp->t_rxtcur;
2182                 log.u_bbr.flex7 = rack->rc_in_persist;
2183                 log.u_bbr.flex8 = which;
2184                 if (rack->rack_no_prr)
2185                         log.u_bbr.pkts_out = 0;
2186                 else
2187                         log.u_bbr.pkts_out = rack->r_ctl.rc_prr_sndcnt;
2188                 log.u_bbr.inhpts = tcp_in_hpts(rack->rc_inp);
2189                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2190                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2191                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2192                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2193                 log.u_bbr.pacing_gain = rack->r_must_retran;
2194                 log.u_bbr.cwnd_gain = rack->rc_has_collapsed;
2195                 log.u_bbr.lt_epoch = rack->rc_tp->t_rxtshift;
2196                 log.u_bbr.lost = rack_rto_min;
2197                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2198                     &rack->rc_inp->inp_socket->so_rcv,
2199                     &rack->rc_inp->inp_socket->so_snd,
2200                     BBR_LOG_TIMERSTAR, 0,
2201                     0, &log, false, &tv);
2202         }
2203 }
2204
2205 static void
2206 rack_log_to_event(struct tcp_rack *rack, int32_t to_num, struct rack_sendmap *rsm)
2207 {
2208         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2209                 union tcp_log_stackspecific log;
2210                 struct timeval tv;
2211
2212                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2213                 log.u_bbr.inhpts = tcp_in_hpts(rack->rc_inp);
2214                 log.u_bbr.flex8 = to_num;
2215                 log.u_bbr.flex1 = rack->r_ctl.rc_rack_min_rtt;
2216                 log.u_bbr.flex2 = rack->rc_rack_rtt;
2217                 if (rsm == NULL)
2218                         log.u_bbr.flex3 = 0;
2219                 else
2220                         log.u_bbr.flex3 = rsm->r_end - rsm->r_start;
2221                 if (rack->rack_no_prr)
2222                         log.u_bbr.flex5 = 0;
2223                 else
2224                         log.u_bbr.flex5 = rack->r_ctl.rc_prr_sndcnt;
2225                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2226                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2227                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2228                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2229                 log.u_bbr.pacing_gain = rack->r_must_retran;
2230                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2231                     &rack->rc_inp->inp_socket->so_rcv,
2232                     &rack->rc_inp->inp_socket->so_snd,
2233                     BBR_LOG_RTO, 0,
2234                     0, &log, false, &tv);
2235         }
2236 }
2237
2238 static void
2239 rack_log_map_chg(struct tcpcb *tp, struct tcp_rack *rack,
2240                  struct rack_sendmap *prev,
2241                  struct rack_sendmap *rsm,
2242                  struct rack_sendmap *next,
2243                  int flag, uint32_t th_ack, int line)
2244 {
2245         if (rack_verbose_logging && (tp->t_logstate != TCP_LOG_STATE_OFF)) {
2246                 union tcp_log_stackspecific log;
2247                 struct timeval tv;
2248
2249                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2250                 log.u_bbr.flex8 = flag;
2251                 log.u_bbr.inhpts = tcp_in_hpts(rack->rc_inp);
2252                 log.u_bbr.cur_del_rate = (uint64_t)prev;
2253                 log.u_bbr.delRate = (uint64_t)rsm;
2254                 log.u_bbr.rttProp = (uint64_t)next;
2255                 log.u_bbr.flex7 = 0;
2256                 if (prev) {
2257                         log.u_bbr.flex1 = prev->r_start;
2258                         log.u_bbr.flex2 = prev->r_end;
2259                         log.u_bbr.flex7 |= 0x4;
2260                 }
2261                 if (rsm) {
2262                         log.u_bbr.flex3 = rsm->r_start;
2263                         log.u_bbr.flex4 = rsm->r_end;
2264                         log.u_bbr.flex7 |= 0x2;
2265                 }
2266                 if (next) {
2267                         log.u_bbr.flex5 = next->r_start;
2268                         log.u_bbr.flex6 = next->r_end;
2269                         log.u_bbr.flex7 |= 0x1;
2270                 }
2271                 log.u_bbr.applimited = line;
2272                 log.u_bbr.pkts_out = th_ack;
2273                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2274                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2275                 if (rack->rack_no_prr)
2276                         log.u_bbr.lost = 0;
2277                 else
2278                         log.u_bbr.lost = rack->r_ctl.rc_prr_sndcnt;
2279                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2280                     &rack->rc_inp->inp_socket->so_rcv,
2281                     &rack->rc_inp->inp_socket->so_snd,
2282                     TCP_LOG_MAPCHG, 0,
2283                     0, &log, false, &tv);
2284         }
2285 }
2286
2287 static void
2288 rack_log_rtt_upd(struct tcpcb *tp, struct tcp_rack *rack, uint32_t t, uint32_t len,
2289                  struct rack_sendmap *rsm, int conf)
2290 {
2291         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
2292                 union tcp_log_stackspecific log;
2293                 struct timeval tv;
2294                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2295                 log.u_bbr.inhpts = tcp_in_hpts(rack->rc_inp);
2296                 log.u_bbr.flex1 = t;
2297                 log.u_bbr.flex2 = len;
2298                 log.u_bbr.flex3 = rack->r_ctl.rc_rack_min_rtt;
2299                 log.u_bbr.flex4 = rack->r_ctl.rack_rs.rs_rtt_lowest;
2300                 log.u_bbr.flex5 = rack->r_ctl.rack_rs.rs_rtt_highest;
2301                 log.u_bbr.flex6 = rack->r_ctl.rack_rs.rs_us_rtrcnt;
2302                 log.u_bbr.flex7 = conf;
2303                 log.u_bbr.rttProp = (uint64_t)rack->r_ctl.rack_rs.rs_rtt_tot;
2304                 log.u_bbr.flex8 = rack->r_ctl.rc_rate_sample_method;
2305                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2306                 log.u_bbr.delivered = rack->r_ctl.rack_rs.rs_us_rtrcnt;
2307                 log.u_bbr.pkts_out = rack->r_ctl.rack_rs.rs_flags;
2308                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2309                 if (rsm) {
2310                         log.u_bbr.pkt_epoch = rsm->r_start;
2311                         log.u_bbr.lost = rsm->r_end;
2312                         log.u_bbr.cwnd_gain = rsm->r_rtr_cnt;
2313                         /* We loose any upper of the 24 bits */
2314                         log.u_bbr.pacing_gain = (uint16_t)rsm->r_flags;
2315                 } else {
2316                         /* Its a SYN */
2317                         log.u_bbr.pkt_epoch = rack->rc_tp->iss;
2318                         log.u_bbr.lost = 0;
2319                         log.u_bbr.cwnd_gain = 0;
2320                         log.u_bbr.pacing_gain = 0;
2321                 }
2322                 /* Write out general bits of interest rrs here */
2323                 log.u_bbr.use_lt_bw = rack->rc_highly_buffered;
2324                 log.u_bbr.use_lt_bw <<= 1;
2325                 log.u_bbr.use_lt_bw |= rack->forced_ack;
2326                 log.u_bbr.use_lt_bw <<= 1;
2327                 log.u_bbr.use_lt_bw |= rack->rc_gp_dyn_mul;
2328                 log.u_bbr.use_lt_bw <<= 1;
2329                 log.u_bbr.use_lt_bw |= rack->in_probe_rtt;
2330                 log.u_bbr.use_lt_bw <<= 1;
2331                 log.u_bbr.use_lt_bw |= rack->measure_saw_probe_rtt;
2332                 log.u_bbr.use_lt_bw <<= 1;
2333                 log.u_bbr.use_lt_bw |= rack->app_limited_needs_set;
2334                 log.u_bbr.use_lt_bw <<= 1;
2335                 log.u_bbr.use_lt_bw |= rack->rc_gp_filled;
2336                 log.u_bbr.use_lt_bw <<= 1;
2337                 log.u_bbr.use_lt_bw |= rack->rc_dragged_bottom;
2338                 log.u_bbr.applimited = rack->r_ctl.rc_target_probertt_flight;
2339                 log.u_bbr.epoch = rack->r_ctl.rc_time_probertt_starts;
2340                 log.u_bbr.lt_epoch = rack->r_ctl.rc_time_probertt_entered;
2341                 log.u_bbr.cur_del_rate = rack->r_ctl.rc_lower_rtt_us_cts;
2342                 log.u_bbr.delRate = rack->r_ctl.rc_gp_srtt;
2343                 log.u_bbr.bw_inuse = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
2344                 log.u_bbr.bw_inuse <<= 32;
2345                 if (rsm)
2346                         log.u_bbr.bw_inuse |= ((uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
2347                 TCP_LOG_EVENTP(tp, NULL,
2348                     &rack->rc_inp->inp_socket->so_rcv,
2349                     &rack->rc_inp->inp_socket->so_snd,
2350                     BBR_LOG_BBRRTT, 0,
2351                     0, &log, false, &tv);
2352
2353
2354         }
2355 }
2356
2357 static void
2358 rack_log_rtt_sample(struct tcp_rack *rack, uint32_t rtt)
2359 {
2360         /*
2361          * Log the rtt sample we are
2362          * applying to the srtt algorithm in
2363          * useconds.
2364          */
2365         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2366                 union tcp_log_stackspecific log;
2367                 struct timeval tv;
2368
2369                 /* Convert our ms to a microsecond */
2370                 memset(&log, 0, sizeof(log));
2371                 log.u_bbr.flex1 = rtt;
2372                 log.u_bbr.flex2 = rack->r_ctl.ack_count;
2373                 log.u_bbr.flex3 = rack->r_ctl.sack_count;
2374                 log.u_bbr.flex4 = rack->r_ctl.sack_noextra_move;
2375                 log.u_bbr.flex5 = rack->r_ctl.sack_moved_extra;
2376                 log.u_bbr.flex6 = rack->rc_tp->t_rxtcur;
2377                 log.u_bbr.flex7 = 1;
2378                 log.u_bbr.flex8 = rack->sack_attack_disable;
2379                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2380                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2381                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2382                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2383                 log.u_bbr.pacing_gain = rack->r_must_retran;
2384                 /*
2385                  * We capture in delRate the upper 32 bits as
2386                  * the confidence level we had declared, and the
2387                  * lower 32 bits as the actual RTT using the arrival
2388                  * timestamp.
2389                  */
2390                 log.u_bbr.delRate = rack->r_ctl.rack_rs.confidence;
2391                 log.u_bbr.delRate <<= 32;
2392                 log.u_bbr.delRate |= rack->r_ctl.rack_rs.rs_us_rtt;
2393                 /* Lets capture all the things that make up t_rtxcur */
2394                 log.u_bbr.applimited = rack_rto_min;
2395                 log.u_bbr.epoch = rack_rto_max;
2396                 log.u_bbr.lt_epoch = rack->r_ctl.timer_slop;
2397                 log.u_bbr.lost = rack_rto_min;
2398                 log.u_bbr.pkt_epoch = TICKS_2_USEC(tcp_rexmit_slop);
2399                 log.u_bbr.rttProp = RACK_REXMTVAL(rack->rc_tp);
2400                 log.u_bbr.bw_inuse = rack->r_ctl.act_rcv_time.tv_sec;
2401                 log.u_bbr.bw_inuse *= HPTS_USEC_IN_SEC;
2402                 log.u_bbr.bw_inuse += rack->r_ctl.act_rcv_time.tv_usec;
2403                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2404                     &rack->rc_inp->inp_socket->so_rcv,
2405                     &rack->rc_inp->inp_socket->so_snd,
2406                     TCP_LOG_RTT, 0,
2407                     0, &log, false, &tv);
2408         }
2409 }
2410
2411 static void
2412 rack_log_rtt_sample_calc(struct tcp_rack *rack, uint32_t rtt, uint32_t send_time, uint32_t ack_time, int where)
2413 {
2414         if (rack_verbose_logging && (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2415                 union tcp_log_stackspecific log;
2416                 struct timeval tv;
2417
2418                 /* Convert our ms to a microsecond */
2419                 memset(&log, 0, sizeof(log));
2420                 log.u_bbr.flex1 = rtt;
2421                 log.u_bbr.flex2 = send_time;
2422                 log.u_bbr.flex3 = ack_time;
2423                 log.u_bbr.flex4 = where;
2424                 log.u_bbr.flex7 = 2;
2425                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2426                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2427                     &rack->rc_inp->inp_socket->so_rcv,
2428                     &rack->rc_inp->inp_socket->so_snd,
2429                     TCP_LOG_RTT, 0,
2430                     0, &log, false, &tv);
2431         }
2432 }
2433
2434
2435
2436 static inline void
2437 rack_log_progress_event(struct tcp_rack *rack, struct tcpcb *tp, uint32_t tick,  int event, int line)
2438 {
2439         if (rack_verbose_logging && (tp->t_logstate != TCP_LOG_STATE_OFF)) {
2440                 union tcp_log_stackspecific log;
2441                 struct timeval tv;
2442
2443                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2444                 log.u_bbr.inhpts = tcp_in_hpts(rack->rc_inp);
2445                 log.u_bbr.flex1 = line;
2446                 log.u_bbr.flex2 = tick;
2447                 log.u_bbr.flex3 = tp->t_maxunacktime;
2448                 log.u_bbr.flex4 = tp->t_acktime;
2449                 log.u_bbr.flex8 = event;
2450                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2451                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2452                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2453                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2454                 log.u_bbr.pacing_gain = rack->r_must_retran;
2455                 TCP_LOG_EVENTP(tp, NULL,
2456                     &rack->rc_inp->inp_socket->so_rcv,
2457                     &rack->rc_inp->inp_socket->so_snd,
2458                     BBR_LOG_PROGRESS, 0,
2459                     0, &log, false, &tv);
2460         }
2461 }
2462
2463 static void
2464 rack_log_type_bbrsnd(struct tcp_rack *rack, uint32_t len, uint32_t slot, uint32_t cts, struct timeval *tv)
2465 {
2466         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2467                 union tcp_log_stackspecific log;
2468
2469                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2470                 log.u_bbr.inhpts = tcp_in_hpts(rack->rc_inp);
2471                 log.u_bbr.flex1 = slot;
2472                 if (rack->rack_no_prr)
2473                         log.u_bbr.flex2 = 0;
2474                 else
2475                         log.u_bbr.flex2 = rack->r_ctl.rc_prr_sndcnt;
2476                 log.u_bbr.flex7 = (0x0000ffff & rack->r_ctl.rc_hpts_flags);
2477                 log.u_bbr.flex8 = rack->rc_in_persist;
2478                 log.u_bbr.timeStamp = cts;
2479                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2480                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2481                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2482                 log.u_bbr.pacing_gain = rack->r_must_retran;
2483                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2484                     &rack->rc_inp->inp_socket->so_rcv,
2485                     &rack->rc_inp->inp_socket->so_snd,
2486                     BBR_LOG_BBRSND, 0,
2487                     0, &log, false, tv);
2488         }
2489 }
2490
2491 static void
2492 rack_log_doseg_done(struct tcp_rack *rack, uint32_t cts, int32_t nxt_pkt, int32_t did_out, int way_out, int nsegs)
2493 {
2494         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2495                 union tcp_log_stackspecific log;
2496                 struct timeval tv;
2497
2498                 memset(&log, 0, sizeof(log));
2499                 log.u_bbr.flex1 = did_out;
2500                 log.u_bbr.flex2 = nxt_pkt;
2501                 log.u_bbr.flex3 = way_out;
2502                 log.u_bbr.flex4 = rack->r_ctl.rc_hpts_flags;
2503                 if (rack->rack_no_prr)
2504                         log.u_bbr.flex5 = 0;
2505                 else
2506                         log.u_bbr.flex5 = rack->r_ctl.rc_prr_sndcnt;
2507                 log.u_bbr.flex6 = nsegs;
2508                 log.u_bbr.applimited = rack->r_ctl.rc_pace_min_segs;
2509                 log.u_bbr.flex7 = rack->rc_ack_can_sendout_data;        /* Do we have ack-can-send set */
2510                 log.u_bbr.flex7 <<= 1;
2511                 log.u_bbr.flex7 |= rack->r_fast_output; /* is fast output primed */
2512                 log.u_bbr.flex7 <<= 1;
2513                 log.u_bbr.flex7 |= rack->r_wanted_output;       /* Do we want output */
2514                 log.u_bbr.flex8 = rack->rc_in_persist;
2515                 log.u_bbr.inhpts = tcp_in_hpts(rack->rc_inp);
2516                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2517                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2518                 log.u_bbr.use_lt_bw = rack->r_ent_rec_ns;
2519                 log.u_bbr.use_lt_bw <<= 1;
2520                 log.u_bbr.use_lt_bw |= rack->r_might_revert;
2521                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2522                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2523                 log.u_bbr.pacing_gain = rack->r_must_retran;
2524                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2525                     &rack->rc_inp->inp_socket->so_rcv,
2526                     &rack->rc_inp->inp_socket->so_snd,
2527                     BBR_LOG_DOSEG_DONE, 0,
2528                     0, &log, false, &tv);
2529         }
2530 }
2531
2532 static void
2533 rack_log_type_pacing_sizes(struct tcpcb *tp, struct tcp_rack *rack, uint32_t arg1, uint32_t arg2, uint32_t arg3, uint8_t frm)
2534 {
2535         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
2536                 union tcp_log_stackspecific log;
2537                 struct timeval tv;
2538
2539                 memset(&log, 0, sizeof(log));
2540                 log.u_bbr.flex1 = rack->r_ctl.rc_pace_min_segs;
2541                 log.u_bbr.flex3 = rack->r_ctl.rc_pace_max_segs;
2542                 log.u_bbr.flex4 = arg1;
2543                 log.u_bbr.flex5 = arg2;
2544                 log.u_bbr.flex6 = arg3;
2545                 log.u_bbr.flex8 = frm;
2546                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2547                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2548                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2549                 log.u_bbr.applimited = rack->r_ctl.rc_sacked;
2550                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2551                 log.u_bbr.pacing_gain = rack->r_must_retran;
2552                 TCP_LOG_EVENTP(tp, NULL, &tptosocket(tp)->so_rcv,
2553                     &tptosocket(tp)->so_snd,
2554                     TCP_HDWR_PACE_SIZE, 0, 0, &log, false, &tv);
2555         }
2556 }
2557
2558 static void
2559 rack_log_type_just_return(struct tcp_rack *rack, uint32_t cts, uint32_t tlen, uint32_t slot,
2560                           uint8_t hpts_calling, int reason, uint32_t cwnd_to_use)
2561 {
2562         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2563                 union tcp_log_stackspecific log;
2564                 struct timeval tv;
2565
2566                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2567                 log.u_bbr.inhpts = tcp_in_hpts(rack->rc_inp);
2568                 log.u_bbr.flex1 = slot;
2569                 log.u_bbr.flex2 = rack->r_ctl.rc_hpts_flags;
2570                 log.u_bbr.flex4 = reason;
2571                 if (rack->rack_no_prr)
2572                         log.u_bbr.flex5 = 0;
2573                 else
2574                         log.u_bbr.flex5 = rack->r_ctl.rc_prr_sndcnt;
2575                 log.u_bbr.flex7 = hpts_calling;
2576                 log.u_bbr.flex8 = rack->rc_in_persist;
2577                 log.u_bbr.lt_epoch = cwnd_to_use;
2578                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2579                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2580                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2581                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2582                 log.u_bbr.pacing_gain = rack->r_must_retran;
2583                 log.u_bbr.cwnd_gain = rack->rc_has_collapsed;
2584                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2585                     &rack->rc_inp->inp_socket->so_rcv,
2586                     &rack->rc_inp->inp_socket->so_snd,
2587                     BBR_LOG_JUSTRET, 0,
2588                     tlen, &log, false, &tv);
2589         }
2590 }
2591
2592 static void
2593 rack_log_to_cancel(struct tcp_rack *rack, int32_t hpts_removed, int line, uint32_t us_cts,
2594                    struct timeval *tv, uint32_t flags_on_entry)
2595 {
2596         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2597                 union tcp_log_stackspecific log;
2598
2599                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2600                 log.u_bbr.inhpts = tcp_in_hpts(rack->rc_inp);
2601                 log.u_bbr.flex1 = line;
2602                 log.u_bbr.flex2 = rack->r_ctl.rc_last_output_to;
2603                 log.u_bbr.flex3 = flags_on_entry;
2604                 log.u_bbr.flex4 = us_cts;
2605                 if (rack->rack_no_prr)
2606                         log.u_bbr.flex5 = 0;
2607                 else
2608                         log.u_bbr.flex5 = rack->r_ctl.rc_prr_sndcnt;
2609                 log.u_bbr.flex6 = rack->rc_tp->t_rxtcur;
2610                 log.u_bbr.flex7 = hpts_removed;
2611                 log.u_bbr.flex8 = 1;
2612                 log.u_bbr.applimited = rack->r_ctl.rc_hpts_flags;
2613                 log.u_bbr.timeStamp = us_cts;
2614                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2615                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2616                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2617                 log.u_bbr.pacing_gain = rack->r_must_retran;
2618                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2619                     &rack->rc_inp->inp_socket->so_rcv,
2620                     &rack->rc_inp->inp_socket->so_snd,
2621                     BBR_LOG_TIMERCANC, 0,
2622                     0, &log, false, tv);
2623         }
2624 }
2625
2626 static void
2627 rack_log_alt_to_to_cancel(struct tcp_rack *rack,
2628                           uint32_t flex1, uint32_t flex2,
2629                           uint32_t flex3, uint32_t flex4,
2630                           uint32_t flex5, uint32_t flex6,
2631                           uint16_t flex7, uint8_t mod)
2632 {
2633         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2634                 union tcp_log_stackspecific log;
2635                 struct timeval tv;
2636
2637                 if (mod == 1) {
2638                         /* No you can't use 1, its for the real to cancel */
2639                         return;
2640                 }
2641                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2642                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2643                 log.u_bbr.flex1 = flex1;
2644                 log.u_bbr.flex2 = flex2;
2645                 log.u_bbr.flex3 = flex3;
2646                 log.u_bbr.flex4 = flex4;
2647                 log.u_bbr.flex5 = flex5;
2648                 log.u_bbr.flex6 = flex6;
2649                 log.u_bbr.flex7 = flex7;
2650                 log.u_bbr.flex8 = mod;
2651                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2652                     &rack->rc_inp->inp_socket->so_rcv,
2653                     &rack->rc_inp->inp_socket->so_snd,
2654                     BBR_LOG_TIMERCANC, 0,
2655                     0, &log, false, &tv);
2656         }
2657 }
2658
2659 static void
2660 rack_log_to_processing(struct tcp_rack *rack, uint32_t cts, int32_t ret, int32_t timers)
2661 {
2662         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2663                 union tcp_log_stackspecific log;
2664                 struct timeval tv;
2665
2666                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2667                 log.u_bbr.flex1 = timers;
2668                 log.u_bbr.flex2 = ret;
2669                 log.u_bbr.flex3 = rack->r_ctl.rc_timer_exp;
2670                 log.u_bbr.flex4 = rack->r_ctl.rc_hpts_flags;
2671                 log.u_bbr.flex5 = cts;
2672                 if (rack->rack_no_prr)
2673                         log.u_bbr.flex6 = 0;
2674                 else
2675                         log.u_bbr.flex6 = rack->r_ctl.rc_prr_sndcnt;
2676                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2677                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2678                 log.u_bbr.pacing_gain = rack->r_must_retran;
2679                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2680                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2681                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2682                     &rack->rc_inp->inp_socket->so_rcv,
2683                     &rack->rc_inp->inp_socket->so_snd,
2684                     BBR_LOG_TO_PROCESS, 0,
2685                     0, &log, false, &tv);
2686         }
2687 }
2688
2689 static void
2690 rack_log_to_prr(struct tcp_rack *rack, int frm, int orig_cwnd, int line)
2691 {
2692         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2693                 union tcp_log_stackspecific log;
2694                 struct timeval tv;
2695
2696                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2697                 log.u_bbr.flex1 = rack->r_ctl.rc_prr_out;
2698                 log.u_bbr.flex2 = rack->r_ctl.rc_prr_recovery_fs;
2699                 if (rack->rack_no_prr)
2700                         log.u_bbr.flex3 = 0;
2701                 else
2702                         log.u_bbr.flex3 = rack->r_ctl.rc_prr_sndcnt;
2703                 log.u_bbr.flex4 = rack->r_ctl.rc_prr_delivered;
2704                 log.u_bbr.flex5 = rack->r_ctl.rc_sacked;
2705                 log.u_bbr.flex6 = rack->r_ctl.rc_holes_rxt;
2706                 log.u_bbr.flex7 = line;
2707                 log.u_bbr.flex8 = frm;
2708                 log.u_bbr.pkts_out = orig_cwnd;
2709                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2710                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2711                 log.u_bbr.use_lt_bw = rack->r_ent_rec_ns;
2712                 log.u_bbr.use_lt_bw <<= 1;
2713                 log.u_bbr.use_lt_bw |= rack->r_might_revert;
2714                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2715                     &rack->rc_inp->inp_socket->so_rcv,
2716                     &rack->rc_inp->inp_socket->so_snd,
2717                     BBR_LOG_BBRUPD, 0,
2718                     0, &log, false, &tv);
2719         }
2720 }
2721
2722 #ifdef NETFLIX_EXP_DETECTION
2723 static void
2724 rack_log_sad(struct tcp_rack *rack, int event)
2725 {
2726         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2727                 union tcp_log_stackspecific log;
2728                 struct timeval tv;
2729
2730                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2731                 log.u_bbr.flex1 = rack->r_ctl.sack_count;
2732                 log.u_bbr.flex2 = rack->r_ctl.ack_count;
2733                 log.u_bbr.flex3 = rack->r_ctl.sack_moved_extra;
2734                 log.u_bbr.flex4 = rack->r_ctl.sack_noextra_move;
2735                 log.u_bbr.flex5 = rack->r_ctl.rc_num_maps_alloced;
2736                 log.u_bbr.flex6 = tcp_sack_to_ack_thresh;
2737                 log.u_bbr.pkts_out = tcp_sack_to_move_thresh;
2738                 log.u_bbr.lt_epoch = (tcp_force_detection << 8);
2739                 log.u_bbr.lt_epoch |= rack->do_detection;
2740                 log.u_bbr.applimited = tcp_map_minimum;
2741                 log.u_bbr.flex7 = rack->sack_attack_disable;
2742                 log.u_bbr.flex8 = event;
2743                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2744                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2745                 log.u_bbr.delivered = tcp_sad_decay_val;
2746                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2747                     &rack->rc_inp->inp_socket->so_rcv,
2748                     &rack->rc_inp->inp_socket->so_snd,
2749                     TCP_SAD_DETECTION, 0,
2750                     0, &log, false, &tv);
2751         }
2752 }
2753 #endif
2754
2755 static void
2756 rack_counter_destroy(void)
2757 {
2758         counter_u64_free(rack_fto_send);
2759         counter_u64_free(rack_fto_rsm_send);
2760         counter_u64_free(rack_nfto_resend);
2761         counter_u64_free(rack_hw_pace_init_fail);
2762         counter_u64_free(rack_hw_pace_lost);
2763         counter_u64_free(rack_non_fto_send);
2764         counter_u64_free(rack_extended_rfo);
2765         counter_u64_free(rack_ack_total);
2766         counter_u64_free(rack_express_sack);
2767         counter_u64_free(rack_sack_total);
2768         counter_u64_free(rack_move_none);
2769         counter_u64_free(rack_move_some);
2770         counter_u64_free(rack_sack_attacks_detected);
2771         counter_u64_free(rack_sack_attacks_reversed);
2772         counter_u64_free(rack_sack_used_next_merge);
2773         counter_u64_free(rack_sack_used_prev_merge);
2774         counter_u64_free(rack_tlp_tot);
2775         counter_u64_free(rack_tlp_newdata);
2776         counter_u64_free(rack_tlp_retran);
2777         counter_u64_free(rack_tlp_retran_bytes);
2778         counter_u64_free(rack_to_tot);
2779         counter_u64_free(rack_saw_enobuf);
2780         counter_u64_free(rack_saw_enobuf_hw);
2781         counter_u64_free(rack_saw_enetunreach);
2782         counter_u64_free(rack_hot_alloc);
2783         counter_u64_free(rack_to_alloc);
2784         counter_u64_free(rack_to_alloc_hard);
2785         counter_u64_free(rack_to_alloc_emerg);
2786         counter_u64_free(rack_to_alloc_limited);
2787         counter_u64_free(rack_alloc_limited_conns);
2788         counter_u64_free(rack_split_limited);
2789         counter_u64_free(rack_multi_single_eq);
2790         counter_u64_free(rack_proc_non_comp_ack);
2791         counter_u64_free(rack_sack_proc_all);
2792         counter_u64_free(rack_sack_proc_restart);
2793         counter_u64_free(rack_sack_proc_short);
2794         counter_u64_free(rack_sack_skipped_acked);
2795         counter_u64_free(rack_sack_splits);
2796         counter_u64_free(rack_input_idle_reduces);
2797         counter_u64_free(rack_collapsed_win);
2798         counter_u64_free(rack_collapsed_win_rxt);
2799         counter_u64_free(rack_collapsed_win_rxt_bytes);
2800         counter_u64_free(rack_collapsed_win_seen);
2801         counter_u64_free(rack_try_scwnd);
2802         counter_u64_free(rack_persists_sends);
2803         counter_u64_free(rack_persists_acks);
2804         counter_u64_free(rack_persists_loss);
2805         counter_u64_free(rack_persists_lost_ends);
2806 #ifdef INVARIANTS
2807         counter_u64_free(rack_adjust_map_bw);
2808 #endif
2809         COUNTER_ARRAY_FREE(rack_out_size, TCP_MSS_ACCT_SIZE);
2810         COUNTER_ARRAY_FREE(rack_opts_arry, RACK_OPTS_SIZE);
2811 }
2812
2813 static struct rack_sendmap *
2814 rack_alloc(struct tcp_rack *rack)
2815 {
2816         struct rack_sendmap *rsm;
2817
2818         /*
2819          * First get the top of the list it in
2820          * theory is the "hottest" rsm we have,
2821          * possibly just freed by ack processing.
2822          */
2823         if (rack->rc_free_cnt > rack_free_cache) {
2824                 rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
2825                 TAILQ_REMOVE(&rack->r_ctl.rc_free, rsm, r_tnext);
2826                 counter_u64_add(rack_hot_alloc, 1);
2827                 rack->rc_free_cnt--;
2828                 return (rsm);
2829         }
2830         /*
2831          * Once we get under our free cache we probably
2832          * no longer have a "hot" one available. Lets
2833          * get one from UMA.
2834          */
2835         rsm = uma_zalloc(rack_zone, M_NOWAIT);
2836         if (rsm) {
2837                 rack->r_ctl.rc_num_maps_alloced++;
2838                 counter_u64_add(rack_to_alloc, 1);
2839                 return (rsm);
2840         }
2841         /*
2842          * Dig in to our aux rsm's (the last two) since
2843          * UMA failed to get us one.
2844          */
2845         if (rack->rc_free_cnt) {
2846                 counter_u64_add(rack_to_alloc_emerg, 1);
2847                 rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
2848                 TAILQ_REMOVE(&rack->r_ctl.rc_free, rsm, r_tnext);
2849                 rack->rc_free_cnt--;
2850                 return (rsm);
2851         }
2852         return (NULL);
2853 }
2854
2855 static struct rack_sendmap *
2856 rack_alloc_full_limit(struct tcp_rack *rack)
2857 {
2858         if ((V_tcp_map_entries_limit > 0) &&
2859             (rack->do_detection == 0) &&
2860             (rack->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
2861                 counter_u64_add(rack_to_alloc_limited, 1);
2862                 if (!rack->alloc_limit_reported) {
2863                         rack->alloc_limit_reported = 1;
2864                         counter_u64_add(rack_alloc_limited_conns, 1);
2865                 }
2866                 return (NULL);
2867         }
2868         return (rack_alloc(rack));
2869 }
2870
2871 /* wrapper to allocate a sendmap entry, subject to a specific limit */
2872 static struct rack_sendmap *
2873 rack_alloc_limit(struct tcp_rack *rack, uint8_t limit_type)
2874 {
2875         struct rack_sendmap *rsm;
2876
2877         if (limit_type) {
2878                 /* currently there is only one limit type */
2879                 if (V_tcp_map_split_limit > 0 &&
2880                     (rack->do_detection == 0) &&
2881                     rack->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
2882                         counter_u64_add(rack_split_limited, 1);
2883                         if (!rack->alloc_limit_reported) {
2884                                 rack->alloc_limit_reported = 1;
2885                                 counter_u64_add(rack_alloc_limited_conns, 1);
2886                         }
2887                         return (NULL);
2888                 }
2889         }
2890
2891         /* allocate and mark in the limit type, if set */
2892         rsm = rack_alloc(rack);
2893         if (rsm != NULL && limit_type) {
2894                 rsm->r_limit_type = limit_type;
2895                 rack->r_ctl.rc_num_split_allocs++;
2896         }
2897         return (rsm);
2898 }
2899
2900 static void
2901 rack_free(struct tcp_rack *rack, struct rack_sendmap *rsm)
2902 {
2903         if (rsm->r_flags & RACK_APP_LIMITED) {
2904                 if (rack->r_ctl.rc_app_limited_cnt > 0) {
2905                         rack->r_ctl.rc_app_limited_cnt--;
2906                 }
2907         }
2908         if (rsm->r_limit_type) {
2909                 /* currently there is only one limit type */
2910                 rack->r_ctl.rc_num_split_allocs--;
2911         }
2912         if (rsm == rack->r_ctl.rc_first_appl) {
2913                 if (rack->r_ctl.rc_app_limited_cnt == 0)
2914                         rack->r_ctl.rc_first_appl = NULL;
2915                 else {
2916                         /* Follow the next one out */
2917                         struct rack_sendmap fe;
2918
2919                         fe.r_start = rsm->r_nseq_appl;
2920                         rack->r_ctl.rc_first_appl = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
2921                 }
2922         }
2923         if (rsm == rack->r_ctl.rc_resend)
2924                 rack->r_ctl.rc_resend = NULL;
2925         if (rsm == rack->r_ctl.rc_end_appl)
2926                 rack->r_ctl.rc_end_appl = NULL;
2927         if (rack->r_ctl.rc_tlpsend == rsm)
2928                 rack->r_ctl.rc_tlpsend = NULL;
2929         if (rack->r_ctl.rc_sacklast == rsm)
2930                 rack->r_ctl.rc_sacklast = NULL;
2931         memset(rsm, 0, sizeof(struct rack_sendmap));
2932         TAILQ_INSERT_HEAD(&rack->r_ctl.rc_free, rsm, r_tnext);
2933         rack->rc_free_cnt++;
2934 }
2935
2936 static void
2937 rack_free_trim(struct tcp_rack *rack)
2938 {
2939         struct rack_sendmap *rsm;
2940
2941         /*
2942          * Free up all the tail entries until
2943          * we get our list down to the limit.
2944          */
2945         while (rack->rc_free_cnt > rack_free_cache) {
2946                 rsm = TAILQ_LAST(&rack->r_ctl.rc_free, rack_head);
2947                 TAILQ_REMOVE(&rack->r_ctl.rc_free, rsm, r_tnext);
2948                 rack->rc_free_cnt--;
2949                 uma_zfree(rack_zone, rsm);
2950         }
2951 }
2952
2953
2954 static uint32_t
2955 rack_get_measure_window(struct tcpcb *tp, struct tcp_rack *rack)
2956 {
2957         uint64_t srtt, bw, len, tim;
2958         uint32_t segsiz, def_len, minl;
2959
2960         segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
2961         def_len = rack_def_data_window * segsiz;
2962         if (rack->rc_gp_filled == 0) {
2963                 /*
2964                  * We have no measurement (IW is in flight?) so
2965                  * we can only guess using our data_window sysctl
2966                  * value (usually 20MSS).
2967                  */
2968                 return (def_len);
2969         }
2970         /*
2971          * Now we have a number of factors to consider.
2972          *
2973          * 1) We have a desired BDP which is usually
2974          *    at least 2.
2975          * 2) We have a minimum number of rtt's usually 1 SRTT
2976          *    but we allow it too to be more.
2977          * 3) We want to make sure a measurement last N useconds (if
2978          *    we have set rack_min_measure_usec.
2979          *
2980          * We handle the first concern here by trying to create a data
2981          * window of max(rack_def_data_window, DesiredBDP). The
2982          * second concern we handle in not letting the measurement
2983          * window end normally until at least the required SRTT's
2984          * have gone by which is done further below in
2985          * rack_enough_for_measurement(). Finally the third concern
2986          * we also handle here by calculating how long that time
2987          * would take at the current BW and then return the
2988          * max of our first calculation and that length. Note
2989          * that if rack_min_measure_usec is 0, we don't deal
2990          * with concern 3. Also for both Concern 1 and 3 an
2991          * application limited period could end the measurement
2992          * earlier.
2993          *
2994          * So lets calculate the BDP with the "known" b/w using
2995          * the SRTT has our rtt and then multiply it by the
2996          * goal.
2997          */
2998         bw = rack_get_bw(rack);
2999         srtt = (uint64_t)tp->t_srtt;
3000         len = bw * srtt;
3001         len /= (uint64_t)HPTS_USEC_IN_SEC;
3002         len *= max(1, rack_goal_bdp);
3003         /* Now we need to round up to the nearest MSS */
3004         len = roundup(len, segsiz);
3005         if (rack_min_measure_usec) {
3006                 /* Now calculate our min length for this b/w */
3007                 tim = rack_min_measure_usec;
3008                 minl = (tim * bw) / (uint64_t)HPTS_USEC_IN_SEC;
3009                 if (minl == 0)
3010                         minl = 1;
3011                 minl = roundup(minl, segsiz);
3012                 if (len < minl)
3013                         len = minl;
3014         }
3015         /*
3016          * Now if we have a very small window we want
3017          * to attempt to get the window that is
3018          * as small as possible. This happens on
3019          * low b/w connections and we don't want to
3020          * span huge numbers of rtt's between measurements.
3021          *
3022          * We basically include 2 over our "MIN window" so
3023          * that the measurement can be shortened (possibly) by
3024          * an ack'ed packet.
3025          */
3026         if (len < def_len)
3027                 return (max((uint32_t)len, ((MIN_GP_WIN+2) * segsiz)));
3028         else
3029                 return (max((uint32_t)len, def_len));
3030
3031 }
3032
3033 static int
3034 rack_enough_for_measurement(struct tcpcb *tp, struct tcp_rack *rack, tcp_seq th_ack, uint8_t *quality)
3035 {
3036         uint32_t tim, srtts, segsiz;
3037
3038         /*
3039          * Has enough time passed for the GP measurement to be valid?
3040          */
3041         if ((tp->snd_max == tp->snd_una) ||
3042             (th_ack == tp->snd_max)){
3043                 /* All is acked */
3044                 *quality = RACK_QUALITY_ALLACKED;
3045                 return (1);
3046         }
3047         if (SEQ_LT(th_ack, tp->gput_seq)) {
3048                 /* Not enough bytes yet */
3049                 return (0);
3050         }
3051         segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
3052         if (SEQ_LT(th_ack, tp->gput_ack) &&
3053             ((th_ack - tp->gput_seq) < max(rc_init_window(rack), (MIN_GP_WIN * segsiz)))) {
3054                 /* Not enough bytes yet */
3055                 return (0);
3056         }
3057         if (rack->r_ctl.rc_first_appl &&
3058             (SEQ_GEQ(th_ack, rack->r_ctl.rc_first_appl->r_end))) {
3059                 /*
3060                  * We are up to the app limited send point
3061                  * we have to measure irrespective of the time..
3062                  */
3063                 *quality = RACK_QUALITY_APPLIMITED;
3064                 return (1);
3065         }
3066         /* Now what about time? */
3067         srtts = (rack->r_ctl.rc_gp_srtt * rack_min_srtts);
3068         tim = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time) - tp->gput_ts;
3069         if (tim >= srtts) {
3070                 *quality = RACK_QUALITY_HIGH;
3071                 return (1);
3072         }
3073         /* Nope not even a full SRTT has passed */
3074         return (0);
3075 }
3076
3077 static void
3078 rack_log_timely(struct tcp_rack *rack,
3079                 uint32_t logged, uint64_t cur_bw, uint64_t low_bnd,
3080                 uint64_t up_bnd, int line, uint8_t method)
3081 {
3082         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
3083                 union tcp_log_stackspecific log;
3084                 struct timeval tv;
3085
3086                 memset(&log, 0, sizeof(log));
3087                 log.u_bbr.flex1 = logged;
3088                 log.u_bbr.flex2 = rack->rc_gp_timely_inc_cnt;
3089                 log.u_bbr.flex2 <<= 4;
3090                 log.u_bbr.flex2 |= rack->rc_gp_timely_dec_cnt;
3091                 log.u_bbr.flex2 <<= 4;
3092                 log.u_bbr.flex2 |= rack->rc_gp_incr;
3093                 log.u_bbr.flex2 <<= 4;
3094                 log.u_bbr.flex2 |= rack->rc_gp_bwred;
3095                 log.u_bbr.flex3 = rack->rc_gp_incr;
3096                 log.u_bbr.flex4 = rack->r_ctl.rack_per_of_gp_ss;
3097                 log.u_bbr.flex5 = rack->r_ctl.rack_per_of_gp_ca;
3098                 log.u_bbr.flex6 = rack->r_ctl.rack_per_of_gp_rec;
3099                 log.u_bbr.flex7 = rack->rc_gp_bwred;
3100                 log.u_bbr.flex8 = method;
3101                 log.u_bbr.cur_del_rate = cur_bw;
3102                 log.u_bbr.delRate = low_bnd;
3103                 log.u_bbr.bw_inuse = up_bnd;
3104                 log.u_bbr.rttProp = rack_get_bw(rack);
3105                 log.u_bbr.pkt_epoch = line;
3106                 log.u_bbr.pkts_out = rack->r_ctl.rc_rtt_diff;
3107                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
3108                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
3109                 log.u_bbr.epoch = rack->r_ctl.rc_gp_srtt;
3110                 log.u_bbr.lt_epoch = rack->r_ctl.rc_prev_gp_srtt;
3111                 log.u_bbr.cwnd_gain = rack->rc_dragged_bottom;
3112                 log.u_bbr.cwnd_gain <<= 1;
3113                 log.u_bbr.cwnd_gain |= rack->rc_gp_saw_rec;
3114                 log.u_bbr.cwnd_gain <<= 1;
3115                 log.u_bbr.cwnd_gain |= rack->rc_gp_saw_ss;
3116                 log.u_bbr.cwnd_gain <<= 1;
3117                 log.u_bbr.cwnd_gain |= rack->rc_gp_saw_ca;
3118                 log.u_bbr.lost = rack->r_ctl.rc_loss_count;
3119                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
3120                     &rack->rc_inp->inp_socket->so_rcv,
3121                     &rack->rc_inp->inp_socket->so_snd,
3122                     TCP_TIMELY_WORK, 0,
3123                     0, &log, false, &tv);
3124         }
3125 }
3126
3127 static int
3128 rack_bw_can_be_raised(struct tcp_rack *rack, uint64_t cur_bw, uint64_t last_bw_est, uint16_t mult)
3129 {
3130         /*
3131          * Before we increase we need to know if
3132          * the estimate just made was less than
3133          * our pacing goal (i.e. (cur_bw * mult) > last_bw_est)
3134          *
3135          * If we already are pacing at a fast enough
3136          * rate to push us faster there is no sense of
3137          * increasing.
3138          *
3139          * We first caculate our actual pacing rate (ss or ca multiplier
3140          * times our cur_bw).
3141          *
3142          * Then we take the last measured rate and multipy by our
3143          * maximum pacing overage to give us a max allowable rate.
3144          *
3145          * If our act_rate is smaller than our max_allowable rate
3146          * then we should increase. Else we should hold steady.
3147          *
3148          */
3149         uint64_t act_rate, max_allow_rate;
3150
3151         if (rack_timely_no_stopping)
3152                 return (1);
3153
3154         if ((cur_bw == 0) || (last_bw_est == 0)) {
3155                 /*
3156                  * Initial startup case or
3157                  * everything is acked case.
3158                  */
3159                 rack_log_timely(rack,  mult, cur_bw, 0, 0,
3160                                 __LINE__, 9);
3161                 return (1);
3162         }
3163         if (mult <= 100) {
3164                 /*
3165                  * We can always pace at or slightly above our rate.
3166                  */
3167                 rack_log_timely(rack,  mult, cur_bw, 0, 0,
3168                                 __LINE__, 9);
3169                 return (1);
3170         }
3171         act_rate = cur_bw * (uint64_t)mult;
3172         act_rate /= 100;
3173         max_allow_rate = last_bw_est * ((uint64_t)rack_max_per_above + (uint64_t)100);
3174         max_allow_rate /= 100;
3175         if (act_rate < max_allow_rate) {
3176                 /*
3177                  * Here the rate we are actually pacing at
3178                  * is smaller than 10% above our last measurement.
3179                  * This means we are pacing below what we would
3180                  * like to try to achieve (plus some wiggle room).
3181                  */
3182                 rack_log_timely(rack,  mult, cur_bw, act_rate, max_allow_rate,
3183                                 __LINE__, 9);
3184                 return (1);
3185         } else {
3186                 /*
3187                  * Here we are already pacing at least rack_max_per_above(10%)
3188                  * what we are getting back. This indicates most likely
3189                  * that we are being limited (cwnd/rwnd/app) and can't
3190                  * get any more b/w. There is no sense of trying to
3191                  * raise up the pacing rate its not speeding us up
3192                  * and we already are pacing faster than we are getting.
3193                  */
3194                 rack_log_timely(rack,  mult, cur_bw, act_rate, max_allow_rate,
3195                                 __LINE__, 8);
3196                 return (0);
3197         }
3198 }
3199
3200 static void
3201 rack_validate_multipliers_at_or_above100(struct tcp_rack *rack)
3202 {
3203         /*
3204          * When we drag bottom, we want to assure
3205          * that no multiplier is below 1.0, if so
3206          * we want to restore it to at least that.
3207          */
3208         if (rack->r_ctl.rack_per_of_gp_rec  < 100) {
3209                 /* This is unlikely we usually do not touch recovery */
3210                 rack->r_ctl.rack_per_of_gp_rec = 100;
3211         }
3212         if (rack->r_ctl.rack_per_of_gp_ca < 100) {
3213                 rack->r_ctl.rack_per_of_gp_ca = 100;
3214         }
3215         if (rack->r_ctl.rack_per_of_gp_ss < 100) {
3216                 rack->r_ctl.rack_per_of_gp_ss = 100;
3217         }
3218 }
3219
3220 static void
3221 rack_validate_multipliers_at_or_below_100(struct tcp_rack *rack)
3222 {
3223         if (rack->r_ctl.rack_per_of_gp_ca > 100) {
3224                 rack->r_ctl.rack_per_of_gp_ca = 100;
3225         }
3226         if (rack->r_ctl.rack_per_of_gp_ss > 100) {
3227                 rack->r_ctl.rack_per_of_gp_ss = 100;
3228         }
3229 }
3230
3231 static void
3232 rack_increase_bw_mul(struct tcp_rack *rack, int timely_says, uint64_t cur_bw, uint64_t last_bw_est, int override)
3233 {
3234         int32_t  calc, logged, plus;
3235
3236         logged = 0;
3237
3238         if (override) {
3239                 /*
3240                  * override is passed when we are
3241                  * loosing b/w and making one last
3242                  * gasp at trying to not loose out
3243                  * to a new-reno flow.
3244                  */
3245                 goto extra_boost;
3246         }
3247         /* In classic timely we boost by 5x if we have 5 increases in a row, lets not */
3248         if (rack->rc_gp_incr &&
3249             ((rack->rc_gp_timely_inc_cnt + 1) >= RACK_TIMELY_CNT_BOOST)) {
3250                 /*
3251                  * Reset and get 5 strokes more before the boost. Note
3252                  * that the count is 0 based so we have to add one.
3253                  */
3254 extra_boost:
3255                 plus = (uint32_t)rack_gp_increase_per * RACK_TIMELY_CNT_BOOST;
3256                 rack->rc_gp_timely_inc_cnt = 0;
3257         } else
3258                 plus = (uint32_t)rack_gp_increase_per;
3259         /* Must be at least 1% increase for true timely increases */
3260         if ((plus < 1) &&
3261             ((rack->r_ctl.rc_rtt_diff <= 0) || (timely_says <= 0)))
3262                 plus = 1;
3263         if (rack->rc_gp_saw_rec &&
3264             (rack->rc_gp_no_rec_chg == 0) &&
3265             rack_bw_can_be_raised(rack, cur_bw, last_bw_est,
3266                                   rack->r_ctl.rack_per_of_gp_rec)) {
3267                 /* We have been in recovery ding it too */
3268                 calc = rack->r_ctl.rack_per_of_gp_rec + plus;
3269                 if (calc > 0xffff)
3270                         calc = 0xffff;
3271                 logged |= 1;
3272                 rack->r_ctl.rack_per_of_gp_rec = (uint16_t)calc;
3273                 if (rack_per_upper_bound_ss &&
3274                     (rack->rc_dragged_bottom == 0) &&
3275                     (rack->r_ctl.rack_per_of_gp_rec > rack_per_upper_bound_ss))
3276                         rack->r_ctl.rack_per_of_gp_rec = rack_per_upper_bound_ss;
3277         }
3278         if (rack->rc_gp_saw_ca &&
3279             (rack->rc_gp_saw_ss == 0) &&
3280             rack_bw_can_be_raised(rack, cur_bw, last_bw_est,
3281                                   rack->r_ctl.rack_per_of_gp_ca)) {
3282                 /* In CA */
3283                 calc = rack->r_ctl.rack_per_of_gp_ca + plus;
3284                 if (calc > 0xffff)
3285                         calc = 0xffff;
3286                 logged |= 2;
3287                 rack->r_ctl.rack_per_of_gp_ca = (uint16_t)calc;
3288                 if (rack_per_upper_bound_ca &&
3289                     (rack->rc_dragged_bottom == 0) &&
3290                     (rack->r_ctl.rack_per_of_gp_ca > rack_per_upper_bound_ca))
3291                         rack->r_ctl.rack_per_of_gp_ca = rack_per_upper_bound_ca;
3292         }
3293         if (rack->rc_gp_saw_ss &&
3294             rack_bw_can_be_raised(rack, cur_bw, last_bw_est,
3295                                   rack->r_ctl.rack_per_of_gp_ss)) {
3296                 /* In SS */
3297                 calc = rack->r_ctl.rack_per_of_gp_ss + plus;
3298                 if (calc > 0xffff)
3299                         calc = 0xffff;
3300                 rack->r_ctl.rack_per_of_gp_ss = (uint16_t)calc;
3301                 if (rack_per_upper_bound_ss &&
3302                     (rack->rc_dragged_bottom == 0) &&
3303                     (rack->r_ctl.rack_per_of_gp_ss > rack_per_upper_bound_ss))
3304                         rack->r_ctl.rack_per_of_gp_ss = rack_per_upper_bound_ss;
3305                 logged |= 4;
3306         }
3307         if (logged &&
3308             (rack->rc_gp_incr == 0)){
3309                 /* Go into increment mode */
3310                 rack->rc_gp_incr = 1;
3311                 rack->rc_gp_timely_inc_cnt = 0;
3312         }
3313         if (rack->rc_gp_incr &&
3314             logged &&
3315             (rack->rc_gp_timely_inc_cnt < RACK_TIMELY_CNT_BOOST)) {
3316                 rack->rc_gp_timely_inc_cnt++;
3317         }
3318         rack_log_timely(rack,  logged, plus, 0, 0,
3319                         __LINE__, 1);
3320 }
3321
3322 static uint32_t
3323 rack_get_decrease(struct tcp_rack *rack, uint32_t curper, int32_t rtt_diff)
3324 {
3325         /*
3326          * norm_grad = rtt_diff / minrtt;
3327          * new_per = curper * (1 - B * norm_grad)
3328          *
3329          * B = rack_gp_decrease_per (default 10%)
3330          * rtt_dif = input var current rtt-diff
3331          * curper = input var current percentage
3332          * minrtt = from rack filter
3333          *
3334          */
3335         uint64_t perf;
3336
3337         perf = (((uint64_t)curper * ((uint64_t)1000000 -
3338                     ((uint64_t)rack_gp_decrease_per * (uint64_t)10000 *
3339                      (((uint64_t)rtt_diff * (uint64_t)1000000)/
3340                       (uint64_t)get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt)))/
3341                      (uint64_t)1000000)) /
3342                 (uint64_t)1000000);
3343         if (perf > curper) {
3344                 /* TSNH */
3345                 perf = curper - 1;
3346         }
3347         return ((uint32_t)perf);
3348 }
3349
3350 static uint32_t
3351 rack_decrease_highrtt(struct tcp_rack *rack, uint32_t curper, uint32_t rtt)
3352 {
3353         /*
3354          *                                   highrttthresh
3355          * result = curper * (1 - (B * ( 1 -  ------          ))
3356          *                                     gp_srtt
3357          *
3358          * B = rack_gp_decrease_per (default 10%)
3359          * highrttthresh = filter_min * rack_gp_rtt_maxmul
3360          */
3361         uint64_t perf;
3362         uint32_t highrttthresh;
3363
3364         highrttthresh = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) * rack_gp_rtt_maxmul;
3365
3366         perf = (((uint64_t)curper * ((uint64_t)1000000 -
3367                                      ((uint64_t)rack_gp_decrease_per * ((uint64_t)1000000 -
3368                                         ((uint64_t)highrttthresh * (uint64_t)1000000) /
3369                                                     (uint64_t)rtt)) / 100)) /(uint64_t)1000000);
3370         return (perf);
3371 }
3372
3373 static void
3374 rack_decrease_bw_mul(struct tcp_rack *rack, int timely_says, uint32_t rtt, int32_t rtt_diff)
3375 {
3376         uint64_t logvar, logvar2, logvar3;
3377         uint32_t logged, new_per, ss_red, ca_red, rec_red, alt, val;
3378
3379         if (rack->rc_gp_incr) {
3380                 /* Turn off increment counting */
3381                 rack->rc_gp_incr = 0;
3382                 rack->rc_gp_timely_inc_cnt = 0;
3383         }
3384         ss_red = ca_red = rec_red = 0;
3385         logged = 0;
3386         /* Calculate the reduction value */
3387         if (rtt_diff < 0) {
3388                 rtt_diff *= -1;
3389         }
3390         /* Must be at least 1% reduction */
3391         if (rack->rc_gp_saw_rec && (rack->rc_gp_no_rec_chg == 0)) {
3392                 /* We have been in recovery ding it too */
3393                 if (timely_says == 2) {
3394                         new_per = rack_decrease_highrtt(rack, rack->r_ctl.rack_per_of_gp_rec, rtt);
3395                         alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_rec, rtt_diff);
3396                         if (alt < new_per)
3397                                 val = alt;
3398                         else
3399                                 val = new_per;
3400                 } else
3401                          val = new_per = alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_rec, rtt_diff);
3402                 if (rack->r_ctl.rack_per_of_gp_rec > val) {
3403                         rec_red = (rack->r_ctl.rack_per_of_gp_rec - val);
3404                         rack->r_ctl.rack_per_of_gp_rec = (uint16_t)val;
3405                 } else {
3406                         rack->r_ctl.rack_per_of_gp_rec = rack_per_lower_bound;
3407                         rec_red = 0;
3408                 }
3409                 if (rack_per_lower_bound > rack->r_ctl.rack_per_of_gp_rec)
3410                         rack->r_ctl.rack_per_of_gp_rec = rack_per_lower_bound;
3411                 logged |= 1;
3412         }
3413         if (rack->rc_gp_saw_ss) {
3414                 /* Sent in SS */
3415                 if (timely_says == 2) {
3416                         new_per = rack_decrease_highrtt(rack, rack->r_ctl.rack_per_of_gp_ss, rtt);
3417                         alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_rec, rtt_diff);
3418                         if (alt < new_per)
3419                                 val = alt;
3420                         else
3421                                 val = new_per;
3422                 } else
3423                         val = new_per = alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_ss, rtt_diff);
3424                 if (rack->r_ctl.rack_per_of_gp_ss > new_per) {
3425                         ss_red = rack->r_ctl.rack_per_of_gp_ss - val;
3426                         rack->r_ctl.rack_per_of_gp_ss = (uint16_t)val;
3427                 } else {
3428                         ss_red = new_per;
3429                         rack->r_ctl.rack_per_of_gp_ss = rack_per_lower_bound;
3430                         logvar = new_per;
3431                         logvar <<= 32;
3432                         logvar |= alt;
3433                         logvar2 = (uint32_t)rtt;
3434                         logvar2 <<= 32;
3435                         logvar2 |= (uint32_t)rtt_diff;
3436                         logvar3 = rack_gp_rtt_maxmul;
3437                         logvar3 <<= 32;
3438                         logvar3 |= get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt);
3439                         rack_log_timely(rack, timely_says,
3440                                         logvar2, logvar3,
3441                                         logvar, __LINE__, 10);
3442                 }
3443                 if (rack_per_lower_bound > rack->r_ctl.rack_per_of_gp_ss)
3444                         rack->r_ctl.rack_per_of_gp_ss = rack_per_lower_bound;
3445                 logged |= 4;
3446         } else if (rack->rc_gp_saw_ca) {
3447                 /* Sent in CA */
3448                 if (timely_says == 2) {
3449                         new_per = rack_decrease_highrtt(rack, rack->r_ctl.rack_per_of_gp_ca, rtt);
3450                         alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_rec, rtt_diff);
3451                         if (alt < new_per)
3452                                 val = alt;
3453                         else
3454                                 val = new_per;
3455                 } else
3456                         val = new_per = alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_ca, rtt_diff);
3457                 if (rack->r_ctl.rack_per_of_gp_ca > val) {
3458                         ca_red = rack->r_ctl.rack_per_of_gp_ca - val;
3459                         rack->r_ctl.rack_per_of_gp_ca = (uint16_t)val;
3460                 } else {
3461                         rack->r_ctl.rack_per_of_gp_ca = rack_per_lower_bound;
3462                         ca_red = 0;
3463                         logvar = new_per;
3464                         logvar <<= 32;
3465                         logvar |= alt;
3466                         logvar2 = (uint32_t)rtt;
3467                         logvar2 <<= 32;
3468                         logvar2 |= (uint32_t)rtt_diff;
3469                         logvar3 = rack_gp_rtt_maxmul;
3470                         logvar3 <<= 32;
3471                         logvar3 |= get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt);
3472                         rack_log_timely(rack, timely_says,
3473                                         logvar2, logvar3,
3474                                         logvar, __LINE__, 10);
3475                 }
3476                 if (rack_per_lower_bound > rack->r_ctl.rack_per_of_gp_ca)
3477                         rack->r_ctl.rack_per_of_gp_ca = rack_per_lower_bound;
3478                 logged |= 2;
3479         }
3480         if (rack->rc_gp_timely_dec_cnt < 0x7) {
3481                 rack->rc_gp_timely_dec_cnt++;
3482                 if (rack_timely_dec_clear &&
3483                     (rack->rc_gp_timely_dec_cnt == rack_timely_dec_clear))
3484                         rack->rc_gp_timely_dec_cnt = 0;
3485         }
3486         logvar = ss_red;
3487         logvar <<= 32;
3488         logvar |= ca_red;
3489         rack_log_timely(rack,  logged, rec_red, rack_per_lower_bound, logvar,
3490                         __LINE__, 2);
3491 }
3492
3493 static void
3494 rack_log_rtt_shrinks(struct tcp_rack *rack, uint32_t us_cts,
3495                      uint32_t rtt, uint32_t line, uint8_t reas)
3496 {
3497         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
3498                 union tcp_log_stackspecific log;
3499                 struct timeval tv;
3500
3501                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
3502                 log.u_bbr.flex1 = line;
3503                 log.u_bbr.flex2 = rack->r_ctl.rc_time_probertt_starts;
3504                 log.u_bbr.flex3 = rack->r_ctl.rc_lower_rtt_us_cts;
3505                 log.u_bbr.flex4 = rack->r_ctl.rack_per_of_gp_ss;
3506                 log.u_bbr.flex5 = rtt;
3507                 log.u_bbr.flex6 = rack->rc_highly_buffered;
3508                 log.u_bbr.flex6 <<= 1;
3509                 log.u_bbr.flex6 |= rack->forced_ack;
3510                 log.u_bbr.flex6 <<= 1;
3511                 log.u_bbr.flex6 |= rack->rc_gp_dyn_mul;
3512                 log.u_bbr.flex6 <<= 1;
3513                 log.u_bbr.flex6 |= rack->in_probe_rtt;
3514                 log.u_bbr.flex6 <<= 1;
3515                 log.u_bbr.flex6 |= rack->measure_saw_probe_rtt;
3516                 log.u_bbr.flex7 = rack->r_ctl.rack_per_of_gp_probertt;
3517                 log.u_bbr.pacing_gain = rack->r_ctl.rack_per_of_gp_ca;
3518                 log.u_bbr.cwnd_gain = rack->r_ctl.rack_per_of_gp_rec;
3519                 log.u_bbr.flex8 = reas;
3520                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
3521                 log.u_bbr.delRate = rack_get_bw(rack);
3522                 log.u_bbr.cur_del_rate = rack->r_ctl.rc_highest_us_rtt;
3523                 log.u_bbr.cur_del_rate <<= 32;
3524                 log.u_bbr.cur_del_rate |= rack->r_ctl.rc_lowest_us_rtt;
3525                 log.u_bbr.applimited = rack->r_ctl.rc_time_probertt_entered;
3526                 log.u_bbr.pkts_out = rack->r_ctl.rc_rtt_diff;
3527                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
3528                 log.u_bbr.epoch = rack->r_ctl.rc_gp_srtt;
3529                 log.u_bbr.lt_epoch = rack->r_ctl.rc_prev_gp_srtt;
3530                 log.u_bbr.pkt_epoch = rack->r_ctl.rc_lower_rtt_us_cts;
3531                 log.u_bbr.delivered = rack->r_ctl.rc_target_probertt_flight;
3532                 log.u_bbr.lost = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt);
3533                 log.u_bbr.rttProp = us_cts;
3534                 log.u_bbr.rttProp <<= 32;
3535                 log.u_bbr.rttProp |= rack->r_ctl.rc_entry_gp_rtt;
3536                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
3537                     &rack->rc_inp->inp_socket->so_rcv,
3538                     &rack->rc_inp->inp_socket->so_snd,
3539                     BBR_LOG_RTT_SHRINKS, 0,
3540                     0, &log, false, &rack->r_ctl.act_rcv_time);
3541         }
3542 }
3543
3544 static void
3545 rack_set_prtt_target(struct tcp_rack *rack, uint32_t segsiz, uint32_t rtt)
3546 {
3547         uint64_t bwdp;
3548
3549         bwdp = rack_get_bw(rack);
3550         bwdp *= (uint64_t)rtt;
3551         bwdp /= (uint64_t)HPTS_USEC_IN_SEC;
3552         rack->r_ctl.rc_target_probertt_flight = roundup((uint32_t)bwdp, segsiz);
3553         if (rack->r_ctl.rc_target_probertt_flight < (segsiz * rack_timely_min_segs)) {
3554                 /*
3555                  * A window protocol must be able to have 4 packets
3556                  * outstanding as the floor in order to function
3557                  * (especially considering delayed ack :D).
3558                  */
3559                 rack->r_ctl.rc_target_probertt_flight = (segsiz * rack_timely_min_segs);
3560         }
3561 }
3562
3563 static void
3564 rack_enter_probertt(struct tcp_rack *rack, uint32_t us_cts)
3565 {
3566         /**
3567          * ProbeRTT is a bit different in rack_pacing than in
3568          * BBR. It is like BBR in that it uses the lowering of
3569          * the RTT as a signal that we saw something new and
3570          * counts from there for how long between. But it is
3571          * different in that its quite simple. It does not
3572          * play with the cwnd and wait until we get down
3573          * to N segments outstanding and hold that for
3574          * 200ms. Instead it just sets the pacing reduction
3575          * rate to a set percentage (70 by default) and hold
3576          * that for a number of recent GP Srtt's.
3577          */
3578         uint32_t segsiz;
3579
3580         if (rack->rc_gp_dyn_mul == 0)
3581                 return;
3582
3583         if (rack->rc_tp->snd_max == rack->rc_tp->snd_una) {
3584                 /* We are idle */
3585                 return;
3586         }
3587         if ((rack->rc_tp->t_flags & TF_GPUTINPROG) &&
3588             SEQ_GT(rack->rc_tp->snd_una, rack->rc_tp->gput_seq)) {
3589                 /*
3590                  * Stop the goodput now, the idea here is
3591                  * that future measurements with in_probe_rtt
3592                  * won't register if they are not greater so
3593                  * we want to get what info (if any) is available
3594                  * now.
3595                  */
3596                 rack_do_goodput_measurement(rack->rc_tp, rack,
3597                                             rack->rc_tp->snd_una, __LINE__,
3598                                             RACK_QUALITY_PROBERTT);
3599         }
3600         rack->r_ctl.rack_per_of_gp_probertt = rack_per_of_gp_probertt;
3601         rack->r_ctl.rc_time_probertt_entered = us_cts;
3602         segsiz = min(ctf_fixed_maxseg(rack->rc_tp),
3603                      rack->r_ctl.rc_pace_min_segs);
3604         rack->in_probe_rtt = 1;
3605         rack->measure_saw_probe_rtt = 1;
3606         rack->r_ctl.rc_lower_rtt_us_cts = us_cts;
3607         rack->r_ctl.rc_time_probertt_starts = 0;
3608         rack->r_ctl.rc_entry_gp_rtt = rack->r_ctl.rc_gp_srtt;
3609         if (rack_probertt_use_min_rtt_entry)
3610                 rack_set_prtt_target(rack, segsiz, get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt));
3611         else
3612                 rack_set_prtt_target(rack, segsiz, rack->r_ctl.rc_gp_srtt);
3613         rack_log_rtt_shrinks(rack,  us_cts,  get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
3614                              __LINE__, RACK_RTTS_ENTERPROBE);
3615 }
3616
3617 static void
3618 rack_exit_probertt(struct tcp_rack *rack, uint32_t us_cts)
3619 {
3620         struct rack_sendmap *rsm;
3621         uint32_t segsiz;
3622
3623         segsiz = min(ctf_fixed_maxseg(rack->rc_tp),
3624                      rack->r_ctl.rc_pace_min_segs);
3625         rack->in_probe_rtt = 0;
3626         if ((rack->rc_tp->t_flags & TF_GPUTINPROG) &&
3627             SEQ_GT(rack->rc_tp->snd_una, rack->rc_tp->gput_seq)) {
3628                 /*
3629                  * Stop the goodput now, the idea here is
3630                  * that future measurements with in_probe_rtt
3631                  * won't register if they are not greater so
3632                  * we want to get what info (if any) is available
3633                  * now.
3634                  */
3635                 rack_do_goodput_measurement(rack->rc_tp, rack,
3636                                             rack->rc_tp->snd_una, __LINE__,
3637                                             RACK_QUALITY_PROBERTT);
3638         } else if (rack->rc_tp->t_flags & TF_GPUTINPROG) {
3639                 /*
3640                  * We don't have enough data to make a measurement.
3641                  * So lets just stop and start here after exiting
3642                  * probe-rtt. We probably are not interested in
3643                  * the results anyway.
3644                  */
3645                 rack->rc_tp->t_flags &= ~TF_GPUTINPROG;
3646         }
3647         /*
3648          * Measurements through the current snd_max are going
3649          * to be limited by the slower pacing rate.
3650          *
3651          * We need to mark these as app-limited so we
3652          * don't collapse the b/w.
3653          */
3654         rsm = RB_MAX(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
3655         if (rsm && ((rsm->r_flags & RACK_APP_LIMITED) == 0)) {
3656                 if (rack->r_ctl.rc_app_limited_cnt == 0)
3657                         rack->r_ctl.rc_end_appl = rack->r_ctl.rc_first_appl = rsm;
3658                 else {
3659                         /*
3660                          * Go out to the end app limited and mark
3661                          * this new one as next and move the end_appl up
3662                          * to this guy.
3663                          */
3664                         if (rack->r_ctl.rc_end_appl)
3665                                 rack->r_ctl.rc_end_appl->r_nseq_appl = rsm->r_start;
3666                         rack->r_ctl.rc_end_appl = rsm;
3667                 }
3668                 rsm->r_flags |= RACK_APP_LIMITED;
3669                 rack->r_ctl.rc_app_limited_cnt++;
3670         }
3671         /*
3672          * Now, we need to examine our pacing rate multipliers.
3673          * If its under 100%, we need to kick it back up to
3674          * 100%. We also don't let it be over our "max" above
3675          * the actual rate i.e. 100% + rack_clamp_atexit_prtt.
3676          * Note setting clamp_atexit_prtt to 0 has the effect
3677          * of setting CA/SS to 100% always at exit (which is
3678          * the default behavior).
3679          */
3680         if (rack_probertt_clear_is) {
3681                 rack->rc_gp_incr = 0;
3682                 rack->rc_gp_bwred = 0;
3683                 rack->rc_gp_timely_inc_cnt = 0;
3684                 rack->rc_gp_timely_dec_cnt = 0;
3685         }
3686         /* Do we do any clamping at exit? */
3687         if (rack->rc_highly_buffered && rack_atexit_prtt_hbp) {
3688                 rack->r_ctl.rack_per_of_gp_ca = rack_atexit_prtt_hbp;
3689                 rack->r_ctl.rack_per_of_gp_ss = rack_atexit_prtt_hbp;
3690         }
3691         if ((rack->rc_highly_buffered == 0) && rack_atexit_prtt) {
3692                 rack->r_ctl.rack_per_of_gp_ca = rack_atexit_prtt;
3693                 rack->r_ctl.rack_per_of_gp_ss = rack_atexit_prtt;
3694         }
3695         /*
3696          * Lets set rtt_diff to 0, so that we will get a "boost"
3697          * after exiting.
3698          */
3699         rack->r_ctl.rc_rtt_diff = 0;
3700
3701         /* Clear all flags so we start fresh */
3702         rack->rc_tp->t_bytes_acked = 0;
3703         rack->rc_tp->ccv->flags &= ~CCF_ABC_SENTAWND;
3704         /*
3705          * If configured to, set the cwnd and ssthresh to
3706          * our targets.
3707          */
3708         if (rack_probe_rtt_sets_cwnd) {
3709                 uint64_t ebdp;
3710                 uint32_t setto;
3711
3712                 /* Set ssthresh so we get into CA once we hit our target */
3713                 if (rack_probertt_use_min_rtt_exit == 1) {
3714                         /* Set to min rtt */
3715                         rack_set_prtt_target(rack, segsiz,
3716                                              get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt));
3717                 } else if (rack_probertt_use_min_rtt_exit == 2) {
3718                         /* Set to current gp rtt */
3719                         rack_set_prtt_target(rack, segsiz,
3720                                              rack->r_ctl.rc_gp_srtt);
3721                 } else if (rack_probertt_use_min_rtt_exit == 3) {
3722                         /* Set to entry gp rtt */
3723                         rack_set_prtt_target(rack, segsiz,
3724                                              rack->r_ctl.rc_entry_gp_rtt);
3725                 } else {
3726                         uint64_t sum;
3727                         uint32_t setval;
3728
3729                         sum = rack->r_ctl.rc_entry_gp_rtt;
3730                         sum *= 10;
3731                         sum /= (uint64_t)(max(1, rack->r_ctl.rc_gp_srtt));
3732                         if (sum >= 20) {
3733                                 /*
3734                                  * A highly buffered path needs
3735                                  * cwnd space for timely to work.
3736                                  * Lets set things up as if
3737                                  * we are heading back here again.
3738                                  */
3739                                 setval = rack->r_ctl.rc_entry_gp_rtt;
3740                         } else if (sum >= 15) {
3741                                 /*
3742                                  * Lets take the smaller of the
3743                                  * two since we are just somewhat
3744                                  * buffered.
3745                                  */
3746                                 setval = rack->r_ctl.rc_gp_srtt;
3747                                 if (setval > rack->r_ctl.rc_entry_gp_rtt)
3748                                         setval = rack->r_ctl.rc_entry_gp_rtt;
3749                         } else {
3750                                 /*
3751                                  * Here we are not highly buffered
3752                                  * and should pick the min we can to
3753                                  * keep from causing loss.
3754                                  */
3755                                 setval = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt);
3756                         }
3757                         rack_set_prtt_target(rack, segsiz,
3758                                              setval);
3759                 }
3760                 if (rack_probe_rtt_sets_cwnd > 1) {
3761                         /* There is a percentage here to boost */
3762                         ebdp = rack->r_ctl.rc_target_probertt_flight;
3763                         ebdp *= rack_probe_rtt_sets_cwnd;
3764                         ebdp /= 100;
3765                         setto = rack->r_ctl.rc_target_probertt_flight + ebdp;
3766                 } else
3767                         setto = rack->r_ctl.rc_target_probertt_flight;
3768                 rack->rc_tp->snd_cwnd = roundup(setto, segsiz);
3769                 if (rack->rc_tp->snd_cwnd < (segsiz * rack_timely_min_segs)) {
3770                         /* Enforce a min */
3771                         rack->rc_tp->snd_cwnd = segsiz * rack_timely_min_segs;
3772                 }
3773                 /* If we set in the cwnd also set the ssthresh point so we are in CA */
3774                 rack->rc_tp->snd_ssthresh = (rack->rc_tp->snd_cwnd - 1);
3775         }
3776         rack_log_rtt_shrinks(rack,  us_cts,
3777                              get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
3778                              __LINE__, RACK_RTTS_EXITPROBE);
3779         /* Clear times last so log has all the info */
3780         rack->r_ctl.rc_probertt_sndmax_atexit = rack->rc_tp->snd_max;
3781         rack->r_ctl.rc_time_probertt_entered = us_cts;
3782         rack->r_ctl.rc_time_probertt_starts = rack->r_ctl.rc_lower_rtt_us_cts = us_cts;
3783         rack->r_ctl.rc_time_of_last_probertt = us_cts;
3784 }
3785
3786 static void
3787 rack_check_probe_rtt(struct tcp_rack *rack, uint32_t us_cts)
3788 {
3789         /* Check in on probe-rtt */
3790         if (rack->rc_gp_filled == 0) {
3791                 /* We do not do p-rtt unless we have gp measurements */
3792                 return;
3793         }
3794         if (rack->in_probe_rtt) {
3795                 uint64_t no_overflow;
3796                 uint32_t endtime, must_stay;
3797
3798                 if (rack->r_ctl.rc_went_idle_time &&
3799                     ((us_cts - rack->r_ctl.rc_went_idle_time) > rack_min_probertt_hold)) {
3800                         /*
3801                          * We went idle during prtt, just exit now.
3802                          */
3803                         rack_exit_probertt(rack, us_cts);
3804                 } else if (rack_probe_rtt_safety_val &&
3805                     TSTMP_GT(us_cts, rack->r_ctl.rc_time_probertt_entered) &&
3806                     ((us_cts - rack->r_ctl.rc_time_probertt_entered) > rack_probe_rtt_safety_val)) {
3807                         /*
3808                          * Probe RTT safety value triggered!
3809                          */
3810                         rack_log_rtt_shrinks(rack,  us_cts,
3811                                              get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
3812                                              __LINE__, RACK_RTTS_SAFETY);
3813                         rack_exit_probertt(rack, us_cts);
3814                 }
3815                 /* Calculate the max we will wait */
3816                 endtime = rack->r_ctl.rc_time_probertt_entered + (rack->r_ctl.rc_gp_srtt * rack_max_drain_wait);
3817                 if (rack->rc_highly_buffered)
3818                         endtime += (rack->r_ctl.rc_gp_srtt * rack_max_drain_hbp);
3819                 /* Calculate the min we must wait */
3820                 must_stay = rack->r_ctl.rc_time_probertt_entered + (rack->r_ctl.rc_gp_srtt * rack_must_drain);
3821                 if ((ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked) > rack->r_ctl.rc_target_probertt_flight) &&
3822                     TSTMP_LT(us_cts, endtime)) {
3823                         uint32_t calc;
3824                         /* Do we lower more? */
3825 no_exit:
3826                         if (TSTMP_GT(us_cts, rack->r_ctl.rc_time_probertt_entered))
3827                                 calc = us_cts - rack->r_ctl.rc_time_probertt_entered;
3828                         else
3829                                 calc = 0;
3830                         calc /= max(rack->r_ctl.rc_gp_srtt, 1);
3831                         if (calc) {
3832                                 /* Maybe */
3833                                 calc *= rack_per_of_gp_probertt_reduce;
3834                                 rack->r_ctl.rack_per_of_gp_probertt = rack_per_of_gp_probertt - calc;
3835                                 /* Limit it too */
3836                                 if (rack->r_ctl.rack_per_of_gp_probertt < rack_per_of_gp_lowthresh)
3837                                         rack->r_ctl.rack_per_of_gp_probertt = rack_per_of_gp_lowthresh;
3838                         }
3839                         /* We must reach target or the time set */
3840                         return;
3841                 }
3842                 if (rack->r_ctl.rc_time_probertt_starts == 0) {
3843                         if ((TSTMP_LT(us_cts, must_stay) &&
3844                              rack->rc_highly_buffered) ||
3845                              (ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked) >
3846                               rack->r_ctl.rc_target_probertt_flight)) {
3847                                 /* We are not past the must_stay time */
3848                                 goto no_exit;
3849                         }
3850                         rack_log_rtt_shrinks(rack,  us_cts,
3851                                              get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
3852                                              __LINE__, RACK_RTTS_REACHTARGET);
3853                         rack->r_ctl.rc_time_probertt_starts = us_cts;
3854                         if (rack->r_ctl.rc_time_probertt_starts == 0)
3855                                 rack->r_ctl.rc_time_probertt_starts = 1;
3856                         /* Restore back to our rate we want to pace at in prtt */
3857                         rack->r_ctl.rack_per_of_gp_probertt = rack_per_of_gp_probertt;
3858                 }
3859                 /*
3860                  * Setup our end time, some number of gp_srtts plus 200ms.
3861                  */
3862                 no_overflow = ((uint64_t)rack->r_ctl.rc_gp_srtt *
3863                                (uint64_t)rack_probertt_gpsrtt_cnt_mul);
3864                 if (rack_probertt_gpsrtt_cnt_div)
3865                         endtime = (uint32_t)(no_overflow / (uint64_t)rack_probertt_gpsrtt_cnt_div);
3866                 else
3867                         endtime = 0;
3868                 endtime += rack_min_probertt_hold;
3869                 endtime += rack->r_ctl.rc_time_probertt_starts;
3870                 if (TSTMP_GEQ(us_cts,  endtime)) {
3871                         /* yes, exit probertt */
3872                         rack_exit_probertt(rack, us_cts);
3873                 }
3874
3875         } else if ((us_cts - rack->r_ctl.rc_lower_rtt_us_cts) >= rack_time_between_probertt) {
3876                 /* Go into probertt, its been too long since we went lower */
3877                 rack_enter_probertt(rack, us_cts);
3878         }
3879 }
3880
3881 static void
3882 rack_update_multiplier(struct tcp_rack *rack, int32_t timely_says, uint64_t last_bw_est,
3883                        uint32_t rtt, int32_t rtt_diff)
3884 {
3885         uint64_t cur_bw, up_bnd, low_bnd, subfr;
3886         uint32_t losses;
3887
3888         if ((rack->rc_gp_dyn_mul == 0) ||
3889             (rack->use_fixed_rate) ||
3890             (rack->in_probe_rtt) ||
3891             (rack->rc_always_pace == 0)) {
3892                 /* No dynamic GP multiplier in play */
3893                 return;
3894         }
3895         losses = rack->r_ctl.rc_loss_count - rack->r_ctl.rc_loss_at_start;
3896         cur_bw = rack_get_bw(rack);
3897         /* Calculate our up and down range */
3898         up_bnd = rack->r_ctl.last_gp_comp_bw * (uint64_t)rack_gp_per_bw_mul_up;
3899         up_bnd /= 100;
3900         up_bnd += rack->r_ctl.last_gp_comp_bw;
3901
3902         subfr = (uint64_t)rack->r_ctl.last_gp_comp_bw * (uint64_t)rack_gp_per_bw_mul_down;
3903         subfr /= 100;
3904         low_bnd = rack->r_ctl.last_gp_comp_bw - subfr;
3905         if ((timely_says == 2) && (rack->r_ctl.rc_no_push_at_mrtt)) {
3906                 /*
3907                  * This is the case where our RTT is above
3908                  * the max target and we have been configured
3909                  * to just do timely no bonus up stuff in that case.
3910                  *
3911                  * There are two configurations, set to 1, and we
3912                  * just do timely if we are over our max. If its
3913                  * set above 1 then we slam the multipliers down
3914                  * to 100 and then decrement per timely.
3915                  */
3916                 rack_log_timely(rack,  timely_says, cur_bw, low_bnd, up_bnd,
3917                                 __LINE__, 3);
3918                 if (rack->r_ctl.rc_no_push_at_mrtt > 1)
3919                         rack_validate_multipliers_at_or_below_100(rack);
3920                 rack_decrease_bw_mul(rack, timely_says, rtt, rtt_diff);
3921         } else if ((last_bw_est < low_bnd) && !losses) {
3922                 /*
3923                  * We are decreasing this is a bit complicated this
3924                  * means we are loosing ground. This could be
3925                  * because another flow entered and we are competing
3926                  * for b/w with it. This will push the RTT up which
3927                  * makes timely unusable unless we want to get shoved
3928                  * into a corner and just be backed off (the age
3929                  * old problem with delay based CC).
3930                  *
3931                  * On the other hand if it was a route change we
3932                  * would like to stay somewhat contained and not
3933                  * blow out the buffers.
3934                  */
3935                 rack_log_timely(rack,  timely_says, cur_bw, low_bnd, up_bnd,
3936                                 __LINE__, 3);
3937                 rack->r_ctl.last_gp_comp_bw = cur_bw;
3938                 if (rack->rc_gp_bwred == 0) {
3939                         /* Go into reduction counting */
3940                         rack->rc_gp_bwred = 1;
3941                         rack->rc_gp_timely_dec_cnt = 0;
3942                 }
3943                 if ((rack->rc_gp_timely_dec_cnt < rack_timely_max_push_drop) ||
3944                     (timely_says == 0)) {
3945                         /*
3946                          * Push another time with a faster pacing
3947                          * to try to gain back (we include override to
3948                          * get a full raise factor).
3949                          */
3950                         if ((rack->rc_gp_saw_ca && rack->r_ctl.rack_per_of_gp_ca <= rack_down_raise_thresh) ||
3951                             (rack->rc_gp_saw_ss && rack->r_ctl.rack_per_of_gp_ss <= rack_down_raise_thresh) ||
3952                             (timely_says == 0) ||
3953                             (rack_down_raise_thresh == 0)) {
3954                                 /*
3955                                  * Do an override up in b/w if we were
3956                                  * below the threshold or if the threshold
3957                                  * is zero we always do the raise.
3958                                  */
3959                                 rack_increase_bw_mul(rack, timely_says, cur_bw, last_bw_est, 1);
3960                         } else {
3961                                 /* Log it stays the same */
3962                                 rack_log_timely(rack,  0, last_bw_est, low_bnd, 0,
3963                                                 __LINE__, 11);
3964                         }
3965                         rack->rc_gp_timely_dec_cnt++;
3966                         /* We are not incrementing really no-count */
3967                         rack->rc_gp_incr = 0;
3968                         rack->rc_gp_timely_inc_cnt = 0;
3969                 } else {
3970                         /*
3971                          * Lets just use the RTT
3972                          * information and give up
3973                          * pushing.
3974                          */
3975                         goto use_timely;
3976                 }
3977         } else if ((timely_says != 2) &&
3978                     !losses &&
3979                     (last_bw_est > up_bnd)) {
3980                 /*
3981                  * We are increasing b/w lets keep going, updating
3982                  * our b/w and ignoring any timely input, unless
3983                  * of course we are at our max raise (if there is one).
3984                  */
3985
3986                 rack_log_timely(rack,  timely_says, cur_bw, low_bnd, up_bnd,
3987                                 __LINE__, 3);
3988                 rack->r_ctl.last_gp_comp_bw = cur_bw;
3989                 if (rack->rc_gp_saw_ss &&
3990                     rack_per_upper_bound_ss &&
3991                      (rack->r_ctl.rack_per_of_gp_ss == rack_per_upper_bound_ss)) {
3992                             /*
3993                              * In cases where we can't go higher
3994                              * we should just use timely.
3995                              */
3996                             goto use_timely;
3997                 }
3998                 if (rack->rc_gp_saw_ca &&
3999                     rack_per_upper_bound_ca &&
4000                     (rack->r_ctl.rack_per_of_gp_ca == rack_per_upper_bound_ca)) {
4001                             /*
4002                              * In cases where we can't go higher
4003                              * we should just use timely.
4004                              */
4005                             goto use_timely;
4006                 }
4007                 rack->rc_gp_bwred = 0;
4008                 rack->rc_gp_timely_dec_cnt = 0;
4009                 /* You get a set number of pushes if timely is trying to reduce */
4010                 if ((rack->rc_gp_incr < rack_timely_max_push_rise) || (timely_says == 0)) {
4011                         rack_increase_bw_mul(rack, timely_says, cur_bw, last_bw_est, 0);
4012                 } else {
4013                         /* Log it stays the same */
4014                         rack_log_timely(rack,  0, last_bw_est, up_bnd, 0,
4015                             __LINE__, 12);
4016                 }
4017                 return;
4018         } else {
4019                 /*
4020                  * We are staying between the lower and upper range bounds
4021                  * so use timely to decide.
4022                  */
4023                 rack_log_timely(rack,  timely_says, cur_bw, low_bnd, up_bnd,
4024                                 __LINE__, 3);
4025 use_timely:
4026                 if (timely_says) {
4027                         rack->rc_gp_incr = 0;
4028                         rack->rc_gp_timely_inc_cnt = 0;
4029                         if ((rack->rc_gp_timely_dec_cnt < rack_timely_max_push_drop) &&
4030                             !losses &&
4031                             (last_bw_est < low_bnd)) {
4032                                 /* We are loosing ground */
4033                                 rack_increase_bw_mul(rack, timely_says, cur_bw, last_bw_est, 0);
4034                                 rack->rc_gp_timely_dec_cnt++;
4035                                 /* We are not incrementing really no-count */
4036                                 rack->rc_gp_incr = 0;
4037                                 rack->rc_gp_timely_inc_cnt = 0;
4038                         } else
4039                                 rack_decrease_bw_mul(rack, timely_says, rtt, rtt_diff);
4040                 } else {
4041                         rack->rc_gp_bwred = 0;
4042                         rack->rc_gp_timely_dec_cnt = 0;
4043                         rack_increase_bw_mul(rack, timely_says, cur_bw, last_bw_est, 0);
4044                 }
4045         }
4046 }
4047
4048 static int32_t
4049 rack_make_timely_judgement(struct tcp_rack *rack, uint32_t rtt, int32_t rtt_diff, uint32_t prev_rtt)
4050 {
4051         int32_t timely_says;
4052         uint64_t log_mult, log_rtt_a_diff;
4053
4054         log_rtt_a_diff = rtt;
4055         log_rtt_a_diff <<= 32;
4056         log_rtt_a_diff |= (uint32_t)rtt_diff;
4057         if (rtt >= (get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) *
4058                     rack_gp_rtt_maxmul)) {
4059                 /* Reduce the b/w multiplier */
4060                 timely_says = 2;
4061                 log_mult = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) * rack_gp_rtt_maxmul;
4062                 log_mult <<= 32;
4063                 log_mult |= prev_rtt;
4064                 rack_log_timely(rack,  timely_says, log_mult,
4065                                 get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
4066                                 log_rtt_a_diff, __LINE__, 4);
4067         } else if (rtt <= (get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) +
4068                            ((get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) * rack_gp_rtt_minmul) /
4069                             max(rack_gp_rtt_mindiv , 1)))) {
4070                 /* Increase the b/w multiplier */
4071                 log_mult = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) +
4072                         ((get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) * rack_gp_rtt_minmul) /
4073                          max(rack_gp_rtt_mindiv , 1));
4074                 log_mult <<= 32;
4075                 log_mult |= prev_rtt;
4076                 timely_says = 0;
4077                 rack_log_timely(rack,  timely_says, log_mult ,
4078                                 get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
4079                                 log_rtt_a_diff, __LINE__, 5);
4080         } else {
4081                 /*
4082                  * Use a gradient to find it the timely gradient
4083                  * is:
4084                  * grad = rc_rtt_diff / min_rtt;
4085                  *
4086                  * anything below or equal to 0 will be
4087                  * a increase indication. Anything above
4088                  * zero is a decrease. Note we take care
4089                  * of the actual gradient calculation
4090                  * in the reduction (its not needed for
4091                  * increase).
4092                  */
4093                 log_mult = prev_rtt;
4094                 if (rtt_diff <= 0) {
4095                         /*
4096                          * Rttdiff is less than zero, increase the
4097                          * b/w multiplier (its 0 or negative)
4098                          */
4099                         timely_says = 0;
4100                         rack_log_timely(rack,  timely_says, log_mult,
4101                                         get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt), log_rtt_a_diff, __LINE__, 6);
4102                 } else {
4103                         /* Reduce the b/w multiplier */
4104                         timely_says = 1;
4105                         rack_log_timely(rack,  timely_says, log_mult,
4106                                         get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt), log_rtt_a_diff, __LINE__, 7);
4107                 }
4108         }
4109         return (timely_says);
4110 }
4111
4112 static void
4113 rack_do_goodput_measurement(struct tcpcb *tp, struct tcp_rack *rack,
4114                             tcp_seq th_ack, int line, uint8_t quality)
4115 {
4116         uint64_t tim, bytes_ps, ltim, stim, utim;
4117         uint32_t segsiz, bytes, reqbytes, us_cts;
4118         int32_t gput, new_rtt_diff, timely_says;
4119         uint64_t  resid_bw, subpart = 0, addpart = 0, srtt;
4120         int did_add = 0;
4121
4122         us_cts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
4123         segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
4124         if (TSTMP_GEQ(us_cts, tp->gput_ts))
4125                 tim = us_cts - tp->gput_ts;
4126         else
4127                 tim = 0;
4128         if (rack->r_ctl.rc_gp_cumack_ts > rack->r_ctl.rc_gp_output_ts)
4129                 stim = rack->r_ctl.rc_gp_cumack_ts - rack->r_ctl.rc_gp_output_ts;
4130         else
4131                 stim = 0;
4132         /*
4133          * Use the larger of the send time or ack time. This prevents us
4134          * from being influenced by ack artifacts to come up with too
4135          * high of measurement. Note that since we are spanning over many more
4136          * bytes in most of our measurements hopefully that is less likely to
4137          * occur.
4138          */
4139         if (tim > stim)
4140                 utim = max(tim, 1);
4141         else
4142                 utim = max(stim, 1);
4143         /* Lets get a msec time ltim too for the old stuff */
4144         ltim = max(1, (utim / HPTS_USEC_IN_MSEC));
4145         gput = (((uint64_t) (th_ack - tp->gput_seq)) << 3) / ltim;
4146         reqbytes = min(rc_init_window(rack), (MIN_GP_WIN * segsiz));
4147         if ((tim == 0) && (stim == 0)) {
4148                 /*
4149                  * Invalid measurement time, maybe
4150                  * all on one ack/one send?
4151                  */
4152                 bytes = 0;
4153                 bytes_ps = 0;
4154                 rack_log_pacing_delay_calc(rack, bytes_ps, reqbytes,
4155                                            0, 0, 0, 10, __LINE__, NULL, quality);
4156                 goto skip_measurement;
4157         }
4158         if (rack->r_ctl.rc_gp_lowrtt == 0xffffffff) {
4159                 /* We never made a us_rtt measurement? */
4160                 bytes = 0;
4161                 bytes_ps = 0;
4162                 rack_log_pacing_delay_calc(rack, bytes_ps, reqbytes,
4163                                            0, 0, 0, 10, __LINE__, NULL, quality);
4164                 goto skip_measurement;
4165         }
4166         /*
4167          * Calculate the maximum possible b/w this connection
4168          * could have. We base our calculation on the lowest
4169          * rtt we have seen during the measurement and the
4170          * largest rwnd the client has given us in that time. This
4171          * forms a BDP that is the maximum that we could ever
4172          * get to the client. Anything larger is not valid.
4173          *
4174          * I originally had code here that rejected measurements
4175          * where the time was less than 1/2 the latest us_rtt.
4176          * But after thinking on that I realized its wrong since
4177          * say you had a 150Mbps or even 1Gbps link, and you
4178          * were a long way away.. example I am in Europe (100ms rtt)
4179          * talking to my 1Gbps link in S.C. Now measuring say 150,000
4180          * bytes my time would be 1.2ms, and yet my rtt would say
4181          * the measurement was invalid the time was < 50ms. The
4182          * same thing is true for 150Mb (8ms of time).
4183          *
4184          * A better way I realized is to look at what the maximum
4185          * the connection could possibly do. This is gated on
4186          * the lowest RTT we have seen and the highest rwnd.
4187          * We should in theory never exceed that, if we are
4188          * then something on the path is storing up packets
4189          * and then feeding them all at once to our endpoint
4190          * messing up our measurement.
4191          */
4192         rack->r_ctl.last_max_bw = rack->r_ctl.rc_gp_high_rwnd;
4193         rack->r_ctl.last_max_bw *= HPTS_USEC_IN_SEC;
4194         rack->r_ctl.last_max_bw /= rack->r_ctl.rc_gp_lowrtt;
4195         if (SEQ_LT(th_ack, tp->gput_seq)) {
4196                 /* No measurement can be made */
4197                 bytes = 0;
4198                 bytes_ps = 0;
4199                 rack_log_pacing_delay_calc(rack, bytes_ps, reqbytes,
4200                                            0, 0, 0, 10, __LINE__, NULL, quality);
4201                 goto skip_measurement;
4202         } else
4203                 bytes = (th_ack - tp->gput_seq);
4204         bytes_ps = (uint64_t)bytes;
4205         /*
4206          * Don't measure a b/w for pacing unless we have gotten at least
4207          * an initial windows worth of data in this measurement interval.
4208          *
4209          * Small numbers of bytes get badly influenced by delayed ack and
4210          * other artifacts. Note we take the initial window or our
4211          * defined minimum GP (defaulting to 10 which hopefully is the
4212          * IW).
4213          */
4214         if (rack->rc_gp_filled == 0) {
4215                 /*
4216                  * The initial estimate is special. We
4217                  * have blasted out an IW worth of packets
4218                  * without a real valid ack ts results. We
4219                  * then setup the app_limited_needs_set flag,
4220                  * this should get the first ack in (probably 2
4221                  * MSS worth) to be recorded as the timestamp.
4222                  * We thus allow a smaller number of bytes i.e.
4223                  * IW - 2MSS.
4224                  */
4225                 reqbytes -= (2 * segsiz);
4226                 /* Also lets fill previous for our first measurement to be neutral */
4227                 rack->r_ctl.rc_prev_gp_srtt = rack->r_ctl.rc_gp_srtt;
4228         }
4229         if ((bytes_ps < reqbytes) || rack->app_limited_needs_set) {
4230                 rack_log_pacing_delay_calc(rack, bytes_ps, reqbytes,
4231                                            rack->r_ctl.rc_app_limited_cnt,
4232                                            0, 0, 10, __LINE__, NULL, quality);
4233                 goto skip_measurement;
4234         }
4235         /*
4236          * We now need to calculate the Timely like status so
4237          * we can update (possibly) the b/w multipliers.
4238          */
4239         new_rtt_diff = (int32_t)rack->r_ctl.rc_gp_srtt - (int32_t)rack->r_ctl.rc_prev_gp_srtt;
4240         if (rack->rc_gp_filled == 0) {
4241                 /* No previous reading */
4242                 rack->r_ctl.rc_rtt_diff = new_rtt_diff;
4243         } else {
4244                 if (rack->measure_saw_probe_rtt == 0) {
4245                         /*
4246                          * We don't want a probertt to be counted
4247                          * since it will be negative incorrectly. We
4248                          * expect to be reducing the RTT when we
4249                          * pace at a slower rate.
4250                          */
4251                         rack->r_ctl.rc_rtt_diff -= (rack->r_ctl.rc_rtt_diff / 8);
4252                         rack->r_ctl.rc_rtt_diff += (new_rtt_diff / 8);
4253                 }
4254         }
4255         timely_says = rack_make_timely_judgement(rack,
4256                 rack->r_ctl.rc_gp_srtt,
4257                 rack->r_ctl.rc_rtt_diff,
4258                 rack->r_ctl.rc_prev_gp_srtt
4259                 );
4260         bytes_ps *= HPTS_USEC_IN_SEC;
4261         bytes_ps /= utim;
4262         if (bytes_ps > rack->r_ctl.last_max_bw) {
4263                 /*
4264                  * Something is on path playing
4265                  * since this b/w is not possible based
4266                  * on our BDP (highest rwnd and lowest rtt
4267                  * we saw in the measurement window).
4268                  *
4269                  * Another option here would be to
4270                  * instead skip the measurement.
4271                  */
4272                 rack_log_pacing_delay_calc(rack, bytes, reqbytes,
4273                                            bytes_ps, rack->r_ctl.last_max_bw, 0,
4274                                            11, __LINE__, NULL, quality);
4275                 bytes_ps = rack->r_ctl.last_max_bw;
4276         }
4277         /* We store gp for b/w in bytes per second */
4278         if (rack->rc_gp_filled == 0) {
4279                 /* Initial measurement */
4280                 if (bytes_ps) {
4281                         rack->r_ctl.gp_bw = bytes_ps;
4282                         rack->rc_gp_filled = 1;
4283                         rack->r_ctl.num_measurements = 1;
4284                         rack_set_pace_segments(rack->rc_tp, rack, __LINE__, NULL);
4285                 } else {
4286                         rack_log_pacing_delay_calc(rack, bytes_ps, reqbytes,
4287                                                    rack->r_ctl.rc_app_limited_cnt,
4288                                                    0, 0, 10, __LINE__, NULL, quality);
4289                 }
4290                 if (tcp_in_hpts(rack->rc_inp) &&
4291                     (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
4292                         /*
4293                          * Ok we can't trust the pacer in this case
4294                          * where we transition from un-paced to paced.
4295                          * Or for that matter when the burst mitigation
4296                          * was making a wild guess and got it wrong.
4297                          * Stop the pacer and clear up all the aggregate
4298                          * delays etc.
4299                          */
4300                         tcp_hpts_remove(rack->rc_inp);
4301                         rack->r_ctl.rc_hpts_flags = 0;
4302                         rack->r_ctl.rc_last_output_to = 0;
4303                 }
4304                 did_add = 2;
4305         } else if (rack->r_ctl.num_measurements < RACK_REQ_AVG) {
4306                 /* Still a small number run an average */
4307                 rack->r_ctl.gp_bw += bytes_ps;
4308                 addpart = rack->r_ctl.num_measurements;
4309                 rack->r_ctl.num_measurements++;
4310                 if (rack->r_ctl.num_measurements >= RACK_REQ_AVG) {
4311                         /* We have collected enough to move forward */
4312                         rack->r_ctl.gp_bw /= (uint64_t)rack->r_ctl.num_measurements;
4313                 }
4314                 did_add = 3;
4315         } else {
4316                 /*
4317                  * We want to take 1/wma of the goodput and add in to 7/8th
4318                  * of the old value weighted by the srtt. So if your measurement
4319                  * period is say 2 SRTT's long you would get 1/4 as the
4320                  * value, if it was like 1/2 SRTT then you would get 1/16th.
4321                  *
4322                  * But we must be careful not to take too much i.e. if the
4323                  * srtt is say 20ms and the measurement is taken over
4324                  * 400ms our weight would be 400/20 i.e. 20. On the
4325                  * other hand if we get a measurement over 1ms with a
4326                  * 10ms rtt we only want to take a much smaller portion.
4327                  */
4328                 if (rack->r_ctl.num_measurements < 0xff) {
4329                         rack->r_ctl.num_measurements++;
4330                 }
4331                 srtt = (uint64_t)tp->t_srtt;
4332                 if (srtt == 0) {
4333                         /*
4334                          * Strange why did t_srtt go back to zero?
4335                          */
4336                         if (rack->r_ctl.rc_rack_min_rtt)
4337                                 srtt = rack->r_ctl.rc_rack_min_rtt;
4338                         else
4339                                 srtt = HPTS_USEC_IN_MSEC;
4340                 }
4341                 /*
4342                  * XXXrrs: Note for reviewers, in playing with
4343                  * dynamic pacing I discovered this GP calculation
4344                  * as done originally leads to some undesired results.
4345                  * Basically you can get longer measurements contributing
4346                  * too much to the WMA. Thus I changed it if you are doing
4347                  * dynamic adjustments to only do the aportioned adjustment
4348                  * if we have a very small (time wise) measurement. Longer
4349                  * measurements just get there weight (defaulting to 1/8)
4350                  * add to the WMA. We may want to think about changing
4351                  * this to always do that for both sides i.e. dynamic
4352                  * and non-dynamic... but considering lots of folks
4353                  * were playing with this I did not want to change the
4354                  * calculation per.se. without your thoughts.. Lawerence?
4355                  * Peter??
4356                  */
4357                 if (rack->rc_gp_dyn_mul == 0) {
4358                         subpart = rack->r_ctl.gp_bw * utim;
4359                         subpart /= (srtt * 8);
4360                         if (subpart < (rack->r_ctl.gp_bw / 2)) {
4361                                 /*
4362                                  * The b/w update takes no more
4363                                  * away then 1/2 our running total
4364                                  * so factor it in.
4365                                  */
4366                                 addpart = bytes_ps * utim;
4367                                 addpart /= (srtt * 8);
4368                         } else {
4369                                 /*
4370                                  * Don't allow a single measurement
4371                                  * to account for more than 1/2 of the
4372                                  * WMA. This could happen on a retransmission
4373                                  * where utim becomes huge compared to
4374                                  * srtt (multiple retransmissions when using
4375                                  * the sending rate which factors in all the
4376                                  * transmissions from the first one).
4377                                  */
4378                                 subpart = rack->r_ctl.gp_bw / 2;
4379                                 addpart = bytes_ps / 2;
4380                         }
4381                         resid_bw = rack->r_ctl.gp_bw - subpart;
4382                         rack->r_ctl.gp_bw = resid_bw + addpart;
4383                         did_add = 1;
4384                 } else {
4385                         if ((utim / srtt) <= 1) {
4386                                 /*
4387                                  * The b/w update was over a small period
4388                                  * of time. The idea here is to prevent a small
4389                                  * measurement time period from counting
4390                                  * too much. So we scale it based on the
4391                                  * time so it attributes less than 1/rack_wma_divisor
4392                                  * of its measurement.
4393                                  */
4394                                 subpart = rack->r_ctl.gp_bw * utim;
4395                                 subpart /= (srtt * rack_wma_divisor);
4396                                 addpart = bytes_ps * utim;
4397                                 addpart /= (srtt * rack_wma_divisor);
4398                         } else {
4399                                 /*
4400                                  * The scaled measurement was long
4401                                  * enough so lets just add in the
4402                                  * portion of the measurement i.e. 1/rack_wma_divisor
4403                                  */
4404                                 subpart = rack->r_ctl.gp_bw / rack_wma_divisor;
4405                                 addpart = bytes_ps / rack_wma_divisor;
4406                         }
4407                         if ((rack->measure_saw_probe_rtt == 0) ||
4408                             (bytes_ps > rack->r_ctl.gp_bw)) {
4409                                 /*
4410                                  * For probe-rtt we only add it in
4411                                  * if its larger, all others we just
4412                                  * add in.
4413                                  */
4414                                 did_add = 1;
4415                                 resid_bw = rack->r_ctl.gp_bw - subpart;
4416                                 rack->r_ctl.gp_bw = resid_bw + addpart;
4417                         }
4418                 }
4419         }
4420         if ((rack->gp_ready == 0) &&
4421             (rack->r_ctl.num_measurements >= rack->r_ctl.req_measurements)) {
4422                 /* We have enough measurements now */
4423                 rack->gp_ready = 1;
4424                 rack_set_cc_pacing(rack);
4425                 if (rack->defer_options)
4426                         rack_apply_deferred_options(rack);
4427         }
4428         rack_log_pacing_delay_calc(rack, subpart, addpart, bytes_ps, stim,
4429                                    rack_get_bw(rack), 22, did_add, NULL, quality);
4430         /* We do not update any multipliers if we are in or have seen a probe-rtt */
4431         if ((rack->measure_saw_probe_rtt == 0) && rack->rc_gp_rtt_set)
4432                 rack_update_multiplier(rack, timely_says, bytes_ps,
4433                                        rack->r_ctl.rc_gp_srtt,
4434                                        rack->r_ctl.rc_rtt_diff);
4435         rack_log_pacing_delay_calc(rack, bytes, tim, bytes_ps, stim,
4436                                    rack_get_bw(rack), 3, line, NULL, quality);
4437         /* reset the gp srtt and setup the new prev */
4438         rack->r_ctl.rc_prev_gp_srtt = rack->r_ctl.rc_gp_srtt;
4439         /* Record the lost count for the next measurement */
4440         rack->r_ctl.rc_loss_at_start = rack->r_ctl.rc_loss_count;
4441         /*
4442          * We restart our diffs based on the gpsrtt in the
4443          * measurement window.
4444          */
4445         rack->rc_gp_rtt_set = 0;
4446         rack->rc_gp_saw_rec = 0;
4447         rack->rc_gp_saw_ca = 0;
4448         rack->rc_gp_saw_ss = 0;
4449         rack->rc_dragged_bottom = 0;
4450 skip_measurement:
4451
4452 #ifdef STATS
4453         stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
4454                                  gput);
4455         /*
4456          * XXXLAS: This is a temporary hack, and should be
4457          * chained off VOI_TCP_GPUT when stats(9) grows an
4458          * API to deal with chained VOIs.
4459          */
4460         if (tp->t_stats_gput_prev > 0)
4461                 stats_voi_update_abs_s32(tp->t_stats,
4462                                          VOI_TCP_GPUT_ND,
4463                                          ((gput - tp->t_stats_gput_prev) * 100) /
4464                                          tp->t_stats_gput_prev);
4465 #endif
4466         tp->t_flags &= ~TF_GPUTINPROG;
4467         tp->t_stats_gput_prev = gput;
4468         /*
4469          * Now are we app limited now and there is space from where we
4470          * were to where we want to go?
4471          *
4472          * We don't do the other case i.e. non-applimited here since
4473          * the next send will trigger us picking up the missing data.
4474          */
4475         if (rack->r_ctl.rc_first_appl &&
4476             TCPS_HAVEESTABLISHED(tp->t_state) &&
4477             rack->r_ctl.rc_app_limited_cnt &&
4478             (SEQ_GT(rack->r_ctl.rc_first_appl->r_start, th_ack)) &&
4479             ((rack->r_ctl.rc_first_appl->r_end - th_ack) >
4480              max(rc_init_window(rack), (MIN_GP_WIN * segsiz)))) {
4481                 /*
4482                  * Yep there is enough outstanding to make a measurement here.
4483                  */
4484                 struct rack_sendmap *rsm, fe;
4485
4486                 rack->r_ctl.rc_gp_lowrtt = 0xffffffff;
4487                 rack->r_ctl.rc_gp_high_rwnd = rack->rc_tp->snd_wnd;
4488                 tp->gput_ts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
4489                 rack->app_limited_needs_set = 0;
4490                 tp->gput_seq = th_ack;
4491                 if (rack->in_probe_rtt)
4492                         rack->measure_saw_probe_rtt = 1;
4493                 else if ((rack->measure_saw_probe_rtt) &&
4494                          (SEQ_GEQ(tp->gput_seq, rack->r_ctl.rc_probertt_sndmax_atexit)))
4495                         rack->measure_saw_probe_rtt = 0;
4496                 if ((rack->r_ctl.rc_first_appl->r_end - th_ack) >= rack_get_measure_window(tp, rack)) {
4497                         /* There is a full window to gain info from */
4498                         tp->gput_ack = tp->gput_seq + rack_get_measure_window(tp, rack);
4499                 } else {
4500                         /* We can only measure up to the applimited point */
4501                         tp->gput_ack = tp->gput_seq + (rack->r_ctl.rc_first_appl->r_end - th_ack);
4502                         if ((tp->gput_ack - tp->gput_seq) < (MIN_GP_WIN * segsiz)) {
4503                                 /*
4504                                  * We don't have enough to make a measurement.
4505                                  */
4506                                 tp->t_flags &= ~TF_GPUTINPROG;
4507                                 rack_log_pacing_delay_calc(rack, tp->gput_ack, tp->gput_seq,
4508                                                            0, 0, 0, 6, __LINE__, NULL, quality);
4509                                 return;
4510                         }
4511                 }
4512                 if (tp->t_state >= TCPS_FIN_WAIT_1) {
4513                         /*
4514                          * We will get no more data into the SB
4515                          * this means we need to have the data available
4516                          * before we start a measurement.
4517                          */
4518                         if (sbavail(&tptosocket(tp)->so_snd) < (tp->gput_ack - tp->gput_seq)) {
4519                                 /* Nope not enough data. */
4520                                 return;
4521                         }
4522                 }
4523                 tp->t_flags |= TF_GPUTINPROG;
4524                 /*
4525                  * Now we need to find the timestamp of the send at tp->gput_seq
4526                  * for the send based measurement.
4527                  */
4528                 fe.r_start = tp->gput_seq;
4529                 rsm = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
4530                 if (rsm) {
4531                         /* Ok send-based limit is set */
4532                         if (SEQ_LT(rsm->r_start, tp->gput_seq)) {
4533                                 /*
4534                                  * Move back to include the earlier part
4535                                  * so our ack time lines up right (this may
4536                                  * make an overlapping measurement but thats
4537                                  * ok).
4538                                  */
4539                                 tp->gput_seq = rsm->r_start;
4540                         }
4541                         if (rsm->r_flags & RACK_ACKED)
4542                                 tp->gput_ts = (uint32_t)rsm->r_ack_arrival;
4543                         else
4544                                 rack->app_limited_needs_set = 1;
4545                         rack->r_ctl.rc_gp_output_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
4546                 } else {
4547                         /*
4548                          * If we don't find the rsm due to some
4549                          * send-limit set the current time, which
4550                          * basically disables the send-limit.
4551                          */
4552                         struct timeval tv;
4553
4554                         microuptime(&tv);
4555                         rack->r_ctl.rc_gp_output_ts = rack_to_usec_ts(&tv);
4556                 }
4557                 rack_log_pacing_delay_calc(rack,
4558                                            tp->gput_seq,
4559                                            tp->gput_ack,
4560                                            (uint64_t)rsm,
4561                                            tp->gput_ts,
4562                                            rack->r_ctl.rc_app_limited_cnt,
4563                                            9,
4564                                            __LINE__, NULL, quality);
4565         }
4566 }
4567
4568 /*
4569  * CC wrapper hook functions
4570  */
4571 static void
4572 rack_ack_received(struct tcpcb *tp, struct tcp_rack *rack, uint32_t th_ack, uint16_t nsegs,
4573     uint16_t type, int32_t recovery)
4574 {
4575         uint32_t prior_cwnd, acked;
4576         struct tcp_log_buffer *lgb = NULL;
4577         uint8_t labc_to_use, quality;
4578
4579         INP_WLOCK_ASSERT(tptoinpcb(tp));
4580         tp->ccv->nsegs = nsegs;
4581         acked = tp->ccv->bytes_this_ack = (th_ack - tp->snd_una);
4582         if ((recovery) && (rack->r_ctl.rc_early_recovery_segs)) {
4583                 uint32_t max;
4584
4585                 max = rack->r_ctl.rc_early_recovery_segs * ctf_fixed_maxseg(tp);
4586                 if (tp->ccv->bytes_this_ack > max) {
4587                         tp->ccv->bytes_this_ack = max;
4588                 }
4589         }
4590 #ifdef STATS
4591         stats_voi_update_abs_s32(tp->t_stats, VOI_TCP_CALCFRWINDIFF,
4592             ((int32_t)rack->r_ctl.cwnd_to_use) - tp->snd_wnd);
4593 #endif
4594         quality = RACK_QUALITY_NONE;
4595         if ((tp->t_flags & TF_GPUTINPROG) &&
4596             rack_enough_for_measurement(tp, rack, th_ack, &quality)) {
4597                 /* Measure the Goodput */
4598                 rack_do_goodput_measurement(tp, rack, th_ack, __LINE__, quality);
4599 #ifdef NETFLIX_PEAKRATE
4600                 if ((type == CC_ACK) &&
4601                     (tp->t_maxpeakrate)) {
4602                         /*
4603                          * We update t_peakrate_thr. This gives us roughly
4604                          * one update per round trip time. Note
4605                          * it will only be used if pace_always is off i.e
4606                          * we don't do this for paced flows.
4607                          */
4608                         rack_update_peakrate_thr(tp);
4609                 }
4610 #endif
4611         }
4612         /* Which way our we limited, if not cwnd limited no advance in CA */
4613         if (tp->snd_cwnd <= tp->snd_wnd)
4614                 tp->ccv->flags |= CCF_CWND_LIMITED;
4615         else
4616                 tp->ccv->flags &= ~CCF_CWND_LIMITED;
4617         if (tp->snd_cwnd > tp->snd_ssthresh) {
4618                 tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
4619                          nsegs * V_tcp_abc_l_var * ctf_fixed_maxseg(tp));
4620                 /* For the setting of a window past use the actual scwnd we are using */
4621                 if (tp->t_bytes_acked >= rack->r_ctl.cwnd_to_use) {
4622                         tp->t_bytes_acked -= rack->r_ctl.cwnd_to_use;
4623                         tp->ccv->flags |= CCF_ABC_SENTAWND;
4624                 }
4625         } else {
4626                 tp->ccv->flags &= ~CCF_ABC_SENTAWND;
4627                 tp->t_bytes_acked = 0;
4628         }
4629         prior_cwnd = tp->snd_cwnd;
4630         if ((recovery == 0) || (rack_max_abc_post_recovery == 0) || rack->r_use_labc_for_rec ||
4631             (rack_client_low_buf && (rack->client_bufferlvl < rack_client_low_buf)))
4632                 labc_to_use = rack->rc_labc;
4633         else
4634                 labc_to_use = rack_max_abc_post_recovery;
4635         if (rack_verbose_logging && (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
4636                 union tcp_log_stackspecific log;
4637                 struct timeval tv;
4638
4639                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
4640                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
4641                 log.u_bbr.flex1 = th_ack;
4642                 log.u_bbr.flex2 = tp->ccv->flags;
4643                 log.u_bbr.flex3 = tp->ccv->bytes_this_ack;
4644                 log.u_bbr.flex4 = tp->ccv->nsegs;
4645                 log.u_bbr.flex5 = labc_to_use;
4646                 log.u_bbr.flex6 = prior_cwnd;
4647                 log.u_bbr.flex7 = V_tcp_do_newsack;
4648                 log.u_bbr.flex8 = 1;
4649                 lgb = tcp_log_event_(tp, NULL, NULL, NULL, BBR_LOG_CWND, 0,
4650                                      0, &log, false, NULL, NULL, 0, &tv);
4651         }
4652         if (CC_ALGO(tp)->ack_received != NULL) {
4653                 /* XXXLAS: Find a way to live without this */
4654                 tp->ccv->curack = th_ack;
4655                 tp->ccv->labc = labc_to_use;
4656                 tp->ccv->flags |= CCF_USE_LOCAL_ABC;
4657                 CC_ALGO(tp)->ack_received(tp->ccv, type);
4658         }
4659         if (lgb) {
4660                 lgb->tlb_stackinfo.u_bbr.flex6 = tp->snd_cwnd;
4661         }
4662         if (rack->r_must_retran) {
4663                 if (SEQ_GEQ(th_ack, rack->r_ctl.rc_snd_max_at_rto)) {
4664                         /*
4665                          * We now are beyond the rxt point so lets disable
4666                          * the flag.
4667                          */
4668                         rack->r_ctl.rc_out_at_rto = 0;
4669                         rack->r_must_retran = 0;
4670                 } else if ((prior_cwnd + ctf_fixed_maxseg(tp)) <= tp->snd_cwnd) {
4671                         /*
4672                          * Only decrement the rc_out_at_rto if the cwnd advances
4673                          * at least a whole segment. Otherwise next time the peer
4674                          * acks, we won't be able to send this generaly happens
4675                          * when we are in Congestion Avoidance.
4676                          */
4677                         if (acked <= rack->r_ctl.rc_out_at_rto){
4678                                 rack->r_ctl.rc_out_at_rto -= acked;
4679                         } else {
4680                                 rack->r_ctl.rc_out_at_rto = 0;
4681                         }
4682                 }
4683         }
4684 #ifdef STATS
4685         stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_LCWIN, rack->r_ctl.cwnd_to_use);
4686 #endif
4687         if (rack->r_ctl.rc_rack_largest_cwnd < rack->r_ctl.cwnd_to_use) {
4688                 rack->r_ctl.rc_rack_largest_cwnd = rack->r_ctl.cwnd_to_use;
4689         }
4690 #ifdef NETFLIX_PEAKRATE
4691         /* we enforce max peak rate if it is set and we are not pacing */
4692         if ((rack->rc_always_pace == 0) &&
4693             tp->t_peakrate_thr &&
4694             (tp->snd_cwnd > tp->t_peakrate_thr)) {
4695                 tp->snd_cwnd = tp->t_peakrate_thr;
4696         }
4697 #endif
4698 }
4699
4700 static void
4701 tcp_rack_partialack(struct tcpcb *tp)
4702 {
4703         struct tcp_rack *rack;
4704
4705         rack = (struct tcp_rack *)tp->t_fb_ptr;
4706         INP_WLOCK_ASSERT(tptoinpcb(tp));
4707         /*
4708          * If we are doing PRR and have enough
4709          * room to send <or> we are pacing and prr
4710          * is disabled we will want to see if we
4711          * can send data (by setting r_wanted_output to
4712          * true).
4713          */
4714         if ((rack->r_ctl.rc_prr_sndcnt > 0) ||
4715             rack->rack_no_prr)
4716                 rack->r_wanted_output = 1;
4717 }
4718
4719 static void
4720 rack_post_recovery(struct tcpcb *tp, uint32_t th_ack)
4721 {
4722         struct tcp_rack *rack;
4723         uint32_t orig_cwnd;
4724
4725         orig_cwnd = tp->snd_cwnd;
4726         INP_WLOCK_ASSERT(tptoinpcb(tp));
4727         rack = (struct tcp_rack *)tp->t_fb_ptr;
4728         /* only alert CC if we alerted when we entered */
4729         if (CC_ALGO(tp)->post_recovery != NULL) {
4730                 tp->ccv->curack = th_ack;
4731                 CC_ALGO(tp)->post_recovery(tp->ccv);
4732                 if (tp->snd_cwnd < tp->snd_ssthresh) {
4733                         /*
4734                          * Rack has burst control and pacing
4735                          * so lets not set this any lower than
4736                          * snd_ssthresh per RFC-6582 (option 2).
4737                          */
4738                         tp->snd_cwnd = tp->snd_ssthresh;
4739                 }
4740         }
4741         if (rack_verbose_logging && (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
4742                 union tcp_log_stackspecific log;
4743                 struct timeval tv;
4744
4745                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
4746                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
4747                 log.u_bbr.flex1 = th_ack;
4748                 log.u_bbr.flex2 = tp->ccv->flags;
4749                 log.u_bbr.flex3 = tp->ccv->bytes_this_ack;
4750                 log.u_bbr.flex4 = tp->ccv->nsegs;
4751                 log.u_bbr.flex5 = V_tcp_abc_l_var;
4752                 log.u_bbr.flex6 = orig_cwnd;
4753                 log.u_bbr.flex7 = V_tcp_do_newsack;
4754                 log.u_bbr.pkts_out = rack->r_ctl.rc_prr_sndcnt;
4755                 log.u_bbr.flex8 = 2;
4756                 tcp_log_event_(tp, NULL, NULL, NULL, BBR_LOG_CWND, 0,
4757                                0, &log, false, NULL, NULL, 0, &tv);
4758         }
4759         if ((rack->rack_no_prr == 0) &&
4760             (rack->no_prr_addback == 0) &&
4761             (rack->r_ctl.rc_prr_sndcnt > 0)) {
4762                 /*
4763                  * Suck the next prr cnt back into cwnd, but
4764                  * only do that if we are not application limited.
4765                  */
4766                 if (ctf_outstanding(tp) <= sbavail(&tptosocket(tp)->so_snd)) {
4767                         /*
4768                          * We are allowed to add back to the cwnd the amount we did
4769                          * not get out if:
4770                          * a) no_prr_addback is off.
4771                          * b) we are not app limited
4772                          * c) we are doing prr
4773                          * <and>
4774                          * d) it is bounded by rack_prr_addbackmax (if addback is 0, then none).
4775                          */
4776                         tp->snd_cwnd += min((ctf_fixed_maxseg(tp) * rack_prr_addbackmax),
4777                                             rack->r_ctl.rc_prr_sndcnt);
4778                 }
4779                 rack->r_ctl.rc_prr_sndcnt = 0;
4780                 rack_log_to_prr(rack, 1, 0, __LINE__);
4781         }
4782         rack_log_to_prr(rack, 14, orig_cwnd, __LINE__);
4783         tp->snd_recover = tp->snd_una;
4784         if (rack->r_ctl.dsack_persist) {
4785                 rack->r_ctl.dsack_persist--;
4786                 if (rack->r_ctl.num_dsack && (rack->r_ctl.dsack_persist == 0)) {
4787                         rack->r_ctl.num_dsack = 0;
4788                 }
4789                 rack_log_dsack_event(rack, 1, __LINE__, 0, 0);
4790         }
4791         EXIT_RECOVERY(tp->t_flags);
4792 }
4793
4794 static void
4795 rack_cong_signal(struct tcpcb *tp, uint32_t type, uint32_t ack, int line)
4796 {
4797         struct tcp_rack *rack;
4798         uint32_t ssthresh_enter, cwnd_enter, in_rec_at_entry, orig_cwnd;
4799
4800         INP_WLOCK_ASSERT(tptoinpcb(tp));
4801 #ifdef STATS
4802         stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
4803 #endif
4804         if (IN_RECOVERY(tp->t_flags) == 0) {
4805                 in_rec_at_entry = 0;
4806                 ssthresh_enter = tp->snd_ssthresh;
4807                 cwnd_enter = tp->snd_cwnd;
4808         } else
4809                 in_rec_at_entry = 1;
4810         rack = (struct tcp_rack *)tp->t_fb_ptr;
4811         switch (type) {
4812         case CC_NDUPACK:
4813                 tp->t_flags &= ~TF_WASFRECOVERY;
4814                 tp->t_flags &= ~TF_WASCRECOVERY;
4815                 if (!IN_FASTRECOVERY(tp->t_flags)) {
4816                         rack->r_ctl.rc_prr_delivered = 0;
4817                         rack->r_ctl.rc_prr_out = 0;
4818                         if (rack->rack_no_prr == 0) {
4819                                 rack->r_ctl.rc_prr_sndcnt = ctf_fixed_maxseg(tp);
4820                                 rack_log_to_prr(rack, 2, in_rec_at_entry, line);
4821                         }
4822                         rack->r_ctl.rc_prr_recovery_fs = tp->snd_max - tp->snd_una;
4823                         tp->snd_recover = tp->snd_max;
4824                         if (tp->t_flags2 & TF2_ECN_PERMIT)
4825                                 tp->t_flags2 |= TF2_ECN_SND_CWR;
4826                 }
4827                 break;
4828         case CC_ECN:
4829                 if (!IN_CONGRECOVERY(tp->t_flags) ||
4830                     /*
4831                      * Allow ECN reaction on ACK to CWR, if
4832                      * that data segment was also CE marked.
4833                      */
4834                     SEQ_GEQ(ack, tp->snd_recover)) {
4835                         EXIT_CONGRECOVERY(tp->t_flags);
4836                         KMOD_TCPSTAT_INC(tcps_ecn_rcwnd);
4837                         tp->snd_recover = tp->snd_max + 1;
4838                         if (tp->t_flags2 & TF2_ECN_PERMIT)
4839                                 tp->t_flags2 |= TF2_ECN_SND_CWR;
4840                 }
4841                 break;
4842         case CC_RTO:
4843                 tp->t_dupacks = 0;
4844                 tp->t_bytes_acked = 0;
4845                 EXIT_RECOVERY(tp->t_flags);
4846                 tp->snd_ssthresh = max(2, min(tp->snd_wnd, rack->r_ctl.cwnd_to_use) / 2 /
4847                     ctf_fixed_maxseg(tp)) * ctf_fixed_maxseg(tp);
4848                 orig_cwnd = tp->snd_cwnd;
4849                 tp->snd_cwnd = ctf_fixed_maxseg(tp);
4850                 rack_log_to_prr(rack, 16, orig_cwnd, line);
4851                 if (tp->t_flags2 & TF2_ECN_PERMIT)
4852                         tp->t_flags2 |= TF2_ECN_SND_CWR;
4853                 break;
4854         case CC_RTO_ERR:
4855                 KMOD_TCPSTAT_INC(tcps_sndrexmitbad);
4856                 /* RTO was unnecessary, so reset everything. */
4857                 tp->snd_cwnd = tp->snd_cwnd_prev;
4858                 tp->snd_ssthresh = tp->snd_ssthresh_prev;
4859                 tp->snd_recover = tp->snd_recover_prev;
4860                 if (tp->t_flags & TF_WASFRECOVERY) {
4861                         ENTER_FASTRECOVERY(tp->t_flags);
4862                         tp->t_flags &= ~TF_WASFRECOVERY;
4863                 }
4864                 if (tp->t_flags & TF_WASCRECOVERY) {
4865                         ENTER_CONGRECOVERY(tp->t_flags);
4866                         tp->t_flags &= ~TF_WASCRECOVERY;
4867                 }
4868                 tp->snd_nxt = tp->snd_max;
4869                 tp->t_badrxtwin = 0;
4870                 break;
4871         }
4872         if ((CC_ALGO(tp)->cong_signal != NULL)  &&
4873             (type != CC_RTO)){
4874                 tp->ccv->curack = ack;
4875                 CC_ALGO(tp)->cong_signal(tp->ccv, type);
4876         }
4877         if ((in_rec_at_entry == 0) && IN_RECOVERY(tp->t_flags)) {
4878                 rack_log_to_prr(rack, 15, cwnd_enter, line);
4879                 rack->r_ctl.dsack_byte_cnt = 0;
4880                 rack->r_ctl.retran_during_recovery = 0;
4881                 rack->r_ctl.rc_cwnd_at_erec = cwnd_enter;
4882                 rack->r_ctl.rc_ssthresh_at_erec = ssthresh_enter;
4883                 rack->r_ent_rec_ns = 1;
4884         }
4885 }
4886
4887 static inline void
4888 rack_cc_after_idle(struct tcp_rack *rack, struct tcpcb *tp)
4889 {
4890         uint32_t i_cwnd;
4891
4892         INP_WLOCK_ASSERT(tptoinpcb(tp));
4893
4894 #ifdef NETFLIX_STATS
4895         KMOD_TCPSTAT_INC(tcps_idle_restarts);
4896         if (tp->t_state == TCPS_ESTABLISHED)
4897                 KMOD_TCPSTAT_INC(tcps_idle_estrestarts);
4898 #endif
4899         if (CC_ALGO(tp)->after_idle != NULL)
4900                 CC_ALGO(tp)->after_idle(tp->ccv);
4901
4902         if (tp->snd_cwnd == 1)
4903                 i_cwnd = tp->t_maxseg;          /* SYN(-ACK) lost */
4904         else
4905                 i_cwnd = rc_init_window(rack);
4906
4907         /*
4908          * Being idle is no different than the initial window. If the cc
4909          * clamps it down below the initial window raise it to the initial
4910          * window.
4911          */
4912         if (tp->snd_cwnd < i_cwnd) {
4913                 tp->snd_cwnd = i_cwnd;
4914         }
4915 }
4916
4917 /*
4918  * Indicate whether this ack should be delayed.  We can delay the ack if
4919  * following conditions are met:
4920  *      - There is no delayed ack timer in progress.
4921  *      - Our last ack wasn't a 0-sized window. We never want to delay
4922  *        the ack that opens up a 0-sized window.
4923  *      - LRO wasn't used for this segment. We make sure by checking that the
4924  *        segment size is not larger than the MSS.
4925  *      - Delayed acks are enabled or this is a half-synchronized T/TCP
4926  *        connection.
4927  */
4928 #define DELAY_ACK(tp, tlen)                      \
4929         (((tp->t_flags & TF_RXWIN0SENT) == 0) && \
4930         ((tp->t_flags & TF_DELACK) == 0) &&      \
4931         (tlen <= tp->t_maxseg) &&                \
4932         (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4933
4934 static struct rack_sendmap *
4935 rack_find_lowest_rsm(struct tcp_rack *rack)
4936 {
4937         struct rack_sendmap *rsm;
4938
4939         /*
4940          * Walk the time-order transmitted list looking for an rsm that is
4941          * not acked. This will be the one that was sent the longest time
4942          * ago that is still outstanding.
4943          */
4944         TAILQ_FOREACH(rsm, &rack->r_ctl.rc_tmap, r_tnext) {
4945                 if (rsm->r_flags & RACK_ACKED) {
4946                         continue;
4947                 }
4948                 goto finish;
4949         }
4950 finish:
4951         return (rsm);
4952 }
4953
4954 static struct rack_sendmap *
4955 rack_find_high_nonack(struct tcp_rack *rack, struct rack_sendmap *rsm)
4956 {
4957         struct rack_sendmap *prsm;
4958
4959         /*
4960          * Walk the sequence order list backward until we hit and arrive at
4961          * the highest seq not acked. In theory when this is called it
4962          * should be the last segment (which it was not).
4963          */
4964         prsm = rsm;
4965         RB_FOREACH_REVERSE_FROM(prsm, rack_rb_tree_head, rsm) {
4966                 if (prsm->r_flags & (RACK_ACKED | RACK_HAS_FIN)) {
4967                         continue;
4968                 }
4969                 return (prsm);
4970         }
4971         return (NULL);
4972 }
4973
4974 static uint32_t
4975 rack_calc_thresh_rack(struct tcp_rack *rack, uint32_t srtt, uint32_t cts)
4976 {
4977         int32_t lro;
4978         uint32_t thresh;
4979
4980         /*
4981          * lro is the flag we use to determine if we have seen reordering.
4982          * If it gets set we have seen reordering. The reorder logic either
4983          * works in one of two ways:
4984          *
4985          * If reorder-fade is configured, then we track the last time we saw
4986          * re-ordering occur. If we reach the point where enough time as
4987          * passed we no longer consider reordering has occuring.
4988          *
4989          * Or if reorder-face is 0, then once we see reordering we consider
4990          * the connection to alway be subject to reordering and just set lro
4991          * to 1.
4992          *
4993          * In the end if lro is non-zero we add the extra time for
4994          * reordering in.
4995          */
4996         if (srtt == 0)
4997                 srtt = 1;
4998         if (rack->r_ctl.rc_reorder_ts) {
4999                 if (rack->r_ctl.rc_reorder_fade) {
5000                         if (SEQ_GEQ(cts, rack->r_ctl.rc_reorder_ts)) {
5001                                 lro = cts - rack->r_ctl.rc_reorder_ts;
5002                                 if (lro == 0) {
5003                                         /*
5004                                          * No time as passed since the last
5005                                          * reorder, mark it as reordering.
5006                                          */
5007                                         lro = 1;
5008                                 }
5009                         } else {
5010                                 /* Negative time? */
5011                                 lro = 0;
5012                         }
5013                         if (lro > rack->r_ctl.rc_reorder_fade) {
5014                                 /* Turn off reordering seen too */
5015                                 rack->r_ctl.rc_reorder_ts = 0;
5016                                 lro = 0;
5017                         }
5018                 } else {
5019                         /* Reodering does not fade */
5020                         lro = 1;
5021                 }
5022         } else {
5023                 lro = 0;
5024         }
5025         if (rack->rc_rack_tmr_std_based == 0) {
5026                 thresh = srtt + rack->r_ctl.rc_pkt_delay;
5027         } else {
5028                 /* Standards based pkt-delay is 1/4 srtt */
5029                 thresh = srtt +  (srtt >> 2);
5030         }
5031         if (lro && (rack->rc_rack_tmr_std_based == 0)) {
5032                 /* It must be set, if not you get 1/4 rtt */
5033                 if (rack->r_ctl.rc_reorder_shift)
5034                         thresh += (srtt >> rack->r_ctl.rc_reorder_shift);
5035                 else
5036                         thresh += (srtt >> 2);
5037         }
5038         if (rack->rc_rack_use_dsack &&
5039             lro &&
5040             (rack->r_ctl.num_dsack > 0)) {
5041                 /*
5042                  * We only increase the reordering window if we
5043                  * have seen reordering <and> we have a DSACK count.
5044                  */
5045                 thresh += rack->r_ctl.num_dsack * (srtt >> 2);
5046                 rack_log_dsack_event(rack, 4, __LINE__, srtt, thresh);
5047         }
5048         /* SRTT * 2 is the ceiling */
5049         if (thresh > (srtt * 2)) {
5050                 thresh = srtt * 2;
5051         }
5052         /* And we don't want it above the RTO max either */
5053         if (thresh > rack_rto_max) {
5054                 thresh = rack_rto_max;
5055         }
5056         rack_log_dsack_event(rack, 6, __LINE__, srtt, thresh);
5057         return (thresh);
5058 }
5059
5060 static uint32_t
5061 rack_calc_thresh_tlp(struct tcpcb *tp, struct tcp_rack *rack,
5062                      struct rack_sendmap *rsm, uint32_t srtt)
5063 {
5064         struct rack_sendmap *prsm;
5065         uint32_t thresh, len;
5066         int segsiz;
5067
5068         if (srtt == 0)
5069                 srtt = 1;
5070         if (rack->r_ctl.rc_tlp_threshold)
5071                 thresh = srtt + (srtt / rack->r_ctl.rc_tlp_threshold);
5072         else
5073                 thresh = (srtt * 2);
5074
5075         /* Get the previous sent packet, if any */
5076         segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
5077         len = rsm->r_end - rsm->r_start;
5078         if (rack->rack_tlp_threshold_use == TLP_USE_ID) {
5079                 /* Exactly like the ID */
5080                 if (((tp->snd_max - tp->snd_una) - rack->r_ctl.rc_sacked + rack->r_ctl.rc_holes_rxt) <= segsiz) {
5081                         uint32_t alt_thresh;
5082                         /*
5083                          * Compensate for delayed-ack with the d-ack time.
5084                          */
5085                         alt_thresh = srtt + (srtt / 2) + rack_delayed_ack_time;
5086                         if (alt_thresh > thresh)
5087                                 thresh = alt_thresh;
5088                 }
5089         } else if (rack->rack_tlp_threshold_use == TLP_USE_TWO_ONE) {
5090                 /* 2.1 behavior */
5091                 prsm = TAILQ_PREV(rsm, rack_head, r_tnext);
5092                 if (prsm && (len <= segsiz)) {
5093                         /*
5094                          * Two packets outstanding, thresh should be (2*srtt) +
5095                          * possible inter-packet delay (if any).
5096                          */
5097                         uint32_t inter_gap = 0;
5098                         int idx, nidx;
5099
5100                         idx = rsm->r_rtr_cnt - 1;
5101                         nidx = prsm->r_rtr_cnt - 1;
5102                         if (rsm->r_tim_lastsent[nidx] >= prsm->r_tim_lastsent[idx]) {
5103                                 /* Yes it was sent later (or at the same time) */
5104                                 inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
5105                         }
5106                         thresh += inter_gap;
5107                 } else if (len <= segsiz) {
5108                         /*
5109                          * Possibly compensate for delayed-ack.
5110                          */
5111                         uint32_t alt_thresh;
5112
5113                         alt_thresh = srtt + (srtt / 2) + rack_delayed_ack_time;
5114                         if (alt_thresh > thresh)
5115                                 thresh = alt_thresh;
5116                 }
5117         } else if (rack->rack_tlp_threshold_use == TLP_USE_TWO_TWO) {
5118                 /* 2.2 behavior */
5119                 if (len <= segsiz) {
5120                         uint32_t alt_thresh;
5121                         /*
5122                          * Compensate for delayed-ack with the d-ack time.
5123                          */
5124                         alt_thresh = srtt + (srtt / 2) + rack_delayed_ack_time;
5125                         if (alt_thresh > thresh)
5126                                 thresh = alt_thresh;
5127                 }
5128         }
5129         /* Not above an RTO */
5130         if (thresh > tp->t_rxtcur) {
5131                 thresh = tp->t_rxtcur;
5132         }
5133         /* Not above a RTO max */
5134         if (thresh > rack_rto_max) {
5135                 thresh = rack_rto_max;
5136         }
5137         /* Apply user supplied min TLP */
5138         if (thresh < rack_tlp_min) {
5139                 thresh = rack_tlp_min;
5140         }
5141         return (thresh);
5142 }
5143
5144 static uint32_t
5145 rack_grab_rtt(struct tcpcb *tp, struct tcp_rack *rack)
5146 {
5147         /*
5148          * We want the rack_rtt which is the
5149          * last rtt we measured. However if that
5150          * does not exist we fallback to the srtt (which
5151          * we probably will never do) and then as a last
5152          * resort we use RACK_INITIAL_RTO if no srtt is
5153          * yet set.
5154          */
5155         if (rack->rc_rack_rtt)
5156                 return (rack->rc_rack_rtt);
5157         else if (tp->t_srtt == 0)
5158                 return (RACK_INITIAL_RTO);
5159         return (tp->t_srtt);
5160 }
5161
5162 static struct rack_sendmap *
5163 rack_check_recovery_mode(struct tcpcb *tp, uint32_t tsused)
5164 {
5165         /*
5166          * Check to see that we don't need to fall into recovery. We will
5167          * need to do so if our oldest transmit is past the time we should
5168          * have had an ack.
5169          */
5170         struct tcp_rack *rack;
5171         struct rack_sendmap *rsm;
5172         int32_t idx;
5173         uint32_t srtt, thresh;
5174
5175         rack = (struct tcp_rack *)tp->t_fb_ptr;
5176         if (RB_EMPTY(&rack->r_ctl.rc_mtree)) {
5177                 return (NULL);
5178         }
5179         rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
5180         if (rsm == NULL)
5181                 return (NULL);
5182
5183
5184         if (rsm->r_flags & RACK_ACKED) {
5185                 rsm = rack_find_lowest_rsm(rack);
5186                 if (rsm == NULL)
5187                         return (NULL);
5188         }
5189         idx = rsm->r_rtr_cnt - 1;
5190         srtt = rack_grab_rtt(tp, rack);
5191         thresh = rack_calc_thresh_rack(rack, srtt, tsused);
5192         if (TSTMP_LT(tsused, ((uint32_t)rsm->r_tim_lastsent[idx]))) {
5193                 return (NULL);
5194         }
5195         if ((tsused - ((uint32_t)rsm->r_tim_lastsent[idx])) < thresh) {
5196                 return (NULL);
5197         }
5198         /* Ok if we reach here we are over-due and this guy can be sent */
5199         rack_cong_signal(tp, CC_NDUPACK, tp->snd_una, __LINE__);
5200         return (rsm);
5201 }
5202
5203 static uint32_t
5204 rack_get_persists_timer_val(struct tcpcb *tp, struct tcp_rack *rack)
5205 {
5206         int32_t t;
5207         int32_t tt;
5208         uint32_t ret_val;
5209
5210         t = (tp->t_srtt + (tp->t_rttvar << 2));
5211         RACK_TCPT_RANGESET(tt, t * tcp_backoff[tp->t_rxtshift],
5212             rack_persist_min, rack_persist_max, rack->r_ctl.timer_slop);
5213         rack->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
5214         ret_val = (uint32_t)tt;
5215         return (ret_val);
5216 }
5217
5218 static uint32_t
5219 rack_timer_start(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, int sup_rack)
5220 {
5221         /*
5222          * Start the FR timer, we do this based on getting the first one in
5223          * the rc_tmap. Note that if its NULL we must stop the timer. in all
5224          * events we need to stop the running timer (if its running) before
5225          * starting the new one.
5226          */
5227         uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
5228         uint32_t srtt_cur;
5229         int32_t idx;
5230         int32_t is_tlp_timer = 0;
5231         struct rack_sendmap *rsm;
5232
5233         if (rack->t_timers_stopped) {
5234                 /* All timers have been stopped none are to run */
5235                 return (0);
5236         }
5237         if (rack->rc_in_persist) {
5238                 /* We can't start any timer in persists */
5239                 return (rack_get_persists_timer_val(tp, rack));
5240         }
5241         rack->rc_on_min_to = 0;
5242         if ((tp->t_state < TCPS_ESTABLISHED) ||
5243             ((tp->t_flags & TF_SACK_PERMIT) == 0)) {
5244                 goto activate_rxt;
5245         }
5246         rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
5247         if ((rsm == NULL) || sup_rack) {
5248                 /* Nothing on the send map or no rack */
5249 activate_rxt:
5250                 time_since_sent = 0;
5251                 rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
5252                 if (rsm) {
5253                         /*
5254                          * Should we discount the RTX timer any?
5255                          *
5256                          * We want to discount it the smallest amount.
5257                          * If a timer (Rack/TLP or RXT) has gone off more
5258                          * recently thats the discount we want to use (now - timer time).
5259                          * If the retransmit of the oldest packet was more recent then
5260                          * we want to use that (now - oldest-packet-last_transmit_time).
5261                          *
5262                          */
5263                         idx = rsm->r_rtr_cnt - 1;
5264                         if (TSTMP_GEQ(rack->r_ctl.rc_tlp_rxt_last_time, ((uint32_t)rsm->r_tim_lastsent[idx])))
5265                                 tstmp_touse = (uint32_t)rack->r_ctl.rc_tlp_rxt_last_time;
5266                         else
5267                                 tstmp_touse = (uint32_t)rsm->r_tim_lastsent[idx];
5268                         if (TSTMP_GT(cts, tstmp_touse))
5269                             time_since_sent = cts - tstmp_touse;
5270                 }
5271                 if (SEQ_LT(tp->snd_una, tp->snd_max) ||
5272                     sbavail(&tptosocket(tp)->so_snd)) {
5273                         rack->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
5274                         to = tp->t_rxtcur;
5275                         if (to > time_since_sent)
5276                                 to -= time_since_sent;
5277                         else
5278                                 to = rack->r_ctl.rc_min_to;
5279                         if (to == 0)
5280                                 to = 1;
5281                         /* Special case for KEEPINIT */
5282                         if ((TCPS_HAVEESTABLISHED(tp->t_state) == 0) &&
5283                             (TP_KEEPINIT(tp) != 0) &&
5284                             rsm) {
5285                                 /*
5286                                  * We have to put a ceiling on the rxt timer
5287                                  * of the keep-init timeout.
5288                                  */
5289                                 uint32_t max_time, red;
5290
5291                                 max_time = TICKS_2_USEC(TP_KEEPINIT(tp));
5292                                 if (TSTMP_GT(cts, (uint32_t)rsm->r_tim_lastsent[0])) {
5293                                         red = (cts - (uint32_t)rsm->r_tim_lastsent[0]);
5294                                         if (red < max_time)
5295                                                 max_time -= red;
5296                                         else
5297                                                 max_time = 1;
5298                                 }
5299                                 /* Reduce timeout to the keep value if needed */
5300                                 if (max_time < to)
5301                                         to = max_time;
5302                         }
5303                         return (to);
5304                 }
5305                 return (0);
5306         }
5307         if (rsm->r_flags & RACK_ACKED) {
5308                 rsm = rack_find_lowest_rsm(rack);
5309                 if (rsm == NULL) {
5310                         /* No lowest? */
5311                         goto activate_rxt;
5312                 }
5313         }
5314         if (rack->sack_attack_disable) {
5315                 /*
5316                  * We don't want to do
5317                  * any TLP's if you are an attacker.
5318                  * Though if you are doing what
5319                  * is expected you may still have
5320                  * SACK-PASSED marks.
5321                  */
5322                 goto activate_rxt;
5323         }
5324         /* Convert from ms to usecs */
5325         if ((rsm->r_flags & RACK_SACK_PASSED) ||
5326             (rsm->r_flags & RACK_RWND_COLLAPSED) ||
5327             (rsm->r_dupack >= DUP_ACK_THRESHOLD)) {
5328                 if ((tp->t_flags & TF_SENTFIN) &&
5329                     ((tp->snd_max - tp->snd_una) == 1) &&
5330                     (rsm->r_flags & RACK_HAS_FIN)) {
5331                         /*
5332                          * We don't start a rack timer if all we have is a
5333                          * FIN outstanding.
5334                          */
5335                         goto activate_rxt;
5336                 }
5337                 if ((rack->use_rack_rr == 0) &&
5338                     (IN_FASTRECOVERY(tp->t_flags)) &&
5339                     (rack->rack_no_prr == 0) &&
5340                      (rack->r_ctl.rc_prr_sndcnt  < ctf_fixed_maxseg(tp))) {
5341                         /*
5342                          * We are not cheating, in recovery  and
5343                          * not enough ack's to yet get our next
5344                          * retransmission out.
5345                          *
5346                          * Note that classified attackers do not
5347                          * get to use the rack-cheat.
5348                          */
5349                         goto activate_tlp;
5350                 }
5351                 srtt = rack_grab_rtt(tp, rack);
5352                 thresh = rack_calc_thresh_rack(rack, srtt, cts);
5353                 idx = rsm->r_rtr_cnt - 1;
5354                 exp = ((uint32_t)rsm->r_tim_lastsent[idx]) + thresh;
5355                 if (SEQ_GEQ(exp, cts)) {
5356                         to = exp - cts;
5357                         if (to < rack->r_ctl.rc_min_to) {
5358                                 to = rack->r_ctl.rc_min_to;
5359                                 if (rack->r_rr_config == 3)
5360                                         rack->rc_on_min_to = 1;
5361                         }
5362                 } else {
5363                         to = rack->r_ctl.rc_min_to;
5364                         if (rack->r_rr_config == 3)
5365                                 rack->rc_on_min_to = 1;
5366                 }
5367         } else {
5368                 /* Ok we need to do a TLP not RACK */
5369 activate_tlp:
5370                 if ((rack->rc_tlp_in_progress != 0) &&
5371                     (rack->r_ctl.rc_tlp_cnt_out >= rack_tlp_limit)) {
5372                         /*
5373                          * The previous send was a TLP and we have sent
5374                          * N TLP's without sending new data.
5375                          */
5376                         goto activate_rxt;
5377                 }
5378                 rsm = TAILQ_LAST_FAST(&rack->r_ctl.rc_tmap, rack_sendmap, r_tnext);
5379                 if (rsm == NULL) {
5380                         /* We found no rsm to TLP with. */
5381                         goto activate_rxt;
5382                 }
5383                 if (rsm->r_flags & RACK_HAS_FIN) {
5384                         /* If its a FIN we dont do TLP */
5385                         rsm = NULL;
5386                         goto activate_rxt;
5387                 }
5388                 idx = rsm->r_rtr_cnt - 1;
5389                 time_since_sent = 0;
5390                 if (TSTMP_GEQ(((uint32_t)rsm->r_tim_lastsent[idx]), rack->r_ctl.rc_tlp_rxt_last_time))
5391                         tstmp_touse = (uint32_t)rsm->r_tim_lastsent[idx];
5392                 else
5393                         tstmp_touse = (uint32_t)rack->r_ctl.rc_tlp_rxt_last_time;
5394                 if (TSTMP_GT(cts, tstmp_touse))
5395                     time_since_sent = cts - tstmp_touse;
5396                 is_tlp_timer = 1;
5397                 if (tp->t_srtt) {
5398                         if ((rack->rc_srtt_measure_made == 0) &&
5399                             (tp->t_srtt == 1)) {
5400                                 /*
5401                                  * If another stack as run and set srtt to 1,
5402                                  * then the srtt was 0, so lets use the initial.
5403                                  */
5404                                 srtt = RACK_INITIAL_RTO;
5405                         } else {
5406                                 srtt_cur = tp->t_srtt;
5407                                 srtt = srtt_cur;
5408                         }
5409                 } else
5410                         srtt = RACK_INITIAL_RTO;
5411                 /*
5412                  * If the SRTT is not keeping up and the
5413                  * rack RTT has spiked we want to use
5414                  * the last RTT not the smoothed one.
5415                  */
5416                 if (rack_tlp_use_greater &&
5417                     tp->t_srtt &&
5418                     (srtt < rack_grab_rtt(tp, rack))) {
5419                         srtt = rack_grab_rtt(tp, rack);
5420                 }
5421                 thresh = rack_calc_thresh_tlp(tp, rack, rsm, srtt);
5422                 if (thresh > time_since_sent) {
5423                         to = thresh - time_since_sent;
5424                 } else {
5425                         to = rack->r_ctl.rc_min_to;
5426                         rack_log_alt_to_to_cancel(rack,
5427                                                   thresh,               /* flex1 */
5428                                                   time_since_sent,      /* flex2 */
5429                                                   tstmp_touse,          /* flex3 */
5430                                                   rack->r_ctl.rc_tlp_rxt_last_time, /* flex4 */
5431                                                   (uint32_t)rsm->r_tim_lastsent[idx],
5432                                                   srtt,
5433                                                   idx, 99);
5434                 }
5435                 if (to < rack_tlp_min) {
5436                         to = rack_tlp_min;
5437                 }
5438                 if (to > TICKS_2_USEC(TCPTV_REXMTMAX)) {
5439                         /*
5440                          * If the TLP time works out to larger than the max
5441                          * RTO lets not do TLP.. just RTO.
5442                          */
5443                         goto activate_rxt;
5444                 }
5445         }
5446         if (is_tlp_timer == 0) {
5447                 rack->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
5448         } else {
5449                 rack->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
5450         }
5451         if (to == 0)
5452                 to = 1;
5453         return (to);
5454 }
5455
5456 static void
5457 rack_enter_persist(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
5458 {
5459         if (rack->rc_in_persist == 0) {
5460                 if (tp->t_flags & TF_GPUTINPROG) {
5461                         /*
5462                          * Stop the goodput now, the calling of the
5463                          * measurement function clears the flag.
5464                          */
5465                         rack_do_goodput_measurement(tp, rack, tp->snd_una, __LINE__,
5466                                                     RACK_QUALITY_PERSIST);
5467                 }
5468 #ifdef NETFLIX_SHARED_CWND
5469                 if (rack->r_ctl.rc_scw) {
5470                         tcp_shared_cwnd_idle(rack->r_ctl.rc_scw, rack->r_ctl.rc_scw_index);
5471                         rack->rack_scwnd_is_idle = 1;
5472                 }
5473 #endif
5474                 rack->r_ctl.rc_went_idle_time = tcp_get_usecs(NULL);
5475                 if (rack->r_ctl.rc_went_idle_time == 0)
5476                         rack->r_ctl.rc_went_idle_time = 1;
5477                 rack_timer_cancel(tp, rack, cts, __LINE__);
5478                 rack->r_ctl.persist_lost_ends = 0;
5479                 rack->probe_not_answered = 0;
5480                 rack->forced_ack = 0;
5481                 tp->t_rxtshift = 0;
5482                 RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
5483                               rack_rto_min, rack_rto_max, rack->r_ctl.timer_slop);
5484                 rack->rc_in_persist = 1;
5485         }
5486 }
5487
5488 static void
5489 rack_exit_persist(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
5490 {
5491         if (tcp_in_hpts(rack->rc_inp)) {
5492                 tcp_hpts_remove(rack->rc_inp);
5493                 rack->r_ctl.rc_hpts_flags = 0;
5494         }
5495 #ifdef NETFLIX_SHARED_CWND
5496         if (rack->r_ctl.rc_scw) {
5497                 tcp_shared_cwnd_active(rack->r_ctl.rc_scw, rack->r_ctl.rc_scw_index);
5498                 rack->rack_scwnd_is_idle = 0;
5499         }
5500 #endif
5501         if (rack->rc_gp_dyn_mul &&
5502             (rack->use_fixed_rate == 0) &&
5503             (rack->rc_always_pace)) {
5504                 /*
5505                  * Do we count this as if a probe-rtt just
5506                  * finished?
5507                  */
5508                 uint32_t time_idle, idle_min;
5509
5510                 time_idle = tcp_get_usecs(NULL) - rack->r_ctl.rc_went_idle_time;
5511                 idle_min = rack_min_probertt_hold;
5512                 if (rack_probertt_gpsrtt_cnt_div) {
5513                         uint64_t extra;
5514                         extra = (uint64_t)rack->r_ctl.rc_gp_srtt *
5515                                 (uint64_t)rack_probertt_gpsrtt_cnt_mul;
5516                         extra /= (uint64_t)rack_probertt_gpsrtt_cnt_div;
5517                         idle_min += (uint32_t)extra;
5518                 }
5519                 if (time_idle >= idle_min) {
5520                         /* Yes, we count it as a probe-rtt. */
5521                         uint32_t us_cts;
5522
5523                         us_cts = tcp_get_usecs(NULL);
5524                         if (rack->in_probe_rtt == 0) {
5525                                 rack->r_ctl.rc_lower_rtt_us_cts = us_cts;
5526                                 rack->r_ctl.rc_time_probertt_entered = rack->r_ctl.rc_lower_rtt_us_cts;
5527                                 rack->r_ctl.rc_time_probertt_starts = rack->r_ctl.rc_lower_rtt_us_cts;
5528                                 rack->r_ctl.rc_time_of_last_probertt = rack->r_ctl.rc_lower_rtt_us_cts;
5529                         } else {
5530                                 rack_exit_probertt(rack, us_cts);
5531                         }
5532                 }
5533         }
5534         rack->rc_in_persist = 0;
5535         rack->r_ctl.rc_went_idle_time = 0;
5536         tp->t_rxtshift = 0;
5537         RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
5538            rack_rto_min, rack_rto_max, rack->r_ctl.timer_slop);
5539         rack->r_ctl.rc_agg_delayed = 0;
5540         rack->r_early = 0;
5541         rack->r_late = 0;
5542         rack->r_ctl.rc_agg_early = 0;
5543 }
5544
5545 static void
5546 rack_log_hpts_diag(struct tcp_rack *rack, uint32_t cts,
5547                    struct hpts_diag *diag, struct timeval *tv)
5548 {
5549         if (rack_verbose_logging && rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
5550                 union tcp_log_stackspecific log;
5551
5552                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
5553                 log.u_bbr.flex1 = diag->p_nxt_slot;
5554                 log.u_bbr.flex2 = diag->p_cur_slot;
5555                 log.u_bbr.flex3 = diag->slot_req;
5556                 log.u_bbr.flex4 = diag->inp_hptsslot;
5557                 log.u_bbr.flex5 = diag->slot_remaining;
5558                 log.u_bbr.flex6 = diag->need_new_to;
5559                 log.u_bbr.flex7 = diag->p_hpts_active;
5560                 log.u_bbr.flex8 = diag->p_on_min_sleep;
5561                 /* Hijack other fields as needed */
5562                 log.u_bbr.epoch = diag->have_slept;
5563                 log.u_bbr.lt_epoch = diag->yet_to_sleep;
5564                 log.u_bbr.pkts_out = diag->co_ret;
5565                 log.u_bbr.applimited = diag->hpts_sleep_time;
5566                 log.u_bbr.delivered = diag->p_prev_slot;
5567                 log.u_bbr.inflight = diag->p_runningslot;
5568                 log.u_bbr.bw_inuse = diag->wheel_slot;
5569                 log.u_bbr.rttProp = diag->wheel_cts;
5570                 log.u_bbr.timeStamp = cts;
5571                 log.u_bbr.delRate = diag->maxslots;
5572                 log.u_bbr.cur_del_rate = diag->p_curtick;
5573                 log.u_bbr.cur_del_rate <<= 32;
5574                 log.u_bbr.cur_del_rate |= diag->p_lasttick;
5575                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
5576                     &rack->rc_inp->inp_socket->so_rcv,
5577                     &rack->rc_inp->inp_socket->so_snd,
5578                     BBR_LOG_HPTSDIAG, 0,
5579                     0, &log, false, tv);
5580         }
5581
5582 }
5583
5584 static void
5585 rack_log_wakeup(struct tcpcb *tp, struct tcp_rack *rack, struct sockbuf *sb, uint32_t len, int type)
5586 {
5587         if (rack_verbose_logging && rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
5588                 union tcp_log_stackspecific log;
5589                 struct timeval tv;
5590
5591                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
5592                 log.u_bbr.flex1 = sb->sb_flags;
5593                 log.u_bbr.flex2 = len;
5594                 log.u_bbr.flex3 = sb->sb_state;
5595                 log.u_bbr.flex8 = type;
5596                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
5597                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
5598                     &rack->rc_inp->inp_socket->so_rcv,
5599                     &rack->rc_inp->inp_socket->so_snd,
5600                     TCP_LOG_SB_WAKE, 0,
5601                     len, &log, false, &tv);
5602         }
5603 }
5604
5605 static void
5606 rack_start_hpts_timer(struct tcp_rack *rack, struct tcpcb *tp, uint32_t cts,
5607       int32_t slot, uint32_t tot_len_this_send, int sup_rack)
5608 {
5609         struct hpts_diag diag;
5610         struct inpcb *inp = tptoinpcb(tp);
5611         struct timeval tv;
5612         uint32_t delayed_ack = 0;
5613         uint32_t hpts_timeout;
5614         uint32_t entry_slot = slot;
5615         uint8_t stopped;
5616         uint32_t left = 0;
5617         uint32_t us_cts;
5618
5619         if ((tp->t_state == TCPS_CLOSED) ||
5620             (tp->t_state == TCPS_LISTEN)) {
5621                 return;
5622         }
5623         if (tcp_in_hpts(inp)) {
5624                 /* Already on the pacer */
5625                 return;
5626         }
5627         stopped = rack->rc_tmr_stopped;
5628         if (stopped && TSTMP_GT(rack->r_ctl.rc_timer_exp, cts)) {
5629                 left = rack->r_ctl.rc_timer_exp - cts;
5630         }
5631         rack->r_ctl.rc_timer_exp = 0;
5632         rack->r_ctl.rc_hpts_flags = 0;
5633         us_cts = tcp_get_usecs(&tv);
5634         /* Now early/late accounting */
5635         rack_log_pacing_delay_calc(rack, entry_slot, slot, 0, 0, 0, 26, __LINE__, NULL, 0);
5636         if (rack->r_early && (rack->rc_ack_can_sendout_data == 0)) {
5637                 /*
5638                  * We have a early carry over set,
5639                  * we can always add more time so we
5640                  * can always make this compensation.
5641                  *
5642                  * Note if ack's are allowed to wake us do not
5643                  * penalize the next timer for being awoke
5644                  * by an ack aka the rc_agg_early (non-paced mode).
5645                  */
5646                 slot += rack->r_ctl.rc_agg_early;
5647                 rack->r_early = 0;
5648                 rack->r_ctl.rc_agg_early = 0;
5649         }
5650         if (rack->r_late) {
5651                 /*
5652                  * This is harder, we can
5653                  * compensate some but it
5654                  * really depends on what
5655                  * the current pacing time is.
5656                  */
5657                 if (rack->r_ctl.rc_agg_delayed >= slot) {
5658                         /*
5659                          * We can't compensate for it all.
5660                          * And we have to have some time
5661                          * on the clock. We always have a min
5662                          * 10 slots (10 x 10 i.e. 100 usecs).
5663                          */
5664                         if (slot <= HPTS_TICKS_PER_SLOT) {
5665                                 /* We gain delay */
5666                                 rack->r_ctl.rc_agg_delayed += (HPTS_TICKS_PER_SLOT - slot);
5667                                 slot = HPTS_TICKS_PER_SLOT;
5668                         } else {
5669                                 /* We take off some */
5670                                 rack->r_ctl.rc_agg_delayed -= (slot - HPTS_TICKS_PER_SLOT);
5671                                 slot = HPTS_TICKS_PER_SLOT;
5672                         }
5673                 } else {
5674                         slot -= rack->r_ctl.rc_agg_delayed;
5675                         rack->r_ctl.rc_agg_delayed = 0;
5676                         /* Make sure we have 100 useconds at minimum */
5677                         if (slot < HPTS_TICKS_PER_SLOT) {
5678                                 rack->r_ctl.rc_agg_delayed = HPTS_TICKS_PER_SLOT - slot;
5679                                 slot = HPTS_TICKS_PER_SLOT;
5680                         }
5681                         if (rack->r_ctl.rc_agg_delayed == 0)
5682                                 rack->r_late = 0;
5683                 }
5684         }
5685         if (slot) {
5686                 /* We are pacing too */
5687                 rack->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
5688         }
5689         hpts_timeout = rack_timer_start(tp, rack, cts, sup_rack);
5690 #ifdef NETFLIX_EXP_DETECTION
5691         if (rack->sack_attack_disable &&
5692             (slot < tcp_sad_pacing_interval)) {
5693                 /*
5694                  * We have a potential attacker on
5695                  * the line. We have possibly some
5696                  * (or now) pacing time set. We want to
5697                  * slow down the processing of sacks by some
5698                  * amount (if it is an attacker). Set the default
5699                  * slot for attackers in place (unless the orginal
5700                  * interval is longer). Its stored in
5701                  * micro-seconds, so lets convert to msecs.
5702                  */
5703                 slot = tcp_sad_pacing_interval;
5704         }
5705 #endif
5706         if (tp->t_flags & TF_DELACK) {
5707                 delayed_ack = TICKS_2_USEC(tcp_delacktime);
5708                 rack->r_ctl.rc_hpts_flags |= PACE_TMR_DELACK;
5709         }
5710         if (delayed_ack && ((hpts_timeout == 0) ||
5711                             (delayed_ack < hpts_timeout)))
5712                 hpts_timeout = delayed_ack;
5713         else
5714                 rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
5715         /*
5716          * If no timers are going to run and we will fall off the hptsi
5717          * wheel, we resort to a keep-alive timer if its configured.
5718          */
5719         if ((hpts_timeout == 0) &&
5720             (slot == 0)) {
5721                 if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
5722                     (tp->t_state <= TCPS_CLOSING)) {
5723                         /*
5724                          * Ok we have no timer (persists, rack, tlp, rxt  or
5725                          * del-ack), we don't have segments being paced. So
5726                          * all that is left is the keepalive timer.
5727                          */
5728                         if (TCPS_HAVEESTABLISHED(tp->t_state)) {
5729                                 /* Get the established keep-alive time */
5730                                 hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
5731                         } else {
5732                                 /*
5733                                  * Get the initial setup keep-alive time,
5734                                  * note that this is probably not going to
5735                                  * happen, since rack will be running a rxt timer
5736                                  * if a SYN of some sort is outstanding. It is
5737                                  * actually handled in rack_timeout_rxt().
5738                                  */
5739                                 hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
5740                         }
5741                         rack->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
5742                         if (rack->in_probe_rtt) {
5743                                 /*
5744                                  * We want to instead not wake up a long time from
5745                                  * now but to wake up about the time we would
5746                                  * exit probe-rtt and initiate a keep-alive ack.
5747                                  * This will get us out of probe-rtt and update
5748                                  * our min-rtt.
5749                                  */
5750                                 hpts_timeout = rack_min_probertt_hold;
5751                         }
5752                 }
5753         }
5754         if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
5755             (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
5756                 /*
5757                  * RACK, TLP, persists and RXT timers all are restartable
5758                  * based on actions input .. i.e we received a packet (ack
5759                  * or sack) and that changes things (rw, or snd_una etc).
5760                  * Thus we can restart them with a new value. For
5761                  * keep-alive, delayed_ack we keep track of what was left
5762                  * and restart the timer with a smaller value.
5763                  */
5764                 if (left < hpts_timeout)
5765                         hpts_timeout = left;
5766         }
5767         if (hpts_timeout) {
5768                 /*
5769                  * Hack alert for now we can't time-out over 2,147,483
5770                  * seconds (a bit more than 596 hours), which is probably ok
5771                  * :).
5772                  */
5773                 if (hpts_timeout > 0x7ffffffe)
5774                         hpts_timeout = 0x7ffffffe;
5775                 rack->r_ctl.rc_timer_exp = cts + hpts_timeout;
5776         }
5777         rack_log_pacing_delay_calc(rack, entry_slot, slot, hpts_timeout, 0, 0, 27, __LINE__, NULL, 0);
5778         if ((rack->gp_ready == 0) &&
5779             (rack->use_fixed_rate == 0) &&
5780             (hpts_timeout < slot) &&
5781             (rack->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
5782                 /*
5783                  * We have no good estimate yet for the
5784                  * old clunky burst mitigation or the
5785                  * real pacing. And the tlp or rxt is smaller
5786                  * than the pacing calculation. Lets not
5787                  * pace that long since we know the calculation
5788                  * so far is not accurate.
5789                  */
5790                 slot = hpts_timeout;
5791         }
5792         /**
5793          * Turn off all the flags for queuing by default. The
5794          * flags have important meanings to what happens when
5795          * LRO interacts with the transport. Most likely (by default now)
5796          * mbuf_queueing and ack compression are on. So the transport
5797          * has a couple of flags that control what happens (if those
5798          * are not on then these flags won't have any effect since it
5799          * won't go through the queuing LRO path).
5800          *
5801          * INP_MBUF_QUEUE_READY - This flags says that I am busy
5802          *                        pacing output, so don't disturb. But
5803          *                        it also means LRO can wake me if there
5804          *                        is a SACK arrival.
5805          *
5806          * INP_DONT_SACK_QUEUE - This flag is used in conjunction
5807          *                       with the above flag (QUEUE_READY) and
5808          *                       when present it says don't even wake me
5809          *                       if a SACK arrives.
5810          *
5811          * The idea behind these flags is that if we are pacing we
5812          * set the MBUF_QUEUE_READY and only get woken up if
5813          * a SACK arrives (which could change things) or if
5814          * our pacing timer expires. If, however, we have a rack
5815          * timer running, then we don't even want a sack to wake
5816          * us since the rack timer has to expire before we can send.
5817          *
5818          * Other cases should usually have none of the flags set
5819          * so LRO can call into us.
5820          */
5821         inp->inp_flags2 &= ~(INP_DONT_SACK_QUEUE|INP_MBUF_QUEUE_READY);
5822         if (slot) {
5823                 rack->r_ctl.rc_last_output_to = us_cts + slot;
5824                 /*
5825                  * A pacing timer (slot) is being set, in
5826                  * such a case we cannot send (we are blocked by
5827                  * the timer). So lets tell LRO that it should not
5828                  * wake us unless there is a SACK. Note this only
5829                  * will be effective if mbuf queueing is on or
5830                  * compressed acks are being processed.
5831                  */
5832                 inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
5833                 /*
5834                  * But wait if we have a Rack timer running
5835                  * even a SACK should not disturb us (with
5836                  * the exception of r_rr_config 3).
5837                  */
5838                 if ((rack->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
5839                     (rack->r_rr_config != 3))
5840                         inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
5841                 if (rack->rc_ack_can_sendout_data) {
5842                         /*
5843                          * Ahh but wait, this is that special case
5844                          * where the pacing timer can be disturbed
5845                          * backout the changes (used for non-paced
5846                          * burst limiting).
5847                          */
5848                         inp->inp_flags2 &= ~(INP_DONT_SACK_QUEUE|INP_MBUF_QUEUE_READY);
5849                 }
5850                 if ((rack->use_rack_rr) &&
5851                     (rack->r_rr_config < 2) &&
5852                     ((hpts_timeout) && (hpts_timeout < slot))) {
5853                         /*
5854                          * Arrange for the hpts to kick back in after the
5855                          * t-o if the t-o does not cause a send.
5856                          */
5857                         (void)tcp_hpts_insert_diag(inp, HPTS_USEC_TO_SLOTS(hpts_timeout),
5858                                                    __LINE__, &diag);
5859                         rack_log_hpts_diag(rack, us_cts, &diag, &tv);
5860                         rack_log_to_start(rack, cts, hpts_timeout, slot, 0);
5861                 } else {
5862                         (void)tcp_hpts_insert_diag(inp, HPTS_USEC_TO_SLOTS(slot),
5863                                                    __LINE__, &diag);
5864                         rack_log_hpts_diag(rack, us_cts, &diag, &tv);
5865                         rack_log_to_start(rack, cts, hpts_timeout, slot, 1);
5866                 }
5867         } else if (hpts_timeout) {
5868                 /*
5869                  * With respect to inp_flags2 here, lets let any new acks wake
5870                  * us up here. Since we are not pacing (no pacing timer), output
5871                  * can happen so we should let it. If its a Rack timer, then any inbound
5872                  * packet probably won't change the sending (we will be blocked)
5873                  * but it may change the prr stats so letting it in (the set defaults
5874                  * at the start of this block) are good enough.
5875                  */
5876                 (void)tcp_hpts_insert_diag(inp, HPTS_USEC_TO_SLOTS(hpts_timeout),
5877                                            __LINE__, &diag);
5878                 rack_log_hpts_diag(rack, us_cts, &diag, &tv);
5879                 rack_log_to_start(rack, cts, hpts_timeout, slot, 0);
5880         } else {
5881                 /* No timer starting */
5882 #ifdef INVARIANTS
5883                 if (SEQ_GT(tp->snd_max, tp->snd_una)) {
5884                         panic("tp:%p rack:%p tlts:%d cts:%u slot:%u pto:%u -- no timer started?",
5885                             tp, rack, tot_len_this_send, cts, slot, hpts_timeout);
5886                 }
5887 #endif
5888         }
5889         rack->rc_tmr_stopped = 0;
5890         if (slot)
5891                 rack_log_type_bbrsnd(rack, tot_len_this_send, slot, us_cts, &tv);
5892 }
5893
5894 /*
5895  * RACK Timer, here we simply do logging and house keeping.
5896  * the normal rack_output() function will call the
5897  * appropriate thing to check if we need to do a RACK retransmit.
5898  * We return 1, saying don't proceed with rack_output only
5899  * when all timers have been stopped (destroyed PCB?).
5900  */
5901 static int
5902 rack_timeout_rack(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
5903 {
5904         /*
5905          * This timer simply provides an internal trigger to send out data.
5906          * The check_recovery_mode call will see if there are needed
5907          * retransmissions, if so we will enter fast-recovery. The output
5908          * call may or may not do the same thing depending on sysctl
5909          * settings.
5910          */
5911         struct rack_sendmap *rsm;
5912
5913         if (tp->t_timers->tt_flags & TT_STOPPED) {
5914                 return (1);
5915         }
5916         counter_u64_add(rack_to_tot, 1);
5917         if (rack->r_state && (rack->r_state != tp->t_state))
5918                 rack_set_state(tp, rack);
5919         rack->rc_on_min_to = 0;
5920         rsm = rack_check_recovery_mode(tp, cts);
5921         rack_log_to_event(rack, RACK_TO_FRM_RACK, rsm);
5922         if (rsm) {
5923                 rack->r_ctl.rc_resend = rsm;
5924                 rack->r_timer_override = 1;
5925                 if (rack->use_rack_rr) {
5926                         /*
5927                          * Don't accumulate extra pacing delay
5928                          * we are allowing the rack timer to
5929                          * over-ride pacing i.e. rrr takes precedence
5930                          * if the pacing interval is longer than the rrr
5931                          * time (in other words we get the min pacing
5932                          * time versus rrr pacing time).
5933                          */
5934                         rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
5935                 }
5936         }
5937         rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
5938         if (rsm == NULL) {
5939                 /* restart a timer and return 1 */
5940                 rack_start_hpts_timer(rack, tp, cts,
5941                                       0, 0, 0);
5942                 return (1);
5943         }
5944         return (0);
5945 }
5946
5947 static void
5948 rack_adjust_orig_mlen(struct rack_sendmap *rsm)
5949 {
5950         if (rsm->m->m_len > rsm->orig_m_len) {
5951                 /*
5952                  * Mbuf grew, caused by sbcompress, our offset does
5953                  * not change.
5954                  */
5955                 rsm->orig_m_len = rsm->m->m_len;
5956         } else if (rsm->m->m_len < rsm->orig_m_len) {
5957                 /*
5958                  * Mbuf shrank, trimmed off the top by an ack, our
5959                  * offset changes.
5960                  */
5961                 rsm->soff -= (rsm->orig_m_len - rsm->m->m_len);
5962                 rsm->orig_m_len = rsm->m->m_len;
5963         }
5964 }
5965
5966 static void
5967 rack_setup_offset_for_rsm(struct rack_sendmap *src_rsm, struct rack_sendmap *rsm)
5968 {
5969         struct mbuf *m;
5970         uint32_t soff;
5971
5972         if (src_rsm->m && (src_rsm->orig_m_len != src_rsm->m->m_len)) {
5973                 /* Fix up the orig_m_len and possibly the mbuf offset */
5974                 rack_adjust_orig_mlen(src_rsm);
5975         }
5976         m = src_rsm->m;
5977         soff = src_rsm->soff + (src_rsm->r_end - src_rsm->r_start);
5978         while (soff >= m->m_len) {
5979                 /* Move out past this mbuf */
5980                 soff -= m->m_len;
5981                 m = m->m_next;
5982                 KASSERT((m != NULL),
5983                         ("rsm:%p nrsm:%p hit at soff:%u null m",
5984                          src_rsm, rsm, soff));
5985         }
5986         rsm->m = m;
5987         rsm->soff = soff;
5988         rsm->orig_m_len = m->m_len;
5989 }
5990
5991 static __inline void
5992 rack_clone_rsm(struct tcp_rack *rack, struct rack_sendmap *nrsm,
5993                struct rack_sendmap *rsm, uint32_t start)
5994 {
5995         int idx;
5996
5997         nrsm->r_start = start;
5998         nrsm->r_end = rsm->r_end;
5999         nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
6000         nrsm->r_flags = rsm->r_flags;
6001         nrsm->r_dupack = rsm->r_dupack;
6002         nrsm->r_no_rtt_allowed = rsm->r_no_rtt_allowed;
6003         nrsm->r_rtr_bytes = 0;
6004         nrsm->r_fas = rsm->r_fas;
6005         rsm->r_end = nrsm->r_start;
6006         nrsm->r_just_ret = rsm->r_just_ret;
6007         for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
6008                 nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
6009         }
6010         /* Now if we have SYN flag we keep it on the left edge */
6011         if (nrsm->r_flags & RACK_HAS_SYN)
6012                 nrsm->r_flags &= ~RACK_HAS_SYN;
6013         /* Now if we have a FIN flag we keep it on the right edge */
6014         if (rsm->r_flags & RACK_HAS_FIN)
6015                 rsm->r_flags &= ~RACK_HAS_FIN;
6016         /* Push bit must go to the right edge as well */
6017         if (rsm->r_flags & RACK_HAD_PUSH)
6018                 rsm->r_flags &= ~RACK_HAD_PUSH;
6019         /* Clone over the state of the hw_tls flag */
6020         nrsm->r_hw_tls = rsm->r_hw_tls;
6021         /*
6022          * Now we need to find nrsm's new location in the mbuf chain
6023          * we basically calculate a new offset, which is soff +
6024          * how much is left in original rsm. Then we walk out the mbuf
6025          * chain to find the righ position, it may be the same mbuf
6026          * or maybe not.
6027          */
6028         KASSERT(((rsm->m != NULL) ||
6029                  (rsm->r_flags & (RACK_HAS_SYN|RACK_HAS_FIN))),
6030                 ("rsm:%p nrsm:%p rack:%p -- rsm->m is NULL?", rsm, nrsm, rack));
6031         if (rsm->m)
6032                 rack_setup_offset_for_rsm(rsm, nrsm);
6033 }
6034
6035 static struct rack_sendmap *
6036 rack_merge_rsm(struct tcp_rack *rack,
6037                struct rack_sendmap *l_rsm,
6038                struct rack_sendmap *r_rsm)
6039 {
6040         /*
6041          * We are merging two ack'd RSM's,
6042          * the l_rsm is on the left (lower seq
6043          * values) and the r_rsm is on the right
6044          * (higher seq value). The simplest way
6045          * to merge these is to move the right
6046          * one into the left. I don't think there
6047          * is any reason we need to try to find
6048          * the oldest (or last oldest retransmitted).
6049          */
6050 #ifdef INVARIANTS
6051         struct rack_sendmap *rm;
6052 #endif
6053         rack_log_map_chg(rack->rc_tp, rack, NULL,
6054                          l_rsm, r_rsm, MAP_MERGE, r_rsm->r_end, __LINE__);
6055         l_rsm->r_end = r_rsm->r_end;
6056         if (l_rsm->r_dupack < r_rsm->r_dupack)
6057                 l_rsm->r_dupack = r_rsm->r_dupack;
6058         if (r_rsm->r_rtr_bytes)
6059                 l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
6060         if (r_rsm->r_in_tmap) {
6061                 /* This really should not happen */
6062                 TAILQ_REMOVE(&rack->r_ctl.rc_tmap, r_rsm, r_tnext);
6063                 r_rsm->r_in_tmap = 0;
6064         }
6065
6066         /* Now the flags */
6067         if (r_rsm->r_flags & RACK_HAS_FIN)
6068                 l_rsm->r_flags |= RACK_HAS_FIN;
6069         if (r_rsm->r_flags & RACK_TLP)
6070                 l_rsm->r_flags |= RACK_TLP;
6071         if (r_rsm->r_flags & RACK_RWND_COLLAPSED)
6072                 l_rsm->r_flags |= RACK_RWND_COLLAPSED;
6073         if ((r_rsm->r_flags & RACK_APP_LIMITED)  &&
6074             ((l_rsm->r_flags & RACK_APP_LIMITED) == 0)) {
6075                 /*
6076                  * If both are app-limited then let the
6077                  * free lower the count. If right is app
6078                  * limited and left is not, transfer.
6079                  */
6080                 l_rsm->r_flags |= RACK_APP_LIMITED;
6081                 r_rsm->r_flags &= ~RACK_APP_LIMITED;
6082                 if (r_rsm == rack->r_ctl.rc_first_appl)
6083                         rack->r_ctl.rc_first_appl = l_rsm;
6084         }
6085 #ifndef INVARIANTS
6086         (void)RB_REMOVE(rack_rb_tree_head, &rack->r_ctl.rc_mtree, r_rsm);
6087 #else
6088         rm = RB_REMOVE(rack_rb_tree_head, &rack->r_ctl.rc_mtree, r_rsm);
6089         if (rm != r_rsm) {
6090                 panic("removing head in rack:%p rsm:%p rm:%p",
6091                       rack, r_rsm, rm);
6092         }
6093 #endif
6094         if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
6095                 /* Transfer the split limit to the map we free */
6096                 r_rsm->r_limit_type = l_rsm->r_limit_type;
6097                 l_rsm->r_limit_type = 0;
6098         }
6099         rack_free(rack, r_rsm);
6100         return (l_rsm);
6101 }
6102
6103 /*
6104  * TLP Timer, here we simply setup what segment we want to
6105  * have the TLP expire on, the normal rack_output() will then
6106  * send it out.
6107  *
6108  * We return 1, saying don't proceed with rack_output only
6109  * when all timers have been stopped (destroyed PCB?).
6110  */
6111 static int
6112 rack_timeout_tlp(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, uint8_t *doing_tlp)
6113 {
6114         /*
6115          * Tail Loss Probe.
6116          */
6117         struct rack_sendmap *rsm = NULL;
6118 #ifdef INVARIANTS
6119         struct rack_sendmap *insret;
6120 #endif
6121         struct socket *so = tptosocket(tp);
6122         uint32_t amm;
6123         uint32_t out, avail;
6124         int collapsed_win = 0;
6125
6126         if (tp->t_timers->tt_flags & TT_STOPPED) {
6127                 return (1);
6128         }
6129         if (TSTMP_LT(cts, rack->r_ctl.rc_timer_exp)) {
6130                 /* Its not time yet */
6131                 return (0);
6132         }
6133         if (ctf_progress_timeout_check(tp, true)) {
6134                 rack_log_progress_event(rack, tp, tick, PROGRESS_DROP, __LINE__);
6135                 return (-ETIMEDOUT);    /* tcp_drop() */
6136         }
6137         /*
6138          * A TLP timer has expired. We have been idle for 2 rtts. So we now
6139          * need to figure out how to force a full MSS segment out.
6140          */
6141         rack_log_to_event(rack, RACK_TO_FRM_TLP, NULL);
6142         rack->r_ctl.retran_during_recovery = 0;
6143         rack->r_ctl.dsack_byte_cnt = 0;
6144         counter_u64_add(rack_tlp_tot, 1);
6145         if (rack->r_state && (rack->r_state != tp->t_state))
6146                 rack_set_state(tp, rack);
6147         avail = sbavail(&so->so_snd);
6148         out = tp->snd_max - tp->snd_una;
6149         if ((out > tp->snd_wnd) || rack->rc_has_collapsed) {
6150                 /* special case, we need a retransmission */
6151                 collapsed_win = 1;
6152                 goto need_retran;
6153         }
6154         if (rack->r_ctl.dsack_persist && (rack->r_ctl.rc_tlp_cnt_out >= 1)) {
6155                 rack->r_ctl.dsack_persist--;
6156                 if (rack->r_ctl.num_dsack && (rack->r_ctl.dsack_persist == 0)) {
6157                         rack->r_ctl.num_dsack = 0;
6158                 }
6159                 rack_log_dsack_event(rack, 1, __LINE__, 0, 0);
6160         }
6161         if ((tp->t_flags & TF_GPUTINPROG) &&
6162             (rack->r_ctl.rc_tlp_cnt_out == 1)) {
6163                 /*
6164                  * If this is the second in a row
6165                  * TLP and we are doing a measurement
6166                  * its time to abandon the measurement.
6167                  * Something is likely broken on
6168                  * the clients network and measuring a
6169                  * broken network does us no good.
6170                  */
6171                 tp->t_flags &= ~TF_GPUTINPROG;
6172                 rack_log_pacing_delay_calc(rack, (tp->gput_ack - tp->gput_seq) /*flex2*/,
6173                                            rack->r_ctl.rc_gp_srtt /*flex1*/,
6174                                            tp->gput_seq,
6175                                            0, 0, 18, __LINE__, NULL, 0);
6176         }
6177         /*
6178          * Check our send oldest always settings, and if
6179          * there is an oldest to send jump to the need_retran.
6180          */
6181         if (rack_always_send_oldest && (TAILQ_EMPTY(&rack->r_ctl.rc_tmap) == 0))
6182                 goto need_retran;
6183
6184         if (avail > out) {
6185                 /* New data is available */
6186                 amm = avail - out;
6187                 if (amm > ctf_fixed_maxseg(tp)) {
6188                         amm = ctf_fixed_maxseg(tp);
6189                         if ((amm + out) > tp->snd_wnd) {
6190                                 /* We are rwnd limited */
6191                                 goto need_retran;
6192                         }
6193                 } else if (amm < ctf_fixed_maxseg(tp)) {
6194                         /* not enough to fill a MTU */
6195                         goto need_retran;
6196                 }
6197                 if (IN_FASTRECOVERY(tp->t_flags)) {
6198                         /* Unlikely */
6199                         if (rack->rack_no_prr == 0) {
6200                                 if (out + amm <= tp->snd_wnd) {
6201                                         rack->r_ctl.rc_prr_sndcnt = amm;
6202                                         rack->r_ctl.rc_tlp_new_data = amm;
6203                                         rack_log_to_prr(rack, 4, 0, __LINE__);
6204                                 }
6205                         } else
6206                                 goto need_retran;
6207                 } else {
6208                         /* Set the send-new override */
6209                         if (out + amm <= tp->snd_wnd)
6210                                 rack->r_ctl.rc_tlp_new_data = amm;
6211                         else
6212                                 goto need_retran;
6213                 }
6214                 rack->r_ctl.rc_tlpsend = NULL;
6215                 counter_u64_add(rack_tlp_newdata, 1);
6216                 goto send;
6217         }
6218 need_retran:
6219         /*
6220          * Ok we need to arrange the last un-acked segment to be re-sent, or
6221          * optionally the first un-acked segment.
6222          */
6223         if (collapsed_win == 0) {
6224                 if (rack_always_send_oldest)
6225                         rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
6226                 else {
6227                         rsm = RB_MAX(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
6228                         if (rsm && (rsm->r_flags & (RACK_ACKED | RACK_HAS_FIN))) {
6229                                 rsm = rack_find_high_nonack(rack, rsm);
6230                         }
6231                 }
6232                 if (rsm == NULL) {
6233 #ifdef TCP_BLACKBOX
6234                         tcp_log_dump_tp_logbuf(tp, "nada counter trips", M_NOWAIT, true);
6235 #endif
6236                         goto out;
6237                 }
6238         } else {
6239                 /*
6240                  * We must find the last segment
6241                  * that was acceptable by the client.
6242                  */
6243                 RB_FOREACH_REVERSE(rsm, rack_rb_tree_head, &rack->r_ctl.rc_mtree) {
6244                         if ((rsm->r_flags & RACK_RWND_COLLAPSED) == 0) {
6245                                 /* Found one */
6246                                 break;
6247                         }
6248                 }
6249                 if (rsm == NULL) {
6250                         /* None? if so send the first */
6251                         rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
6252                         if (rsm == NULL) {
6253 #ifdef TCP_BLACKBOX
6254                                 tcp_log_dump_tp_logbuf(tp, "nada counter trips", M_NOWAIT, true);
6255 #endif
6256                                 goto out;
6257                         }
6258                 }
6259         }
6260         if ((rsm->r_end - rsm->r_start) > ctf_fixed_maxseg(tp)) {
6261                 /*
6262                  * We need to split this the last segment in two.
6263                  */
6264                 struct rack_sendmap *nrsm;
6265
6266                 nrsm = rack_alloc_full_limit(rack);
6267                 if (nrsm == NULL) {
6268                         /*
6269                          * No memory to split, we will just exit and punt
6270                          * off to the RXT timer.
6271                          */
6272                         goto out;
6273                 }
6274                 rack_clone_rsm(rack, nrsm, rsm,
6275                                (rsm->r_end - ctf_fixed_maxseg(tp)));
6276                 rack_log_map_chg(tp, rack, NULL, rsm, nrsm, MAP_SPLIT, 0, __LINE__);
6277 #ifndef INVARIANTS
6278                 (void)RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
6279 #else
6280                 insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
6281                 if (insret != NULL) {
6282                         panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
6283                               nrsm, insret, rack, rsm);
6284                 }
6285 #endif
6286                 if (rsm->r_in_tmap) {
6287                         TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6288                         nrsm->r_in_tmap = 1;
6289                 }
6290                 rsm = nrsm;
6291         }
6292         rack->r_ctl.rc_tlpsend = rsm;
6293 send:
6294         /* Make sure output path knows we are doing a TLP */
6295         *doing_tlp = 1;
6296         rack->r_timer_override = 1;
6297         rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
6298         return (0);
6299 out:
6300         rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
6301         return (0);
6302 }
6303
6304 /*
6305  * Delayed ack Timer, here we simply need to setup the
6306  * ACK_NOW flag and remove the DELACK flag. From there
6307  * the output routine will send the ack out.
6308  *
6309  * We only return 1, saying don't proceed, if all timers
6310  * are stopped (destroyed PCB?).
6311  */
6312 static int
6313 rack_timeout_delack(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
6314 {
6315         if (tp->t_timers->tt_flags & TT_STOPPED) {
6316                 return (1);
6317         }
6318         rack_log_to_event(rack, RACK_TO_FRM_DELACK, NULL);
6319         tp->t_flags &= ~TF_DELACK;
6320         tp->t_flags |= TF_ACKNOW;
6321         KMOD_TCPSTAT_INC(tcps_delack);
6322         rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
6323         return (0);
6324 }
6325
6326 /*
6327  * Persists timer, here we simply send the
6328  * same thing as a keepalive will.
6329  * the one byte send.
6330  *
6331  * We only return 1, saying don't proceed, if all timers
6332  * are stopped (destroyed PCB?).
6333  */
6334 static int
6335 rack_timeout_persist(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
6336 {
6337         struct tcptemp *t_template;
6338         int32_t retval = 1;
6339
6340         if (tp->t_timers->tt_flags & TT_STOPPED) {
6341                 return (1);
6342         }
6343         if (rack->rc_in_persist == 0)
6344                 return (0);
6345         if (ctf_progress_timeout_check(tp, false)) {
6346                 tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
6347                 rack_log_progress_event(rack, tp, tick, PROGRESS_DROP, __LINE__);
6348                 counter_u64_add(rack_persists_lost_ends, rack->r_ctl.persist_lost_ends);
6349                 return (-ETIMEDOUT);    /* tcp_drop() */
6350         }
6351         /*
6352          * Persistence timer into zero window. Force a byte to be output, if
6353          * possible.
6354          */
6355         KMOD_TCPSTAT_INC(tcps_persisttimeo);
6356         /*
6357          * Hack: if the peer is dead/unreachable, we do not time out if the
6358          * window is closed.  After a full backoff, drop the connection if
6359          * the idle time (no responses to probes) reaches the maximum
6360          * backoff that we would use if retransmitting.
6361          */
6362         if (tp->t_rxtshift == TCP_MAXRXTSHIFT &&
6363             (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
6364              TICKS_2_USEC(ticks - tp->t_rcvtime) >= RACK_REXMTVAL(tp) * tcp_totbackoff)) {
6365                 KMOD_TCPSTAT_INC(tcps_persistdrop);
6366                 tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
6367                 counter_u64_add(rack_persists_lost_ends, rack->r_ctl.persist_lost_ends);
6368                 retval = -ETIMEDOUT;    /* tcp_drop() */
6369                 goto out;
6370         }
6371         if ((sbavail(&rack->rc_inp->inp_socket->so_snd) == 0) &&
6372             tp->snd_una == tp->snd_max)
6373                 rack_exit_persist(tp, rack, cts);
6374         rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
6375         /*
6376          * If the user has closed the socket then drop a persisting
6377          * connection after a much reduced timeout.
6378          */
6379         if (tp->t_state > TCPS_CLOSE_WAIT &&
6380             (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
6381                 KMOD_TCPSTAT_INC(tcps_persistdrop);
6382                 tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
6383                 counter_u64_add(rack_persists_lost_ends, rack->r_ctl.persist_lost_ends);
6384                 retval = -ETIMEDOUT;    /* tcp_drop() */
6385                 goto out;
6386         }
6387         t_template = tcpip_maketemplate(rack->rc_inp);
6388         if (t_template) {
6389                 /* only set it if we were answered */
6390                 if (rack->forced_ack == 0) {
6391                         rack->forced_ack = 1;
6392                         rack->r_ctl.forced_ack_ts = tcp_get_usecs(NULL);
6393                 } else {
6394                         rack->probe_not_answered = 1;
6395                         counter_u64_add(rack_persists_loss, 1);
6396                         rack->r_ctl.persist_lost_ends++;
6397                 }
6398                 counter_u64_add(rack_persists_sends, 1);
6399                 tcp_respond(tp, t_template->tt_ipgen,
6400                             &t_template->tt_t, (struct mbuf *)NULL,
6401                             tp->rcv_nxt, tp->snd_una - 1, 0);
6402                 /* This sends an ack */
6403                 if (tp->t_flags & TF_DELACK)
6404                         tp->t_flags &= ~TF_DELACK;
6405                 free(t_template, M_TEMP);
6406         }
6407         if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
6408                 tp->t_rxtshift++;
6409 out:
6410         rack_log_to_event(rack, RACK_TO_FRM_PERSIST, NULL);
6411         rack_start_hpts_timer(rack, tp, cts,
6412                               0, 0, 0);
6413         return (retval);
6414 }
6415
6416 /*
6417  * If a keepalive goes off, we had no other timers
6418  * happening. We always return 1 here since this
6419  * routine either drops the connection or sends
6420  * out a segment with respond.
6421  */
6422 static int
6423 rack_timeout_keepalive(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
6424 {
6425         struct tcptemp *t_template;
6426         struct inpcb *inp = tptoinpcb(tp);
6427
6428         if (tp->t_timers->tt_flags & TT_STOPPED) {
6429                 return (1);
6430         }
6431         rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
6432         rack_log_to_event(rack, RACK_TO_FRM_KEEP, NULL);
6433         /*
6434          * Keep-alive timer went off; send something or drop connection if
6435          * idle for too long.
6436          */
6437         KMOD_TCPSTAT_INC(tcps_keeptimeo);
6438         if (tp->t_state < TCPS_ESTABLISHED)
6439                 goto dropit;
6440         if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
6441             tp->t_state <= TCPS_CLOSING) {
6442                 if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
6443                         goto dropit;
6444                 /*
6445                  * Send a packet designed to force a response if the peer is
6446                  * up and reachable: either an ACK if the connection is
6447                  * still alive, or an RST if the peer has closed the
6448                  * connection due to timeout or reboot. Using sequence
6449                  * number tp->snd_una-1 causes the transmitted zero-length
6450                  * segment to lie outside the receive window; by the
6451                  * protocol spec, this requires the correspondent TCP to
6452                  * respond.
6453                  */
6454                 KMOD_TCPSTAT_INC(tcps_keepprobe);
6455                 t_template = tcpip_maketemplate(inp);
6456                 if (t_template) {
6457                         if (rack->forced_ack == 0) {
6458                                 rack->forced_ack = 1;
6459                                 rack->r_ctl.forced_ack_ts = tcp_get_usecs(NULL);
6460                         } else {
6461                                 rack->probe_not_answered = 1;
6462                         }
6463                         tcp_respond(tp, t_template->tt_ipgen,
6464                             &t_template->tt_t, (struct mbuf *)NULL,
6465                             tp->rcv_nxt, tp->snd_una - 1, 0);
6466                         free(t_template, M_TEMP);
6467                 }
6468         }
6469         rack_start_hpts_timer(rack, tp, cts, 0, 0, 0);
6470         return (1);
6471 dropit:
6472         KMOD_TCPSTAT_INC(tcps_keepdrops);
6473         tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
6474         return (-ETIMEDOUT);    /* tcp_drop() */
6475 }
6476
6477 /*
6478  * Retransmit helper function, clear up all the ack
6479  * flags and take care of important book keeping.
6480  */
6481 static void
6482 rack_remxt_tmr(struct tcpcb *tp)
6483 {
6484         /*
6485          * The retransmit timer went off, all sack'd blocks must be
6486          * un-acked.
6487          */
6488         struct rack_sendmap *rsm, *trsm = NULL;
6489         struct tcp_rack *rack;
6490
6491         rack = (struct tcp_rack *)tp->t_fb_ptr;
6492         rack_timer_cancel(tp, rack, tcp_get_usecs(NULL), __LINE__);
6493         rack_log_to_event(rack, RACK_TO_FRM_TMR, NULL);
6494         if (rack->r_state && (rack->r_state != tp->t_state))
6495                 rack_set_state(tp, rack);
6496         /*
6497          * Ideally we would like to be able to
6498          * mark SACK-PASS on anything not acked here.
6499          *
6500          * However, if we do that we would burst out
6501          * all that data 1ms apart. This would be unwise,
6502          * so for now we will just let the normal rxt timer
6503          * and tlp timer take care of it.
6504          *
6505          * Also we really need to stick them back in sequence
6506          * order. This way we send in the proper order and any
6507          * sacks that come floating in will "re-ack" the data.
6508          * To do this we zap the tmap with an INIT and then
6509          * walk through and place every rsm in the RB tree
6510          * back in its seq ordered place.
6511          */
6512         TAILQ_INIT(&rack->r_ctl.rc_tmap);
6513         RB_FOREACH(rsm, rack_rb_tree_head, &rack->r_ctl.rc_mtree) {
6514                 rsm->r_dupack = 0;
6515                 rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
6516                 /* We must re-add it back to the tlist */
6517                 if (trsm == NULL) {
6518                         TAILQ_INSERT_HEAD(&rack->r_ctl.rc_tmap, rsm, r_tnext);
6519                 } else {
6520                         TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, trsm, rsm, r_tnext);
6521                 }
6522                 rsm->r_in_tmap = 1;
6523                 trsm = rsm;
6524                 if (rsm->r_flags & RACK_ACKED)
6525                         rsm->r_flags |= RACK_WAS_ACKED;
6526                 rsm->r_flags &= ~(RACK_ACKED | RACK_SACK_PASSED | RACK_WAS_SACKPASS | RACK_RWND_COLLAPSED);
6527                 rsm->r_flags |= RACK_MUST_RXT;
6528         }
6529         /* Clear the count (we just un-acked them) */
6530         rack->r_ctl.rc_last_timeout_snduna = tp->snd_una;
6531         rack->r_ctl.rc_sacked = 0;
6532         rack->r_ctl.rc_sacklast = NULL;
6533         rack->r_ctl.rc_agg_delayed = 0;
6534         rack->r_early = 0;
6535         rack->r_ctl.rc_agg_early = 0;
6536         rack->r_late = 0;
6537         /* Clear the tlp rtx mark */
6538         rack->r_ctl.rc_resend = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
6539         if (rack->r_ctl.rc_resend != NULL)
6540                 rack->r_ctl.rc_resend->r_flags |= RACK_TO_REXT;
6541         rack->r_ctl.rc_prr_sndcnt = 0;
6542         rack_log_to_prr(rack, 6, 0, __LINE__);
6543         rack->r_timer_override = 1;
6544         if ((((tp->t_flags & TF_SACK_PERMIT) == 0)
6545 #ifdef NETFLIX_EXP_DETECTION
6546             || (rack->sack_attack_disable != 0)
6547 #endif
6548                     ) && ((tp->t_flags & TF_SENTFIN) == 0)) {
6549                 /*
6550                  * For non-sack customers new data
6551                  * needs to go out as retransmits until
6552                  * we retransmit up to snd_max.
6553                  */
6554                 rack->r_must_retran = 1;
6555                 rack->r_ctl.rc_out_at_rto = ctf_flight_size(rack->rc_tp,
6556                                                 rack->r_ctl.rc_sacked);
6557         }
6558         rack->r_ctl.rc_snd_max_at_rto = tp->snd_max;
6559 }
6560
6561 static void
6562 rack_convert_rtts(struct tcpcb *tp)
6563 {
6564         if (tp->t_srtt > 1) {
6565                 uint32_t val, frac;
6566
6567                 val = tp->t_srtt >> TCP_RTT_SHIFT;
6568                 frac = tp->t_srtt & 0x1f;
6569                 tp->t_srtt = TICKS_2_USEC(val);
6570                 /*
6571                  * frac is the fractional part of the srtt (if any)
6572                  * but its in ticks and every bit represents
6573                  * 1/32nd of a hz.
6574                  */
6575                 if (frac) {
6576                         if (hz == 1000) {
6577                                 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE);
6578                         } else {
6579                                 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE));
6580                         }
6581                         tp->t_srtt += frac;
6582                 }
6583         }
6584         if (tp->t_rttvar) {
6585                 uint32_t val, frac;
6586
6587                 val = tp->t_rttvar >> TCP_RTTVAR_SHIFT;
6588                 frac = tp->t_rttvar & 0x1f;
6589                 tp->t_rttvar = TICKS_2_USEC(val);
6590                 /*
6591                  * frac is the fractional part of the srtt (if any)
6592                  * but its in ticks and every bit represents
6593                  * 1/32nd of a hz.
6594                  */
6595                 if (frac) {
6596                         if (hz == 1000) {
6597                                 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE);
6598                         } else {
6599                                 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE));
6600                         }
6601                         tp->t_rttvar += frac;
6602                 }
6603         }
6604         tp->t_rxtcur = RACK_REXMTVAL(tp);
6605         if (TCPS_HAVEESTABLISHED(tp->t_state)) {
6606                 tp->t_rxtcur += TICKS_2_USEC(tcp_rexmit_slop);
6607         }
6608         if (tp->t_rxtcur > rack_rto_max) {
6609                 tp->t_rxtcur = rack_rto_max;
6610         }
6611 }
6612
6613 static void
6614 rack_cc_conn_init(struct tcpcb *tp)
6615 {
6616         struct tcp_rack *rack;
6617         uint32_t srtt;
6618
6619         rack = (struct tcp_rack *)tp->t_fb_ptr;
6620         srtt = tp->t_srtt;
6621         cc_conn_init(tp);
6622         /*
6623          * Now convert to rack's internal format,
6624          * if required.
6625          */
6626         if ((srtt == 0) && (tp->t_srtt != 0))
6627                 rack_convert_rtts(tp);
6628         /*
6629          * We want a chance to stay in slowstart as
6630          * we create a connection. TCP spec says that
6631          * initially ssthresh is infinite. For our
6632          * purposes that is the snd_wnd.
6633          */
6634         if (tp->snd_ssthresh < tp->snd_wnd) {
6635                 tp->snd_ssthresh = tp->snd_wnd;
6636         }
6637         /*
6638          * We also want to assure a IW worth of
6639          * data can get inflight.
6640          */
6641         if (rc_init_window(rack) < tp->snd_cwnd)
6642                 tp->snd_cwnd = rc_init_window(rack);
6643 }
6644
6645 /*
6646  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
6647  * we will setup to retransmit the lowest seq number outstanding.
6648  */
6649 static int
6650 rack_timeout_rxt(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
6651 {
6652         struct inpcb *inp = tptoinpcb(tp);
6653         int32_t rexmt;
6654         int32_t retval = 0;
6655         bool isipv6;
6656
6657         if (tp->t_timers->tt_flags & TT_STOPPED) {
6658                 return (1);
6659         }
6660         if ((tp->t_flags & TF_GPUTINPROG) &&
6661             (tp->t_rxtshift)) {
6662                 /*
6663                  * We have had a second timeout
6664                  * measurements on successive rxt's are not profitable.
6665                  * It is unlikely to be of any use (the network is
6666                  * broken or the client went away).
6667                  */
6668                 tp->t_flags &= ~TF_GPUTINPROG;
6669                 rack_log_pacing_delay_calc(rack, (tp->gput_ack - tp->gput_seq) /*flex2*/,
6670                                            rack->r_ctl.rc_gp_srtt /*flex1*/,
6671                                            tp->gput_seq,
6672                                            0, 0, 18, __LINE__, NULL, 0);
6673         }
6674         if (ctf_progress_timeout_check(tp, false)) {
6675                 tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
6676                 rack_log_progress_event(rack, tp, tick, PROGRESS_DROP, __LINE__);
6677                 return (-ETIMEDOUT);    /* tcp_drop() */
6678         }
6679         rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
6680         rack->r_ctl.retran_during_recovery = 0;
6681         rack->rc_ack_required = 1;
6682         rack->r_ctl.dsack_byte_cnt = 0;
6683         if (IN_FASTRECOVERY(tp->t_flags))
6684                 tp->t_flags |= TF_WASFRECOVERY;
6685         else
6686                 tp->t_flags &= ~TF_WASFRECOVERY;
6687         if (IN_CONGRECOVERY(tp->t_flags))
6688                 tp->t_flags |= TF_WASCRECOVERY;
6689         else
6690                 tp->t_flags &= ~TF_WASCRECOVERY;
6691         if (TCPS_HAVEESTABLISHED(tp->t_state) &&
6692             (tp->snd_una == tp->snd_max)) {
6693                 /* Nothing outstanding .. nothing to do */
6694                 return (0);
6695         }
6696         if (rack->r_ctl.dsack_persist) {
6697                 rack->r_ctl.dsack_persist--;
6698                 if (rack->r_ctl.num_dsack && (rack->r_ctl.dsack_persist == 0)) {
6699                         rack->r_ctl.num_dsack = 0;
6700                 }
6701                 rack_log_dsack_event(rack, 1, __LINE__, 0, 0);
6702         }
6703         /*
6704          * Rack can only run one timer  at a time, so we cannot
6705          * run a KEEPINIT (gating SYN sending) and a retransmit
6706          * timer for the SYN. So if we are in a front state and
6707          * have a KEEPINIT timer we need to check the first transmit
6708          * against now to see if we have exceeded the KEEPINIT time
6709          * (if one is set).
6710          */
6711         if ((TCPS_HAVEESTABLISHED(tp->t_state) == 0) &&
6712             (TP_KEEPINIT(tp) != 0)) {
6713                 struct rack_sendmap *rsm;
6714
6715                 rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
6716                 if (rsm) {
6717                         /* Ok we have something outstanding to test keepinit with */
6718                         if ((TSTMP_GT(cts, (uint32_t)rsm->r_tim_lastsent[0])) &&
6719                             ((cts - (uint32_t)rsm->r_tim_lastsent[0]) >= TICKS_2_USEC(TP_KEEPINIT(tp)))) {
6720                                 /* We have exceeded the KEEPINIT time */
6721                                 tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
6722                                 goto drop_it;
6723                         }
6724                 }
6725         }
6726         /*
6727          * Retransmission timer went off.  Message has not been acked within
6728          * retransmit interval.  Back off to a longer retransmit interval
6729          * and retransmit one segment.
6730          */
6731         rack_remxt_tmr(tp);
6732         if ((rack->r_ctl.rc_resend == NULL) ||
6733             ((rack->r_ctl.rc_resend->r_flags & RACK_RWND_COLLAPSED) == 0)) {
6734                 /*
6735                  * If the rwnd collapsed on
6736                  * the one we are retransmitting
6737                  * it does not count against the
6738                  * rxt count.
6739                  */
6740                 tp->t_rxtshift++;
6741         }
6742         if (tp->t_rxtshift > TCP_MAXRXTSHIFT) {
6743                 tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
6744 drop_it:
6745                 tp->t_rxtshift = TCP_MAXRXTSHIFT;
6746                 KMOD_TCPSTAT_INC(tcps_timeoutdrop);
6747                 /* XXXGL: previously t_softerror was casted to uint16_t */
6748                 MPASS(tp->t_softerror >= 0);
6749                 retval = tp->t_softerror ? -tp->t_softerror : -ETIMEDOUT;
6750                 goto out;       /* tcp_drop() */
6751         }
6752         if (tp->t_state == TCPS_SYN_SENT) {
6753                 /*
6754                  * If the SYN was retransmitted, indicate CWND to be limited
6755                  * to 1 segment in cc_conn_init().
6756                  */
6757                 tp->snd_cwnd = 1;
6758         } else if (tp->t_rxtshift == 1) {
6759                 /*
6760                  * first retransmit; record ssthresh and cwnd so they can be
6761                  * recovered if this turns out to be a "bad" retransmit. A
6762                  * retransmit is considered "bad" if an ACK for this segment
6763                  * is received within RTT/2 interval; the assumption here is
6764                  * that the ACK was already in flight.  See "On Estimating
6765                  * End-to-End Network Path Properties" by Allman and Paxson
6766                  * for more details.
6767                  */
6768                 tp->snd_cwnd_prev = tp->snd_cwnd;
6769                 tp->snd_ssthresh_prev = tp->snd_ssthresh;
6770                 tp->snd_recover_prev = tp->snd_recover;
6771                 tp->t_badrxtwin = ticks + (USEC_2_TICKS(tp->t_srtt)/2);
6772                 tp->t_flags |= TF_PREVVALID;
6773         } else if ((tp->t_flags & TF_RCVD_TSTMP) == 0)
6774                 tp->t_flags &= ~TF_PREVVALID;
6775         KMOD_TCPSTAT_INC(tcps_rexmttimeo);
6776         if ((tp->t_state == TCPS_SYN_SENT) ||
6777             (tp->t_state == TCPS_SYN_RECEIVED))
6778                 rexmt = RACK_INITIAL_RTO * tcp_backoff[tp->t_rxtshift];
6779         else
6780                 rexmt = max(rack_rto_min, (tp->t_srtt + (tp->t_rttvar << 2))) * tcp_backoff[tp->t_rxtshift];
6781
6782         RACK_TCPT_RANGESET(tp->t_rxtcur, rexmt,
6783            max(rack_rto_min, rexmt), rack_rto_max, rack->r_ctl.timer_slop);
6784         /*
6785          * We enter the path for PLMTUD if connection is established or, if
6786          * connection is FIN_WAIT_1 status, reason for the last is that if
6787          * amount of data we send is very small, we could send it in couple
6788          * of packets and process straight to FIN. In that case we won't
6789          * catch ESTABLISHED state.
6790          */
6791 #ifdef INET6
6792         isipv6 = (inp->inp_vflag & INP_IPV6) ? true : false;
6793 #else
6794         isipv6 = false;
6795 #endif
6796         if (((V_tcp_pmtud_blackhole_detect == 1) ||
6797             (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
6798             (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
6799             ((tp->t_state == TCPS_ESTABLISHED) ||
6800             (tp->t_state == TCPS_FIN_WAIT_1))) {
6801                 /*
6802                  * Idea here is that at each stage of mtu probe (usually,
6803                  * 1448 -> 1188 -> 524) should be given 2 chances to recover
6804                  * before further clamping down. 'tp->t_rxtshift % 2 == 0'
6805                  * should take care of that.
6806                  */
6807                 if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
6808                     (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
6809                     (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
6810                     tp->t_rxtshift % 2 == 0)) {
6811                         /*
6812                          * Enter Path MTU Black-hole Detection mechanism: -
6813                          * Disable Path MTU Discovery (IP "DF" bit). -
6814                          * Reduce MTU to lower value than what we negotiated
6815                          * with peer.
6816                          */
6817                         if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
6818                                 /* Record that we may have found a black hole. */
6819                                 tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
6820                                 /* Keep track of previous MSS. */
6821                                 tp->t_pmtud_saved_maxseg = tp->t_maxseg;
6822                         }
6823
6824                         /*
6825                          * Reduce the MSS to blackhole value or to the
6826                          * default in an attempt to retransmit.
6827                          */
6828 #ifdef INET6
6829                         if (isipv6 &&
6830                             tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
6831                                 /* Use the sysctl tuneable blackhole MSS. */
6832                                 tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
6833                                 KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
6834                         } else if (isipv6) {
6835                                 /* Use the default MSS. */
6836                                 tp->t_maxseg = V_tcp_v6mssdflt;
6837                                 /*
6838                                  * Disable Path MTU Discovery when we switch
6839                                  * to minmss.
6840                                  */
6841                                 tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
6842                                 KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
6843                         }
6844 #endif
6845 #if defined(INET6) && defined(INET)
6846                         else
6847 #endif
6848 #ifdef INET
6849                         if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
6850                                 /* Use the sysctl tuneable blackhole MSS. */
6851                                 tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
6852                                 KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
6853                         } else {
6854                                 /* Use the default MSS. */
6855                                 tp->t_maxseg = V_tcp_mssdflt;
6856                                 /*
6857                                  * Disable Path MTU Discovery when we switch
6858                                  * to minmss.
6859                                  */
6860                                 tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
6861                                 KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
6862                         }
6863 #endif
6864                 } else {
6865                         /*
6866                          * If further retransmissions are still unsuccessful
6867                          * with a lowered MTU, maybe this isn't a blackhole
6868                          * and we restore the previous MSS and blackhole
6869                          * detection flags. The limit '6' is determined by
6870                          * giving each probe stage (1448, 1188, 524) 2
6871                          * chances to recover.
6872                          */
6873                         if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
6874                             (tp->t_rxtshift >= 6)) {
6875                                 tp->t_flags2 |= TF2_PLPMTU_PMTUD;
6876                                 tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
6877                                 tp->t_maxseg = tp->t_pmtud_saved_maxseg;
6878                                 KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
6879                         }
6880                 }
6881         }
6882         /*
6883          * Disable RFC1323 and SACK if we haven't got any response to
6884          * our third SYN to work-around some broken terminal servers
6885          * (most of which have hopefully been retired) that have bad VJ
6886          * header compression code which trashes TCP segments containing
6887          * unknown-to-them TCP options.
6888          */
6889         if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
6890             (tp->t_rxtshift == 3))
6891                 tp->t_flags &= ~(TF_REQ_SCALE|TF_REQ_TSTMP|TF_SACK_PERMIT);
6892         /*
6893          * If we backed off this far, our srtt estimate is probably bogus.
6894          * Clobber it so we'll take the next rtt measurement as our srtt;
6895          * move the current srtt into rttvar to keep the current retransmit
6896          * times until then.
6897          */
6898         if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
6899 #ifdef INET6
6900                 if ((inp->inp_vflag & INP_IPV6) != 0)
6901                         in6_losing(inp);
6902                 else
6903 #endif
6904                         in_losing(inp);
6905                 tp->t_rttvar += tp->t_srtt;
6906                 tp->t_srtt = 0;
6907         }
6908         sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
6909         tp->snd_recover = tp->snd_max;
6910         tp->t_flags |= TF_ACKNOW;
6911         tp->t_rtttime = 0;
6912         rack_cong_signal(tp, CC_RTO, tp->snd_una, __LINE__);
6913 out:
6914         return (retval);
6915 }
6916
6917 static int
6918 rack_process_timers(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, uint8_t hpts_calling, uint8_t *doing_tlp)
6919 {
6920         int32_t ret = 0;
6921         int32_t timers = (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
6922
6923         if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
6924             (tp->t_flags & TF_GPUTINPROG)) {
6925                 /*
6926                  * We have a goodput in progress
6927                  * and we have entered a late state.
6928                  * Do we have enough data in the sb
6929                  * to handle the GPUT request?
6930                  */
6931                 uint32_t bytes;
6932
6933                 bytes = tp->gput_ack - tp->gput_seq;
6934                 if (SEQ_GT(tp->gput_seq, tp->snd_una))
6935                         bytes += tp->gput_seq - tp->snd_una;
6936                 if (bytes > sbavail(&tptosocket(tp)->so_snd)) {
6937                         /*
6938                          * There are not enough bytes in the socket
6939                          * buffer that have been sent to cover this
6940                          * measurement. Cancel it.
6941                          */
6942                         rack_log_pacing_delay_calc(rack, (tp->gput_ack - tp->gput_seq) /*flex2*/,
6943                                                    rack->r_ctl.rc_gp_srtt /*flex1*/,
6944                                                    tp->gput_seq,
6945                                                    0, 0, 18, __LINE__, NULL, 0);
6946                         tp->t_flags &= ~TF_GPUTINPROG;
6947                 }
6948         }
6949         if (timers == 0) {
6950                 return (0);
6951         }
6952         if (tp->t_state == TCPS_LISTEN) {
6953                 /* no timers on listen sockets */
6954                 if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
6955                         return (0);
6956                 return (1);
6957         }
6958         if ((timers & PACE_TMR_RACK) &&
6959             rack->rc_on_min_to) {
6960                 /*
6961                  * For the rack timer when we
6962                  * are on a min-timeout (which means rrr_conf = 3)
6963                  * we don't want to check the timer. It may
6964                  * be going off for a pace and thats ok we
6965                  * want to send the retransmit (if its ready).
6966                  *
6967                  * If its on a normal rack timer (non-min) then
6968                  * we will check if its expired.
6969                  */
6970                 goto skip_time_check;
6971         }
6972         if (TSTMP_LT(cts, rack->r_ctl.rc_timer_exp)) {
6973                 uint32_t left;
6974
6975                 if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
6976                         ret = -1;
6977                         rack_log_to_processing(rack, cts, ret, 0);
6978                         return (0);
6979                 }
6980                 if (hpts_calling == 0) {
6981                         /*
6982                          * A user send or queued mbuf (sack) has called us? We
6983                          * return 0 and let the pacing guards
6984                          * deal with it if they should or
6985                          * should not cause a send.
6986                          */
6987                         ret = -2;
6988                         rack_log_to_processing(rack, cts, ret, 0);
6989                         return (0);
6990                 }
6991                 /*
6992                  * Ok our timer went off early and we are not paced false
6993                  * alarm, go back to sleep.
6994                  */
6995                 ret = -3;
6996                 left = rack->r_ctl.rc_timer_exp - cts;
6997                 tcp_hpts_insert(tptoinpcb(tp), HPTS_MS_TO_SLOTS(left));
6998                 rack_log_to_processing(rack, cts, ret, left);
6999                 return (1);
7000         }
7001 skip_time_check:
7002         rack->rc_tmr_stopped = 0;
7003         rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
7004         if (timers & PACE_TMR_DELACK) {
7005                 ret = rack_timeout_delack(tp, rack, cts);
7006         } else if (timers & PACE_TMR_RACK) {
7007                 rack->r_ctl.rc_tlp_rxt_last_time = cts;
7008                 rack->r_fast_output = 0;
7009                 ret = rack_timeout_rack(tp, rack, cts);
7010         } else if (timers & PACE_TMR_TLP) {
7011                 rack->r_ctl.rc_tlp_rxt_last_time = cts;
7012                 ret = rack_timeout_tlp(tp, rack, cts, doing_tlp);
7013         } else if (timers & PACE_TMR_RXT) {
7014                 rack->r_ctl.rc_tlp_rxt_last_time = cts;
7015                 rack->r_fast_output = 0;
7016                 ret = rack_timeout_rxt(tp, rack, cts);
7017         } else if (timers & PACE_TMR_PERSIT) {
7018                 ret = rack_timeout_persist(tp, rack, cts);
7019         } else if (timers & PACE_TMR_KEEP) {
7020                 ret = rack_timeout_keepalive(tp, rack, cts);
7021         }
7022         rack_log_to_processing(rack, cts, ret, timers);
7023         return (ret);
7024 }
7025
7026 static void
7027 rack_timer_cancel(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, int line)
7028 {
7029         struct timeval tv;
7030         uint32_t us_cts, flags_on_entry;
7031         uint8_t hpts_removed = 0;
7032
7033         flags_on_entry = rack->r_ctl.rc_hpts_flags;
7034         us_cts = tcp_get_usecs(&tv);
7035         if ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
7036             ((TSTMP_GEQ(us_cts, rack->r_ctl.rc_last_output_to)) ||
7037              ((tp->snd_max - tp->snd_una) == 0))) {
7038                 tcp_hpts_remove(rack->rc_inp);
7039                 hpts_removed = 1;
7040                 /* If we were not delayed cancel out the flag. */
7041                 if ((tp->snd_max - tp->snd_una) == 0)
7042                         rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
7043                 rack_log_to_cancel(rack, hpts_removed, line, us_cts, &tv, flags_on_entry);
7044         }
7045         if (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
7046                 rack->rc_tmr_stopped = rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
7047                 if (tcp_in_hpts(rack->rc_inp) &&
7048                     ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0)) {
7049                         /*
7050                          * Canceling timer's when we have no output being
7051                          * paced. We also must remove ourselves from the
7052                          * hpts.
7053                          */
7054                         tcp_hpts_remove(rack->rc_inp);
7055                         hpts_removed = 1;
7056                 }
7057                 rack->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
7058         }
7059         if (hpts_removed == 0)
7060                 rack_log_to_cancel(rack, hpts_removed, line, us_cts, &tv, flags_on_entry);
7061 }
7062
7063 static void
7064 rack_timer_stop(struct tcpcb *tp, uint32_t timer_type)
7065 {
7066         return;
7067 }
7068
7069 static int
7070 rack_stopall(struct tcpcb *tp)
7071 {
7072         struct tcp_rack *rack;
7073         rack = (struct tcp_rack *)tp->t_fb_ptr;
7074         rack->t_timers_stopped = 1;
7075         return (0);
7076 }
7077
7078 static void
7079 rack_timer_activate(struct tcpcb *tp, uint32_t timer_type, uint32_t delta)
7080 {
7081         return;
7082 }
7083
7084 static int
7085 rack_timer_active(struct tcpcb *tp, uint32_t timer_type)
7086 {
7087         return (0);
7088 }
7089
7090 static void
7091 rack_stop_all_timers(struct tcpcb *tp)
7092 {
7093         struct tcp_rack *rack;
7094
7095         /*
7096          * Assure no timers are running.
7097          */
7098         if (tcp_timer_active(tp, TT_PERSIST)) {
7099                 /* We enter in persists, set the flag appropriately */
7100                 rack = (struct tcp_rack *)tp->t_fb_ptr;
7101                 rack->rc_in_persist = 1;
7102         }
7103         tcp_timer_suspend(tp, TT_PERSIST);
7104         tcp_timer_suspend(tp, TT_REXMT);
7105         tcp_timer_suspend(tp, TT_KEEP);
7106         tcp_timer_suspend(tp, TT_DELACK);
7107 }
7108
7109 static void
7110 rack_update_rsm(struct tcpcb *tp, struct tcp_rack *rack,
7111     struct rack_sendmap *rsm, uint64_t ts, uint16_t add_flag)
7112 {
7113         int32_t idx;
7114
7115         rsm->r_rtr_cnt++;
7116         rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
7117         rsm->r_dupack = 0;
7118         if (rsm->r_rtr_cnt > RACK_NUM_OF_RETRANS) {
7119                 rsm->r_rtr_cnt = RACK_NUM_OF_RETRANS;
7120                 rsm->r_flags |= RACK_OVERMAX;
7121         }
7122         if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & RACK_TLP) == 0)) {
7123                 rack->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
7124                 rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
7125         }
7126         idx = rsm->r_rtr_cnt - 1;
7127         rsm->r_tim_lastsent[idx] = ts;
7128         /*
7129          * Here we don't add in the len of send, since its already
7130          * in snduna <->snd_max.
7131          */
7132         rsm->r_fas = ctf_flight_size(rack->rc_tp,
7133                                      rack->r_ctl.rc_sacked);
7134         if (rsm->r_flags & RACK_ACKED) {
7135                 /* Problably MTU discovery messing with us */
7136                 rsm->r_flags &= ~RACK_ACKED;
7137                 rack->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7138         }
7139         if (rsm->r_in_tmap) {
7140                 TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
7141                 rsm->r_in_tmap = 0;
7142         }
7143         TAILQ_INSERT_TAIL(&rack->r_ctl.rc_tmap, rsm, r_tnext);
7144         rsm->r_in_tmap = 1;
7145         /* Take off the must retransmit flag, if its on */
7146         if (rsm->r_flags & RACK_MUST_RXT) {
7147                 if (rack->r_must_retran)
7148                         rack->r_ctl.rc_out_at_rto -= (rsm->r_end - rsm->r_start);
7149                 if (SEQ_GEQ(rsm->r_end, rack->r_ctl.rc_snd_max_at_rto)) {
7150                         /*
7151                          * We have retransmitted all we need. Clear
7152                          * any must retransmit flags.
7153                          */
7154                         rack->r_must_retran = 0;
7155                         rack->r_ctl.rc_out_at_rto = 0;
7156                 }
7157                 rsm->r_flags &= ~RACK_MUST_RXT;
7158         }
7159         if (rsm->r_flags & RACK_SACK_PASSED) {
7160                 /* We have retransmitted due to the SACK pass */
7161                 rsm->r_flags &= ~RACK_SACK_PASSED;
7162                 rsm->r_flags |= RACK_WAS_SACKPASS;
7163         }
7164 }
7165
7166 static uint32_t
7167 rack_update_entry(struct tcpcb *tp, struct tcp_rack *rack,
7168     struct rack_sendmap *rsm, uint64_t ts, int32_t *lenp, uint16_t add_flag)
7169 {
7170         /*
7171          * We (re-)transmitted starting at rsm->r_start for some length
7172          * (possibly less than r_end.
7173          */
7174         struct rack_sendmap *nrsm;
7175 #ifdef INVARIANTS
7176         struct rack_sendmap *insret;
7177 #endif
7178         uint32_t c_end;
7179         int32_t len;
7180
7181         len = *lenp;
7182         c_end = rsm->r_start + len;
7183         if (SEQ_GEQ(c_end, rsm->r_end)) {
7184                 /*
7185                  * We retransmitted the whole piece or more than the whole
7186                  * slopping into the next rsm.
7187                  */
7188                 rack_update_rsm(tp, rack, rsm, ts, add_flag);
7189                 if (c_end == rsm->r_end) {
7190                         *lenp = 0;
7191                         return (0);
7192                 } else {
7193                         int32_t act_len;
7194
7195                         /* Hangs over the end return whats left */
7196                         act_len = rsm->r_end - rsm->r_start;
7197                         *lenp = (len - act_len);
7198                         return (rsm->r_end);
7199                 }
7200                 /* We don't get out of this block. */
7201         }
7202         /*
7203          * Here we retransmitted less than the whole thing which means we
7204          * have to split this into what was transmitted and what was not.
7205          */
7206         nrsm = rack_alloc_full_limit(rack);
7207         if (nrsm == NULL) {
7208                 /*
7209                  * We can't get memory, so lets not proceed.
7210                  */
7211                 *lenp = 0;
7212                 return (0);
7213         }
7214         /*
7215          * So here we are going to take the original rsm and make it what we
7216          * retransmitted. nrsm will be the tail portion we did not
7217          * retransmit. For example say the chunk was 1, 11 (10 bytes). And
7218          * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
7219          * 1, 6 and the new piece will be 6, 11.
7220          */
7221         rack_clone_rsm(rack, nrsm, rsm, c_end);
7222         nrsm->r_dupack = 0;
7223         rack_log_retran_reason(rack, nrsm, __LINE__, 0, 2);
7224 #ifndef INVARIANTS
7225         (void)RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
7226 #else
7227         insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
7228         if (insret != NULL) {
7229                 panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
7230                       nrsm, insret, rack, rsm);
7231         }
7232 #endif
7233         if (rsm->r_in_tmap) {
7234                 TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7235                 nrsm->r_in_tmap = 1;
7236         }
7237         rsm->r_flags &= (~RACK_HAS_FIN);
7238         rack_update_rsm(tp, rack, rsm, ts, add_flag);
7239         /* Log a split of rsm into rsm and nrsm */
7240         rack_log_map_chg(tp, rack, NULL, rsm, nrsm, MAP_SPLIT, 0, __LINE__);
7241         *lenp = 0;
7242         return (0);
7243 }
7244
7245 static void
7246 rack_log_output(struct tcpcb *tp, struct tcpopt *to, int32_t len,
7247                 uint32_t seq_out, uint16_t th_flags, int32_t err, uint64_t cts,
7248                 struct rack_sendmap *hintrsm, uint16_t add_flag, struct mbuf *s_mb, uint32_t s_moff, int hw_tls)
7249 {
7250         struct tcp_rack *rack;
7251         struct rack_sendmap *rsm, *nrsm, fe;
7252 #ifdef INVARIANTS
7253         struct rack_sendmap *insret;
7254 #endif
7255         register uint32_t snd_max, snd_una;
7256
7257         /*
7258          * Add to the RACK log of packets in flight or retransmitted. If
7259          * there is a TS option we will use the TS echoed, if not we will
7260          * grab a TS.
7261          *
7262          * Retransmissions will increment the count and move the ts to its
7263          * proper place. Note that if options do not include TS's then we
7264          * won't be able to effectively use the ACK for an RTT on a retran.
7265          *
7266          * Notes about r_start and r_end. Lets consider a send starting at
7267          * sequence 1 for 10 bytes. In such an example the r_start would be
7268          * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
7269          * This means that r_end is actually the first sequence for the next
7270          * slot (11).
7271          *
7272          */
7273         /*
7274          * If err is set what do we do XXXrrs? should we not add the thing?
7275          * -- i.e. return if err != 0 or should we pretend we sent it? --
7276          * i.e. proceed with add ** do this for now.
7277          */
7278         INP_WLOCK_ASSERT(tptoinpcb(tp));
7279         if (err)
7280                 /*
7281                  * We don't log errors -- we could but snd_max does not
7282                  * advance in this case either.
7283                  */
7284                 return;
7285
7286         if (th_flags & TH_RST) {
7287                 /*
7288                  * We don't log resets and we return immediately from
7289                  * sending
7290                  */
7291                 return;
7292         }
7293         rack = (struct tcp_rack *)tp->t_fb_ptr;
7294         snd_una = tp->snd_una;
7295         snd_max = tp->snd_max;
7296         if (th_flags & (TH_SYN | TH_FIN)) {
7297                 /*
7298                  * The call to rack_log_output is made before bumping
7299                  * snd_max. This means we can record one extra byte on a SYN
7300                  * or FIN if seq_out is adding more on and a FIN is present
7301                  * (and we are not resending).
7302                  */
7303                 if ((th_flags & TH_SYN) && (seq_out == tp->iss))
7304                         len++;
7305                 if (th_flags & TH_FIN)
7306                         len++;
7307                 if (SEQ_LT(snd_max, tp->snd_nxt)) {
7308                         /*
7309                          * The add/update as not been done for the FIN/SYN
7310                          * yet.
7311                          */
7312                         snd_max = tp->snd_nxt;
7313                 }
7314         }
7315         if (SEQ_LEQ((seq_out + len), snd_una)) {
7316                 /* Are sending an old segment to induce an ack (keep-alive)? */
7317                 return;
7318         }
7319         if (SEQ_LT(seq_out, snd_una)) {
7320                 /* huh? should we panic? */
7321                 uint32_t end;
7322
7323                 end = seq_out + len;
7324                 seq_out = snd_una;
7325                 if (SEQ_GEQ(end, seq_out))
7326                         len = end - seq_out;
7327                 else
7328                         len = 0;
7329         }
7330         if (len == 0) {
7331                 /* We don't log zero window probes */
7332                 return;
7333         }
7334         if (IN_FASTRECOVERY(tp->t_flags)) {
7335                 rack->r_ctl.rc_prr_out += len;
7336         }
7337         /* First question is it a retransmission or new? */
7338         if (seq_out == snd_max) {
7339                 /* Its new */
7340 again:
7341                 rsm = rack_alloc(rack);
7342                 if (rsm == NULL) {
7343                         /*
7344                          * Hmm out of memory and the tcb got destroyed while
7345                          * we tried to wait.
7346                          */
7347                         return;
7348                 }
7349                 if (th_flags & TH_FIN) {
7350                         rsm->r_flags = RACK_HAS_FIN|add_flag;
7351                 } else {
7352                         rsm->r_flags = add_flag;
7353                 }
7354                 if (hw_tls)
7355                         rsm->r_hw_tls = 1;
7356                 rsm->r_tim_lastsent[0] = cts;
7357                 rsm->r_rtr_cnt = 1;
7358                 rsm->r_rtr_bytes = 0;
7359                 if (th_flags & TH_SYN) {
7360                         /* The data space is one beyond snd_una */
7361                         rsm->r_flags |= RACK_HAS_SYN;
7362                 }
7363                 rsm->r_start = seq_out;
7364                 rsm->r_end = rsm->r_start + len;
7365                 rsm->r_dupack = 0;
7366                 /*
7367                  * save off the mbuf location that
7368                  * sndmbuf_noadv returned (which is
7369                  * where we started copying from)..
7370                  */
7371                 rsm->m = s_mb;
7372                 rsm->soff = s_moff;
7373                 /*
7374                  * Here we do add in the len of send, since its not yet
7375                  * reflected in in snduna <->snd_max
7376                  */
7377                 rsm->r_fas = (ctf_flight_size(rack->rc_tp,
7378                                               rack->r_ctl.rc_sacked) +
7379                               (rsm->r_end - rsm->r_start));
7380                 /* rsm->m will be NULL if RACK_HAS_SYN or RACK_HAS_FIN is set */
7381                 if (rsm->m) {
7382                         if (rsm->m->m_len <= rsm->soff) {
7383                                 /*
7384                                  * XXXrrs Question, will this happen?
7385                                  *
7386                                  * If sbsndptr is set at the correct place
7387                                  * then s_moff should always be somewhere
7388                                  * within rsm->m. But if the sbsndptr was
7389                                  * off then that won't be true. If it occurs
7390                                  * we need to walkout to the correct location.
7391                                  */
7392                                 struct mbuf *lm;
7393
7394                                 lm = rsm->m;
7395                                 while (lm->m_len <= rsm->soff) {
7396                                         rsm->soff -= lm->m_len;
7397                                         lm = lm->m_next;
7398                                         KASSERT(lm != NULL, ("%s rack:%p lm goes null orig_off:%u origmb:%p rsm->soff:%u",
7399                                                              __func__, rack, s_moff, s_mb, rsm->soff));
7400                                 }
7401                                 rsm->m = lm;
7402                         }
7403                         rsm->orig_m_len = rsm->m->m_len;
7404                 } else
7405                         rsm->orig_m_len = 0;
7406                 rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
7407                 /* Log a new rsm */
7408                 rack_log_map_chg(tp, rack, NULL, rsm, NULL, MAP_NEW, 0, __LINE__);
7409 #ifndef INVARIANTS
7410                 (void)RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
7411 #else
7412                 insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
7413                 if (insret != NULL) {
7414                         panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
7415                               nrsm, insret, rack, rsm);
7416                 }
7417 #endif
7418                 TAILQ_INSERT_TAIL(&rack->r_ctl.rc_tmap, rsm, r_tnext);
7419                 rsm->r_in_tmap = 1;
7420                 /*
7421                  * Special case detection, is there just a single
7422                  * packet outstanding when we are not in recovery?
7423                  *
7424                  * If this is true mark it so.
7425                  */
7426                 if ((IN_FASTRECOVERY(tp->t_flags) == 0) &&
7427                     (ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked) == ctf_fixed_maxseg(tp))) {
7428                         struct rack_sendmap *prsm;
7429
7430                         prsm = RB_PREV(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
7431                         if (prsm)
7432                                 prsm->r_one_out_nr = 1;
7433                 }
7434                 return;
7435         }
7436         /*
7437          * If we reach here its a retransmission and we need to find it.
7438          */
7439         memset(&fe, 0, sizeof(fe));
7440 more:
7441         if (hintrsm && (hintrsm->r_start == seq_out)) {
7442                 rsm = hintrsm;
7443                 hintrsm = NULL;
7444         } else {
7445                 /* No hints sorry */
7446                 rsm = NULL;
7447         }
7448         if ((rsm) && (rsm->r_start == seq_out)) {
7449                 seq_out = rack_update_entry(tp, rack, rsm, cts, &len, add_flag);
7450                 if (len == 0) {
7451                         return;
7452                 } else {
7453                         goto more;
7454                 }
7455         }
7456         /* Ok it was not the last pointer go through it the hard way. */
7457 refind:
7458         fe.r_start = seq_out;
7459         rsm = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
7460         if (rsm) {
7461                 if (rsm->r_start == seq_out) {
7462                         seq_out = rack_update_entry(tp, rack, rsm, cts, &len, add_flag);
7463                         if (len == 0) {
7464                                 return;
7465                         } else {
7466                                 goto refind;
7467                         }
7468                 }
7469                 if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
7470                         /* Transmitted within this piece */
7471                         /*
7472                          * Ok we must split off the front and then let the
7473                          * update do the rest
7474                          */
7475                         nrsm = rack_alloc_full_limit(rack);
7476                         if (nrsm == NULL) {
7477                                 rack_update_rsm(tp, rack, rsm, cts, add_flag);
7478                                 return;
7479                         }
7480                         /*
7481                          * copy rsm to nrsm and then trim the front of rsm
7482                          * to not include this part.
7483                          */
7484                         rack_clone_rsm(rack, nrsm, rsm, seq_out);
7485                         rack_log_map_chg(tp, rack, NULL, rsm, nrsm, MAP_SPLIT, 0, __LINE__);
7486 #ifndef INVARIANTS
7487                         (void)RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
7488 #else
7489                         insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
7490                         if (insret != NULL) {
7491                                 panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
7492                                       nrsm, insret, rack, rsm);
7493                         }
7494 #endif
7495                         if (rsm->r_in_tmap) {
7496                                 TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7497                                 nrsm->r_in_tmap = 1;
7498                         }
7499                         rsm->r_flags &= (~RACK_HAS_FIN);
7500                         seq_out = rack_update_entry(tp, rack, nrsm, cts, &len, add_flag);
7501                         if (len == 0) {
7502                                 return;
7503                         } else if (len > 0)
7504                                 goto refind;
7505                 }
7506         }
7507         /*
7508          * Hmm not found in map did they retransmit both old and on into the
7509          * new?
7510          */
7511         if (seq_out == tp->snd_max) {
7512                 goto again;
7513         } else if (SEQ_LT(seq_out, tp->snd_max)) {
7514 #ifdef INVARIANTS
7515                 printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
7516                        seq_out, len, tp->snd_una, tp->snd_max);
7517                 printf("Starting Dump of all rack entries\n");
7518                 RB_FOREACH(rsm, rack_rb_tree_head, &rack->r_ctl.rc_mtree) {
7519                         printf("rsm:%p start:%u end:%u\n",
7520                                rsm, rsm->r_start, rsm->r_end);
7521                 }
7522                 printf("Dump complete\n");
7523                 panic("seq_out not found rack:%p tp:%p",
7524                       rack, tp);
7525 #endif
7526         } else {
7527 #ifdef INVARIANTS
7528                 /*
7529                  * Hmm beyond sndmax? (only if we are using the new rtt-pack
7530                  * flag)
7531                  */
7532                 panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
7533                       seq_out, len, tp->snd_max, tp);
7534 #endif
7535         }
7536 }
7537
7538 /*
7539  * Record one of the RTT updates from an ack into
7540  * our sample structure.
7541  */
7542
7543 static void
7544 tcp_rack_xmit_timer(struct tcp_rack *rack, int32_t rtt, uint32_t len, uint32_t us_rtt,
7545                     int confidence, struct rack_sendmap *rsm, uint16_t rtrcnt)
7546 {
7547         if ((rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY) ||
7548             (rack->r_ctl.rack_rs.rs_rtt_lowest > rtt)) {
7549                 rack->r_ctl.rack_rs.rs_rtt_lowest = rtt;
7550         }
7551         if ((rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY) ||
7552             (rack->r_ctl.rack_rs.rs_rtt_highest < rtt)) {
7553                 rack->r_ctl.rack_rs.rs_rtt_highest = rtt;
7554         }
7555         if (rack->rc_tp->t_flags & TF_GPUTINPROG) {
7556             if (us_rtt < rack->r_ctl.rc_gp_lowrtt)
7557                 rack->r_ctl.rc_gp_lowrtt = us_rtt;
7558             if (rack->rc_tp->snd_wnd > rack->r_ctl.rc_gp_high_rwnd)
7559                     rack->r_ctl.rc_gp_high_rwnd = rack->rc_tp->snd_wnd;
7560         }
7561         if ((confidence == 1) &&
7562             ((rsm == NULL) ||
7563              (rsm->r_just_ret) ||
7564              (rsm->r_one_out_nr &&
7565               len < (ctf_fixed_maxseg(rack->rc_tp) * 2)))) {
7566                 /*
7567                  * If the rsm had a just return
7568                  * hit it then we can't trust the
7569                  * rtt measurement for buffer deterimination
7570                  * Note that a confidence of 2, indicates
7571                  * SACK'd which overrides the r_just_ret or
7572                  * the r_one_out_nr. If it was a CUM-ACK and
7573                  * we had only two outstanding, but get an
7574                  * ack for only 1. Then that also lowers our
7575                  * confidence.
7576                  */
7577                 confidence = 0;
7578         }
7579         if ((rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY) ||
7580             (rack->r_ctl.rack_rs.rs_us_rtt > us_rtt)) {
7581                 if (rack->r_ctl.rack_rs.confidence == 0) {
7582                         /*
7583                          * We take anything with no current confidence
7584                          * saved.
7585                          */
7586                         rack->r_ctl.rack_rs.rs_us_rtt = us_rtt;
7587                         rack->r_ctl.rack_rs.confidence = confidence;
7588                         rack->r_ctl.rack_rs.rs_us_rtrcnt = rtrcnt;
7589                 } else if (confidence || rack->r_ctl.rack_rs.confidence) {
7590                         /*
7591                          * Once we have a confident number,
7592                          * we can update it with a smaller
7593                          * value since this confident number
7594                          * may include the DSACK time until
7595                          * the next segment (the second one) arrived.
7596                          */
7597                         rack->r_ctl.rack_rs.rs_us_rtt = us_rtt;
7598                         rack->r_ctl.rack_rs.confidence = confidence;
7599                         rack->r_ctl.rack_rs.rs_us_rtrcnt = rtrcnt;
7600                 }
7601         }
7602         rack_log_rtt_upd(rack->rc_tp, rack, us_rtt, len, rsm, confidence);
7603         rack->r_ctl.rack_rs.rs_flags = RACK_RTT_VALID;
7604         rack->r_ctl.rack_rs.rs_rtt_tot += rtt;
7605         rack->r_ctl.rack_rs.rs_rtt_cnt++;
7606 }
7607
7608 /*
7609  * Collect new round-trip time estimate
7610  * and update averages and current timeout.
7611  */
7612 static void
7613 tcp_rack_xmit_timer_commit(struct tcp_rack *rack, struct tcpcb *tp)
7614 {
7615         int32_t delta;
7616         int32_t rtt;
7617
7618         if (rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY)
7619                 /* No valid sample */
7620                 return;
7621         if (rack->r_ctl.rc_rate_sample_method == USE_RTT_LOW) {
7622                 /* We are to use the lowest RTT seen in a single ack */
7623                 rtt = rack->r_ctl.rack_rs.rs_rtt_lowest;
7624         } else if (rack->r_ctl.rc_rate_sample_method == USE_RTT_HIGH) {
7625                 /* We are to use the highest RTT seen in a single ack */
7626                 rtt = rack->r_ctl.rack_rs.rs_rtt_highest;
7627         } else if (rack->r_ctl.rc_rate_sample_method == USE_RTT_AVG) {
7628                 /* We are to use the average RTT seen in a single ack */
7629                 rtt = (int32_t)(rack->r_ctl.rack_rs.rs_rtt_tot /
7630                                 (uint64_t)rack->r_ctl.rack_rs.rs_rtt_cnt);
7631         } else {
7632 #ifdef INVARIANTS
7633                 panic("Unknown rtt variant %d", rack->r_ctl.rc_rate_sample_method);
7634 #endif
7635                 return;
7636         }
7637         if (rtt == 0)
7638                 rtt = 1;
7639         if (rack->rc_gp_rtt_set == 0) {
7640                 /*
7641                  * With no RTT we have to accept
7642                  * even one we are not confident of.
7643                  */
7644                 rack->r_ctl.rc_gp_srtt = rack->r_ctl.rack_rs.rs_us_rtt;
7645                 rack->rc_gp_rtt_set = 1;
7646         } else if (rack->r_ctl.rack_rs.confidence) {
7647                 /* update the running gp srtt */
7648                 rack->r_ctl.rc_gp_srtt -= (rack->r_ctl.rc_gp_srtt/8);
7649                 rack->r_ctl.rc_gp_srtt += rack->r_ctl.rack_rs.rs_us_rtt / 8;
7650         }
7651         if (rack->r_ctl.rack_rs.confidence) {
7652                 /*
7653                  * record the low and high for highly buffered path computation,
7654                  * we only do this if we are confident (not a retransmission).
7655                  */
7656                 if (rack->r_ctl.rc_highest_us_rtt < rack->r_ctl.rack_rs.rs_us_rtt) {
7657                         rack->r_ctl.rc_highest_us_rtt = rack->r_ctl.rack_rs.rs_us_rtt;
7658                 }
7659                 if (rack->rc_highly_buffered == 0) {
7660                         /*
7661                          * Currently once we declare a path has
7662                          * highly buffered there is no going
7663                          * back, which may be a problem...
7664                          */
7665                         if ((rack->r_ctl.rc_highest_us_rtt / rack->r_ctl.rc_lowest_us_rtt) > rack_hbp_thresh) {
7666                                 rack_log_rtt_shrinks(rack, rack->r_ctl.rack_rs.rs_us_rtt,
7667                                                      rack->r_ctl.rc_highest_us_rtt,
7668                                                      rack->r_ctl.rc_lowest_us_rtt,
7669                                                      RACK_RTTS_SEEHBP);
7670                                 rack->rc_highly_buffered = 1;
7671                         }
7672                 }
7673         }
7674         if ((rack->r_ctl.rack_rs.confidence) ||
7675             (rack->r_ctl.rack_rs.rs_us_rtrcnt == 1)) {
7676                 /*
7677                  * If we are highly confident of it <or> it was
7678                  * never retransmitted we accept it as the last us_rtt.
7679                  */
7680                 rack->r_ctl.rc_last_us_rtt = rack->r_ctl.rack_rs.rs_us_rtt;
7681                 /* The lowest rtt can be set if its was not retransmited */
7682                 if (rack->r_ctl.rc_lowest_us_rtt > rack->r_ctl.rack_rs.rs_us_rtt) {
7683                         rack->r_ctl.rc_lowest_us_rtt = rack->r_ctl.rack_rs.rs_us_rtt;
7684                         if (rack->r_ctl.rc_lowest_us_rtt == 0)
7685                                 rack->r_ctl.rc_lowest_us_rtt = 1;
7686                 }
7687         }
7688         rack = (struct tcp_rack *)tp->t_fb_ptr;
7689         if (tp->t_srtt != 0) {
7690                 /*
7691                  * We keep a simple srtt in microseconds, like our rtt
7692                  * measurement. We don't need to do any tricks with shifting
7693                  * etc. Instead we just add in 1/8th of the new measurement
7694                  * and subtract out 1/8 of the old srtt. We do the same with
7695                  * the variance after finding the absolute value of the
7696                  * difference between this sample and the current srtt.
7697                  */
7698                 delta = tp->t_srtt - rtt;
7699                 /* Take off 1/8th of the current sRTT */
7700                 tp->t_srtt -= (tp->t_srtt >> 3);
7701                 /* Add in 1/8th of the new RTT just measured */
7702                 tp->t_srtt += (rtt >> 3);
7703                 if (tp->t_srtt <= 0)
7704                         tp->t_srtt = 1;
7705                 /* Now lets make the absolute value of the variance */
7706                 if (delta < 0)
7707                         delta = -delta;
7708                 /* Subtract out 1/8th */
7709                 tp->t_rttvar -= (tp->t_rttvar >> 3);
7710                 /* Add in 1/8th of the new variance we just saw */
7711                 tp->t_rttvar += (delta >> 3);
7712                 if (tp->t_rttvar <= 0)
7713                         tp->t_rttvar = 1;
7714         } else {
7715                 /*
7716                  * No rtt measurement yet - use the unsmoothed rtt. Set the
7717                  * variance to half the rtt (so our first retransmit happens
7718                  * at 3*rtt).
7719                  */
7720                 tp->t_srtt = rtt;
7721                 tp->t_rttvar = rtt >> 1;
7722         }
7723         rack->rc_srtt_measure_made = 1;
7724         KMOD_TCPSTAT_INC(tcps_rttupdated);
7725         tp->t_rttupdated++;
7726 #ifdef STATS
7727         if (rack_stats_gets_ms_rtt == 0) {
7728                 /* Send in the microsecond rtt used for rxt timeout purposes */
7729                 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt));
7730         } else if (rack_stats_gets_ms_rtt == 1) {
7731                 /* Send in the millisecond rtt used for rxt timeout purposes */
7732                 int32_t ms_rtt;
7733
7734                 /* Round up */
7735                 ms_rtt = (rtt + HPTS_USEC_IN_MSEC - 1) / HPTS_USEC_IN_MSEC;
7736                 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, ms_rtt));
7737         } else if (rack_stats_gets_ms_rtt == 2) {
7738                 /* Send in the millisecond rtt has close to the path RTT as we can get  */
7739                 int32_t ms_rtt;
7740
7741                 /* Round up */
7742                 ms_rtt = (rack->r_ctl.rack_rs.rs_us_rtt + HPTS_USEC_IN_MSEC - 1) / HPTS_USEC_IN_MSEC;
7743                 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, ms_rtt));
7744         }  else {
7745                 /* Send in the microsecond rtt has close to the path RTT as we can get  */
7746                 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rack->r_ctl.rack_rs.rs_us_rtt));
7747         }
7748
7749 #endif
7750         /*
7751          * the retransmit should happen at rtt + 4 * rttvar. Because of the
7752          * way we do the smoothing, srtt and rttvar will each average +1/2
7753          * tick of bias.  When we compute the retransmit timer, we want 1/2
7754          * tick of rounding and 1 extra tick because of +-1/2 tick
7755          * uncertainty in the firing of the timer.  The bias will give us
7756          * exactly the 1.5 tick we need.  But, because the bias is
7757          * statistical, we have to test that we don't drop below the minimum
7758          * feasible timer (which is 2 ticks).
7759          */
7760         tp->t_rxtshift = 0;
7761         RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
7762                       max(rack_rto_min, rtt + 2), rack_rto_max, rack->r_ctl.timer_slop);
7763         rack_log_rtt_sample(rack, rtt);
7764         tp->t_softerror = 0;
7765 }
7766
7767
7768 static void
7769 rack_apply_updated_usrtt(struct tcp_rack *rack, uint32_t us_rtt, uint32_t us_cts)
7770 {
7771         /*
7772          * Apply to filter the inbound us-rtt at us_cts.
7773          */
7774         uint32_t old_rtt;
7775
7776         old_rtt = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt);
7777         apply_filter_min_small(&rack->r_ctl.rc_gp_min_rtt,
7778                                us_rtt, us_cts);
7779         if (old_rtt > us_rtt) {
7780                 /* We just hit a new lower rtt time */
7781                 rack_log_rtt_shrinks(rack,  us_cts,  old_rtt,
7782                                      __LINE__, RACK_RTTS_NEWRTT);
7783                 /*
7784                  * Only count it if its lower than what we saw within our
7785                  * calculated range.
7786                  */
7787                 if ((old_rtt - us_rtt) > rack_min_rtt_movement) {
7788                         if (rack_probertt_lower_within &&
7789                             rack->rc_gp_dyn_mul &&
7790                             (rack->use_fixed_rate == 0) &&
7791                             (rack->rc_always_pace)) {
7792                                 /*
7793                                  * We are seeing a new lower rtt very close
7794                                  * to the time that we would have entered probe-rtt.
7795                                  * This is probably due to the fact that a peer flow
7796                                  * has entered probe-rtt. Lets go in now too.
7797                                  */
7798                                 uint32_t val;
7799
7800                                 val = rack_probertt_lower_within * rack_time_between_probertt;
7801                                 val /= 100;
7802                                 if ((rack->in_probe_rtt == 0)  &&
7803                                     ((us_cts - rack->r_ctl.rc_lower_rtt_us_cts) >= (rack_time_between_probertt - val))) {
7804                                         rack_enter_probertt(rack, us_cts);
7805                                 }
7806                         }
7807                         rack->r_ctl.rc_lower_rtt_us_cts = us_cts;
7808                 }
7809         }
7810 }
7811
7812 static int
7813 rack_update_rtt(struct tcpcb *tp, struct tcp_rack *rack,
7814     struct rack_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, tcp_seq th_ack)
7815 {
7816         uint32_t us_rtt;
7817         int32_t i, all;
7818         uint32_t t, len_acked;
7819
7820         if ((rsm->r_flags & RACK_ACKED) ||
7821             (rsm->r_flags & RACK_WAS_ACKED))
7822                 /* Already done */
7823                 return (0);
7824         if (rsm->r_no_rtt_allowed) {
7825                 /* Not allowed */
7826                 return (0);
7827         }
7828         if (ack_type == CUM_ACKED) {
7829                 if (SEQ_GT(th_ack, rsm->r_end)) {
7830                         len_acked = rsm->r_end - rsm->r_start;
7831                         all = 1;
7832                 } else {
7833                         len_acked = th_ack - rsm->r_start;
7834                         all = 0;
7835                 }
7836         } else {
7837                 len_acked = rsm->r_end - rsm->r_start;
7838                 all = 0;
7839         }
7840         if (rsm->r_rtr_cnt == 1) {
7841
7842                 t = cts - (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
7843                 if ((int)t <= 0)
7844                         t = 1;
7845                 if (!tp->t_rttlow || tp->t_rttlow > t)
7846                         tp->t_rttlow = t;
7847                 if (!rack->r_ctl.rc_rack_min_rtt ||
7848                     SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
7849                         rack->r_ctl.rc_rack_min_rtt = t;
7850                         if (rack->r_ctl.rc_rack_min_rtt == 0) {
7851                                 rack->r_ctl.rc_rack_min_rtt = 1;
7852                         }
7853                 }
7854                 if (TSTMP_GT(tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time), rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]))
7855                         us_rtt = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time) - (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
7856                 else
7857                         us_rtt = tcp_get_usecs(NULL) - (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
7858                 if (us_rtt == 0)
7859                         us_rtt = 1;
7860                 if (CC_ALGO(tp)->rttsample != NULL) {
7861                         /* Kick the RTT to the CC */
7862                         CC_ALGO(tp)->rttsample(tp->ccv, us_rtt, 1, rsm->r_fas);
7863                 }
7864                 rack_apply_updated_usrtt(rack, us_rtt, tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time));
7865                 if (ack_type == SACKED) {
7866                         rack_log_rtt_sample_calc(rack, t, (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)], cts, 1);
7867                         tcp_rack_xmit_timer(rack, t + 1, len_acked, us_rtt, 2 , rsm, rsm->r_rtr_cnt);
7868                 } else {
7869                         /*
7870                          * We need to setup what our confidence
7871                          * is in this ack.
7872                          *
7873                          * If the rsm was app limited and it is
7874                          * less than a mss in length (the end
7875                          * of the send) then we have a gap. If we
7876                          * were app limited but say we were sending
7877                          * multiple MSS's then we are more confident
7878                          * int it.
7879                          *
7880                          * When we are not app-limited then we see if
7881                          * the rsm is being included in the current
7882                          * measurement, we tell this by the app_limited_needs_set
7883                          * flag.
7884                          *
7885                          * Note that being cwnd blocked is not applimited
7886                          * as well as the pacing delay between packets which
7887                          * are sending only 1 or 2 MSS's also will show up
7888                          * in the RTT. We probably need to examine this algorithm
7889                          * a bit more and enhance it to account for the delay
7890                          * between rsm's. We could do that by saving off the
7891                          * pacing delay of each rsm (in an rsm) and then
7892                          * factoring that in somehow though for now I am
7893                          * not sure how :)
7894                          */
7895                         int calc_conf = 0;
7896
7897                         if (rsm->r_flags & RACK_APP_LIMITED) {
7898                                 if (all && (len_acked <= ctf_fixed_maxseg(tp)))
7899                                         calc_conf = 0;
7900                                 else
7901                                         calc_conf = 1;
7902                         } else if (rack->app_limited_needs_set == 0) {
7903                                 calc_conf = 1;
7904                         } else {
7905                                 calc_conf = 0;
7906                         }
7907                         rack_log_rtt_sample_calc(rack, t, (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)], cts, 2);
7908                         tcp_rack_xmit_timer(rack, t + 1, len_acked, us_rtt,
7909                                             calc_conf, rsm, rsm->r_rtr_cnt);
7910                 }
7911                 if ((rsm->r_flags & RACK_TLP) &&
7912                     (!IN_FASTRECOVERY(tp->t_flags))) {
7913                         /* Segment was a TLP and our retrans matched */
7914                         if (rack->r_ctl.rc_tlp_cwnd_reduce) {
7915                                 rack_cong_signal(tp, CC_NDUPACK, tp->snd_una, __LINE__);
7916                         }
7917                 }
7918                 if (SEQ_LT(rack->r_ctl.rc_rack_tmit_time, (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)])) {
7919                         /* New more recent rack_tmit_time */
7920                         rack->r_ctl.rc_rack_tmit_time = (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
7921                         rack->rc_rack_rtt = t;
7922                 }
7923                 return (1);
7924         }
7925         /*
7926          * We clear the soft/rxtshift since we got an ack.
7927          * There is no assurance we will call the commit() function
7928          * so we need to clear these to avoid incorrect handling.
7929          */
7930         tp->t_rxtshift = 0;
7931         RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
7932                       rack_rto_min, rack_rto_max, rack->r_ctl.timer_slop);
7933         tp->t_softerror = 0;
7934         if (to && (to->to_flags & TOF_TS) &&
7935             (ack_type == CUM_ACKED) &&
7936             (to->to_tsecr) &&
7937             ((rsm->r_flags & RACK_OVERMAX) == 0)) {
7938                 /*
7939                  * Now which timestamp does it match? In this block the ACK
7940                  * must be coming from a previous transmission.
7941                  */
7942                 for (i = 0; i < rsm->r_rtr_cnt; i++) {
7943                         if (rack_ts_to_msec(rsm->r_tim_lastsent[i]) == to->to_tsecr) {
7944                                 t = cts - (uint32_t)rsm->r_tim_lastsent[i];
7945                                 if ((int)t <= 0)
7946                                         t = 1;
7947                                 if (CC_ALGO(tp)->rttsample != NULL) {
7948                                         /*
7949                                          * Kick the RTT to the CC, here
7950                                          * we lie a bit in that we know the
7951                                          * retransmission is correct even though
7952                                          * we retransmitted. This is because
7953                                          * we match the timestamps.
7954                                          */
7955                                         if (TSTMP_GT(tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time), rsm->r_tim_lastsent[i]))
7956                                                 us_rtt = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time) - (uint32_t)rsm->r_tim_lastsent[i];
7957                                         else
7958                                                 us_rtt = tcp_get_usecs(NULL) - (uint32_t)rsm->r_tim_lastsent[i];
7959                                         CC_ALGO(tp)->rttsample(tp->ccv, us_rtt, 1, rsm->r_fas);
7960                                 }
7961                                 if ((i + 1) < rsm->r_rtr_cnt) {
7962                                         /*
7963                                          * The peer ack'd from our previous
7964                                          * transmission. We have a spurious
7965                                          * retransmission and thus we dont
7966                                          * want to update our rack_rtt.
7967                                          *
7968                                          * Hmm should there be a CC revert here?
7969                                          *
7970                                          */
7971                                         return (0);
7972                                 }
7973                                 if (!tp->t_rttlow || tp->t_rttlow > t)
7974                                         tp->t_rttlow = t;
7975                                 if (!rack->r_ctl.rc_rack_min_rtt || SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
7976                                         rack->r_ctl.rc_rack_min_rtt = t;
7977                                         if (rack->r_ctl.rc_rack_min_rtt == 0) {
7978                                                 rack->r_ctl.rc_rack_min_rtt = 1;
7979                                         }
7980                                 }
7981                                 if (SEQ_LT(rack->r_ctl.rc_rack_tmit_time,
7982                                            (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)])) {
7983                                         /* New more recent rack_tmit_time */
7984                                         rack->r_ctl.rc_rack_tmit_time = (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
7985                                         rack->rc_rack_rtt = t;
7986                                 }
7987                                 rack_log_rtt_sample_calc(rack, t, (uint32_t)rsm->r_tim_lastsent[i], cts, 3);
7988                                 tcp_rack_xmit_timer(rack, t + 1, len_acked, t, 0, rsm,
7989                                                     rsm->r_rtr_cnt);
7990                                 return (1);
7991                         }
7992                 }
7993                 goto ts_not_found;
7994         } else {
7995                 /*
7996                  * Ok its a SACK block that we retransmitted. or a windows
7997                  * machine without timestamps. We can tell nothing from the
7998                  * time-stamp since its not there or the time the peer last
7999                  * recieved a segment that moved forward its cum-ack point.
8000                  */
8001 ts_not_found:
8002                 i = rsm->r_rtr_cnt - 1;
8003                 t = cts - (uint32_t)rsm->r_tim_lastsent[i];
8004                 if ((int)t <= 0)
8005                         t = 1;
8006                 if (rack->r_ctl.rc_rack_min_rtt && SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
8007                         /*
8008                          * We retransmitted and the ack came back in less
8009                          * than the smallest rtt we have observed. We most
8010                          * likely did an improper retransmit as outlined in
8011                          * 6.2 Step 2 point 2 in the rack-draft so we
8012                          * don't want to update our rack_rtt. We in
8013                          * theory (in future) might want to think about reverting our
8014                          * cwnd state but we won't for now.
8015                          */
8016                         return (0);
8017                 } else if (rack->r_ctl.rc_rack_min_rtt) {
8018                         /*
8019                          * We retransmitted it and the retransmit did the
8020                          * job.
8021                          */
8022                         if (!rack->r_ctl.rc_rack_min_rtt ||
8023                             SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
8024                                 rack->r_ctl.rc_rack_min_rtt = t;
8025                                 if (rack->r_ctl.rc_rack_min_rtt == 0) {
8026                                         rack->r_ctl.rc_rack_min_rtt = 1;
8027                                 }
8028                         }
8029                         if (SEQ_LT(rack->r_ctl.rc_rack_tmit_time, (uint32_t)rsm->r_tim_lastsent[i])) {
8030                                 /* New more recent rack_tmit_time */
8031                                 rack->r_ctl.rc_rack_tmit_time = (uint32_t)rsm->r_tim_lastsent[i];
8032                                 rack->rc_rack_rtt = t;
8033                         }
8034                         return (1);
8035                 }
8036         }
8037         return (0);
8038 }
8039
8040 /*
8041  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
8042  */
8043 static void
8044 rack_log_sack_passed(struct tcpcb *tp,
8045     struct tcp_rack *rack, struct rack_sendmap *rsm)
8046 {
8047         struct rack_sendmap *nrsm;
8048
8049         nrsm = rsm;
8050         TAILQ_FOREACH_REVERSE_FROM(nrsm, &rack->r_ctl.rc_tmap,
8051             rack_head, r_tnext) {
8052                 if (nrsm == rsm) {
8053                         /* Skip orginal segment he is acked */
8054                         continue;
8055                 }
8056                 if (nrsm->r_flags & RACK_ACKED) {
8057                         /*
8058                          * Skip ack'd segments, though we
8059                          * should not see these, since tmap
8060                          * should not have ack'd segments.
8061                          */
8062                         continue;
8063                 }
8064                 if (nrsm->r_flags & RACK_RWND_COLLAPSED) {
8065                         /*
8066                          * If the peer dropped the rwnd on
8067                          * these then we don't worry about them.
8068                          */
8069                         continue;
8070                 }
8071                 if (nrsm->r_flags & RACK_SACK_PASSED) {
8072                         /*
8073                          * We found one that is already marked
8074                          * passed, we have been here before and
8075                          * so all others below this are marked.
8076                          */
8077                         break;
8078                 }
8079                 nrsm->r_flags |= RACK_SACK_PASSED;
8080                 nrsm->r_flags &= ~RACK_WAS_SACKPASS;
8081         }
8082 }
8083
8084 static void
8085 rack_need_set_test(struct tcpcb *tp,
8086                    struct tcp_rack *rack,
8087                    struct rack_sendmap *rsm,
8088                    tcp_seq th_ack,
8089                    int line,
8090                    int use_which)
8091 {
8092
8093         if ((tp->t_flags & TF_GPUTINPROG) &&
8094             SEQ_GEQ(rsm->r_end, tp->gput_seq)) {
8095                 /*
8096                  * We were app limited, and this ack
8097                  * butts up or goes beyond the point where we want
8098                  * to start our next measurement. We need
8099                  * to record the new gput_ts as here and
8100                  * possibly update the start sequence.
8101                  */
8102                 uint32_t seq, ts;
8103
8104                 if (rsm->r_rtr_cnt > 1) {
8105                         /*
8106                          * This is a retransmit, can we
8107                          * really make any assessment at this
8108                          * point?  We are not really sure of
8109                          * the timestamp, is it this or the
8110                          * previous transmission?
8111                          *
8112                          * Lets wait for something better that
8113                          * is not retransmitted.
8114                          */
8115                         return;
8116                 }
8117                 seq = tp->gput_seq;
8118                 ts = tp->gput_ts;
8119                 rack->app_limited_needs_set = 0;
8120                 tp->gput_ts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
8121                 /* Do we start at a new end? */
8122                 if ((use_which == RACK_USE_BEG) &&
8123                     SEQ_GEQ(rsm->r_start, tp->gput_seq)) {
8124                         /*
8125                          * When we get an ACK that just eats
8126                          * up some of the rsm, we set RACK_USE_BEG
8127                          * since whats at r_start (i.e. th_ack)
8128                          * is left unacked and thats where the
8129                          * measurement not starts.
8130                          */
8131                         tp->gput_seq = rsm->r_start;
8132                         rack->r_ctl.rc_gp_output_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
8133                 }
8134                 if ((use_which == RACK_USE_END) &&
8135                     SEQ_GEQ(rsm->r_end, tp->gput_seq)) {
8136                             /*
8137                              * We use the end when the cumack
8138                              * is moving forward and completely
8139                              * deleting the rsm passed so basically
8140                              * r_end holds th_ack.
8141                              *
8142                              * For SACK's we also want to use the end
8143                              * since this piece just got sacked and
8144                              * we want to target anything after that
8145                              * in our measurement.
8146                              */
8147                             tp->gput_seq = rsm->r_end;
8148                             rack->r_ctl.rc_gp_output_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
8149                 }
8150                 if (use_which == RACK_USE_END_OR_THACK) {
8151                         /*
8152                          * special case for ack moving forward,
8153                          * not a sack, we need to move all the
8154                          * way up to where this ack cum-ack moves
8155                          * to.
8156                          */
8157                         if (SEQ_GT(th_ack, rsm->r_end))
8158                                 tp->gput_seq = th_ack;
8159                         else
8160                                 tp->gput_seq = rsm->r_end;
8161                         rack->r_ctl.rc_gp_output_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
8162                 }
8163                 if (SEQ_GT(tp->gput_seq, tp->gput_ack)) {
8164                         /*
8165                          * We moved beyond this guy's range, re-calculate
8166                          * the new end point.
8167                          */
8168                         if (rack->rc_gp_filled == 0) {
8169                                 tp->gput_ack = tp->gput_seq + max(rc_init_window(rack), (MIN_GP_WIN * ctf_fixed_maxseg(tp)));
8170                         } else {
8171                                 tp->gput_ack = tp->gput_seq + rack_get_measure_window(tp, rack);
8172                         }
8173                 }
8174                 /*
8175                  * We are moving the goal post, we may be able to clear the
8176                  * measure_saw_probe_rtt flag.
8177                  */
8178                 if ((rack->in_probe_rtt == 0) &&
8179                     (rack->measure_saw_probe_rtt) &&
8180                     (SEQ_GEQ(tp->gput_seq, rack->r_ctl.rc_probertt_sndmax_atexit)))
8181                         rack->measure_saw_probe_rtt = 0;
8182                 rack_log_pacing_delay_calc(rack, ts, tp->gput_ts,
8183                                            seq, tp->gput_seq, 0, 5, line, NULL, 0);
8184                 if (rack->rc_gp_filled &&
8185                     ((tp->gput_ack - tp->gput_seq) <
8186                      max(rc_init_window(rack), (MIN_GP_WIN *
8187                                                 ctf_fixed_maxseg(tp))))) {
8188                         uint32_t ideal_amount;
8189
8190                         ideal_amount = rack_get_measure_window(tp, rack);
8191                         if (ideal_amount > sbavail(&tptosocket(tp)->so_snd)) {
8192                                 /*
8193                                  * There is no sense of continuing this measurement
8194                                  * because its too small to gain us anything we
8195                                  * trust. Skip it and that way we can start a new
8196                                  * measurement quicker.
8197                                  */
8198                                 tp->t_flags &= ~TF_GPUTINPROG;
8199                                 rack_log_pacing_delay_calc(rack, tp->gput_ack, tp->gput_seq,
8200                                                            0, 0, 0, 6, __LINE__, NULL, 0);
8201                         } else {
8202                                 /*
8203                                  * Reset the window further out.
8204                                  */
8205                                 tp->gput_ack = tp->gput_seq + ideal_amount;
8206                         }
8207                 }
8208         }
8209 }
8210
8211 static inline int
8212 is_rsm_inside_declared_tlp_block(struct tcp_rack *rack, struct rack_sendmap *rsm)
8213 {
8214         if (SEQ_LT(rsm->r_end, rack->r_ctl.last_tlp_acked_start)) {
8215                 /* Behind our TLP definition or right at */
8216                 return (0);
8217         }
8218         if (SEQ_GT(rsm->r_start, rack->r_ctl.last_tlp_acked_end)) {
8219                 /* The start is beyond or right at our end of TLP definition */
8220                 return (0);
8221         }
8222         /* It has to be a sub-part of the original TLP recorded */
8223         return (1);
8224 }
8225
8226
8227 static uint32_t
8228 rack_proc_sack_blk(struct tcpcb *tp, struct tcp_rack *rack, struct sackblk *sack,
8229                    struct tcpopt *to, struct rack_sendmap **prsm, uint32_t cts, int *moved_two)
8230 {
8231         uint32_t start, end, changed = 0;
8232         struct rack_sendmap stack_map;
8233         struct rack_sendmap *rsm, *nrsm, fe, *prev, *next;
8234 #ifdef INVARIANTS
8235         struct rack_sendmap *insret;
8236 #endif
8237         int32_t used_ref = 1;
8238         int moved = 0;
8239
8240         start = sack->start;
8241         end = sack->end;
8242         rsm = *prsm;
8243         memset(&fe, 0, sizeof(fe));
8244 do_rest_ofb:
8245         if ((rsm == NULL) ||
8246             (SEQ_LT(end, rsm->r_start)) ||
8247             (SEQ_GEQ(start, rsm->r_end)) ||
8248             (SEQ_LT(start, rsm->r_start))) {
8249                 /*
8250                  * We are not in the right spot,
8251                  * find the correct spot in the tree.
8252                  */
8253                 used_ref = 0;
8254                 fe.r_start = start;
8255                 rsm = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
8256                 moved++;
8257         }
8258         if (rsm == NULL) {
8259                 /* TSNH */
8260                 goto out;
8261         }
8262         /* Ok we have an ACK for some piece of this rsm */
8263         if (rsm->r_start != start) {
8264                 if ((rsm->r_flags & RACK_ACKED) == 0) {
8265                         /*
8266                          * Before any splitting or hookery is
8267                          * done is it a TLP of interest i.e. rxt?
8268                          */
8269                         if ((rsm->r_flags & RACK_TLP) &&
8270                             (rsm->r_rtr_cnt > 1)) {
8271                                 /*
8272                                  * We are splitting a rxt TLP, check
8273                                  * if we need to save off the start/end
8274                                  */
8275                                 if (rack->rc_last_tlp_acked_set &&
8276                                     (is_rsm_inside_declared_tlp_block(rack, rsm))) {
8277                                         /*
8278                                          * We already turned this on since we are inside
8279                                          * the previous one was a partially sack now we
8280                                          * are getting another one (maybe all of it).
8281                                          *
8282                                          */
8283                                         rack_log_dsack_event(rack, 10, __LINE__, rsm->r_start, rsm->r_end);
8284                                         /*
8285                                          * Lets make sure we have all of it though.
8286                                          */
8287                                         if (SEQ_LT(rsm->r_start, rack->r_ctl.last_tlp_acked_start)) {
8288                                                 rack->r_ctl.last_tlp_acked_start = rsm->r_start;
8289                                                 rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
8290                                                                      rack->r_ctl.last_tlp_acked_end);
8291                                         }
8292                                         if (SEQ_GT(rsm->r_end, rack->r_ctl.last_tlp_acked_end)) {
8293                                                 rack->r_ctl.last_tlp_acked_end = rsm->r_end;
8294                                                 rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
8295                                                                      rack->r_ctl.last_tlp_acked_end);
8296                                         }
8297                                 } else {
8298                                         rack->r_ctl.last_tlp_acked_start = rsm->r_start;
8299                                         rack->r_ctl.last_tlp_acked_end = rsm->r_end;
8300                                         rack->rc_last_tlp_past_cumack = 0;
8301                                         rack->rc_last_tlp_acked_set = 1;
8302                                         rack_log_dsack_event(rack, 8, __LINE__, rsm->r_start, rsm->r_end);
8303                                 }
8304                         }
8305                         /**
8306                          * Need to split this in two pieces the before and after,
8307                          * the before remains in the map, the after must be
8308                          * added. In other words we have:
8309                          * rsm        |--------------|
8310                          * sackblk        |------->
8311                          * rsm will become
8312                          *     rsm    |---|
8313                          * and nrsm will be  the sacked piece
8314                          *     nrsm       |----------|
8315                          *
8316                          * But before we start down that path lets
8317                          * see if the sack spans over on top of
8318                          * the next guy and it is already sacked.
8319                          *
8320                          */
8321                         next = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8322                         if (next && (next->r_flags & RACK_ACKED) &&
8323                             SEQ_GEQ(end, next->r_start)) {
8324                                 /**
8325                                  * So the next one is already acked, and
8326                                  * we can thus by hookery use our stack_map
8327                                  * to reflect the piece being sacked and
8328                                  * then adjust the two tree entries moving
8329                                  * the start and ends around. So we start like:
8330                                  *  rsm     |------------|             (not-acked)
8331                                  *  next                 |-----------| (acked)
8332                                  *  sackblk        |-------->
8333                                  *  We want to end like so:
8334                                  *  rsm     |------|                   (not-acked)
8335                                  *  next           |-----------------| (acked)
8336                                  *  nrsm           |-----|
8337                                  * Where nrsm is a temporary stack piece we
8338                                  * use to update all the gizmos.
8339                                  */
8340                                 /* Copy up our fudge block */
8341                                 nrsm = &stack_map;
8342                                 memcpy(nrsm, rsm, sizeof(struct rack_sendmap));
8343                                 /* Now adjust our tree blocks */
8344                                 rsm->r_end = start;
8345                                 next->r_start = start;
8346                                 /* Now we must adjust back where next->m is */
8347                                 rack_setup_offset_for_rsm(rsm, next);
8348
8349                                 /* We don't need to adjust rsm, it did not change */
8350                                 /* Clear out the dup ack count of the remainder */
8351                                 rsm->r_dupack = 0;
8352                                 rsm->r_just_ret = 0;
8353                                 rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
8354                                 /* Now lets make sure our fudge block is right */
8355                                 nrsm->r_start = start;
8356                                 /* Now lets update all the stats and such */
8357                                 rack_update_rtt(tp, rack, nrsm, to, cts, SACKED, 0);
8358                                 if (rack->app_limited_needs_set)
8359                                         rack_need_set_test(tp, rack, nrsm, tp->snd_una, __LINE__, RACK_USE_END);
8360                                 changed += (nrsm->r_end - nrsm->r_start);
8361                                 rack->r_ctl.rc_sacked += (nrsm->r_end - nrsm->r_start);
8362                                 if (nrsm->r_flags & RACK_SACK_PASSED) {
8363                                         rack->r_ctl.rc_reorder_ts = cts;
8364                                 }
8365                                 /*
8366                                  * Now we want to go up from rsm (the
8367                                  * one left un-acked) to the next one
8368                                  * in the tmap. We do this so when
8369                                  * we walk backwards we include marking
8370                                  * sack-passed on rsm (The one passed in
8371                                  * is skipped since it is generally called
8372                                  * on something sacked before removing it
8373                                  * from the tmap).
8374                                  */
8375                                 if (rsm->r_in_tmap) {
8376                                         nrsm = TAILQ_NEXT(rsm, r_tnext);
8377                                         /*
8378                                          * Now that we have the next
8379                                          * one walk backwards from there.
8380                                          */
8381                                         if (nrsm && nrsm->r_in_tmap)
8382                                                 rack_log_sack_passed(tp, rack, nrsm);
8383                                 }
8384                                 /* Now are we done? */
8385                                 if (SEQ_LT(end, next->r_end) ||
8386                                     (end == next->r_end)) {
8387                                         /* Done with block */
8388                                         goto out;
8389                                 }
8390                                 rack_log_map_chg(tp, rack, &stack_map, rsm, next, MAP_SACK_M1, end, __LINE__);
8391                                 counter_u64_add(rack_sack_used_next_merge, 1);
8392                                 /* Postion for the next block */
8393                                 start = next->r_end;
8394                                 rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, next);
8395                                 if (rsm == NULL)
8396                                         goto out;
8397                         } else {
8398                                 /**
8399                                  * We can't use any hookery here, so we
8400                                  * need to split the map. We enter like
8401                                  * so:
8402                                  *  rsm      |--------|
8403                                  *  sackblk       |----->
8404                                  * We will add the new block nrsm and
8405                                  * that will be the new portion, and then
8406                                  * fall through after reseting rsm. So we
8407                                  * split and look like this:
8408                                  *  rsm      |----|
8409                                  *  sackblk       |----->
8410                                  *  nrsm          |---|
8411                                  * We then fall through reseting
8412                                  * rsm to nrsm, so the next block
8413                                  * picks it up.
8414                                  */
8415                                 nrsm = rack_alloc_limit(rack, RACK_LIMIT_TYPE_SPLIT);
8416                                 if (nrsm == NULL) {
8417                                         /*
8418                                          * failed XXXrrs what can we do but loose the sack
8419                                          * info?
8420                                          */
8421                                         goto out;
8422                                 }
8423                                 counter_u64_add(rack_sack_splits, 1);
8424                                 rack_clone_rsm(rack, nrsm, rsm, start);
8425                                 rsm->r_just_ret = 0;
8426 #ifndef INVARIANTS
8427                                 (void)RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
8428 #else
8429                                 insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
8430                                 if (insret != NULL) {
8431                                         panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
8432                                               nrsm, insret, rack, rsm);
8433                                 }
8434 #endif
8435                                 if (rsm->r_in_tmap) {
8436                                         TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8437                                         nrsm->r_in_tmap = 1;
8438                                 }
8439                                 rack_log_map_chg(tp, rack, NULL, rsm, nrsm, MAP_SACK_M2, end, __LINE__);
8440                                 rsm->r_flags &= (~RACK_HAS_FIN);
8441                                 /* Position us to point to the new nrsm that starts the sack blk */
8442                                 rsm = nrsm;
8443                         }
8444                 } else {
8445                         /* Already sacked this piece */
8446                         counter_u64_add(rack_sack_skipped_acked, 1);
8447                         moved++;
8448                         if (end == rsm->r_end) {
8449                                 /* Done with block */
8450                                 rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8451                                 goto out;
8452                         } else if (SEQ_LT(end, rsm->r_end)) {
8453                                 /* A partial sack to a already sacked block */
8454                                 moved++;
8455                                 rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8456                                 goto out;
8457                         } else {
8458                                 /*
8459                                  * The end goes beyond this guy
8460                                  * reposition the start to the
8461                                  * next block.
8462                                  */
8463                                 start = rsm->r_end;
8464                                 rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8465                                 if (rsm == NULL)
8466                                         goto out;
8467                         }
8468                 }
8469         }
8470         if (SEQ_GEQ(end, rsm->r_end)) {
8471                 /**
8472                  * The end of this block is either beyond this guy or right
8473                  * at this guy. I.e.:
8474                  *  rsm ---                 |-----|
8475                  *  end                     |-----|
8476                  *  <or>
8477                  *  end                     |---------|
8478                  */
8479                 if ((rsm->r_flags & RACK_ACKED) == 0) {
8480                         /*
8481                          * Is it a TLP of interest?
8482                          */
8483                         if ((rsm->r_flags & RACK_TLP) &&
8484                             (rsm->r_rtr_cnt > 1)) {
8485                                 /*
8486                                  * We are splitting a rxt TLP, check
8487                                  * if we need to save off the start/end
8488                                  */
8489                                 if (rack->rc_last_tlp_acked_set &&
8490                                     (is_rsm_inside_declared_tlp_block(rack, rsm))) {
8491                                         /*
8492                                          * We already turned this on since we are inside
8493                                          * the previous one was a partially sack now we
8494                                          * are getting another one (maybe all of it).
8495                                          */
8496                                         rack_log_dsack_event(rack, 10, __LINE__, rsm->r_start, rsm->r_end);
8497                                         /*
8498                                          * Lets make sure we have all of it though.
8499                                          */
8500                                         if (SEQ_LT(rsm->r_start, rack->r_ctl.last_tlp_acked_start)) {
8501                                                 rack->r_ctl.last_tlp_acked_start = rsm->r_start;
8502                                                 rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
8503                                                                      rack->r_ctl.last_tlp_acked_end);
8504                                         }
8505                                         if (SEQ_GT(rsm->r_end, rack->r_ctl.last_tlp_acked_end)) {
8506                                                 rack->r_ctl.last_tlp_acked_end = rsm->r_end;
8507                                                 rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
8508                                                                      rack->r_ctl.last_tlp_acked_end);
8509                                         }
8510                                 } else {
8511                                         rack->r_ctl.last_tlp_acked_start = rsm->r_start;
8512                                         rack->r_ctl.last_tlp_acked_end = rsm->r_end;
8513                                         rack->rc_last_tlp_past_cumack = 0;
8514                                         rack->rc_last_tlp_acked_set = 1;
8515                                         rack_log_dsack_event(rack, 8, __LINE__, rsm->r_start, rsm->r_end);
8516                                 }
8517                         }
8518                         rack_update_rtt(tp, rack, rsm, to, cts, SACKED, 0);
8519                         changed += (rsm->r_end - rsm->r_start);
8520                         rack->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
8521                         if (rsm->r_in_tmap) /* should be true */
8522                                 rack_log_sack_passed(tp, rack, rsm);
8523                         /* Is Reordering occuring? */
8524                         if (rsm->r_flags & RACK_SACK_PASSED) {
8525                                 rsm->r_flags &= ~RACK_SACK_PASSED;
8526                                 rack->r_ctl.rc_reorder_ts = cts;
8527                         }
8528                         if (rack->app_limited_needs_set)
8529                                 rack_need_set_test(tp, rack, rsm, tp->snd_una, __LINE__, RACK_USE_END);
8530                         rsm->r_ack_arrival = rack_to_usec_ts(&rack->r_ctl.act_rcv_time);
8531                         rsm->r_flags |= RACK_ACKED;
8532                         if (rsm->r_in_tmap) {
8533                                 TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
8534                                 rsm->r_in_tmap = 0;
8535                         }
8536                         rack_log_map_chg(tp, rack, NULL, rsm, NULL, MAP_SACK_M3, end, __LINE__);
8537                 } else {
8538                         counter_u64_add(rack_sack_skipped_acked, 1);
8539                         moved++;
8540                 }
8541                 if (end == rsm->r_end) {
8542                         /* This block only - done, setup for next */
8543                         goto out;
8544                 }
8545                 /*
8546                  * There is more not coverend by this rsm move on
8547                  * to the next block in the RB tree.
8548                  */
8549                 nrsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8550                 start = rsm->r_end;
8551                 rsm = nrsm;
8552                 if (rsm == NULL)
8553                         goto out;
8554                 goto do_rest_ofb;
8555         }
8556         /**
8557          * The end of this sack block is smaller than
8558          * our rsm i.e.:
8559          *  rsm ---                 |-----|
8560          *  end                     |--|
8561          */
8562         if ((rsm->r_flags & RACK_ACKED) == 0) {
8563                 /*
8564                  * Is it a TLP of interest?
8565                  */
8566                 if ((rsm->r_flags & RACK_TLP) &&
8567                     (rsm->r_rtr_cnt > 1)) {
8568                         /*
8569                          * We are splitting a rxt TLP, check
8570                          * if we need to save off the start/end
8571                          */
8572                         if (rack->rc_last_tlp_acked_set &&
8573                             (is_rsm_inside_declared_tlp_block(rack, rsm))) {
8574                                 /*
8575                                  * We already turned this on since we are inside
8576                                  * the previous one was a partially sack now we
8577                                  * are getting another one (maybe all of it).
8578                                  */
8579                                 rack_log_dsack_event(rack, 10, __LINE__, rsm->r_start, rsm->r_end);
8580                                 /*
8581                                  * Lets make sure we have all of it though.
8582                                  */
8583                                 if (SEQ_LT(rsm->r_start, rack->r_ctl.last_tlp_acked_start)) {
8584                                         rack->r_ctl.last_tlp_acked_start = rsm->r_start;
8585                                         rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
8586                                                              rack->r_ctl.last_tlp_acked_end);
8587                                 }
8588                                 if (SEQ_GT(rsm->r_end, rack->r_ctl.last_tlp_acked_end)) {
8589                                         rack->r_ctl.last_tlp_acked_end = rsm->r_end;
8590                                         rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
8591                                                              rack->r_ctl.last_tlp_acked_end);
8592                                 }
8593                         } else {
8594                                 rack->r_ctl.last_tlp_acked_start = rsm->r_start;
8595                                 rack->r_ctl.last_tlp_acked_end = rsm->r_end;
8596                                 rack->rc_last_tlp_past_cumack = 0;
8597                                 rack->rc_last_tlp_acked_set = 1;
8598                                 rack_log_dsack_event(rack, 8, __LINE__, rsm->r_start, rsm->r_end);
8599                         }
8600                 }
8601                 prev = RB_PREV(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8602                 if (prev &&
8603                     (prev->r_flags & RACK_ACKED)) {
8604                         /**
8605                          * Goal, we want the right remainder of rsm to shrink
8606                          * in place and span from (rsm->r_start = end) to rsm->r_end.
8607                          * We want to expand prev to go all the way
8608                          * to prev->r_end <- end.
8609                          * so in the tree we have before:
8610                          *   prev     |--------|         (acked)
8611                          *   rsm               |-------| (non-acked)
8612                          *   sackblk           |-|
8613                          * We churn it so we end up with
8614                          *   prev     |----------|       (acked)
8615                          *   rsm                 |-----| (non-acked)
8616                          *   nrsm              |-| (temporary)
8617                          *
8618                          * Note if either prev/rsm is a TLP we don't
8619                          * do this.
8620                          */
8621                         nrsm = &stack_map;
8622                         memcpy(nrsm, rsm, sizeof(struct rack_sendmap));
8623                         prev->r_end = end;
8624                         rsm->r_start = end;
8625                         /* Now adjust nrsm (stack copy) to be
8626                          * the one that is the small
8627                          * piece that was "sacked".
8628                          */
8629                         nrsm->r_end = end;
8630                         rsm->r_dupack = 0;
8631                         rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
8632                         /*
8633                          * Now that the rsm has had its start moved forward
8634                          * lets go ahead and get its new place in the world.
8635                          */
8636                         rack_setup_offset_for_rsm(prev, rsm);
8637                         /*
8638                          * Now nrsm is our new little piece
8639                          * that is acked (which was merged
8640                          * to prev). Update the rtt and changed
8641                          * based on that. Also check for reordering.
8642                          */
8643                         rack_update_rtt(tp, rack, nrsm, to, cts, SACKED, 0);
8644                         if (rack->app_limited_needs_set)
8645                                 rack_need_set_test(tp, rack, nrsm, tp->snd_una, __LINE__, RACK_USE_END);
8646                         changed += (nrsm->r_end - nrsm->r_start);
8647                         rack->r_ctl.rc_sacked += (nrsm->r_end - nrsm->r_start);
8648                         if (nrsm->r_flags & RACK_SACK_PASSED) {
8649                                 rack->r_ctl.rc_reorder_ts = cts;
8650                         }
8651                         rack_log_map_chg(tp, rack, prev, &stack_map, rsm, MAP_SACK_M4, end, __LINE__);
8652                         rsm = prev;
8653                         counter_u64_add(rack_sack_used_prev_merge, 1);
8654                 } else {
8655                         /**
8656                          * This is the case where our previous
8657                          * block is not acked either, so we must
8658                          * split the block in two.
8659                          */
8660                         nrsm = rack_alloc_limit(rack, RACK_LIMIT_TYPE_SPLIT);
8661                         if (nrsm == NULL) {
8662                                 /* failed rrs what can we do but loose the sack info? */
8663                                 goto out;
8664                         }
8665                         if ((rsm->r_flags & RACK_TLP) &&
8666                             (rsm->r_rtr_cnt > 1)) {
8667                                 /*
8668                                  * We are splitting a rxt TLP, check
8669                                  * if we need to save off the start/end
8670                                  */
8671                                 if (rack->rc_last_tlp_acked_set &&
8672                                     (is_rsm_inside_declared_tlp_block(rack, rsm))) {
8673                                             /*
8674                                              * We already turned this on since this block is inside
8675                                              * the previous one was a partially sack now we
8676                                              * are getting another one (maybe all of it).
8677                                              */
8678                                             rack_log_dsack_event(rack, 10, __LINE__, rsm->r_start, rsm->r_end);
8679                                             /*
8680                                              * Lets make sure we have all of it though.
8681                                              */
8682                                             if (SEQ_LT(rsm->r_start, rack->r_ctl.last_tlp_acked_start)) {
8683                                                     rack->r_ctl.last_tlp_acked_start = rsm->r_start;
8684                                                     rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
8685                                                                          rack->r_ctl.last_tlp_acked_end);
8686                                             }
8687                                             if (SEQ_GT(rsm->r_end, rack->r_ctl.last_tlp_acked_end)) {
8688                                                     rack->r_ctl.last_tlp_acked_end = rsm->r_end;
8689                                                     rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
8690                                                                          rack->r_ctl.last_tlp_acked_end);
8691                                             }
8692                                     } else {
8693                                             rack->r_ctl.last_tlp_acked_start = rsm->r_start;
8694                                             rack->r_ctl.last_tlp_acked_end = rsm->r_end;
8695                                             rack->rc_last_tlp_acked_set = 1;
8696                                             rack->rc_last_tlp_past_cumack = 0;
8697                                             rack_log_dsack_event(rack, 8, __LINE__, rsm->r_start, rsm->r_end);
8698                                     }
8699                         }
8700                         /**
8701                          * In this case nrsm becomes
8702                          * nrsm->r_start = end;
8703                          * nrsm->r_end = rsm->r_end;
8704                          * which is un-acked.
8705                          * <and>
8706                          * rsm->r_end = nrsm->r_start;
8707                          * i.e. the remaining un-acked
8708                          * piece is left on the left
8709                          * hand side.
8710                          *
8711                          * So we start like this
8712                          * rsm      |----------| (not acked)
8713                          * sackblk  |---|
8714                          * build it so we have
8715                          * rsm      |---|         (acked)
8716                          * nrsm         |------|  (not acked)
8717                          */
8718                         counter_u64_add(rack_sack_splits, 1);
8719                         rack_clone_rsm(rack, nrsm, rsm, end);
8720                         rsm->r_flags &= (~RACK_HAS_FIN);
8721                         rsm->r_just_ret = 0;
8722 #ifndef INVARIANTS
8723                         (void)RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
8724 #else
8725                         insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
8726                         if (insret != NULL) {
8727                                 panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
8728                                       nrsm, insret, rack, rsm);
8729                         }
8730 #endif
8731                         if (rsm->r_in_tmap) {
8732                                 TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8733                                 nrsm->r_in_tmap = 1;
8734                         }
8735                         nrsm->r_dupack = 0;
8736                         rack_log_retran_reason(rack, nrsm, __LINE__, 0, 2);
8737                         rack_update_rtt(tp, rack, rsm, to, cts, SACKED, 0);
8738                         changed += (rsm->r_end - rsm->r_start);
8739                         rack->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
8740                         if (rsm->r_in_tmap) /* should be true */
8741                                 rack_log_sack_passed(tp, rack, rsm);
8742                         /* Is Reordering occuring? */
8743                         if (rsm->r_flags & RACK_SACK_PASSED) {
8744                                 rsm->r_flags &= ~RACK_SACK_PASSED;
8745                                 rack->r_ctl.rc_reorder_ts = cts;
8746                         }
8747                         if (rack->app_limited_needs_set)
8748                                 rack_need_set_test(tp, rack, rsm, tp->snd_una, __LINE__, RACK_USE_END);
8749                         rsm->r_ack_arrival = rack_to_usec_ts(&rack->r_ctl.act_rcv_time);
8750                         rsm->r_flags |= RACK_ACKED;
8751                         rack_log_map_chg(tp, rack, NULL, rsm, nrsm, MAP_SACK_M5, end, __LINE__);
8752                         if (rsm->r_in_tmap) {
8753                                 TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
8754                                 rsm->r_in_tmap = 0;
8755                         }
8756                 }
8757         } else if (start != end){
8758                 /*
8759                  * The block was already acked.
8760                  */
8761                 counter_u64_add(rack_sack_skipped_acked, 1);
8762                 moved++;
8763         }
8764 out:
8765         if (rsm &&
8766             ((rsm->r_flags & RACK_TLP) == 0) &&
8767             (rsm->r_flags & RACK_ACKED)) {
8768                 /*
8769                  * Now can we merge where we worked
8770                  * with either the previous or
8771                  * next block?
8772                  */
8773                 next = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8774                 while (next) {
8775                         if (next->r_flags & RACK_TLP)
8776                                 break;
8777                         if (next->r_flags & RACK_ACKED) {
8778                         /* yep this and next can be merged */
8779                                 rsm = rack_merge_rsm(rack, rsm, next);
8780                                 next = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8781                         } else
8782                                 break;
8783                 }
8784                 /* Now what about the previous? */
8785                 prev = RB_PREV(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8786                 while (prev) {
8787                         if (prev->r_flags & RACK_TLP)
8788                                 break;
8789                         if (prev->r_flags & RACK_ACKED) {
8790                                 /* yep the previous and this can be merged */
8791                                 rsm = rack_merge_rsm(rack, prev, rsm);
8792                                 prev = RB_PREV(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8793                         } else
8794                                 break;
8795                 }
8796         }
8797         if (used_ref == 0) {
8798                 counter_u64_add(rack_sack_proc_all, 1);
8799         } else {
8800                 counter_u64_add(rack_sack_proc_short, 1);
8801         }
8802         /* Save off the next one for quick reference. */
8803         if (rsm)
8804                 nrsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8805         else
8806                 nrsm = NULL;
8807         *prsm = rack->r_ctl.rc_sacklast = nrsm;
8808         /* Pass back the moved. */
8809         *moved_two = moved;
8810         return (changed);
8811 }
8812
8813 static void inline
8814 rack_peer_reneges(struct tcp_rack *rack, struct rack_sendmap *rsm, tcp_seq th_ack)
8815 {
8816         struct rack_sendmap *tmap;
8817
8818         tmap = NULL;
8819         while (rsm && (rsm->r_flags & RACK_ACKED)) {
8820                 /* Its no longer sacked, mark it so */
8821                 rack->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
8822 #ifdef INVARIANTS
8823                 if (rsm->r_in_tmap) {
8824                         panic("rack:%p rsm:%p flags:0x%x in tmap?",
8825                               rack, rsm, rsm->r_flags);
8826                 }
8827 #endif
8828                 rsm->r_flags &= ~(RACK_ACKED|RACK_SACK_PASSED|RACK_WAS_SACKPASS);
8829                 /* Rebuild it into our tmap */
8830                 if (tmap == NULL) {
8831                         TAILQ_INSERT_HEAD(&rack->r_ctl.rc_tmap, rsm, r_tnext);
8832                         tmap = rsm;
8833                 } else {
8834                         TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, tmap, rsm, r_tnext);
8835                         tmap = rsm;
8836                 }
8837                 tmap->r_in_tmap = 1;
8838                 rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8839         }
8840         /*
8841          * Now lets possibly clear the sack filter so we start
8842          * recognizing sacks that cover this area.
8843          */
8844         sack_filter_clear(&rack->r_ctl.rack_sf, th_ack);
8845
8846 }
8847
8848 static void
8849 rack_do_decay(struct tcp_rack *rack)
8850 {
8851         struct timeval res;
8852
8853 #define timersub(tvp, uvp, vvp)                                         \
8854         do {                                                            \
8855                 (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;          \
8856                 (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;       \
8857                 if ((vvp)->tv_usec < 0) {                               \
8858                         (vvp)->tv_sec--;                                \
8859                         (vvp)->tv_usec += 1000000;                      \
8860                 }                                                       \
8861         } while (0)
8862
8863         timersub(&rack->r_ctl.act_rcv_time, &rack->r_ctl.rc_last_time_decay, &res);
8864 #undef timersub
8865
8866         rack->r_ctl.input_pkt++;
8867         if ((rack->rc_in_persist) ||
8868             (res.tv_sec >= 1) ||
8869             (rack->rc_tp->snd_max == rack->rc_tp->snd_una)) {
8870                 /*
8871                  * Check for decay of non-SAD,
8872                  * we want all SAD detection metrics to
8873                  * decay 1/4 per second (or more) passed.
8874                  */
8875 #ifdef NETFLIX_EXP_DETECTION
8876                 uint32_t pkt_delta;
8877
8878                 pkt_delta = rack->r_ctl.input_pkt - rack->r_ctl.saved_input_pkt;
8879 #endif
8880                 /* Update our saved tracking values */
8881                 rack->r_ctl.saved_input_pkt = rack->r_ctl.input_pkt;
8882                 rack->r_ctl.rc_last_time_decay = rack->r_ctl.act_rcv_time;
8883                 /* Now do we escape without decay? */
8884 #ifdef NETFLIX_EXP_DETECTION
8885                 if (rack->rc_in_persist ||
8886                     (rack->rc_tp->snd_max == rack->rc_tp->snd_una) ||
8887                     (pkt_delta < tcp_sad_low_pps)){
8888                         /*
8889                          * We don't decay idle connections
8890                          * or ones that have a low input pps.
8891                          */
8892                         return;
8893                 }
8894                 /* Decay the counters */
8895                 rack->r_ctl.ack_count = ctf_decay_count(rack->r_ctl.ack_count,
8896                                                         tcp_sad_decay_val);
8897                 rack->r_ctl.sack_count = ctf_decay_count(rack->r_ctl.sack_count,
8898                                                          tcp_sad_decay_val);
8899                 rack->r_ctl.sack_moved_extra = ctf_decay_count(rack->r_ctl.sack_moved_extra,
8900                                                                tcp_sad_decay_val);
8901                 rack->r_ctl.sack_noextra_move = ctf_decay_count(rack->r_ctl.sack_noextra_move,
8902                                                                 tcp_sad_decay_val);
8903 #endif
8904         }
8905 }
8906
8907 static void
8908 rack_process_to_cumack(struct tcpcb *tp, struct tcp_rack *rack, register uint32_t th_ack, uint32_t cts, struct tcpopt *to)
8909 {
8910         struct rack_sendmap *rsm;
8911 #ifdef INVARIANTS
8912         struct rack_sendmap *rm;
8913 #endif
8914
8915         /*
8916          * The ACK point is advancing to th_ack, we must drop off
8917          * the packets in the rack log and calculate any eligble
8918          * RTT's.
8919          */
8920         rack->r_wanted_output = 1;
8921
8922         /* Tend any TLP that has been marked for 1/2 the seq space (its old)  */
8923         if ((rack->rc_last_tlp_acked_set == 1)&&
8924             (rack->rc_last_tlp_past_cumack == 1) &&
8925             (SEQ_GT(rack->r_ctl.last_tlp_acked_start, th_ack))) {
8926                 /*
8927                  * We have reached the point where our last rack
8928                  * tlp retransmit sequence is ahead of the cum-ack.
8929                  * This can only happen when the cum-ack moves all
8930                  * the way around (its been a full 2^^31+1 bytes
8931                  * or more since we sent a retransmitted TLP). Lets
8932                  * turn off the valid flag since its not really valid.
8933                  *
8934                  * Note since sack's also turn on this event we have
8935                  * a complication, we have to wait to age it out until
8936                  * the cum-ack is by the TLP before checking which is
8937                  * what the next else clause does.
8938                  */
8939                 rack_log_dsack_event(rack, 9, __LINE__,
8940                                      rack->r_ctl.last_tlp_acked_start,
8941                                      rack->r_ctl.last_tlp_acked_end);
8942                 rack->rc_last_tlp_acked_set = 0;
8943                 rack->rc_last_tlp_past_cumack = 0;
8944         } else if ((rack->rc_last_tlp_acked_set == 1) &&
8945                    (rack->rc_last_tlp_past_cumack == 0) &&
8946                    (SEQ_GEQ(th_ack, rack->r_ctl.last_tlp_acked_end))) {
8947                 /*
8948                  * It is safe to start aging TLP's out.
8949                  */
8950                 rack->rc_last_tlp_past_cumack = 1;
8951         }
8952         /* We do the same for the tlp send seq as well */
8953         if ((rack->rc_last_sent_tlp_seq_valid == 1) &&
8954             (rack->rc_last_sent_tlp_past_cumack == 1) &&
8955             (SEQ_GT(rack->r_ctl.last_sent_tlp_seq,  th_ack))) {
8956                 rack_log_dsack_event(rack, 9, __LINE__,
8957                                      rack->r_ctl.last_sent_tlp_seq,
8958                                      (rack->r_ctl.last_sent_tlp_seq +
8959                                       rack->r_ctl.last_sent_tlp_len));
8960                 rack->rc_last_sent_tlp_seq_valid = 0;
8961                 rack->rc_last_sent_tlp_past_cumack = 0;
8962         } else if ((rack->rc_last_sent_tlp_seq_valid == 1) &&
8963                    (rack->rc_last_sent_tlp_past_cumack == 0) &&
8964                    (SEQ_GEQ(th_ack, rack->r_ctl.last_sent_tlp_seq))) {
8965                 /*
8966                  * It is safe to start aging TLP's send.
8967                  */
8968                 rack->rc_last_sent_tlp_past_cumack = 1;
8969         }
8970 more:
8971         rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
8972         if (rsm == NULL) {
8973                 if ((th_ack - 1) == tp->iss) {
8974                         /*
8975                          * For the SYN incoming case we will not
8976                          * have called tcp_output for the sending of
8977                          * the SYN, so there will be no map. All
8978                          * other cases should probably be a panic.
8979                          */
8980                         return;
8981                 }
8982                 if (tp->t_flags & TF_SENTFIN) {
8983                         /* if we sent a FIN we often will not have map */
8984                         return;
8985                 }
8986 #ifdef INVARIANTS
8987                 panic("No rack map tp:%p for state:%d ack:%u rack:%p snd_una:%u snd_max:%u snd_nxt:%u\n",
8988                       tp,
8989                       tp->t_state, th_ack, rack,
8990                       tp->snd_una, tp->snd_max, tp->snd_nxt);
8991 #endif
8992                 return;
8993         }
8994         if (SEQ_LT(th_ack, rsm->r_start)) {
8995                 /* Huh map is missing this */
8996 #ifdef INVARIANTS
8997                 printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d\n",
8998                        rsm->r_start,
8999                        th_ack, tp->t_state, rack->r_state);
9000 #endif
9001                 return;
9002         }
9003         rack_update_rtt(tp, rack, rsm, to, cts, CUM_ACKED, th_ack);
9004
9005         /* Now was it a retransmitted TLP? */
9006         if ((rsm->r_flags & RACK_TLP) &&
9007             (rsm->r_rtr_cnt > 1)) {
9008                 /*
9009                  * Yes, this rsm was a TLP and retransmitted, remember that
9010                  * since if a DSACK comes back on this we don't want
9011                  * to think of it as a reordered segment. This may
9012                  * get updated again with possibly even other TLPs
9013                  * in flight, but thats ok. Only when we don't send
9014                  * a retransmitted TLP for 1/2 the sequences space
9015                  * will it get turned off (above).
9016                  */
9017                 if (rack->rc_last_tlp_acked_set &&
9018                     (is_rsm_inside_declared_tlp_block(rack, rsm))) {
9019                         /*
9020                          * We already turned this on since the end matches,
9021                          * the previous one was a partially ack now we
9022                          * are getting another one (maybe all of it).
9023                          */
9024                         rack_log_dsack_event(rack, 10, __LINE__, rsm->r_start, rsm->r_end);
9025                         /*
9026                          * Lets make sure we have all of it though.
9027                          */
9028                         if (SEQ_LT(rsm->r_start, rack->r_ctl.last_tlp_acked_start)) {
9029                                 rack->r_ctl.last_tlp_acked_start = rsm->r_start;
9030                                 rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
9031                                                      rack->r_ctl.last_tlp_acked_end);
9032                         }
9033                         if (SEQ_GT(rsm->r_end, rack->r_ctl.last_tlp_acked_end)) {
9034                                 rack->r_ctl.last_tlp_acked_end = rsm->r_end;
9035                                 rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
9036                                                      rack->r_ctl.last_tlp_acked_end);
9037                         }
9038                 } else {
9039                         rack->rc_last_tlp_past_cumack = 1;
9040                         rack->r_ctl.last_tlp_acked_start = rsm->r_start;
9041                         rack->r_ctl.last_tlp_acked_end = rsm->r_end;
9042                         rack->rc_last_tlp_acked_set = 1;
9043                         rack_log_dsack_event(rack, 8, __LINE__, rsm->r_start, rsm->r_end);
9044                 }
9045         }
9046         /* Now do we consume the whole thing? */
9047         if (SEQ_GEQ(th_ack, rsm->r_end)) {
9048                 /* Its all consumed. */
9049                 uint32_t left;
9050                 uint8_t newly_acked;
9051
9052                 rack_log_map_chg(tp, rack, NULL, rsm, NULL, MAP_FREE, rsm->r_end, __LINE__);
9053                 rack->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
9054                 rsm->r_rtr_bytes = 0;
9055                 /* Record the time of highest cumack sent */
9056                 rack->r_ctl.rc_gp_cumack_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
9057 #ifndef INVARIANTS
9058                 (void)RB_REMOVE(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
9059 #else
9060                 rm = RB_REMOVE(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
9061                 if (rm != rsm) {
9062                         panic("removing head in rack:%p rsm:%p rm:%p",
9063                               rack, rsm, rm);
9064                 }
9065 #endif
9066                 if (rsm->r_in_tmap) {
9067                         TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
9068                         rsm->r_in_tmap = 0;
9069                 }
9070                 newly_acked = 1;
9071                 if (rsm->r_flags & RACK_ACKED) {
9072                         /*
9073                          * It was acked on the scoreboard -- remove
9074                          * it from total
9075                          */
9076                         rack->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
9077                         newly_acked = 0;
9078                 } else if (rsm->r_flags & RACK_SACK_PASSED) {
9079                         /*
9080                          * There are segments ACKED on the
9081                          * scoreboard further up. We are seeing
9082                          * reordering.
9083                          */
9084                         rsm->r_flags &= ~RACK_SACK_PASSED;
9085                         rsm->r_ack_arrival = rack_to_usec_ts(&rack->r_ctl.act_rcv_time);
9086                         rsm->r_flags |= RACK_ACKED;
9087                         rack->r_ctl.rc_reorder_ts = cts;
9088                         if (rack->r_ent_rec_ns) {
9089                                 /*
9090                                  * We have sent no more, and we saw an sack
9091                                  * then ack arrive.
9092                                  */
9093                                 rack->r_might_revert = 1;
9094                         }
9095                 }
9096                 if ((rsm->r_flags & RACK_TO_REXT) &&
9097                     (tp->t_flags & TF_RCVD_TSTMP) &&
9098                     (to->to_flags & TOF_TS) &&
9099                     (to->to_tsecr != 0) &&
9100                     (tp->t_flags & TF_PREVVALID)) {
9101                         /*
9102                          * We can use the timestamp to see
9103                          * if this retransmission was from the
9104                          * first transmit. If so we made a mistake.
9105                          */
9106                         tp->t_flags &= ~TF_PREVVALID;
9107                         if (to->to_tsecr == rack_ts_to_msec(rsm->r_tim_lastsent[0])) {
9108                                 /* The first transmit is what this ack is for */
9109                                 rack_cong_signal(tp, CC_RTO_ERR, th_ack, __LINE__);
9110                         }
9111                 }
9112                 left = th_ack - rsm->r_end;
9113                 if (rack->app_limited_needs_set && newly_acked)
9114                         rack_need_set_test(tp, rack, rsm, th_ack, __LINE__, RACK_USE_END_OR_THACK);
9115                 /* Free back to zone */
9116                 rack_free(rack, rsm);
9117                 if (left) {
9118                         goto more;
9119                 }
9120                 /* Check for reneging */
9121                 rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
9122                 if (rsm && (rsm->r_flags & RACK_ACKED) && (th_ack == rsm->r_start)) {
9123                         /*
9124                          * The peer has moved snd_una up to
9125                          * the edge of this send, i.e. one
9126                          * that it had previously acked. The only
9127                          * way that can be true if the peer threw
9128                          * away data (space issues) that it had
9129                          * previously sacked (else it would have
9130                          * given us snd_una up to (rsm->r_end).
9131                          * We need to undo the acked markings here.
9132                          *
9133                          * Note we have to look to make sure th_ack is
9134                          * our rsm->r_start in case we get an old ack
9135                          * where th_ack is behind snd_una.
9136                          */
9137                         rack_peer_reneges(rack, rsm, th_ack);
9138                 }
9139                 return;
9140         }
9141         if (rsm->r_flags & RACK_ACKED) {
9142                 /*
9143                  * It was acked on the scoreboard -- remove it from
9144                  * total for the part being cum-acked.
9145                  */
9146                 rack->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
9147         }
9148         /*
9149          * Clear the dup ack count for
9150          * the piece that remains.
9151          */
9152         rsm->r_dupack = 0;
9153         rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
9154         if (rsm->r_rtr_bytes) {
9155                 /*
9156                  * It was retransmitted adjust the
9157                  * sack holes for what was acked.
9158                  */
9159                 int ack_am;
9160
9161                 ack_am = (th_ack - rsm->r_start);
9162                 if (ack_am >= rsm->r_rtr_bytes) {
9163                         rack->r_ctl.rc_holes_rxt -= ack_am;
9164                         rsm->r_rtr_bytes -= ack_am;
9165                 }
9166         }
9167         /*
9168          * Update where the piece starts and record
9169          * the time of send of highest cumack sent.
9170          */
9171         rack->r_ctl.rc_gp_cumack_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
9172         rack_log_map_chg(tp, rack, NULL, rsm, NULL, MAP_TRIM_HEAD, th_ack, __LINE__);
9173         /* Now we need to move our offset forward too */
9174         if (rsm->m && (rsm->orig_m_len != rsm->m->m_len)) {
9175                 /* Fix up the orig_m_len and possibly the mbuf offset */
9176                 rack_adjust_orig_mlen(rsm);
9177         }
9178         rsm->soff += (th_ack - rsm->r_start);
9179         rsm->r_start = th_ack;
9180         /* Now do we need to move the mbuf fwd too? */
9181         if (rsm->m) {
9182                 while (rsm->soff >= rsm->m->m_len) {
9183                         rsm->soff -= rsm->m->m_len;
9184                         rsm->m = rsm->m->m_next;
9185                         KASSERT((rsm->m != NULL),
9186                                 (" nrsm:%p hit at soff:%u null m",
9187                                  rsm, rsm->soff));
9188                 }
9189                 rsm->orig_m_len = rsm->m->m_len;
9190         }
9191         if (rack->app_limited_needs_set)
9192                 rack_need_set_test(tp, rack, rsm, tp->snd_una, __LINE__, RACK_USE_BEG);
9193 }
9194
9195 static void
9196 rack_handle_might_revert(struct tcpcb *tp, struct tcp_rack *rack)
9197 {
9198         struct rack_sendmap *rsm;
9199         int sack_pass_fnd = 0;
9200
9201         if (rack->r_might_revert) {
9202                 /*
9203                  * Ok we have reordering, have not sent anything, we
9204                  * might want to revert the congestion state if nothing
9205                  * further has SACK_PASSED on it. Lets check.
9206                  *
9207                  * We also get here when we have DSACKs come in for
9208                  * all the data that we FR'd. Note that a rxt or tlp
9209                  * timer clears this from happening.
9210                  */
9211
9212                 TAILQ_FOREACH(rsm, &rack->r_ctl.rc_tmap, r_tnext) {
9213                         if (rsm->r_flags & RACK_SACK_PASSED) {
9214                                 sack_pass_fnd = 1;
9215                                 break;
9216                         }
9217                 }
9218                 if (sack_pass_fnd == 0) {
9219                         /*
9220                          * We went into recovery
9221                          * incorrectly due to reordering!
9222                          */
9223                         int orig_cwnd;
9224
9225                         rack->r_ent_rec_ns = 0;
9226                         orig_cwnd = tp->snd_cwnd;
9227                         tp->snd_ssthresh = rack->r_ctl.rc_ssthresh_at_erec;
9228                         tp->snd_recover = tp->snd_una;
9229                         rack_log_to_prr(rack, 14, orig_cwnd, __LINE__);
9230                         EXIT_RECOVERY(tp->t_flags);
9231                 }
9232                 rack->r_might_revert = 0;
9233         }
9234 }
9235
9236 #ifdef NETFLIX_EXP_DETECTION
9237 static void
9238 rack_do_detection(struct tcpcb *tp, struct tcp_rack *rack,  uint32_t bytes_this_ack, uint32_t segsiz)
9239 {
9240         if ((rack->do_detection || tcp_force_detection) &&
9241             tcp_sack_to_ack_thresh &&
9242             tcp_sack_to_move_thresh &&
9243             ((rack->r_ctl.rc_num_maps_alloced > tcp_map_minimum) || rack->sack_attack_disable)) {
9244                 /*
9245                  * We have thresholds set to find
9246                  * possible attackers and disable sack.
9247                  * Check them.
9248                  */
9249                 uint64_t ackratio, moveratio, movetotal;
9250
9251                 /* Log detecting */
9252                 rack_log_sad(rack, 1);
9253                 ackratio = (uint64_t)(rack->r_ctl.sack_count);
9254                 ackratio *= (uint64_t)(1000);
9255                 if (rack->r_ctl.ack_count)
9256                         ackratio /= (uint64_t)(rack->r_ctl.ack_count);
9257                 else {
9258                         /* We really should not hit here */
9259                         ackratio = 1000;
9260                 }
9261                 if ((rack->sack_attack_disable == 0) &&
9262                     (ackratio > rack_highest_sack_thresh_seen))
9263                         rack_highest_sack_thresh_seen = (uint32_t)ackratio;
9264                 movetotal = rack->r_ctl.sack_moved_extra;
9265                 movetotal += rack->r_ctl.sack_noextra_move;
9266                 moveratio = rack->r_ctl.sack_moved_extra;
9267                 moveratio *= (uint64_t)1000;
9268                 if (movetotal)
9269                         moveratio /= movetotal;
9270                 else {
9271                         /* No moves, thats pretty good */
9272                         moveratio = 0;
9273                 }
9274                 if ((rack->sack_attack_disable == 0) &&
9275                     (moveratio > rack_highest_move_thresh_seen))
9276                         rack_highest_move_thresh_seen = (uint32_t)moveratio;
9277                 if (rack->sack_attack_disable == 0) {
9278                         if ((ackratio > tcp_sack_to_ack_thresh) &&
9279                             (moveratio > tcp_sack_to_move_thresh)) {
9280                                 /* Disable sack processing */
9281                                 rack->sack_attack_disable = 1;
9282                                 if (rack->r_rep_attack == 0) {
9283                                         rack->r_rep_attack = 1;
9284                                         counter_u64_add(rack_sack_attacks_detected, 1);
9285                                 }
9286                                 if (tcp_attack_on_turns_on_logging) {
9287                                         /*
9288                                          * Turn on logging, used for debugging
9289                                          * false positives.
9290                                          */
9291                                         rack->rc_tp->t_logstate = tcp_attack_on_turns_on_logging;
9292                                 }
9293                                 /* Clamp the cwnd at flight size */
9294                                 rack->r_ctl.rc_saved_cwnd = rack->rc_tp->snd_cwnd;
9295                                 rack->rc_tp->snd_cwnd = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
9296                                 rack_log_sad(rack, 2);
9297                         }
9298                 } else {
9299                         /* We are sack-disabled check for false positives */
9300                         if ((ackratio <= tcp_restoral_thresh) ||
9301                             (rack->r_ctl.rc_num_maps_alloced  < tcp_map_minimum)) {
9302                                 rack->sack_attack_disable = 0;
9303                                 rack_log_sad(rack, 3);
9304                                 /* Restart counting */
9305                                 rack->r_ctl.sack_count = 0;
9306                                 rack->r_ctl.sack_moved_extra = 0;
9307                                 rack->r_ctl.sack_noextra_move = 1;
9308                                 rack->r_ctl.ack_count = max(1,
9309                                       (bytes_this_ack / segsiz));
9310
9311                                 if (rack->r_rep_reverse == 0) {
9312                                         rack->r_rep_reverse = 1;
9313                                         counter_u64_add(rack_sack_attacks_reversed, 1);
9314                                 }
9315                                 /* Restore the cwnd */
9316                                 if (rack->r_ctl.rc_saved_cwnd > rack->rc_tp->snd_cwnd)
9317                                         rack->rc_tp->snd_cwnd = rack->r_ctl.rc_saved_cwnd;
9318                         }
9319                 }
9320         }
9321 }
9322 #endif
9323
9324 static int
9325 rack_note_dsack(struct tcp_rack *rack, tcp_seq start, tcp_seq end)
9326 {
9327
9328         uint32_t am, l_end;
9329         int was_tlp = 0;
9330
9331         if (SEQ_GT(end, start))
9332                 am = end - start;
9333         else
9334                 am = 0;
9335         if ((rack->rc_last_tlp_acked_set ) &&
9336             (SEQ_GEQ(start, rack->r_ctl.last_tlp_acked_start)) &&
9337             (SEQ_LEQ(end, rack->r_ctl.last_tlp_acked_end))) {
9338                 /*
9339                  * The DSACK is because of a TLP which we don't
9340                  * do anything with the reordering window over since
9341                  * it was not reordering that caused the DSACK but
9342                  * our previous retransmit TLP.
9343                  */
9344                 rack_log_dsack_event(rack, 7, __LINE__, start, end);
9345                 was_tlp = 1;
9346                 goto skip_dsack_round;
9347         }
9348         if (rack->rc_last_sent_tlp_seq_valid) {
9349                 l_end = rack->r_ctl.last_sent_tlp_seq + rack->r_ctl.last_sent_tlp_len;
9350                 if (SEQ_GEQ(start, rack->r_ctl.last_sent_tlp_seq) &&
9351                     (SEQ_LEQ(end, l_end))) {
9352                         /*
9353                          * This dsack is from the last sent TLP, ignore it
9354                          * for reordering purposes.
9355                          */
9356                         rack_log_dsack_event(rack, 7, __LINE__, start, end);
9357                         was_tlp = 1;
9358                         goto skip_dsack_round;
9359                 }
9360         }
9361         if (rack->rc_dsack_round_seen == 0) {
9362                 rack->rc_dsack_round_seen = 1;
9363                 rack->r_ctl.dsack_round_end = rack->rc_tp->snd_max;
9364                 rack->r_ctl.num_dsack++;
9365                 rack->r_ctl.dsack_persist = 16; /* 16 is from the standard */
9366                 rack_log_dsack_event(rack, 2, __LINE__, 0, 0);
9367         }
9368 skip_dsack_round:
9369         /*
9370          * We keep track of how many DSACK blocks we get
9371          * after a recovery incident.
9372          */
9373         rack->r_ctl.dsack_byte_cnt += am;
9374         if (!IN_FASTRECOVERY(rack->rc_tp->t_flags) &&
9375             rack->r_ctl.retran_during_recovery &&
9376             (rack->r_ctl.dsack_byte_cnt >= rack->r_ctl.retran_during_recovery)) {
9377                 /*
9378                  * False recovery most likely culprit is reordering. If
9379                  * nothing else is missing we need to revert.
9380                  */
9381                 rack->r_might_revert = 1;
9382                 rack_handle_might_revert(rack->rc_tp, rack);
9383                 rack->r_might_revert = 0;
9384                 rack->r_ctl.retran_during_recovery = 0;
9385                 rack->r_ctl.dsack_byte_cnt = 0;
9386         }
9387         return (was_tlp);
9388 }
9389
9390 static uint32_t
9391 do_rack_compute_pipe(struct tcpcb *tp, struct tcp_rack *rack, uint32_t snd_una)
9392 {
9393         return (((tp->snd_max - snd_una) - rack->r_ctl.rc_sacked) + rack->r_ctl.rc_holes_rxt);
9394 }
9395
9396 static int32_t
9397 rack_compute_pipe(struct tcpcb *tp)
9398 {
9399         return ((int32_t)do_rack_compute_pipe(tp,
9400                                               (struct tcp_rack *)tp->t_fb_ptr,
9401                                               tp->snd_una));
9402 }
9403
9404 static void
9405 rack_update_prr(struct tcpcb *tp, struct tcp_rack *rack, uint32_t changed, tcp_seq th_ack)
9406 {
9407         /* Deal with changed and PRR here (in recovery only) */
9408         uint32_t pipe, snd_una;
9409
9410         rack->r_ctl.rc_prr_delivered += changed;
9411
9412         if (sbavail(&rack->rc_inp->inp_socket->so_snd) <= (tp->snd_max - tp->snd_una)) {
9413                 /*
9414                  * It is all outstanding, we are application limited
9415                  * and thus we don't need more room to send anything.
9416                  * Note we use tp->snd_una here and not th_ack because
9417                  * the data as yet not been cut from the sb.
9418                  */
9419                 rack->r_ctl.rc_prr_sndcnt = 0;
9420                 return;
9421         }
9422         /* Compute prr_sndcnt */
9423         if (SEQ_GT(tp->snd_una, th_ack)) {
9424                 snd_una = tp->snd_una;
9425         } else {
9426                 snd_una = th_ack;
9427         }
9428         pipe = do_rack_compute_pipe(tp, rack, snd_una);
9429         if (pipe > tp->snd_ssthresh) {
9430                 long sndcnt;
9431
9432                 sndcnt = rack->r_ctl.rc_prr_delivered * tp->snd_ssthresh;
9433                 if (rack->r_ctl.rc_prr_recovery_fs > 0)
9434                         sndcnt /= (long)rack->r_ctl.rc_prr_recovery_fs;
9435                 else {
9436                         rack->r_ctl.rc_prr_sndcnt = 0;
9437                         rack_log_to_prr(rack, 9, 0, __LINE__);
9438                         sndcnt = 0;
9439                 }
9440                 sndcnt++;
9441                 if (sndcnt > (long)rack->r_ctl.rc_prr_out)
9442                         sndcnt -= rack->r_ctl.rc_prr_out;
9443                 else
9444                         sndcnt = 0;
9445                 rack->r_ctl.rc_prr_sndcnt = sndcnt;
9446                 rack_log_to_prr(rack, 10, 0, __LINE__);
9447         } else {
9448                 uint32_t limit;
9449
9450                 if (rack->r_ctl.rc_prr_delivered > rack->r_ctl.rc_prr_out)
9451                         limit = (rack->r_ctl.rc_prr_delivered - rack->r_ctl.rc_prr_out);
9452                 else
9453                         limit = 0;
9454                 if (changed > limit)
9455                         limit = changed;
9456                 limit += ctf_fixed_maxseg(tp);
9457                 if (tp->snd_ssthresh > pipe) {
9458                         rack->r_ctl.rc_prr_sndcnt = min((tp->snd_ssthresh - pipe), limit);
9459                         rack_log_to_prr(rack, 11, 0, __LINE__);
9460                 } else {
9461                         rack->r_ctl.rc_prr_sndcnt = min(0, limit);
9462                         rack_log_to_prr(rack, 12, 0, __LINE__);
9463                 }
9464         }
9465 }
9466
9467 static void
9468 rack_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th, int entered_recovery, int dup_ack_struck)
9469 {
9470         uint32_t changed;
9471         struct tcp_rack *rack;
9472         struct rack_sendmap *rsm;
9473         struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
9474         register uint32_t th_ack;
9475         int32_t i, j, k, num_sack_blks = 0;
9476         uint32_t cts, acked, ack_point;
9477         int loop_start = 0, moved_two = 0;
9478         uint32_t tsused;
9479
9480
9481         INP_WLOCK_ASSERT(tptoinpcb(tp));
9482         if (tcp_get_flags(th) & TH_RST) {
9483                 /* We don't log resets */
9484                 return;
9485         }
9486         rack = (struct tcp_rack *)tp->t_fb_ptr;
9487         cts = tcp_get_usecs(NULL);
9488         rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
9489         changed = 0;
9490         th_ack = th->th_ack;
9491         if (rack->sack_attack_disable == 0)
9492                 rack_do_decay(rack);
9493         if (BYTES_THIS_ACK(tp, th) >= ctf_fixed_maxseg(rack->rc_tp)) {
9494                 /*
9495                  * You only get credit for
9496                  * MSS and greater (and you get extra
9497                  * credit for larger cum-ack moves).
9498                  */
9499                 int ac;
9500
9501                 ac = BYTES_THIS_ACK(tp, th) / ctf_fixed_maxseg(rack->rc_tp);
9502                 rack->r_ctl.ack_count += ac;
9503                 counter_u64_add(rack_ack_total, ac);
9504         }
9505         if (rack->r_ctl.ack_count > 0xfff00000) {
9506                 /*
9507                  * reduce the number to keep us under
9508                  * a uint32_t.
9509                  */
9510                 rack->r_ctl.ack_count /= 2;
9511                 rack->r_ctl.sack_count /= 2;
9512         }
9513         if (SEQ_GT(th_ack, tp->snd_una)) {
9514                 rack_log_progress_event(rack, tp, ticks, PROGRESS_UPDATE, __LINE__);
9515                 tp->t_acktime = ticks;
9516         }
9517         if (rsm && SEQ_GT(th_ack, rsm->r_start))
9518                 changed = th_ack - rsm->r_start;
9519         if (changed) {
9520                 rack_process_to_cumack(tp, rack, th_ack, cts, to);
9521         }
9522         if ((to->to_flags & TOF_SACK) == 0) {
9523                 /* We are done nothing left and no sack. */
9524                 rack_handle_might_revert(tp, rack);
9525                 /*
9526                  * For cases where we struck a dup-ack
9527                  * with no SACK, add to the changes so
9528                  * PRR will work right.
9529                  */
9530                 if (dup_ack_struck && (changed == 0)) {
9531                         changed += ctf_fixed_maxseg(rack->rc_tp);
9532                 }
9533                 goto out;
9534         }
9535         /* Sack block processing */
9536         if (SEQ_GT(th_ack, tp->snd_una))
9537                 ack_point = th_ack;
9538         else
9539                 ack_point = tp->snd_una;
9540         for (i = 0; i < to->to_nsacks; i++) {
9541                 bcopy((to->to_sacks + i * TCPOLEN_SACK),
9542                       &sack, sizeof(sack));
9543                 sack.start = ntohl(sack.start);
9544                 sack.end = ntohl(sack.end);
9545                 if (SEQ_GT(sack.end, sack.start) &&
9546                     SEQ_GT(sack.start, ack_point) &&
9547                     SEQ_LT(sack.start, tp->snd_max) &&
9548                     SEQ_GT(sack.end, ack_point) &&
9549                     SEQ_LEQ(sack.end, tp->snd_max)) {
9550                         sack_blocks[num_sack_blks] = sack;
9551                         num_sack_blks++;
9552                 } else if (SEQ_LEQ(sack.start, th_ack) &&
9553                            SEQ_LEQ(sack.end, th_ack)) {
9554                         int was_tlp;
9555
9556                         was_tlp = rack_note_dsack(rack, sack.start, sack.end);
9557                         /*
9558                          * Its a D-SACK block.
9559                          */
9560                         tcp_record_dsack(tp, sack.start, sack.end, was_tlp);
9561                 }
9562         }
9563         if (rack->rc_dsack_round_seen) {
9564                 /* Is the dsack roound over? */
9565                 if (SEQ_GEQ(th_ack, rack->r_ctl.dsack_round_end)) {
9566                         /* Yes it is */
9567                         rack->rc_dsack_round_seen = 0;
9568                         rack_log_dsack_event(rack, 3, __LINE__, 0, 0);
9569                 }
9570         }
9571         /*
9572          * Sort the SACK blocks so we can update the rack scoreboard with
9573          * just one pass.
9574          */
9575         num_sack_blks = sack_filter_blks(&rack->r_ctl.rack_sf, sack_blocks,
9576                                          num_sack_blks, th->th_ack);
9577         ctf_log_sack_filter(rack->rc_tp, num_sack_blks, sack_blocks);
9578         if (num_sack_blks == 0) {
9579                 /* Nothing to sack (DSACKs?) */
9580                 goto out_with_totals;
9581         }
9582         if (num_sack_blks < 2) {
9583                 /* Only one, we don't need to sort */
9584                 goto do_sack_work;
9585         }
9586         /* Sort the sacks */
9587         for (i = 0; i < num_sack_blks; i++) {
9588                 for (j = i + 1; j < num_sack_blks; j++) {
9589                         if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
9590                                 sack = sack_blocks[i];
9591                                 sack_blocks[i] = sack_blocks[j];
9592                                 sack_blocks[j] = sack;
9593                         }
9594                 }
9595         }
9596         /*
9597          * Now are any of the sack block ends the same (yes some
9598          * implementations send these)?
9599          */
9600 again:
9601         if (num_sack_blks == 0)
9602                 goto out_with_totals;
9603         if (num_sack_blks > 1) {
9604                 for (i = 0; i < num_sack_blks; i++) {
9605                         for (j = i + 1; j < num_sack_blks; j++) {
9606                                 if (sack_blocks[i].end == sack_blocks[j].end) {
9607                                         /*
9608                                          * Ok these two have the same end we
9609                                          * want the smallest end and then
9610                                          * throw away the larger and start
9611                                          * again.
9612                                          */
9613                                         if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
9614                                                 /*
9615                                                  * The second block covers
9616                                                  * more area use that
9617                                                  */
9618                                                 sack_blocks[i].start = sack_blocks[j].start;
9619                                         }
9620                                         /*
9621                                          * Now collapse out the dup-sack and
9622                                          * lower the count
9623                                          */
9624                                         for (k = (j + 1); k < num_sack_blks; k++) {
9625                                                 sack_blocks[j].start = sack_blocks[k].start;
9626                                                 sack_blocks[j].end = sack_blocks[k].end;
9627                                                 j++;
9628                                         }
9629                                         num_sack_blks--;
9630                                         goto again;
9631                                 }
9632                         }
9633                 }
9634         }
9635 do_sack_work:
9636         /*
9637          * First lets look to see if
9638          * we have retransmitted and
9639          * can use the transmit next?
9640          */
9641         rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
9642         if (rsm &&
9643             SEQ_GT(sack_blocks[0].end, rsm->r_start) &&
9644             SEQ_LT(sack_blocks[0].start, rsm->r_end)) {
9645                 /*
9646                  * We probably did the FR and the next
9647                  * SACK in continues as we would expect.
9648                  */
9649                 acked = rack_proc_sack_blk(tp, rack, &sack_blocks[0], to, &rsm, cts, &moved_two);
9650                 if (acked) {
9651                         rack->r_wanted_output = 1;
9652                         changed += acked;
9653                 }
9654                 if (num_sack_blks == 1) {
9655                         /*
9656                          * This is what we would expect from
9657                          * a normal implementation to happen
9658                          * after we have retransmitted the FR,
9659                          * i.e the sack-filter pushes down
9660                          * to 1 block and the next to be retransmitted
9661                          * is the sequence in the sack block (has more
9662                          * are acked). Count this as ACK'd data to boost
9663                          * up the chances of recovering any false positives.
9664                          */
9665                         rack->r_ctl.ack_count += (acked / ctf_fixed_maxseg(rack->rc_tp));
9666                         counter_u64_add(rack_ack_total, (acked / ctf_fixed_maxseg(rack->rc_tp)));
9667                         counter_u64_add(rack_express_sack, 1);
9668                         if (rack->r_ctl.ack_count > 0xfff00000) {
9669                                 /*
9670                                  * reduce the number to keep us under
9671                                  * a uint32_t.
9672                                  */
9673                                 rack->r_ctl.ack_count /= 2;
9674                                 rack->r_ctl.sack_count /= 2;
9675                         }
9676                         goto out_with_totals;
9677                 } else {
9678                         /*
9679                          * Start the loop through the
9680                          * rest of blocks, past the first block.
9681                          */
9682                         moved_two = 0;
9683                         loop_start = 1;
9684                 }
9685         }
9686         /* Its a sack of some sort */
9687         rack->r_ctl.sack_count++;
9688         if (rack->r_ctl.sack_count > 0xfff00000) {
9689                 /*
9690                  * reduce the number to keep us under
9691                  * a uint32_t.
9692                  */
9693                 rack->r_ctl.ack_count /= 2;
9694                 rack->r_ctl.sack_count /= 2;
9695         }
9696         counter_u64_add(rack_sack_total, 1);
9697         if (rack->sack_attack_disable) {
9698                 /* An attacker disablement is in place */
9699                 if (num_sack_blks > 1) {
9700                         rack->r_ctl.sack_count += (num_sack_blks - 1);
9701                         rack->r_ctl.sack_moved_extra++;
9702                         counter_u64_add(rack_move_some, 1);
9703                         if (rack->r_ctl.sack_moved_extra > 0xfff00000) {
9704                                 rack->r_ctl.sack_moved_extra /= 2;
9705                                 rack->r_ctl.sack_noextra_move /= 2;
9706                         }
9707                 }
9708                 goto out;
9709         }
9710         rsm = rack->r_ctl.rc_sacklast;
9711         for (i = loop_start; i < num_sack_blks; i++) {
9712                 acked = rack_proc_sack_blk(tp, rack, &sack_blocks[i], to, &rsm, cts, &moved_two);
9713                 if (acked) {
9714                         rack->r_wanted_output = 1;
9715                         changed += acked;
9716                 }
9717                 if (moved_two) {
9718                         /*
9719                          * If we did not get a SACK for at least a MSS and
9720                          * had to move at all, or if we moved more than our
9721                          * threshold, it counts against the "extra" move.
9722                          */
9723                         rack->r_ctl.sack_moved_extra += moved_two;
9724                         counter_u64_add(rack_move_some, 1);
9725                 } else {
9726                         /*
9727                          * else we did not have to move
9728                          * any more than we would expect.
9729                          */
9730                         rack->r_ctl.sack_noextra_move++;
9731                         counter_u64_add(rack_move_none, 1);
9732                 }
9733                 if (moved_two && (acked < ctf_fixed_maxseg(rack->rc_tp))) {
9734                         /*
9735                          * If the SACK was not a full MSS then
9736                          * we add to sack_count the number of
9737                          * MSS's (or possibly more than
9738                          * a MSS if its a TSO send) we had to skip by.
9739                          */
9740                         rack->r_ctl.sack_count += moved_two;
9741                         counter_u64_add(rack_sack_total, moved_two);
9742                 }
9743                 /*
9744                  * Now we need to setup for the next
9745                  * round. First we make sure we won't
9746                  * exceed the size of our uint32_t on
9747                  * the various counts, and then clear out
9748                  * moved_two.
9749                  */
9750                 if ((rack->r_ctl.sack_moved_extra > 0xfff00000) ||
9751                     (rack->r_ctl.sack_noextra_move > 0xfff00000)) {
9752                         rack->r_ctl.sack_moved_extra /= 2;
9753                         rack->r_ctl.sack_noextra_move /= 2;
9754                 }
9755                 if (rack->r_ctl.sack_count > 0xfff00000) {
9756                         rack->r_ctl.ack_count /= 2;
9757                         rack->r_ctl.sack_count /= 2;
9758                 }
9759                 moved_two = 0;
9760         }
9761 out_with_totals:
9762         if (num_sack_blks > 1) {
9763                 /*
9764                  * You get an extra stroke if
9765                  * you have more than one sack-blk, this
9766                  * could be where we are skipping forward
9767                  * and the sack-filter is still working, or
9768                  * it could be an attacker constantly
9769                  * moving us.
9770                  */
9771                 rack->r_ctl.sack_moved_extra++;
9772                 counter_u64_add(rack_move_some, 1);
9773         }
9774 out:
9775 #ifdef NETFLIX_EXP_DETECTION
9776         rack_do_detection(tp, rack, BYTES_THIS_ACK(tp, th), ctf_fixed_maxseg(rack->rc_tp));
9777 #endif
9778         if (changed) {
9779                 /* Something changed cancel the rack timer */
9780                 rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
9781         }
9782         tsused = tcp_get_usecs(NULL);
9783         rsm = tcp_rack_output(tp, rack, tsused);
9784         if ((!IN_FASTRECOVERY(tp->t_flags)) &&
9785             rsm &&
9786             ((rsm->r_flags & RACK_MUST_RXT) == 0)) {
9787                 /* Enter recovery */
9788                 entered_recovery = 1;
9789                 rack_cong_signal(tp, CC_NDUPACK, tp->snd_una, __LINE__);
9790                 /*
9791                  * When we enter recovery we need to assure we send
9792                  * one packet.
9793                  */
9794                 if (rack->rack_no_prr == 0) {
9795                         rack->r_ctl.rc_prr_sndcnt = ctf_fixed_maxseg(tp);
9796                         rack_log_to_prr(rack, 8, 0, __LINE__);
9797                 }
9798                 rack->r_timer_override = 1;
9799                 rack->r_early = 0;
9800                 rack->r_ctl.rc_agg_early = 0;
9801         } else if (IN_FASTRECOVERY(tp->t_flags) &&
9802                    rsm &&
9803                    (rack->r_rr_config == 3)) {
9804                 /*
9805                  * Assure we can output and we get no
9806                  * remembered pace time except the retransmit.
9807                  */
9808                 rack->r_timer_override = 1;
9809                 rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
9810                 rack->r_ctl.rc_resend = rsm;
9811         }
9812         if (IN_FASTRECOVERY(tp->t_flags) &&
9813             (rack->rack_no_prr == 0) &&
9814             (entered_recovery == 0)) {
9815                 rack_update_prr(tp, rack, changed, th_ack);
9816                 if ((rsm && (rack->r_ctl.rc_prr_sndcnt >= ctf_fixed_maxseg(tp)) &&
9817                      ((tcp_in_hpts(rack->rc_inp) == 0) &&
9818                       ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0)))) {
9819                         /*
9820                          * If you are pacing output you don't want
9821                          * to override.
9822                          */
9823                         rack->r_early = 0;
9824                         rack->r_ctl.rc_agg_early = 0;
9825                         rack->r_timer_override = 1;
9826                 }
9827         }
9828 }
9829
9830 static void
9831 rack_strike_dupack(struct tcp_rack *rack)
9832 {
9833         struct rack_sendmap *rsm;
9834
9835         rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
9836         while (rsm && (rsm->r_dupack >= DUP_ACK_THRESHOLD)) {
9837                 rsm = TAILQ_NEXT(rsm, r_tnext);
9838                 if (rsm->r_flags & RACK_MUST_RXT) {
9839                         /* Sendmap entries that are marked to
9840                          * be retransmitted do not need dupack's
9841                          * struck. We get these marks for a number
9842                          * of reasons (rxt timeout with no sack,
9843                          * mtu change, or rwnd collapses). When
9844                          * these events occur, we know we must retransmit
9845                          * them and mark the sendmap entries. Dupack counting
9846                          * is not needed since we are already set to retransmit
9847                          * it as soon as we can.
9848                          */
9849                         continue;
9850                 }
9851         }
9852         if (rsm && (rsm->r_dupack < 0xff)) {
9853                 rsm->r_dupack++;
9854                 if (rsm->r_dupack >= DUP_ACK_THRESHOLD) {
9855                         struct timeval tv;
9856                         uint32_t cts;
9857                         /*
9858                          * Here we see if we need to retransmit. For
9859                          * a SACK type connection if enough time has passed
9860                          * we will get a return of the rsm. For a non-sack
9861                          * connection we will get the rsm returned if the
9862                          * dupack value is 3 or more.
9863                          */
9864                         cts = tcp_get_usecs(&tv);
9865                         rack->r_ctl.rc_resend = tcp_rack_output(rack->rc_tp, rack, cts);
9866                         if (rack->r_ctl.rc_resend != NULL) {
9867                                 if (!IN_FASTRECOVERY(rack->rc_tp->t_flags)) {
9868                                         rack_cong_signal(rack->rc_tp, CC_NDUPACK,
9869                                                          rack->rc_tp->snd_una, __LINE__);
9870                                 }
9871                                 rack->r_wanted_output = 1;
9872                                 rack->r_timer_override = 1;
9873                                 rack_log_retran_reason(rack, rsm, __LINE__, 1, 3);
9874                         }
9875                 } else {
9876                         rack_log_retran_reason(rack, rsm, __LINE__, 0, 3);
9877                 }
9878         }
9879 }
9880
9881 static void
9882 rack_check_bottom_drag(struct tcpcb *tp,
9883                        struct tcp_rack *rack,
9884                        struct socket *so, int32_t acked)
9885 {
9886         uint32_t segsiz, minseg;
9887
9888         segsiz = ctf_fixed_maxseg(tp);
9889         minseg = segsiz;
9890
9891         if (tp->snd_max == tp->snd_una) {
9892                 /*
9893                  * We are doing dynamic pacing and we are way
9894                  * under. Basically everything got acked while
9895                  * we were still waiting on the pacer to expire.
9896                  *
9897                  * This means we need to boost the b/w in
9898                  * addition to any earlier boosting of
9899                  * the multiplier.
9900                  */
9901                 rack->rc_dragged_bottom = 1;
9902                 rack_validate_multipliers_at_or_above100(rack);
9903                 /*
9904                  * Lets use the segment bytes acked plus
9905                  * the lowest RTT seen as the basis to
9906                  * form a b/w estimate. This will be off
9907                  * due to the fact that the true estimate
9908                  * should be around 1/2 the time of the RTT
9909                  * but we can settle for that.
9910                  */
9911                 if ((rack->r_ctl.rack_rs.rs_flags & RACK_RTT_VALID) &&
9912                     acked) {
9913                         uint64_t bw, calc_bw, rtt;
9914
9915                         rtt = rack->r_ctl.rack_rs.rs_us_rtt;
9916                         if (rtt == 0) {
9917                                 /* no us sample is there a ms one? */
9918                                 if (rack->r_ctl.rack_rs.rs_rtt_lowest) {
9919                                         rtt = rack->r_ctl.rack_rs.rs_rtt_lowest;
9920                                 } else {
9921                                         goto no_measurement;
9922                                 }
9923                         }
9924                         bw = acked;
9925                         calc_bw = bw * 1000000;
9926                         calc_bw /= rtt;
9927                         if (rack->r_ctl.last_max_bw &&
9928                             (rack->r_ctl.last_max_bw < calc_bw)) {
9929                                 /*
9930                                  * If we have a last calculated max bw
9931                                  * enforce it.
9932                                  */
9933                                 calc_bw = rack->r_ctl.last_max_bw;
9934                         }
9935                         /* now plop it in */
9936                         if (rack->rc_gp_filled == 0) {
9937                                 if (calc_bw > ONE_POINT_TWO_MEG) {
9938                                         /*
9939                                          * If we have no measurement
9940                                          * don't let us set in more than
9941                                          * 1.2Mbps. If we are still too
9942                                          * low after pacing with this we
9943                                          * will hopefully have a max b/w
9944                                          * available to sanity check things.
9945                                          */
9946                                         calc_bw = ONE_POINT_TWO_MEG;
9947                                 }
9948                                 rack->r_ctl.rc_rtt_diff = 0;
9949                                 rack->r_ctl.gp_bw = calc_bw;
9950                                 rack->rc_gp_filled = 1;
9951                                 if (rack->r_ctl.num_measurements < RACK_REQ_AVG)
9952                                         rack->r_ctl.num_measurements = RACK_REQ_AVG;
9953                                 rack_set_pace_segments(rack->rc_tp, rack, __LINE__, NULL);
9954                         } else if (calc_bw > rack->r_ctl.gp_bw) {
9955                                 rack->r_ctl.rc_rtt_diff = 0;
9956                                 if (rack->r_ctl.num_measurements < RACK_REQ_AVG)
9957                                         rack->r_ctl.num_measurements = RACK_REQ_AVG;
9958                                 rack->r_ctl.gp_bw = calc_bw;
9959                                 rack_set_pace_segments(rack->rc_tp, rack, __LINE__, NULL);
9960                         } else
9961                                 rack_increase_bw_mul(rack, -1, 0, 0, 1);
9962                         if ((rack->gp_ready == 0) &&
9963                             (rack->r_ctl.num_measurements >= rack->r_ctl.req_measurements)) {
9964                                 /* We have enough measurements now */
9965                                 rack->gp_ready = 1;
9966                                 rack_set_cc_pacing(rack);
9967                                 if (rack->defer_options)
9968                                         rack_apply_deferred_options(rack);
9969                         }
9970                         /*
9971                          * For acks over 1mss we do a extra boost to simulate
9972                          * where we would get 2 acks (we want 110 for the mul).
9973                          */
9974                         if (acked > segsiz)
9975                                 rack_increase_bw_mul(rack, -1, 0, 0, 1);
9976                 } else {
9977                         /*
9978                          * zero rtt possibly?, settle for just an old increase.
9979                          */
9980 no_measurement:
9981                         rack_increase_bw_mul(rack, -1, 0, 0, 1);
9982                 }
9983         } else if ((IN_FASTRECOVERY(tp->t_flags) == 0) &&
9984                    (sbavail(&so->so_snd) > max((segsiz * (4 + rack_req_segs)),
9985                                                minseg)) &&
9986                    (rack->r_ctl.cwnd_to_use > max((segsiz * (rack_req_segs + 2)), minseg)) &&
9987                    (tp->snd_wnd > max((segsiz * (rack_req_segs + 2)), minseg)) &&
9988                    (ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked) <=
9989                     (segsiz * rack_req_segs))) {
9990                 /*
9991                  * We are doing dynamic GP pacing and
9992                  * we have everything except 1MSS or less
9993                  * bytes left out. We are still pacing away.
9994                  * And there is data that could be sent, This
9995                  * means we are inserting delayed ack time in
9996                  * our measurements because we are pacing too slow.
9997                  */
9998                 rack_validate_multipliers_at_or_above100(rack);
9999                 rack->rc_dragged_bottom = 1;
10000                 rack_increase_bw_mul(rack, -1, 0, 0, 1);
10001         }
10002 }
10003
10004
10005
10006 static void
10007 rack_gain_for_fastoutput(struct tcp_rack *rack, struct tcpcb *tp, struct socket *so, uint32_t acked_amount)
10008 {
10009         /*
10010          * The fast output path is enabled and we
10011          * have moved the cumack forward. Lets see if
10012          * we can expand forward the fast path length by
10013          * that amount. What we would ideally like to
10014          * do is increase the number of bytes in the
10015          * fast path block (left_to_send) by the
10016          * acked amount. However we have to gate that
10017          * by two factors:
10018          * 1) The amount outstanding and the rwnd of the peer
10019          *    (i.e. we don't want to exceed the rwnd of the peer).
10020          *    <and>
10021          * 2) The amount of data left in the socket buffer (i.e.
10022          *    we can't send beyond what is in the buffer).
10023          *
10024          * Note that this does not take into account any increase
10025          * in the cwnd. We will only extend the fast path by
10026          * what was acked.
10027          */
10028         uint32_t new_total, gating_val;
10029
10030         new_total = acked_amount + rack->r_ctl.fsb.left_to_send;
10031         gating_val = min((sbavail(&so->so_snd) - (tp->snd_max - tp->snd_una)),
10032                          (tp->snd_wnd - (tp->snd_max - tp->snd_una)));
10033         if (new_total <= gating_val) {
10034                 /* We can increase left_to_send by the acked amount */
10035                 counter_u64_add(rack_extended_rfo, 1);
10036                 rack->r_ctl.fsb.left_to_send = new_total;
10037                 KASSERT((rack->r_ctl.fsb.left_to_send <= (sbavail(&rack->rc_inp->inp_socket->so_snd) - (tp->snd_max - tp->snd_una))),
10038                         ("rack:%p left_to_send:%u sbavail:%u out:%u",
10039                          rack, rack->r_ctl.fsb.left_to_send,
10040                          sbavail(&rack->rc_inp->inp_socket->so_snd),
10041                          (tp->snd_max - tp->snd_una)));
10042
10043         }
10044 }
10045
10046 static void
10047 rack_adjust_sendmap(struct tcp_rack *rack, struct sockbuf *sb, tcp_seq snd_una)
10048 {
10049         /*
10050          * Here any sendmap entry that points to the
10051          * beginning mbuf must be adjusted to the correct
10052          * offset. This must be called with:
10053          * 1) The socket buffer locked
10054          * 2) snd_una adjusted to its new postion.
10055          *
10056          * Note that (2) implies rack_ack_received has also
10057          * been called.
10058          *
10059          * We grab the first mbuf in the socket buffer and
10060          * then go through the front of the sendmap, recalculating
10061          * the stored offset for any sendmap entry that has
10062          * that mbuf. We must use the sb functions to do this
10063          * since its possible an add was done has well as
10064          * the subtraction we may have just completed. This should
10065          * not be a penalty though, since we just referenced the sb
10066          * to go in and trim off the mbufs that we freed (of course
10067          * there will be a penalty for the sendmap references though).
10068          */
10069         struct mbuf *m;
10070         struct rack_sendmap *rsm;
10071
10072         SOCKBUF_LOCK_ASSERT(sb);
10073         m = sb->sb_mb;
10074         rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
10075         if ((rsm == NULL) || (m == NULL)) {
10076                 /* Nothing outstanding */
10077                 return;
10078         }
10079         while (rsm->m && (rsm->m == m)) {
10080                 /* one to adjust */
10081 #ifdef INVARIANTS
10082                 struct mbuf *tm;
10083                 uint32_t soff;
10084
10085                 tm = sbsndmbuf(sb, (rsm->r_start - snd_una), &soff);
10086                 if (rsm->orig_m_len != m->m_len) {
10087                         rack_adjust_orig_mlen(rsm);
10088                 }
10089                 if (rsm->soff != soff) {
10090                         /*
10091                          * This is not a fatal error, we anticipate it
10092                          * might happen (the else code), so we count it here
10093                          * so that under invariant we can see that it really
10094                          * does happen.
10095                          */
10096                         counter_u64_add(rack_adjust_map_bw, 1);
10097                 }
10098                 rsm->m = tm;
10099                 rsm->soff = soff;
10100                 if (tm)
10101                         rsm->orig_m_len = rsm->m->m_len;
10102                 else
10103                         rsm->orig_m_len = 0;
10104 #else
10105                 rsm->m = sbsndmbuf(sb, (rsm->r_start - snd_una), &rsm->soff);
10106                 if (rsm->m)
10107                         rsm->orig_m_len = rsm->m->m_len;
10108                 else
10109                         rsm->orig_m_len = 0;
10110 #endif
10111                 rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree,
10112                               rsm);
10113                 if (rsm == NULL)
10114                         break;
10115         }
10116 }
10117
10118 /*
10119  * Return value of 1, we do not need to call rack_process_data().
10120  * return value of 0, rack_process_data can be called.
10121  * For ret_val if its 0 the TCP is locked, if its non-zero
10122  * its unlocked and probably unsafe to touch the TCB.
10123  */
10124 static int
10125 rack_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
10126     struct tcpcb *tp, struct tcpopt *to,
10127     uint32_t tiwin, int32_t tlen,
10128     int32_t * ofia, int32_t thflags, int32_t *ret_val)
10129 {
10130         int32_t ourfinisacked = 0;
10131         int32_t nsegs, acked_amount;
10132         int32_t acked;
10133         struct mbuf *mfree;
10134         struct tcp_rack *rack;
10135         int32_t under_pacing = 0;
10136         int32_t recovery = 0;
10137
10138         INP_WLOCK_ASSERT(tptoinpcb(tp));
10139
10140         rack = (struct tcp_rack *)tp->t_fb_ptr;
10141         if (SEQ_GT(th->th_ack, tp->snd_max)) {
10142                 __ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val,
10143                                       &rack->r_ctl.challenge_ack_ts,
10144                                       &rack->r_ctl.challenge_ack_cnt);
10145                 rack->r_wanted_output = 1;
10146                 return (1);
10147         }
10148         if (rack->gp_ready &&
10149             (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
10150                 under_pacing = 1;
10151         }
10152         if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
10153                 int in_rec, dup_ack_struck = 0;
10154
10155                 in_rec = IN_FASTRECOVERY(tp->t_flags);
10156                 if (rack->rc_in_persist) {
10157                         tp->t_rxtshift = 0;
10158                         RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
10159                                       rack_rto_min, rack_rto_max, rack->r_ctl.timer_slop);
10160                 }
10161                 if ((th->th_ack == tp->snd_una) &&
10162                     (tiwin == tp->snd_wnd) &&
10163                     ((to->to_flags & TOF_SACK) == 0)) {
10164                         rack_strike_dupack(rack);
10165                         dup_ack_struck = 1;
10166                 }
10167                 rack_log_ack(tp, to, th, ((in_rec == 0) && IN_FASTRECOVERY(tp->t_flags)), dup_ack_struck);
10168         }
10169         if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
10170                 /*
10171                  * Old ack, behind (or duplicate to) the last one rcv'd
10172                  * Note: We mark reordering is occuring if its
10173                  * less than and we have not closed our window.
10174                  */
10175                 if (SEQ_LT(th->th_ack, tp->snd_una) && (sbspace(&so->so_rcv) > ctf_fixed_maxseg(tp))) {
10176                         rack->r_ctl.rc_reorder_ts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
10177                 }
10178                 return (0);
10179         }
10180         /*
10181          * If we reach this point, ACK is not a duplicate, i.e., it ACKs
10182          * something we sent.
10183          */
10184         if (tp->t_flags & TF_NEEDSYN) {
10185                 /*
10186                  * T/TCP: Connection was half-synchronized, and our SYN has
10187                  * been ACK'd (so connection is now fully synchronized).  Go
10188                  * to non-starred state, increment snd_una for ACK of SYN,
10189                  * and check if we can do window scaling.
10190                  */
10191                 tp->t_flags &= ~TF_NEEDSYN;
10192                 tp->snd_una++;
10193                 /* Do window scaling? */
10194                 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
10195                     (TF_RCVD_SCALE | TF_REQ_SCALE)) {
10196                         tp->rcv_scale = tp->request_r_scale;
10197                         /* Send window already scaled. */
10198                 }
10199         }
10200         nsegs = max(1, m->m_pkthdr.lro_nsegs);
10201
10202         acked = BYTES_THIS_ACK(tp, th);
10203         if (acked) {
10204                 /*
10205                  * Any time we move the cum-ack forward clear
10206                  * keep-alive tied probe-not-answered. The
10207                  * persists clears its own on entry.
10208                  */
10209                 rack->probe_not_answered = 0;
10210         }
10211         KMOD_TCPSTAT_ADD(tcps_rcvackpack, nsegs);
10212         KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
10213         /*
10214          * If we just performed our first retransmit, and the ACK arrives
10215          * within our recovery window, then it was a mistake to do the
10216          * retransmit in the first place.  Recover our original cwnd and
10217          * ssthresh, and proceed to transmit where we left off.
10218          */
10219         if ((tp->t_flags & TF_PREVVALID) &&
10220             ((tp->t_flags & TF_RCVD_TSTMP) == 0)) {
10221                 tp->t_flags &= ~TF_PREVVALID;
10222                 if (tp->t_rxtshift == 1 &&
10223                     (int)(ticks - tp->t_badrxtwin) < 0)
10224                         rack_cong_signal(tp, CC_RTO_ERR, th->th_ack, __LINE__);
10225         }
10226         if (acked) {
10227                 /* assure we are not backed off */
10228                 tp->t_rxtshift = 0;
10229                 RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
10230                               rack_rto_min, rack_rto_max, rack->r_ctl.timer_slop);
10231                 rack->rc_tlp_in_progress = 0;
10232                 rack->r_ctl.rc_tlp_cnt_out = 0;
10233                 /*
10234                  * If it is the RXT timer we want to
10235                  * stop it, so we can restart a TLP.
10236                  */
10237                 if (rack->r_ctl.rc_hpts_flags & PACE_TMR_RXT)
10238                         rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
10239 #ifdef NETFLIX_HTTP_LOGGING
10240                 tcp_http_check_for_comp(rack->rc_tp, th->th_ack);
10241 #endif
10242         }
10243         /*
10244          * If we have a timestamp reply, update smoothed round trip time. If
10245          * no timestamp is present but transmit timer is running and timed
10246          * sequence number was acked, update smoothed round trip time. Since
10247          * we now have an rtt measurement, cancel the timer backoff (cf.,
10248          * Phil Karn's retransmit alg.). Recompute the initial retransmit
10249          * timer.
10250          *
10251          * Some boxes send broken timestamp replies during the SYN+ACK
10252          * phase, ignore timestamps of 0 or we could calculate a huge RTT
10253          * and blow up the retransmit timer.
10254          */
10255         /*
10256          * If all outstanding data is acked, stop retransmit timer and
10257          * remember to restart (more output or persist). If there is more
10258          * data to be acked, restart retransmit timer, using current
10259          * (possibly backed-off) value.
10260          */
10261         if (acked == 0) {
10262                 if (ofia)
10263                         *ofia = ourfinisacked;
10264                 return (0);
10265         }
10266         if (IN_RECOVERY(tp->t_flags)) {
10267                 if (SEQ_LT(th->th_ack, tp->snd_recover) &&
10268                     (SEQ_LT(th->th_ack, tp->snd_max))) {
10269                         tcp_rack_partialack(tp);
10270                 } else {
10271                         rack_post_recovery(tp, th->th_ack);
10272                         recovery = 1;
10273                 }
10274         }
10275         /*
10276          * Let the congestion control algorithm update congestion control
10277          * related information. This typically means increasing the
10278          * congestion window.
10279          */
10280         rack_ack_received(tp, rack, th->th_ack, nsegs, CC_ACK, recovery);
10281         SOCKBUF_LOCK(&so->so_snd);
10282         acked_amount = min(acked, (int)sbavail(&so->so_snd));
10283         tp->snd_wnd -= acked_amount;
10284         mfree = sbcut_locked(&so->so_snd, acked_amount);
10285         if ((sbused(&so->so_snd) == 0) &&
10286             (acked > acked_amount) &&
10287             (tp->t_state >= TCPS_FIN_WAIT_1) &&
10288             (tp->t_flags & TF_SENTFIN)) {
10289                 /*
10290                  * We must be sure our fin
10291                  * was sent and acked (we can be
10292                  * in FIN_WAIT_1 without having
10293                  * sent the fin).
10294                  */
10295                 ourfinisacked = 1;
10296         }
10297         tp->snd_una = th->th_ack;
10298         if (acked_amount && sbavail(&so->so_snd))
10299                 rack_adjust_sendmap(rack, &so->so_snd, tp->snd_una);
10300         rack_log_wakeup(tp,rack, &so->so_snd, acked, 2);
10301         /* NB: sowwakeup_locked() does an implicit unlock. */
10302         sowwakeup_locked(so);
10303         m_freem(mfree);
10304         if (SEQ_GT(tp->snd_una, tp->snd_recover))
10305                 tp->snd_recover = tp->snd_una;
10306
10307         if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
10308                 tp->snd_nxt = tp->snd_una;
10309         }
10310         if (under_pacing &&
10311             (rack->use_fixed_rate == 0) &&
10312             (rack->in_probe_rtt == 0) &&
10313             rack->rc_gp_dyn_mul &&
10314             rack->rc_always_pace) {
10315                 /* Check if we are dragging bottom */
10316                 rack_check_bottom_drag(tp, rack, so, acked);
10317         }
10318         if (tp->snd_una == tp->snd_max) {
10319                 /* Nothing left outstanding */
10320                 tp->t_flags &= ~TF_PREVVALID;
10321                 rack->r_ctl.rc_went_idle_time = tcp_get_usecs(NULL);
10322                 rack->r_ctl.retran_during_recovery = 0;
10323                 rack->r_ctl.dsack_byte_cnt = 0;
10324                 if (rack->r_ctl.rc_went_idle_time == 0)
10325                         rack->r_ctl.rc_went_idle_time = 1;
10326                 rack_log_progress_event(rack, tp, 0, PROGRESS_CLEAR, __LINE__);
10327                 if (sbavail(&tptosocket(tp)->so_snd) == 0)
10328                         tp->t_acktime = 0;
10329                 rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
10330                 /* Set need output so persist might get set */
10331                 rack->r_wanted_output = 1;
10332                 sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
10333                 if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
10334                     (sbavail(&so->so_snd) == 0) &&
10335                     (tp->t_flags2 & TF2_DROP_AF_DATA)) {
10336                         /*
10337                          * The socket was gone and the
10338                          * peer sent data (now or in the past), time to
10339                          * reset him.
10340                          */
10341                         *ret_val = 1;
10342                         /* tcp_close will kill the inp pre-log the Reset */
10343                         tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
10344                         tp = tcp_close(tp);
10345                         ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
10346                         return (1);
10347                 }
10348         }
10349         if (ofia)
10350                 *ofia = ourfinisacked;
10351         return (0);
10352 }
10353
10354
10355 static void
10356 rack_log_collapse(struct tcp_rack *rack, uint32_t cnt, uint32_t split, uint32_t out, int line,
10357                   int dir, uint32_t flags, struct rack_sendmap *rsm)
10358 {
10359         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
10360                 union tcp_log_stackspecific log;
10361                 struct timeval tv;
10362
10363                 memset(&log, 0, sizeof(log));
10364                 log.u_bbr.flex1 = cnt;
10365                 log.u_bbr.flex2 = split;
10366                 log.u_bbr.flex3 = out;
10367                 log.u_bbr.flex4 = line;
10368                 log.u_bbr.flex5 = rack->r_must_retran;
10369                 log.u_bbr.flex6 = flags;
10370                 log.u_bbr.flex7 = rack->rc_has_collapsed;
10371                 log.u_bbr.flex8 = dir;  /*
10372                                          * 1 is collapsed, 0 is uncollapsed,
10373                                          * 2 is log of a rsm being marked, 3 is a split.
10374                                          */
10375                 if (rsm == NULL)
10376                         log.u_bbr.rttProp = 0;
10377                 else
10378                         log.u_bbr.rttProp = (uint64_t)rsm;
10379                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
10380                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
10381                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
10382                     &rack->rc_inp->inp_socket->so_rcv,
10383                     &rack->rc_inp->inp_socket->so_snd,
10384                     TCP_RACK_LOG_COLLAPSE, 0,
10385                     0, &log, false, &tv);
10386         }
10387 }
10388
10389 static void
10390 rack_collapsed_window(struct tcp_rack *rack, uint32_t out, int line)
10391 {
10392         /*
10393          * Here all we do is mark the collapsed point and set the flag.
10394          * This may happen again and again, but there is no
10395          * sense splitting our map until we know where the
10396          * peer finally lands in the collapse.
10397          */
10398         rack_trace_point(rack, RACK_TP_COLLAPSED_WND);
10399         if ((rack->rc_has_collapsed == 0) ||
10400             (rack->r_ctl.last_collapse_point != (rack->rc_tp->snd_una + rack->rc_tp->snd_wnd)))
10401                 counter_u64_add(rack_collapsed_win_seen, 1);
10402         rack->r_ctl.last_collapse_point = rack->rc_tp->snd_una + rack->rc_tp->snd_wnd;
10403         rack->r_ctl.high_collapse_point = rack->rc_tp->snd_max;
10404         rack->rc_has_collapsed = 1;
10405         rack->r_collapse_point_valid = 1;
10406         rack_log_collapse(rack, 0, 0, rack->r_ctl.last_collapse_point, line, 1, 0, NULL);
10407 }
10408
10409 static void
10410 rack_un_collapse_window(struct tcp_rack *rack, int line)
10411 {
10412         struct rack_sendmap *nrsm, *rsm, fe;
10413         int cnt = 0, split = 0;
10414 #ifdef INVARIANTS
10415         struct rack_sendmap *insret;
10416 #endif
10417
10418         memset(&fe, 0, sizeof(fe));
10419         rack->rc_has_collapsed = 0;
10420         fe.r_start = rack->r_ctl.last_collapse_point;
10421         rsm = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
10422         if (rsm == NULL) {
10423                 /* Nothing to do maybe the peer ack'ed it all */
10424                 rack_log_collapse(rack, 0, 0, ctf_outstanding(rack->rc_tp), line, 0, 0, NULL);
10425                 return;
10426         }
10427         /* Now do we need to split this one? */
10428         if (SEQ_GT(rack->r_ctl.last_collapse_point, rsm->r_start)) {
10429                 rack_log_collapse(rack, rsm->r_start, rsm->r_end,
10430                                   rack->r_ctl.last_collapse_point, line, 3, rsm->r_flags, rsm);
10431                 nrsm = rack_alloc_limit(rack, RACK_LIMIT_TYPE_SPLIT);
10432                 if (nrsm == NULL) {
10433                         /* We can't get a rsm, mark all? */
10434                         nrsm = rsm;
10435                         goto no_split;
10436                 }
10437                 /* Clone it */
10438                 split = 1;
10439                 rack_clone_rsm(rack, nrsm, rsm, rack->r_ctl.last_collapse_point);
10440 #ifndef INVARIANTS
10441                 (void)RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
10442 #else
10443                 insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
10444                 if (insret != NULL) {
10445                         panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
10446                               nrsm, insret, rack, rsm);
10447                 }
10448 #endif
10449                 rack_log_map_chg(rack->rc_tp, rack, NULL, rsm, nrsm, MAP_SPLIT,
10450                                  rack->r_ctl.last_collapse_point, __LINE__);
10451                 if (rsm->r_in_tmap) {
10452                         TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
10453                         nrsm->r_in_tmap = 1;
10454                 }
10455                 /*
10456                  * Set in the new RSM as the
10457                  * collapsed starting point
10458                  */
10459                 rsm = nrsm;
10460         }
10461 no_split:
10462         RB_FOREACH_FROM(nrsm, rack_rb_tree_head, rsm) {
10463                 nrsm->r_flags |= RACK_RWND_COLLAPSED;
10464                 rack_log_collapse(rack, nrsm->r_start, nrsm->r_end, 0, line, 4, nrsm->r_flags, nrsm);
10465                 cnt++;
10466         }
10467         if (cnt) {
10468                 counter_u64_add(rack_collapsed_win, 1);
10469         }
10470         rack_log_collapse(rack, cnt, split, ctf_outstanding(rack->rc_tp), line, 0, 0, NULL);
10471 }
10472
10473 static void
10474 rack_handle_delayed_ack(struct tcpcb *tp, struct tcp_rack *rack,
10475                         int32_t tlen, int32_t tfo_syn)
10476 {
10477         if (DELAY_ACK(tp, tlen) || tfo_syn) {
10478                 if (rack->rc_dack_mode &&
10479                     (tlen > 500) &&
10480                     (rack->rc_dack_toggle == 1)) {
10481                         goto no_delayed_ack;
10482                 }
10483                 rack_timer_cancel(tp, rack,
10484                                   rack->r_ctl.rc_rcvtime, __LINE__);
10485                 tp->t_flags |= TF_DELACK;
10486         } else {
10487 no_delayed_ack:
10488                 rack->r_wanted_output = 1;
10489                 tp->t_flags |= TF_ACKNOW;
10490                 if (rack->rc_dack_mode) {
10491                         if (tp->t_flags & TF_DELACK)
10492                                 rack->rc_dack_toggle = 1;
10493                         else
10494                                 rack->rc_dack_toggle = 0;
10495                 }
10496         }
10497 }
10498
10499 static void
10500 rack_validate_fo_sendwin_up(struct tcpcb *tp, struct tcp_rack *rack)
10501 {
10502         /*
10503          * If fast output is in progress, lets validate that
10504          * the new window did not shrink on us and make it
10505          * so fast output should end.
10506          */
10507         if (rack->r_fast_output) {
10508                 uint32_t out;
10509
10510                 /*
10511                  * Calculate what we will send if left as is
10512                  * and compare that to our send window.
10513                  */
10514                 out = ctf_outstanding(tp);
10515                 if ((out + rack->r_ctl.fsb.left_to_send) > tp->snd_wnd) {
10516                         /* ok we have an issue */
10517                         if (out >= tp->snd_wnd) {
10518                                 /* Turn off fast output the window is met or collapsed */
10519                                 rack->r_fast_output = 0;
10520                         } else {
10521                                 /* we have some room left */
10522                                 rack->r_ctl.fsb.left_to_send = tp->snd_wnd - out;
10523                                 if (rack->r_ctl.fsb.left_to_send < ctf_fixed_maxseg(tp)) {
10524                                         /* If not at least 1 full segment never mind */
10525                                         rack->r_fast_output = 0;
10526                                 }
10527                         }
10528                 }
10529         }
10530 }
10531
10532
10533 /*
10534  * Return value of 1, the TCB is unlocked and most
10535  * likely gone, return value of 0, the TCP is still
10536  * locked.
10537  */
10538 static int
10539 rack_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
10540     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
10541     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
10542 {
10543         /*
10544          * Update window information. Don't look at window if no ACK: TAC's
10545          * send garbage on first SYN.
10546          */
10547         int32_t nsegs;
10548         int32_t tfo_syn;
10549         struct tcp_rack *rack;
10550
10551         INP_WLOCK_ASSERT(tptoinpcb(tp));
10552
10553         rack = (struct tcp_rack *)tp->t_fb_ptr;
10554         nsegs = max(1, m->m_pkthdr.lro_nsegs);
10555         if ((thflags & TH_ACK) &&
10556             (SEQ_LT(tp->snd_wl1, th->th_seq) ||
10557             (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
10558             (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
10559                 /* keep track of pure window updates */
10560                 if (tlen == 0 &&
10561                     tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
10562                         KMOD_TCPSTAT_INC(tcps_rcvwinupd);
10563                 tp->snd_wnd = tiwin;
10564                 rack_validate_fo_sendwin_up(tp, rack);
10565                 tp->snd_wl1 = th->th_seq;
10566                 tp->snd_wl2 = th->th_ack;
10567                 if (tp->snd_wnd > tp->max_sndwnd)
10568                         tp->max_sndwnd = tp->snd_wnd;
10569                 rack->r_wanted_output = 1;
10570         } else if (thflags & TH_ACK) {
10571                 if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
10572                         tp->snd_wnd = tiwin;
10573                         rack_validate_fo_sendwin_up(tp, rack);
10574                         tp->snd_wl1 = th->th_seq;
10575                         tp->snd_wl2 = th->th_ack;
10576                 }
10577         }
10578         if (tp->snd_wnd < ctf_outstanding(tp))
10579                 /* The peer collapsed the window */
10580                 rack_collapsed_window(rack, ctf_outstanding(tp), __LINE__);
10581         else if (rack->rc_has_collapsed)
10582                 rack_un_collapse_window(rack, __LINE__);
10583         if ((rack->r_collapse_point_valid) &&
10584             (SEQ_GT(th->th_ack, rack->r_ctl.high_collapse_point)))
10585                 rack->r_collapse_point_valid = 0;
10586         /* Was persist timer active and now we have window space? */
10587         if ((rack->rc_in_persist != 0) &&
10588             (tp->snd_wnd >= min((rack->r_ctl.rc_high_rwnd/2),
10589                                 rack->r_ctl.rc_pace_min_segs))) {
10590                 rack_exit_persist(tp, rack, rack->r_ctl.rc_rcvtime);
10591                 tp->snd_nxt = tp->snd_max;
10592                 /* Make sure we output to start the timer */
10593                 rack->r_wanted_output = 1;
10594         }
10595         /* Do we enter persists? */
10596         if ((rack->rc_in_persist == 0) &&
10597             (tp->snd_wnd < min((rack->r_ctl.rc_high_rwnd/2), rack->r_ctl.rc_pace_min_segs)) &&
10598             TCPS_HAVEESTABLISHED(tp->t_state) &&
10599             ((tp->snd_max == tp->snd_una) || rack->rc_has_collapsed) &&
10600             sbavail(&tptosocket(tp)->so_snd) &&
10601             (sbavail(&tptosocket(tp)->so_snd) > tp->snd_wnd)) {
10602                 /*
10603                  * Here the rwnd is less than
10604                  * the pacing size, we are established,
10605                  * nothing is outstanding, and there is
10606                  * data to send. Enter persists.
10607                  */
10608                 rack_enter_persist(tp, rack, rack->r_ctl.rc_rcvtime);
10609         }
10610         if (tp->t_flags2 & TF2_DROP_AF_DATA) {
10611                 m_freem(m);
10612                 return (0);
10613         }
10614         /*
10615          * don't process the URG bit, ignore them drag
10616          * along the up.
10617          */
10618         tp->rcv_up = tp->rcv_nxt;
10619
10620         /*
10621          * Process the segment text, merging it into the TCP sequencing
10622          * queue, and arranging for acknowledgment of receipt if necessary.
10623          * This process logically involves adjusting tp->rcv_wnd as data is
10624          * presented to the user (this happens in tcp_usrreq.c, case
10625          * PRU_RCVD).  If a FIN has already been received on this connection
10626          * then we just ignore the text.
10627          */
10628         tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
10629                    IS_FASTOPEN(tp->t_flags));
10630         if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
10631             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
10632                 tcp_seq save_start = th->th_seq;
10633                 tcp_seq save_rnxt  = tp->rcv_nxt;
10634                 int     save_tlen  = tlen;
10635
10636                 m_adj(m, drop_hdrlen);  /* delayed header drop */
10637                 /*
10638                  * Insert segment which includes th into TCP reassembly
10639                  * queue with control block tp.  Set thflags to whether
10640                  * reassembly now includes a segment with FIN.  This handles
10641                  * the common case inline (segment is the next to be
10642                  * received on an established connection, and the queue is
10643                  * empty), avoiding linkage into and removal from the queue
10644                  * and repetition of various conversions. Set DELACK for
10645                  * segments received in order, but ack immediately when
10646                  * segments are out of order (so fast retransmit can work).
10647                  */
10648                 if (th->th_seq == tp->rcv_nxt &&
10649                     SEGQ_EMPTY(tp) &&
10650                     (TCPS_HAVEESTABLISHED(tp->t_state) ||
10651                     tfo_syn)) {
10652 #ifdef NETFLIX_SB_LIMITS
10653                         u_int mcnt, appended;
10654
10655                         if (so->so_rcv.sb_shlim) {
10656                                 mcnt = m_memcnt(m);
10657                                 appended = 0;
10658                                 if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
10659                                     CFO_NOSLEEP, NULL) == false) {
10660                                         counter_u64_add(tcp_sb_shlim_fails, 1);
10661                                         m_freem(m);
10662                                         return (0);
10663                                 }
10664                         }
10665 #endif
10666                         rack_handle_delayed_ack(tp, rack, tlen, tfo_syn);
10667                         tp->rcv_nxt += tlen;
10668                         if (tlen &&
10669                             ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
10670                             (tp->t_fbyte_in == 0)) {
10671                                 tp->t_fbyte_in = ticks;
10672                                 if (tp->t_fbyte_in == 0)
10673                                         tp->t_fbyte_in = 1;
10674                                 if (tp->t_fbyte_out && tp->t_fbyte_in)
10675                                         tp->t_flags2 |= TF2_FBYTES_COMPLETE;
10676                         }
10677                         thflags = tcp_get_flags(th) & TH_FIN;
10678                         KMOD_TCPSTAT_ADD(tcps_rcvpack, nsegs);
10679                         KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
10680                         SOCKBUF_LOCK(&so->so_rcv);
10681                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
10682                                 m_freem(m);
10683                         } else
10684 #ifdef NETFLIX_SB_LIMITS
10685                                 appended =
10686 #endif
10687                                         sbappendstream_locked(&so->so_rcv, m, 0);
10688
10689                         rack_log_wakeup(tp,rack, &so->so_rcv, tlen, 1);
10690                         /* NB: sorwakeup_locked() does an implicit unlock. */
10691                         sorwakeup_locked(so);
10692 #ifdef NETFLIX_SB_LIMITS
10693                         if (so->so_rcv.sb_shlim && appended != mcnt)
10694                                 counter_fo_release(so->so_rcv.sb_shlim,
10695                                     mcnt - appended);
10696 #endif
10697                 } else {
10698                         /*
10699                          * XXX: Due to the header drop above "th" is
10700                          * theoretically invalid by now.  Fortunately
10701                          * m_adj() doesn't actually frees any mbufs when
10702                          * trimming from the head.
10703                          */
10704                         tcp_seq temp = save_start;
10705
10706                         thflags = tcp_reass(tp, th, &temp, &tlen, m);
10707                         tp->t_flags |= TF_ACKNOW;
10708                         if (tp->t_flags & TF_WAKESOR) {
10709                                 tp->t_flags &= ~TF_WAKESOR;
10710                                 /* NB: sorwakeup_locked() does an implicit unlock. */
10711                                 sorwakeup_locked(so);
10712                         }
10713                 }
10714                 if ((tp->t_flags & TF_SACK_PERMIT) &&
10715                     (save_tlen > 0) &&
10716                     TCPS_HAVEESTABLISHED(tp->t_state)) {
10717                         if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
10718                                 /*
10719                                  * DSACK actually handled in the fastpath
10720                                  * above.
10721                                  */
10722                                 RACK_OPTS_INC(tcp_sack_path_1);
10723                                 tcp_update_sack_list(tp, save_start,
10724                                     save_start + save_tlen);
10725                         } else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
10726                                 if ((tp->rcv_numsacks >= 1) &&
10727                                     (tp->sackblks[0].end == save_start)) {
10728                                         /*
10729                                          * Partial overlap, recorded at todrop
10730                                          * above.
10731                                          */
10732                                         RACK_OPTS_INC(tcp_sack_path_2a);
10733                                         tcp_update_sack_list(tp,
10734                                             tp->sackblks[0].start,
10735                                             tp->sackblks[0].end);
10736                                 } else {
10737                                         RACK_OPTS_INC(tcp_sack_path_2b);
10738                                         tcp_update_dsack_list(tp, save_start,
10739                                             save_start + save_tlen);
10740                                 }
10741                         } else if (tlen >= save_tlen) {
10742                                 /* Update of sackblks. */
10743                                 RACK_OPTS_INC(tcp_sack_path_3);
10744                                 tcp_update_dsack_list(tp, save_start,
10745                                     save_start + save_tlen);
10746                         } else if (tlen > 0) {
10747                                 RACK_OPTS_INC(tcp_sack_path_4);
10748                                 tcp_update_dsack_list(tp, save_start,
10749                                     save_start + tlen);
10750                         }
10751                 }
10752         } else {
10753                 m_freem(m);
10754                 thflags &= ~TH_FIN;
10755         }
10756
10757         /*
10758          * If FIN is received ACK the FIN and let the user know that the
10759          * connection is closing.
10760          */
10761         if (thflags & TH_FIN) {
10762                 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
10763                         /* The socket upcall is handled by socantrcvmore. */
10764                         socantrcvmore(so);
10765                         /*
10766                          * If connection is half-synchronized (ie NEEDSYN
10767                          * flag on) then delay ACK, so it may be piggybacked
10768                          * when SYN is sent. Otherwise, since we received a
10769                          * FIN then no more input can be expected, send ACK
10770                          * now.
10771                          */
10772                         if (tp->t_flags & TF_NEEDSYN) {
10773                                 rack_timer_cancel(tp, rack,
10774                                     rack->r_ctl.rc_rcvtime, __LINE__);
10775                                 tp->t_flags |= TF_DELACK;
10776                         } else {
10777                                 tp->t_flags |= TF_ACKNOW;
10778                         }
10779                         tp->rcv_nxt++;
10780                 }
10781                 switch (tp->t_state) {
10782                         /*
10783                          * In SYN_RECEIVED and ESTABLISHED STATES enter the
10784                          * CLOSE_WAIT state.
10785                          */
10786                 case TCPS_SYN_RECEIVED:
10787                         tp->t_starttime = ticks;
10788                         /* FALLTHROUGH */
10789                 case TCPS_ESTABLISHED:
10790                         rack_timer_cancel(tp, rack,
10791                             rack->r_ctl.rc_rcvtime, __LINE__);
10792                         tcp_state_change(tp, TCPS_CLOSE_WAIT);
10793                         break;
10794
10795                         /*
10796                          * If still in FIN_WAIT_1 STATE FIN has not been
10797                          * acked so enter the CLOSING state.
10798                          */
10799                 case TCPS_FIN_WAIT_1:
10800                         rack_timer_cancel(tp, rack,
10801                             rack->r_ctl.rc_rcvtime, __LINE__);
10802                         tcp_state_change(tp, TCPS_CLOSING);
10803                         break;
10804
10805                         /*
10806                          * In FIN_WAIT_2 state enter the TIME_WAIT state,
10807                          * starting the time-wait timer, turning off the
10808                          * other standard timers.
10809                          */
10810                 case TCPS_FIN_WAIT_2:
10811                         rack_timer_cancel(tp, rack,
10812                             rack->r_ctl.rc_rcvtime, __LINE__);
10813                         tcp_twstart(tp);
10814                         return (1);
10815                 }
10816         }
10817         /*
10818          * Return any desired output.
10819          */
10820         if ((tp->t_flags & TF_ACKNOW) ||
10821             (sbavail(&so->so_snd) > (tp->snd_max - tp->snd_una))) {
10822                 rack->r_wanted_output = 1;
10823         }
10824         return (0);
10825 }
10826
10827 /*
10828  * Here nothing is really faster, its just that we
10829  * have broken out the fast-data path also just like
10830  * the fast-ack.
10831  */
10832 static int
10833 rack_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
10834     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
10835     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
10836 {
10837         int32_t nsegs;
10838         int32_t newsize = 0;    /* automatic sockbuf scaling */
10839         struct tcp_rack *rack;
10840 #ifdef NETFLIX_SB_LIMITS
10841         u_int mcnt, appended;
10842 #endif
10843 #ifdef TCPDEBUG
10844         /*
10845          * The size of tcp_saveipgen must be the size of the max ip header,
10846          * now IPv6.
10847          */
10848         u_char tcp_saveipgen[IP6_HDR_LEN];
10849         struct tcphdr tcp_savetcp;
10850         short ostate = 0;
10851
10852 #endif
10853         /*
10854          * If last ACK falls within this segment's sequence numbers, record
10855          * the timestamp. NOTE that the test is modified according to the
10856          * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
10857          */
10858         if (__predict_false(th->th_seq != tp->rcv_nxt)) {
10859                 return (0);
10860         }
10861         if (__predict_false(tp->snd_nxt != tp->snd_max)) {
10862                 return (0);
10863         }
10864         if (tiwin && tiwin != tp->snd_wnd) {
10865                 return (0);
10866         }
10867         if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
10868                 return (0);
10869         }
10870         if (__predict_false((to->to_flags & TOF_TS) &&
10871             (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
10872                 return (0);
10873         }
10874         if (__predict_false((th->th_ack != tp->snd_una))) {
10875                 return (0);
10876         }
10877         if (__predict_false(tlen > sbspace(&so->so_rcv))) {
10878                 return (0);
10879         }
10880         if ((to->to_flags & TOF_TS) != 0 &&
10881             SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
10882                 tp->ts_recent_age = tcp_ts_getticks();
10883                 tp->ts_recent = to->to_tsval;
10884         }
10885         rack = (struct tcp_rack *)tp->t_fb_ptr;
10886         /*
10887          * This is a pure, in-sequence data packet with nothing on the
10888          * reassembly queue and we have enough buffer space to take it.
10889          */
10890         nsegs = max(1, m->m_pkthdr.lro_nsegs);
10891
10892 #ifdef NETFLIX_SB_LIMITS
10893         if (so->so_rcv.sb_shlim) {
10894                 mcnt = m_memcnt(m);
10895                 appended = 0;
10896                 if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
10897                     CFO_NOSLEEP, NULL) == false) {
10898                         counter_u64_add(tcp_sb_shlim_fails, 1);
10899                         m_freem(m);
10900                         return (1);
10901                 }
10902         }
10903 #endif
10904         /* Clean receiver SACK report if present */
10905         if (tp->rcv_numsacks)
10906                 tcp_clean_sackreport(tp);
10907         KMOD_TCPSTAT_INC(tcps_preddat);
10908         tp->rcv_nxt += tlen;
10909         if (tlen &&
10910             ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
10911             (tp->t_fbyte_in == 0)) {
10912                 tp->t_fbyte_in = ticks;
10913                 if (tp->t_fbyte_in == 0)
10914                         tp->t_fbyte_in = 1;
10915                 if (tp->t_fbyte_out && tp->t_fbyte_in)
10916                         tp->t_flags2 |= TF2_FBYTES_COMPLETE;
10917         }
10918         /*
10919          * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
10920          */
10921         tp->snd_wl1 = th->th_seq;
10922         /*
10923          * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
10924          */
10925         tp->rcv_up = tp->rcv_nxt;
10926         KMOD_TCPSTAT_ADD(tcps_rcvpack, nsegs);
10927         KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
10928 #ifdef TCPDEBUG
10929         if (so->so_options & SO_DEBUG)
10930                 tcp_trace(TA_INPUT, ostate, tp,
10931                     (void *)tcp_saveipgen, &tcp_savetcp, 0);
10932 #endif
10933         newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
10934
10935         /* Add data to socket buffer. */
10936         SOCKBUF_LOCK(&so->so_rcv);
10937         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
10938                 m_freem(m);
10939         } else {
10940                 /*
10941                  * Set new socket buffer size. Give up when limit is
10942                  * reached.
10943                  */
10944                 if (newsize)
10945                         if (!sbreserve_locked(so, SO_RCV, newsize, NULL))
10946                                 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
10947                 m_adj(m, drop_hdrlen);  /* delayed header drop */
10948 #ifdef NETFLIX_SB_LIMITS
10949                 appended =
10950 #endif
10951                         sbappendstream_locked(&so->so_rcv, m, 0);
10952                 ctf_calc_rwin(so, tp);
10953         }
10954         rack_log_wakeup(tp,rack, &so->so_rcv, tlen, 1);
10955         /* NB: sorwakeup_locked() does an implicit unlock. */
10956         sorwakeup_locked(so);
10957 #ifdef NETFLIX_SB_LIMITS
10958         if (so->so_rcv.sb_shlim && mcnt != appended)
10959                 counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
10960 #endif
10961         rack_handle_delayed_ack(tp, rack, tlen, 0);
10962         if (tp->snd_una == tp->snd_max)
10963                 sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
10964         return (1);
10965 }
10966
10967 /*
10968  * This subfunction is used to try to highly optimize the
10969  * fast path. We again allow window updates that are
10970  * in sequence to remain in the fast-path. We also add
10971  * in the __predict's to attempt to help the compiler.
10972  * Note that if we return a 0, then we can *not* process
10973  * it and the caller should push the packet into the
10974  * slow-path.
10975  */
10976 static int
10977 rack_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
10978     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
10979     uint32_t tiwin, int32_t nxt_pkt, uint32_t cts)
10980 {
10981         int32_t acked;
10982         int32_t nsegs;
10983 #ifdef TCPDEBUG
10984         /*
10985          * The size of tcp_saveipgen must be the size of the max ip header,
10986          * now IPv6.
10987          */
10988         u_char tcp_saveipgen[IP6_HDR_LEN];
10989         struct tcphdr tcp_savetcp;
10990         short ostate = 0;
10991 #endif
10992         int32_t under_pacing = 0;
10993         struct tcp_rack *rack;
10994
10995         if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
10996                 /* Old ack, behind (or duplicate to) the last one rcv'd */
10997                 return (0);
10998         }
10999         if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
11000                 /* Above what we have sent? */
11001                 return (0);
11002         }
11003         if (__predict_false(tp->snd_nxt != tp->snd_max)) {
11004                 /* We are retransmitting */
11005                 return (0);
11006         }
11007         if (__predict_false(tiwin == 0)) {
11008                 /* zero window */
11009                 return (0);
11010         }
11011         if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
11012                 /* We need a SYN or a FIN, unlikely.. */
11013                 return (0);
11014         }
11015         if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
11016                 /* Timestamp is behind .. old ack with seq wrap? */
11017                 return (0);
11018         }
11019         if (__predict_false(IN_RECOVERY(tp->t_flags))) {
11020                 /* Still recovering */
11021                 return (0);
11022         }
11023         rack = (struct tcp_rack *)tp->t_fb_ptr;
11024         if (rack->r_ctl.rc_sacked) {
11025                 /* We have sack holes on our scoreboard */
11026                 return (0);
11027         }
11028         /* Ok if we reach here, we can process a fast-ack */
11029         if (rack->gp_ready &&
11030             (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11031                 under_pacing = 1;
11032         }
11033         nsegs = max(1, m->m_pkthdr.lro_nsegs);
11034         rack_log_ack(tp, to, th, 0, 0);
11035         /* Did the window get updated? */
11036         if (tiwin != tp->snd_wnd) {
11037                 tp->snd_wnd = tiwin;
11038                 rack_validate_fo_sendwin_up(tp, rack);
11039                 tp->snd_wl1 = th->th_seq;
11040                 if (tp->snd_wnd > tp->max_sndwnd)
11041                         tp->max_sndwnd = tp->snd_wnd;
11042         }
11043         /* Do we exit persists? */
11044         if ((rack->rc_in_persist != 0) &&
11045             (tp->snd_wnd >= min((rack->r_ctl.rc_high_rwnd/2),
11046                                rack->r_ctl.rc_pace_min_segs))) {
11047                 rack_exit_persist(tp, rack, cts);
11048         }
11049         /* Do we enter persists? */
11050         if ((rack->rc_in_persist == 0) &&
11051             (tp->snd_wnd < min((rack->r_ctl.rc_high_rwnd/2), rack->r_ctl.rc_pace_min_segs)) &&
11052             TCPS_HAVEESTABLISHED(tp->t_state) &&
11053             ((tp->snd_max == tp->snd_una) || rack->rc_has_collapsed) &&
11054             sbavail(&tptosocket(tp)->so_snd) &&
11055             (sbavail(&tptosocket(tp)->so_snd) > tp->snd_wnd)) {
11056                 /*
11057                  * Here the rwnd is less than
11058                  * the pacing size, we are established,
11059                  * nothing is outstanding, and there is
11060                  * data to send. Enter persists.
11061                  */
11062                 rack_enter_persist(tp, rack, rack->r_ctl.rc_rcvtime);
11063         }
11064         /*
11065          * If last ACK falls within this segment's sequence numbers, record
11066          * the timestamp. NOTE that the test is modified according to the
11067          * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
11068          */
11069         if ((to->to_flags & TOF_TS) != 0 &&
11070             SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
11071                 tp->ts_recent_age = tcp_ts_getticks();
11072                 tp->ts_recent = to->to_tsval;
11073         }
11074         /*
11075          * This is a pure ack for outstanding data.
11076          */
11077         KMOD_TCPSTAT_INC(tcps_predack);
11078
11079         /*
11080          * "bad retransmit" recovery.
11081          */
11082         if ((tp->t_flags & TF_PREVVALID) &&
11083             ((tp->t_flags & TF_RCVD_TSTMP) == 0)) {
11084                 tp->t_flags &= ~TF_PREVVALID;
11085                 if (tp->t_rxtshift == 1 &&
11086                     (int)(ticks - tp->t_badrxtwin) < 0)
11087                         rack_cong_signal(tp, CC_RTO_ERR, th->th_ack, __LINE__);
11088         }
11089         /*
11090          * Recalculate the transmit timer / rtt.
11091          *
11092          * Some boxes send broken timestamp replies during the SYN+ACK
11093          * phase, ignore timestamps of 0 or we could calculate a huge RTT
11094          * and blow up the retransmit timer.
11095          */
11096         acked = BYTES_THIS_ACK(tp, th);
11097
11098 #ifdef TCP_HHOOK
11099         /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
11100         hhook_run_tcp_est_in(tp, th, to);
11101 #endif
11102         KMOD_TCPSTAT_ADD(tcps_rcvackpack, nsegs);
11103         KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
11104         if (acked) {
11105                 struct mbuf *mfree;
11106
11107                 rack_ack_received(tp, rack, th->th_ack, nsegs, CC_ACK, 0);
11108                 SOCKBUF_LOCK(&so->so_snd);
11109                 mfree = sbcut_locked(&so->so_snd, acked);
11110                 tp->snd_una = th->th_ack;
11111                 /* Note we want to hold the sb lock through the sendmap adjust */
11112                 rack_adjust_sendmap(rack, &so->so_snd, tp->snd_una);
11113                 /* Wake up the socket if we have room to write more */
11114                 rack_log_wakeup(tp,rack, &so->so_snd, acked, 2);
11115                 sowwakeup_locked(so);
11116                 m_freem(mfree);
11117                 tp->t_rxtshift = 0;
11118                 RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
11119                               rack_rto_min, rack_rto_max, rack->r_ctl.timer_slop);
11120                 rack->rc_tlp_in_progress = 0;
11121                 rack->r_ctl.rc_tlp_cnt_out = 0;
11122                 /*
11123                  * If it is the RXT timer we want to
11124                  * stop it, so we can restart a TLP.
11125                  */
11126                 if (rack->r_ctl.rc_hpts_flags & PACE_TMR_RXT)
11127                         rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
11128 #ifdef NETFLIX_HTTP_LOGGING
11129                 tcp_http_check_for_comp(rack->rc_tp, th->th_ack);
11130 #endif
11131         }
11132         /*
11133          * Let the congestion control algorithm update congestion control
11134          * related information. This typically means increasing the
11135          * congestion window.
11136          */
11137         if (tp->snd_wnd < ctf_outstanding(tp)) {
11138                 /* The peer collapsed the window */
11139                 rack_collapsed_window(rack, ctf_outstanding(tp), __LINE__);
11140         } else if (rack->rc_has_collapsed)
11141                 rack_un_collapse_window(rack, __LINE__);
11142         if ((rack->r_collapse_point_valid) &&
11143             (SEQ_GT(tp->snd_una, rack->r_ctl.high_collapse_point)))
11144                 rack->r_collapse_point_valid = 0;
11145         /*
11146          * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
11147          */
11148         tp->snd_wl2 = th->th_ack;
11149         tp->t_dupacks = 0;
11150         m_freem(m);
11151         /* ND6_HINT(tp);         *//* Some progress has been made. */
11152
11153         /*
11154          * If all outstanding data are acked, stop retransmit timer,
11155          * otherwise restart timer using current (possibly backed-off)
11156          * value. If process is waiting for space, wakeup/selwakeup/signal.
11157          * If data are ready to send, let tcp_output decide between more
11158          * output or persist.
11159          */
11160 #ifdef TCPDEBUG
11161         if (so->so_options & SO_DEBUG)
11162                 tcp_trace(TA_INPUT, ostate, tp,
11163                     (void *)tcp_saveipgen,
11164                     &tcp_savetcp, 0);
11165 #endif
11166         if (under_pacing &&
11167             (rack->use_fixed_rate == 0) &&
11168             (rack->in_probe_rtt == 0) &&
11169             rack->rc_gp_dyn_mul &&
11170             rack->rc_always_pace) {
11171                 /* Check if we are dragging bottom */
11172                 rack_check_bottom_drag(tp, rack, so, acked);
11173         }
11174         if (tp->snd_una == tp->snd_max) {
11175                 tp->t_flags &= ~TF_PREVVALID;
11176                 rack->r_ctl.retran_during_recovery = 0;
11177                 rack->r_ctl.dsack_byte_cnt = 0;
11178                 rack->r_ctl.rc_went_idle_time = tcp_get_usecs(NULL);
11179                 if (rack->r_ctl.rc_went_idle_time == 0)
11180                         rack->r_ctl.rc_went_idle_time = 1;
11181                 rack_log_progress_event(rack, tp, 0, PROGRESS_CLEAR, __LINE__);
11182                 if (sbavail(&tptosocket(tp)->so_snd) == 0)
11183                         tp->t_acktime = 0;
11184                 rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
11185         }
11186         if (acked && rack->r_fast_output)
11187                 rack_gain_for_fastoutput(rack, tp, so, (uint32_t)acked);
11188         if (sbavail(&so->so_snd)) {
11189                 rack->r_wanted_output = 1;
11190         }
11191         return (1);
11192 }
11193
11194 /*
11195  * Return value of 1, the TCB is unlocked and most
11196  * likely gone, return value of 0, the TCP is still
11197  * locked.
11198  */
11199 static int
11200 rack_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
11201     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
11202     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
11203 {
11204         int32_t ret_val = 0;
11205         int32_t todrop;
11206         int32_t ourfinisacked = 0;
11207         struct tcp_rack *rack;
11208
11209         INP_WLOCK_ASSERT(tptoinpcb(tp));
11210
11211         ctf_calc_rwin(so, tp);
11212         /*
11213          * If the state is SYN_SENT: if seg contains an ACK, but not for our
11214          * SYN, drop the input. if seg contains a RST, then drop the
11215          * connection. if seg does not contain SYN, then drop it. Otherwise
11216          * this is an acceptable SYN segment initialize tp->rcv_nxt and
11217          * tp->irs if seg contains ack then advance tp->snd_una if seg
11218          * contains an ECE and ECN support is enabled, the stream is ECN
11219          * capable. if SYN has been acked change to ESTABLISHED else
11220          * SYN_RCVD state arrange for segment to be acked (eventually)
11221          * continue processing rest of data/controls.
11222          */
11223         if ((thflags & TH_ACK) &&
11224             (SEQ_LEQ(th->th_ack, tp->iss) ||
11225             SEQ_GT(th->th_ack, tp->snd_max))) {
11226                 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11227                 ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11228                 return (1);
11229         }
11230         if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
11231                 TCP_PROBE5(connect__refused, NULL, tp,
11232                     mtod(m, const char *), tp, th);
11233                 tp = tcp_drop(tp, ECONNREFUSED);
11234                 ctf_do_drop(m, tp);
11235                 return (1);
11236         }
11237         if (thflags & TH_RST) {
11238                 ctf_do_drop(m, tp);
11239                 return (1);
11240         }
11241         if (!(thflags & TH_SYN)) {
11242                 ctf_do_drop(m, tp);
11243                 return (1);
11244         }
11245         tp->irs = th->th_seq;
11246         tcp_rcvseqinit(tp);
11247         rack = (struct tcp_rack *)tp->t_fb_ptr;
11248         if (thflags & TH_ACK) {
11249                 int tfo_partial = 0;
11250
11251                 KMOD_TCPSTAT_INC(tcps_connects);
11252                 soisconnected(so);
11253 #ifdef MAC
11254                 mac_socketpeer_set_from_mbuf(m, so);
11255 #endif
11256                 /* Do window scaling on this connection? */
11257                 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
11258                     (TF_RCVD_SCALE | TF_REQ_SCALE)) {
11259                         tp->rcv_scale = tp->request_r_scale;
11260                 }
11261                 tp->rcv_adv += min(tp->rcv_wnd,
11262                     TCP_MAXWIN << tp->rcv_scale);
11263                 /*
11264                  * If not all the data that was sent in the TFO SYN
11265                  * has been acked, resend the remainder right away.
11266                  */
11267                 if (IS_FASTOPEN(tp->t_flags) &&
11268                     (tp->snd_una != tp->snd_max)) {
11269                         tp->snd_nxt = th->th_ack;
11270                         tfo_partial = 1;
11271                 }
11272                 /*
11273                  * If there's data, delay ACK; if there's also a FIN ACKNOW
11274                  * will be turned on later.
11275                  */
11276                 if (DELAY_ACK(tp, tlen) && tlen != 0 && !tfo_partial) {
11277                         rack_timer_cancel(tp, rack,
11278                                           rack->r_ctl.rc_rcvtime, __LINE__);
11279                         tp->t_flags |= TF_DELACK;
11280                 } else {
11281                         rack->r_wanted_output = 1;
11282                         tp->t_flags |= TF_ACKNOW;
11283                         rack->rc_dack_toggle = 0;
11284                 }
11285
11286                 tcp_ecn_input_syn_sent(tp, thflags, iptos);
11287
11288                 if (SEQ_GT(th->th_ack, tp->snd_una)) {
11289                         /*
11290                          * We advance snd_una for the
11291                          * fast open case. If th_ack is
11292                          * acknowledging data beyond
11293                          * snd_una we can't just call
11294                          * ack-processing since the
11295                          * data stream in our send-map
11296                          * will start at snd_una + 1 (one
11297                          * beyond the SYN). If its just
11298                          * equal we don't need to do that
11299                          * and there is no send_map.
11300                          */
11301                         tp->snd_una++;
11302                 }
11303                 /*
11304                  * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
11305                  * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
11306                  */
11307                 tp->t_starttime = ticks;
11308                 if (tp->t_flags & TF_NEEDFIN) {
11309                         tcp_state_change(tp, TCPS_FIN_WAIT_1);
11310                         tp->t_flags &= ~TF_NEEDFIN;
11311                         thflags &= ~TH_SYN;
11312                 } else {
11313                         tcp_state_change(tp, TCPS_ESTABLISHED);
11314                         TCP_PROBE5(connect__established, NULL, tp,
11315                             mtod(m, const char *), tp, th);
11316                         rack_cc_conn_init(tp);
11317                 }
11318         } else {
11319                 /*
11320                  * Received initial SYN in SYN-SENT[*] state => simultaneous
11321                  * open.  If segment contains CC option and there is a
11322                  * cached CC, apply TAO test. If it succeeds, connection is *
11323                  * half-synchronized. Otherwise, do 3-way handshake:
11324                  * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
11325                  * there was no CC option, clear cached CC value.
11326                  */
11327                 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN | TF_SONOTCONN);
11328                 tcp_state_change(tp, TCPS_SYN_RECEIVED);
11329         }
11330         /*
11331          * Advance th->th_seq to correspond to first data byte. If data,
11332          * trim to stay within window, dropping FIN if necessary.
11333          */
11334         th->th_seq++;
11335         if (tlen > tp->rcv_wnd) {
11336                 todrop = tlen - tp->rcv_wnd;
11337                 m_adj(m, -todrop);
11338                 tlen = tp->rcv_wnd;
11339                 thflags &= ~TH_FIN;
11340                 KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
11341                 KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
11342         }
11343         tp->snd_wl1 = th->th_seq - 1;
11344         tp->rcv_up = th->th_seq;
11345         /*
11346          * Client side of transaction: already sent SYN and data. If the
11347          * remote host used T/TCP to validate the SYN, our data will be
11348          * ACK'd; if so, enter normal data segment processing in the middle
11349          * of step 5, ack processing. Otherwise, goto step 6.
11350          */
11351         if (thflags & TH_ACK) {
11352                 /* For syn-sent we need to possibly update the rtt */
11353                 if ((to->to_flags & TOF_TS) != 0 && to->to_tsecr) {
11354                         uint32_t t, mcts;
11355
11356                         mcts = tcp_ts_getticks();
11357                         t = (mcts - to->to_tsecr) * HPTS_USEC_IN_MSEC;
11358                         if (!tp->t_rttlow || tp->t_rttlow > t)
11359                                 tp->t_rttlow = t;
11360                         rack_log_rtt_sample_calc(rack, t, (to->to_tsecr * 1000), (mcts * 1000), 4);
11361                         tcp_rack_xmit_timer(rack, t + 1, 1, t, 0, NULL, 2);
11362                         tcp_rack_xmit_timer_commit(rack, tp);
11363                 }
11364                 if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
11365                         return (ret_val);
11366                 /* We may have changed to FIN_WAIT_1 above */
11367                 if (tp->t_state == TCPS_FIN_WAIT_1) {
11368                         /*
11369                          * In FIN_WAIT_1 STATE in addition to the processing
11370                          * for the ESTABLISHED state if our FIN is now
11371                          * acknowledged then enter FIN_WAIT_2.
11372                          */
11373                         if (ourfinisacked) {
11374                                 /*
11375                                  * If we can't receive any more data, then
11376                                  * closing user can proceed. Starting the
11377                                  * timer is contrary to the specification,
11378                                  * but if we don't get a FIN we'll hang
11379                                  * forever.
11380                                  *
11381                                  * XXXjl: we should release the tp also, and
11382                                  * use a compressed state.
11383                                  */
11384                                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
11385                                         soisdisconnected(so);
11386                                         tcp_timer_activate(tp, TT_2MSL,
11387                                             (tcp_fast_finwait2_recycle ?
11388                                             tcp_finwait2_timeout :
11389                                             TP_MAXIDLE(tp)));
11390                                 }
11391                                 tcp_state_change(tp, TCPS_FIN_WAIT_2);
11392                         }
11393                 }
11394         }
11395         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11396            tiwin, thflags, nxt_pkt));
11397 }
11398
11399 /*
11400  * Return value of 1, the TCB is unlocked and most
11401  * likely gone, return value of 0, the TCP is still
11402  * locked.
11403  */
11404 static int
11405 rack_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
11406     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
11407     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
11408 {
11409         struct tcp_rack *rack;
11410         int32_t ret_val = 0;
11411         int32_t ourfinisacked = 0;
11412
11413         ctf_calc_rwin(so, tp);
11414         if ((thflags & TH_ACK) &&
11415             (SEQ_LEQ(th->th_ack, tp->snd_una) ||
11416             SEQ_GT(th->th_ack, tp->snd_max))) {
11417                 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11418                 ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11419                 return (1);
11420         }
11421         rack = (struct tcp_rack *)tp->t_fb_ptr;
11422         if (IS_FASTOPEN(tp->t_flags)) {
11423                 /*
11424                  * When a TFO connection is in SYN_RECEIVED, the
11425                  * only valid packets are the initial SYN, a
11426                  * retransmit/copy of the initial SYN (possibly with
11427                  * a subset of the original data), a valid ACK, a
11428                  * FIN, or a RST.
11429                  */
11430                 if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
11431                         tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11432                         ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11433                         return (1);
11434                 } else if (thflags & TH_SYN) {
11435                         /* non-initial SYN is ignored */
11436                         if ((rack->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
11437                             (rack->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
11438                             (rack->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
11439                                 ctf_do_drop(m, NULL);
11440                                 return (0);
11441                         }
11442                 } else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
11443                         ctf_do_drop(m, NULL);
11444                         return (0);
11445                 }
11446         }
11447
11448         if ((thflags & TH_RST) ||
11449             (tp->t_fin_is_rst && (thflags & TH_FIN)))
11450                 return (__ctf_process_rst(m, th, so, tp,
11451                                           &rack->r_ctl.challenge_ack_ts,
11452                                           &rack->r_ctl.challenge_ack_cnt));
11453         /*
11454          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
11455          * it's less than ts_recent, drop it.
11456          */
11457         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
11458             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
11459                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
11460                         return (ret_val);
11461         }
11462         /*
11463          * In the SYN-RECEIVED state, validate that the packet belongs to
11464          * this connection before trimming the data to fit the receive
11465          * window.  Check the sequence number versus IRS since we know the
11466          * sequence numbers haven't wrapped.  This is a partial fix for the
11467          * "LAND" DoS attack.
11468          */
11469         if (SEQ_LT(th->th_seq, tp->irs)) {
11470                 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11471                 ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11472                 return (1);
11473         }
11474         if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
11475                               &rack->r_ctl.challenge_ack_ts,
11476                               &rack->r_ctl.challenge_ack_cnt)) {
11477                 return (ret_val);
11478         }
11479         /*
11480          * If last ACK falls within this segment's sequence numbers, record
11481          * its timestamp. NOTE: 1) That the test incorporates suggestions
11482          * from the latest proposal of the tcplw@cray.com list (Braden
11483          * 1993/04/26). 2) That updating only on newer timestamps interferes
11484          * with our earlier PAWS tests, so this check should be solely
11485          * predicated on the sequence space of this segment. 3) That we
11486          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
11487          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
11488          * SEG.Len, This modified check allows us to overcome RFC1323's
11489          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
11490          * p.869. In such cases, we can still calculate the RTT correctly
11491          * when RCV.NXT == Last.ACK.Sent.
11492          */
11493         if ((to->to_flags & TOF_TS) != 0 &&
11494             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
11495             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
11496             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
11497                 tp->ts_recent_age = tcp_ts_getticks();
11498                 tp->ts_recent = to->to_tsval;
11499         }
11500         tp->snd_wnd = tiwin;
11501         rack_validate_fo_sendwin_up(tp, rack);
11502         /*
11503          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
11504          * is on (half-synchronized state), then queue data for later
11505          * processing; else drop segment and return.
11506          */
11507         if ((thflags & TH_ACK) == 0) {
11508                 if (IS_FASTOPEN(tp->t_flags)) {
11509                         rack_cc_conn_init(tp);
11510                 }
11511                 return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11512                     tiwin, thflags, nxt_pkt));
11513         }
11514         KMOD_TCPSTAT_INC(tcps_connects);
11515         if (tp->t_flags & TF_SONOTCONN) {
11516                 tp->t_flags &= ~TF_SONOTCONN;
11517                 soisconnected(so);
11518         }
11519         /* Do window scaling? */
11520         if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
11521             (TF_RCVD_SCALE | TF_REQ_SCALE)) {
11522                 tp->rcv_scale = tp->request_r_scale;
11523         }
11524         /*
11525          * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
11526          * FIN-WAIT-1
11527          */
11528         tp->t_starttime = ticks;
11529         if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
11530                 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
11531                 tp->t_tfo_pending = NULL;
11532         }
11533         if (tp->t_flags & TF_NEEDFIN) {
11534                 tcp_state_change(tp, TCPS_FIN_WAIT_1);
11535                 tp->t_flags &= ~TF_NEEDFIN;
11536         } else {
11537                 tcp_state_change(tp, TCPS_ESTABLISHED);
11538                 TCP_PROBE5(accept__established, NULL, tp,
11539                     mtod(m, const char *), tp, th);
11540                 /*
11541                  * TFO connections call cc_conn_init() during SYN
11542                  * processing.  Calling it again here for such connections
11543                  * is not harmless as it would undo the snd_cwnd reduction
11544                  * that occurs when a TFO SYN|ACK is retransmitted.
11545                  */
11546                 if (!IS_FASTOPEN(tp->t_flags))
11547                         rack_cc_conn_init(tp);
11548         }
11549         /*
11550          * Account for the ACK of our SYN prior to
11551          * regular ACK processing below, except for
11552          * simultaneous SYN, which is handled later.
11553          */
11554         if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
11555                 tp->snd_una++;
11556         /*
11557          * If segment contains data or ACK, will call tcp_reass() later; if
11558          * not, do so now to pass queued data to user.
11559          */
11560         if (tlen == 0 && (thflags & TH_FIN) == 0) {
11561                 (void) tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
11562                     (struct mbuf *)0);
11563                 if (tp->t_flags & TF_WAKESOR) {
11564                         tp->t_flags &= ~TF_WAKESOR;
11565                         /* NB: sorwakeup_locked() does an implicit unlock. */
11566                         sorwakeup_locked(so);
11567                 }
11568         }
11569         tp->snd_wl1 = th->th_seq - 1;
11570         /* For syn-recv we need to possibly update the rtt */
11571         if ((to->to_flags & TOF_TS) != 0 && to->to_tsecr) {
11572                 uint32_t t, mcts;
11573
11574                 mcts = tcp_ts_getticks();
11575                 t = (mcts - to->to_tsecr) * HPTS_USEC_IN_MSEC;
11576                 if (!tp->t_rttlow || tp->t_rttlow > t)
11577                         tp->t_rttlow = t;
11578                 rack_log_rtt_sample_calc(rack, t, (to->to_tsecr * 1000), (mcts * 1000), 5);
11579                 tcp_rack_xmit_timer(rack, t + 1, 1, t, 0, NULL, 2);
11580                 tcp_rack_xmit_timer_commit(rack, tp);
11581         }
11582         if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
11583                 return (ret_val);
11584         }
11585         if (tp->t_state == TCPS_FIN_WAIT_1) {
11586                 /* We could have went to FIN_WAIT_1 (or EST) above */
11587                 /*
11588                  * In FIN_WAIT_1 STATE in addition to the processing for the
11589                  * ESTABLISHED state if our FIN is now acknowledged then
11590                  * enter FIN_WAIT_2.
11591                  */
11592                 if (ourfinisacked) {
11593                         /*
11594                          * If we can't receive any more data, then closing
11595                          * user can proceed. Starting the timer is contrary
11596                          * to the specification, but if we don't get a FIN
11597                          * we'll hang forever.
11598                          *
11599                          * XXXjl: we should release the tp also, and use a
11600                          * compressed state.
11601                          */
11602                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
11603                                 soisdisconnected(so);
11604                                 tcp_timer_activate(tp, TT_2MSL,
11605                                     (tcp_fast_finwait2_recycle ?
11606                                     tcp_finwait2_timeout :
11607                                     TP_MAXIDLE(tp)));
11608                         }
11609                         tcp_state_change(tp, TCPS_FIN_WAIT_2);
11610                 }
11611         }
11612         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11613             tiwin, thflags, nxt_pkt));
11614 }
11615
11616 /*
11617  * Return value of 1, the TCB is unlocked and most
11618  * likely gone, return value of 0, the TCP is still
11619  * locked.
11620  */
11621 static int
11622 rack_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
11623     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
11624     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
11625 {
11626         int32_t ret_val = 0;
11627         struct tcp_rack *rack;
11628
11629         /*
11630          * Header prediction: check for the two common cases of a
11631          * uni-directional data xfer.  If the packet has no control flags,
11632          * is in-sequence, the window didn't change and we're not
11633          * retransmitting, it's a candidate.  If the length is zero and the
11634          * ack moved forward, we're the sender side of the xfer.  Just free
11635          * the data acked & wake any higher level process that was blocked
11636          * waiting for space.  If the length is non-zero and the ack didn't
11637          * move, we're the receiver side.  If we're getting packets in-order
11638          * (the reassembly queue is empty), add the data toc The socket
11639          * buffer and note that we need a delayed ack. Make sure that the
11640          * hidden state-flags are also off. Since we check for
11641          * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
11642          */
11643         rack = (struct tcp_rack *)tp->t_fb_ptr;
11644         if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
11645             __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_ACK)) == TH_ACK) &&
11646             __predict_true(SEGQ_EMPTY(tp)) &&
11647             __predict_true(th->th_seq == tp->rcv_nxt)) {
11648                 if (tlen == 0) {
11649                         if (rack_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
11650                             tiwin, nxt_pkt, rack->r_ctl.rc_rcvtime)) {
11651                                 return (0);
11652                         }
11653                 } else {
11654                         if (rack_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
11655                             tiwin, nxt_pkt, iptos)) {
11656                                 return (0);
11657                         }
11658                 }
11659         }
11660         ctf_calc_rwin(so, tp);
11661
11662         if ((thflags & TH_RST) ||
11663             (tp->t_fin_is_rst && (thflags & TH_FIN)))
11664                 return (__ctf_process_rst(m, th, so, tp,
11665                                           &rack->r_ctl.challenge_ack_ts,
11666                                           &rack->r_ctl.challenge_ack_cnt));
11667
11668         /*
11669          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
11670          * synchronized state.
11671          */
11672         if (thflags & TH_SYN) {
11673                 ctf_challenge_ack(m, th, tp, iptos, &ret_val);
11674                 return (ret_val);
11675         }
11676         /*
11677          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
11678          * it's less than ts_recent, drop it.
11679          */
11680         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
11681             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
11682                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
11683                         return (ret_val);
11684         }
11685         if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
11686                               &rack->r_ctl.challenge_ack_ts,
11687                               &rack->r_ctl.challenge_ack_cnt)) {
11688                 return (ret_val);
11689         }
11690         /*
11691          * If last ACK falls within this segment's sequence numbers, record
11692          * its timestamp. NOTE: 1) That the test incorporates suggestions
11693          * from the latest proposal of the tcplw@cray.com list (Braden
11694          * 1993/04/26). 2) That updating only on newer timestamps interferes
11695          * with our earlier PAWS tests, so this check should be solely
11696          * predicated on the sequence space of this segment. 3) That we
11697          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
11698          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
11699          * SEG.Len, This modified check allows us to overcome RFC1323's
11700          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
11701          * p.869. In such cases, we can still calculate the RTT correctly
11702          * when RCV.NXT == Last.ACK.Sent.
11703          */
11704         if ((to->to_flags & TOF_TS) != 0 &&
11705             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
11706             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
11707             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
11708                 tp->ts_recent_age = tcp_ts_getticks();
11709                 tp->ts_recent = to->to_tsval;
11710         }
11711         /*
11712          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
11713          * is on (half-synchronized state), then queue data for later
11714          * processing; else drop segment and return.
11715          */
11716         if ((thflags & TH_ACK) == 0) {
11717                 if (tp->t_flags & TF_NEEDSYN) {
11718                         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11719                             tiwin, thflags, nxt_pkt));
11720
11721                 } else if (tp->t_flags & TF_ACKNOW) {
11722                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
11723                         ((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
11724                         return (ret_val);
11725                 } else {
11726                         ctf_do_drop(m, NULL);
11727                         return (0);
11728                 }
11729         }
11730         /*
11731          * Ack processing.
11732          */
11733         if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
11734                 return (ret_val);
11735         }
11736         if (sbavail(&so->so_snd)) {
11737                 if (ctf_progress_timeout_check(tp, true)) {
11738                         rack_log_progress_event(rack, tp, tick, PROGRESS_DROP, __LINE__);
11739                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11740                         return (1);
11741                 }
11742         }
11743         /* State changes only happen in rack_process_data() */
11744         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11745             tiwin, thflags, nxt_pkt));
11746 }
11747
11748 /*
11749  * Return value of 1, the TCB is unlocked and most
11750  * likely gone, return value of 0, the TCP is still
11751  * locked.
11752  */
11753 static int
11754 rack_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
11755     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
11756     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
11757 {
11758         int32_t ret_val = 0;
11759         struct tcp_rack *rack;
11760
11761         rack = (struct tcp_rack *)tp->t_fb_ptr;
11762         ctf_calc_rwin(so, tp);
11763         if ((thflags & TH_RST) ||
11764             (tp->t_fin_is_rst && (thflags & TH_FIN)))
11765                 return (__ctf_process_rst(m, th, so, tp,
11766                                           &rack->r_ctl.challenge_ack_ts,
11767                                           &rack->r_ctl.challenge_ack_cnt));
11768         /*
11769          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
11770          * synchronized state.
11771          */
11772         if (thflags & TH_SYN) {
11773                 ctf_challenge_ack(m, th, tp, iptos, &ret_val);
11774                 return (ret_val);
11775         }
11776         /*
11777          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
11778          * it's less than ts_recent, drop it.
11779          */
11780         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
11781             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
11782                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
11783                         return (ret_val);
11784         }
11785         if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
11786                               &rack->r_ctl.challenge_ack_ts,
11787                               &rack->r_ctl.challenge_ack_cnt)) {
11788                 return (ret_val);
11789         }
11790         /*
11791          * If last ACK falls within this segment's sequence numbers, record
11792          * its timestamp. NOTE: 1) That the test incorporates suggestions
11793          * from the latest proposal of the tcplw@cray.com list (Braden
11794          * 1993/04/26). 2) That updating only on newer timestamps interferes
11795          * with our earlier PAWS tests, so this check should be solely
11796          * predicated on the sequence space of this segment. 3) That we
11797          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
11798          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
11799          * SEG.Len, This modified check allows us to overcome RFC1323's
11800          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
11801          * p.869. In such cases, we can still calculate the RTT correctly
11802          * when RCV.NXT == Last.ACK.Sent.
11803          */
11804         if ((to->to_flags & TOF_TS) != 0 &&
11805             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
11806             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
11807             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
11808                 tp->ts_recent_age = tcp_ts_getticks();
11809                 tp->ts_recent = to->to_tsval;
11810         }
11811         /*
11812          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
11813          * is on (half-synchronized state), then queue data for later
11814          * processing; else drop segment and return.
11815          */
11816         if ((thflags & TH_ACK) == 0) {
11817                 if (tp->t_flags & TF_NEEDSYN) {
11818                         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11819                             tiwin, thflags, nxt_pkt));
11820
11821                 } else if (tp->t_flags & TF_ACKNOW) {
11822                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
11823                         ((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
11824                         return (ret_val);
11825                 } else {
11826                         ctf_do_drop(m, NULL);
11827                         return (0);
11828                 }
11829         }
11830         /*
11831          * Ack processing.
11832          */
11833         if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
11834                 return (ret_val);
11835         }
11836         if (sbavail(&so->so_snd)) {
11837                 if (ctf_progress_timeout_check(tp, true)) {
11838                         rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
11839                                                 tp, tick, PROGRESS_DROP, __LINE__);
11840                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11841                         return (1);
11842                 }
11843         }
11844         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11845             tiwin, thflags, nxt_pkt));
11846 }
11847
11848 static int
11849 rack_check_data_after_close(struct mbuf *m,
11850     struct tcpcb *tp, int32_t *tlen, struct tcphdr *th, struct socket *so)
11851 {
11852         struct tcp_rack *rack;
11853
11854         rack = (struct tcp_rack *)tp->t_fb_ptr;
11855         if (rack->rc_allow_data_af_clo == 0) {
11856         close_now:
11857                 tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
11858                 /* tcp_close will kill the inp pre-log the Reset */
11859                 tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
11860                 tp = tcp_close(tp);
11861                 KMOD_TCPSTAT_INC(tcps_rcvafterclose);
11862                 ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
11863                 return (1);
11864         }
11865         if (sbavail(&so->so_snd) == 0)
11866                 goto close_now;
11867         /* Ok we allow data that is ignored and a followup reset */
11868         tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
11869         tp->rcv_nxt = th->th_seq + *tlen;
11870         tp->t_flags2 |= TF2_DROP_AF_DATA;
11871         rack->r_wanted_output = 1;
11872         *tlen = 0;
11873         return (0);
11874 }
11875
11876 /*
11877  * Return value of 1, the TCB is unlocked and most
11878  * likely gone, return value of 0, the TCP is still
11879  * locked.
11880  */
11881 static int
11882 rack_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
11883     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
11884     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
11885 {
11886         int32_t ret_val = 0;
11887         int32_t ourfinisacked = 0;
11888         struct tcp_rack *rack;
11889
11890         rack = (struct tcp_rack *)tp->t_fb_ptr;
11891         ctf_calc_rwin(so, tp);
11892
11893         if ((thflags & TH_RST) ||
11894             (tp->t_fin_is_rst && (thflags & TH_FIN)))
11895                 return (__ctf_process_rst(m, th, so, tp,
11896                                           &rack->r_ctl.challenge_ack_ts,
11897                                           &rack->r_ctl.challenge_ack_cnt));
11898         /*
11899          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
11900          * synchronized state.
11901          */
11902         if (thflags & TH_SYN) {
11903                 ctf_challenge_ack(m, th, tp, iptos, &ret_val);
11904                 return (ret_val);
11905         }
11906         /*
11907          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
11908          * it's less than ts_recent, drop it.
11909          */
11910         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
11911             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
11912                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
11913                         return (ret_val);
11914         }
11915         if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
11916                               &rack->r_ctl.challenge_ack_ts,
11917                               &rack->r_ctl.challenge_ack_cnt)) {
11918                 return (ret_val);
11919         }
11920         /*
11921          * If new data are received on a connection after the user processes
11922          * are gone, then RST the other end.
11923          */
11924         if ((tp->t_flags & TF_CLOSED) && tlen &&
11925             rack_check_data_after_close(m, tp, &tlen, th, so))
11926                 return (1);
11927         /*
11928          * If last ACK falls within this segment's sequence numbers, record
11929          * its timestamp. NOTE: 1) That the test incorporates suggestions
11930          * from the latest proposal of the tcplw@cray.com list (Braden
11931          * 1993/04/26). 2) That updating only on newer timestamps interferes
11932          * with our earlier PAWS tests, so this check should be solely
11933          * predicated on the sequence space of this segment. 3) That we
11934          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
11935          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
11936          * SEG.Len, This modified check allows us to overcome RFC1323's
11937          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
11938          * p.869. In such cases, we can still calculate the RTT correctly
11939          * when RCV.NXT == Last.ACK.Sent.
11940          */
11941         if ((to->to_flags & TOF_TS) != 0 &&
11942             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
11943             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
11944             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
11945                 tp->ts_recent_age = tcp_ts_getticks();
11946                 tp->ts_recent = to->to_tsval;
11947         }
11948         /*
11949          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
11950          * is on (half-synchronized state), then queue data for later
11951          * processing; else drop segment and return.
11952          */
11953         if ((thflags & TH_ACK) == 0) {
11954                 if (tp->t_flags & TF_NEEDSYN) {
11955                         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11956                             tiwin, thflags, nxt_pkt));
11957                 } else if (tp->t_flags & TF_ACKNOW) {
11958                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
11959                         ((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
11960                         return (ret_val);
11961                 } else {
11962                         ctf_do_drop(m, NULL);
11963                         return (0);
11964                 }
11965         }
11966         /*
11967          * Ack processing.
11968          */
11969         if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
11970                 return (ret_val);
11971         }
11972         if (ourfinisacked) {
11973                 /*
11974                  * If we can't receive any more data, then closing user can
11975                  * proceed. Starting the timer is contrary to the
11976                  * specification, but if we don't get a FIN we'll hang
11977                  * forever.
11978                  *
11979                  * XXXjl: we should release the tp also, and use a
11980                  * compressed state.
11981                  */
11982                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
11983                         soisdisconnected(so);
11984                         tcp_timer_activate(tp, TT_2MSL,
11985                             (tcp_fast_finwait2_recycle ?
11986                             tcp_finwait2_timeout :
11987                             TP_MAXIDLE(tp)));
11988                 }
11989                 tcp_state_change(tp, TCPS_FIN_WAIT_2);
11990         }
11991         if (sbavail(&so->so_snd)) {
11992                 if (ctf_progress_timeout_check(tp, true)) {
11993                         rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
11994                                                 tp, tick, PROGRESS_DROP, __LINE__);
11995                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11996                         return (1);
11997                 }
11998         }
11999         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
12000             tiwin, thflags, nxt_pkt));
12001 }
12002
12003 /*
12004  * Return value of 1, the TCB is unlocked and most
12005  * likely gone, return value of 0, the TCP is still
12006  * locked.
12007  */
12008 static int
12009 rack_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
12010     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
12011     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
12012 {
12013         int32_t ret_val = 0;
12014         int32_t ourfinisacked = 0;
12015         struct tcp_rack *rack;
12016
12017         rack = (struct tcp_rack *)tp->t_fb_ptr;
12018         ctf_calc_rwin(so, tp);
12019
12020         if ((thflags & TH_RST) ||
12021             (tp->t_fin_is_rst && (thflags & TH_FIN)))
12022                 return (__ctf_process_rst(m, th, so, tp,
12023                                           &rack->r_ctl.challenge_ack_ts,
12024                                           &rack->r_ctl.challenge_ack_cnt));
12025         /*
12026          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
12027          * synchronized state.
12028          */
12029         if (thflags & TH_SYN) {
12030                 ctf_challenge_ack(m, th, tp, iptos, &ret_val);
12031                 return (ret_val);
12032         }
12033         /*
12034          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
12035          * it's less than ts_recent, drop it.
12036          */
12037         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
12038             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
12039                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
12040                         return (ret_val);
12041         }
12042         if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
12043                               &rack->r_ctl.challenge_ack_ts,
12044                               &rack->r_ctl.challenge_ack_cnt)) {
12045                 return (ret_val);
12046         }
12047         /*
12048          * If new data are received on a connection after the user processes
12049          * are gone, then RST the other end.
12050          */
12051         if ((tp->t_flags & TF_CLOSED) && tlen &&
12052             rack_check_data_after_close(m, tp, &tlen, th, so))
12053                 return (1);
12054         /*
12055          * If last ACK falls within this segment's sequence numbers, record
12056          * its timestamp. NOTE: 1) That the test incorporates suggestions
12057          * from the latest proposal of the tcplw@cray.com list (Braden
12058          * 1993/04/26). 2) That updating only on newer timestamps interferes
12059          * with our earlier PAWS tests, so this check should be solely
12060          * predicated on the sequence space of this segment. 3) That we
12061          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
12062          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
12063          * SEG.Len, This modified check allows us to overcome RFC1323's
12064          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
12065          * p.869. In such cases, we can still calculate the RTT correctly
12066          * when RCV.NXT == Last.ACK.Sent.
12067          */
12068         if ((to->to_flags & TOF_TS) != 0 &&
12069             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
12070             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
12071             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
12072                 tp->ts_recent_age = tcp_ts_getticks();
12073                 tp->ts_recent = to->to_tsval;
12074         }
12075         /*
12076          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
12077          * is on (half-synchronized state), then queue data for later
12078          * processing; else drop segment and return.
12079          */
12080         if ((thflags & TH_ACK) == 0) {
12081                 if (tp->t_flags & TF_NEEDSYN) {
12082                         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
12083                             tiwin, thflags, nxt_pkt));
12084                 } else if (tp->t_flags & TF_ACKNOW) {
12085                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
12086                         ((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
12087                         return (ret_val);
12088                 } else {
12089                         ctf_do_drop(m, NULL);
12090                         return (0);
12091                 }
12092         }
12093         /*
12094          * Ack processing.
12095          */
12096         if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
12097                 return (ret_val);
12098         }
12099         if (ourfinisacked) {
12100                 tcp_twstart(tp);
12101                 m_freem(m);
12102                 return (1);
12103         }
12104         if (sbavail(&so->so_snd)) {
12105                 if (ctf_progress_timeout_check(tp, true)) {
12106                         rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
12107                                                 tp, tick, PROGRESS_DROP, __LINE__);
12108                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
12109                         return (1);
12110                 }
12111         }
12112         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
12113             tiwin, thflags, nxt_pkt));
12114 }
12115
12116 /*
12117  * Return value of 1, the TCB is unlocked and most
12118  * likely gone, return value of 0, the TCP is still
12119  * locked.
12120  */
12121 static int
12122 rack_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
12123     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
12124     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
12125 {
12126         int32_t ret_val = 0;
12127         int32_t ourfinisacked = 0;
12128         struct tcp_rack *rack;
12129
12130         rack = (struct tcp_rack *)tp->t_fb_ptr;
12131         ctf_calc_rwin(so, tp);
12132
12133         if ((thflags & TH_RST) ||
12134             (tp->t_fin_is_rst && (thflags & TH_FIN)))
12135                 return (__ctf_process_rst(m, th, so, tp,
12136                                           &rack->r_ctl.challenge_ack_ts,
12137                                           &rack->r_ctl.challenge_ack_cnt));
12138         /*
12139          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
12140          * synchronized state.
12141          */
12142         if (thflags & TH_SYN) {
12143                 ctf_challenge_ack(m, th, tp, iptos, &ret_val);
12144                 return (ret_val);
12145         }
12146         /*
12147          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
12148          * it's less than ts_recent, drop it.
12149          */
12150         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
12151             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
12152                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
12153                         return (ret_val);
12154         }
12155         if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
12156                               &rack->r_ctl.challenge_ack_ts,
12157                               &rack->r_ctl.challenge_ack_cnt)) {
12158                 return (ret_val);
12159         }
12160         /*
12161          * If new data are received on a connection after the user processes
12162          * are gone, then RST the other end.
12163          */
12164         if ((tp->t_flags & TF_CLOSED) && tlen &&
12165             rack_check_data_after_close(m, tp, &tlen, th, so))
12166                 return (1);
12167         /*
12168          * If last ACK falls within this segment's sequence numbers, record
12169          * its timestamp. NOTE: 1) That the test incorporates suggestions
12170          * from the latest proposal of the tcplw@cray.com list (Braden
12171          * 1993/04/26). 2) That updating only on newer timestamps interferes
12172          * with our earlier PAWS tests, so this check should be solely
12173          * predicated on the sequence space of this segment. 3) That we
12174          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
12175          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
12176          * SEG.Len, This modified check allows us to overcome RFC1323's
12177          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
12178          * p.869. In such cases, we can still calculate the RTT correctly
12179          * when RCV.NXT == Last.ACK.Sent.
12180          */
12181         if ((to->to_flags & TOF_TS) != 0 &&
12182             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
12183             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
12184             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
12185                 tp->ts_recent_age = tcp_ts_getticks();
12186                 tp->ts_recent = to->to_tsval;
12187         }
12188         /*
12189          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
12190          * is on (half-synchronized state), then queue data for later
12191          * processing; else drop segment and return.
12192          */
12193         if ((thflags & TH_ACK) == 0) {
12194                 if (tp->t_flags & TF_NEEDSYN) {
12195                         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
12196                             tiwin, thflags, nxt_pkt));
12197                 } else if (tp->t_flags & TF_ACKNOW) {
12198                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
12199                         ((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
12200                         return (ret_val);
12201                 } else {
12202                         ctf_do_drop(m, NULL);
12203                         return (0);
12204                 }
12205         }
12206         /*
12207          * case TCPS_LAST_ACK: Ack processing.
12208          */
12209         if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
12210                 return (ret_val);
12211         }
12212         if (ourfinisacked) {
12213                 tp = tcp_close(tp);
12214                 ctf_do_drop(m, tp);
12215                 return (1);
12216         }
12217         if (sbavail(&so->so_snd)) {
12218                 if (ctf_progress_timeout_check(tp, true)) {
12219                         rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
12220                                                 tp, tick, PROGRESS_DROP, __LINE__);
12221                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
12222                         return (1);
12223                 }
12224         }
12225         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
12226             tiwin, thflags, nxt_pkt));
12227 }
12228
12229 /*
12230  * Return value of 1, the TCB is unlocked and most
12231  * likely gone, return value of 0, the TCP is still
12232  * locked.
12233  */
12234 static int
12235 rack_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
12236     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
12237     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
12238 {
12239         int32_t ret_val = 0;
12240         int32_t ourfinisacked = 0;
12241         struct tcp_rack *rack;
12242
12243         rack = (struct tcp_rack *)tp->t_fb_ptr;
12244         ctf_calc_rwin(so, tp);
12245
12246         /* Reset receive buffer auto scaling when not in bulk receive mode. */
12247         if ((thflags & TH_RST) ||
12248             (tp->t_fin_is_rst && (thflags & TH_FIN)))
12249                 return (__ctf_process_rst(m, th, so, tp,
12250                                           &rack->r_ctl.challenge_ack_ts,
12251                                           &rack->r_ctl.challenge_ack_cnt));
12252         /*
12253          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
12254          * synchronized state.
12255          */
12256         if (thflags & TH_SYN) {
12257                 ctf_challenge_ack(m, th, tp, iptos, &ret_val);
12258                 return (ret_val);
12259         }
12260         /*
12261          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
12262          * it's less than ts_recent, drop it.
12263          */
12264         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
12265             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
12266                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
12267                         return (ret_val);
12268         }
12269         if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
12270                               &rack->r_ctl.challenge_ack_ts,
12271                               &rack->r_ctl.challenge_ack_cnt)) {
12272                 return (ret_val);
12273         }
12274         /*
12275          * If new data are received on a connection after the user processes
12276          * are gone, then RST the other end.
12277          */
12278         if ((tp->t_flags & TF_CLOSED) && tlen &&
12279             rack_check_data_after_close(m, tp, &tlen, th, so))
12280                 return (1);
12281         /*
12282          * If last ACK falls within this segment's sequence numbers, record
12283          * its timestamp. NOTE: 1) That the test incorporates suggestions
12284          * from the latest proposal of the tcplw@cray.com list (Braden
12285          * 1993/04/26). 2) That updating only on newer timestamps interferes
12286          * with our earlier PAWS tests, so this check should be solely
12287          * predicated on the sequence space of this segment. 3) That we
12288          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
12289          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
12290          * SEG.Len, This modified check allows us to overcome RFC1323's
12291          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
12292          * p.869. In such cases, we can still calculate the RTT correctly
12293          * when RCV.NXT == Last.ACK.Sent.
12294          */
12295         if ((to->to_flags & TOF_TS) != 0 &&
12296             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
12297             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
12298             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
12299                 tp->ts_recent_age = tcp_ts_getticks();
12300                 tp->ts_recent = to->to_tsval;
12301         }
12302         /*
12303          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
12304          * is on (half-synchronized state), then queue data for later
12305          * processing; else drop segment and return.
12306          */
12307         if ((thflags & TH_ACK) == 0) {
12308                 if (tp->t_flags & TF_NEEDSYN) {
12309                         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
12310                             tiwin, thflags, nxt_pkt));
12311                 } else if (tp->t_flags & TF_ACKNOW) {
12312                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
12313                         ((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
12314                         return (ret_val);
12315                 } else {
12316                         ctf_do_drop(m, NULL);
12317                         return (0);
12318                 }
12319         }
12320         /*
12321          * Ack processing.
12322          */
12323         if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
12324                 return (ret_val);
12325         }
12326         if (sbavail(&so->so_snd)) {
12327                 if (ctf_progress_timeout_check(tp, true)) {
12328                         rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
12329                                                 tp, tick, PROGRESS_DROP, __LINE__);
12330                         ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
12331                         return (1);
12332                 }
12333         }
12334         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
12335             tiwin, thflags, nxt_pkt));
12336 }
12337
12338 static void inline
12339 rack_clear_rate_sample(struct tcp_rack *rack)
12340 {
12341         rack->r_ctl.rack_rs.rs_flags = RACK_RTT_EMPTY;
12342         rack->r_ctl.rack_rs.rs_rtt_cnt = 0;
12343         rack->r_ctl.rack_rs.rs_rtt_tot = 0;
12344 }
12345
12346 static void
12347 rack_set_pace_segments(struct tcpcb *tp, struct tcp_rack *rack, uint32_t line, uint64_t *fill_override)
12348 {
12349         uint64_t bw_est, rate_wanted;
12350         int chged = 0;
12351         uint32_t user_max, orig_min, orig_max;
12352
12353         orig_min = rack->r_ctl.rc_pace_min_segs;
12354         orig_max = rack->r_ctl.rc_pace_max_segs;
12355         user_max = ctf_fixed_maxseg(tp) * rack->rc_user_set_max_segs;
12356         if (ctf_fixed_maxseg(tp) != rack->r_ctl.rc_pace_min_segs)
12357                 chged = 1;
12358         rack->r_ctl.rc_pace_min_segs = ctf_fixed_maxseg(tp);
12359         if (rack->use_fixed_rate || rack->rc_force_max_seg) {
12360                 if (user_max != rack->r_ctl.rc_pace_max_segs)
12361                         chged = 1;
12362         }
12363         if (rack->rc_force_max_seg) {
12364                 rack->r_ctl.rc_pace_max_segs = user_max;
12365         } else if (rack->use_fixed_rate) {
12366                 bw_est = rack_get_bw(rack);
12367                 if ((rack->r_ctl.crte == NULL) ||
12368                     (bw_est != rack->r_ctl.crte->rate)) {
12369                         rack->r_ctl.rc_pace_max_segs = user_max;
12370                 } else {
12371                         /* We are pacing right at the hardware rate */
12372                         uint32_t segsiz;
12373
12374                         segsiz = min(ctf_fixed_maxseg(tp),
12375                                      rack->r_ctl.rc_pace_min_segs);
12376                         rack->r_ctl.rc_pace_max_segs = tcp_get_pacing_burst_size(
12377                                                            tp, bw_est, segsiz, 0,
12378                                                            rack->r_ctl.crte, NULL);
12379                 }
12380         } else if (rack->rc_always_pace) {
12381                 if (rack->r_ctl.gp_bw ||
12382 #ifdef NETFLIX_PEAKRATE
12383                     rack->rc_tp->t_maxpeakrate ||
12384 #endif
12385                     rack->r_ctl.init_rate) {
12386                         /* We have a rate of some sort set */
12387                         uint32_t  orig;
12388
12389                         bw_est = rack_get_bw(rack);
12390                         orig = rack->r_ctl.rc_pace_max_segs;
12391                         if (fill_override)
12392                                 rate_wanted = *fill_override;
12393                         else
12394                                 rate_wanted = rack_get_output_bw(rack, bw_est, NULL, NULL);
12395                         if (rate_wanted) {
12396                                 /* We have something */
12397                                 rack->r_ctl.rc_pace_max_segs = rack_get_pacing_len(rack,
12398                                                                                    rate_wanted,
12399                                                                                    ctf_fixed_maxseg(rack->rc_tp));
12400                         } else
12401                                 rack->r_ctl.rc_pace_max_segs = rack->r_ctl.rc_pace_min_segs;
12402                         if (orig != rack->r_ctl.rc_pace_max_segs)
12403                                 chged = 1;
12404                 } else if ((rack->r_ctl.gp_bw == 0) &&
12405                            (rack->r_ctl.rc_pace_max_segs == 0)) {
12406                         /*
12407                          * If we have nothing limit us to bursting
12408                          * out IW sized pieces.
12409                          */
12410                         chged = 1;
12411                         rack->r_ctl.rc_pace_max_segs = rc_init_window(rack);
12412                 }
12413         }
12414         if (rack->r_ctl.rc_pace_max_segs > PACE_MAX_IP_BYTES) {
12415                 chged = 1;
12416                 rack->r_ctl.rc_pace_max_segs = PACE_MAX_IP_BYTES;
12417         }
12418         if (chged)
12419                 rack_log_type_pacing_sizes(tp, rack, orig_min, orig_max, line, 2);
12420 }
12421
12422
12423 static void
12424 rack_init_fsb_block(struct tcpcb *tp, struct tcp_rack *rack)
12425 {
12426 #ifdef INET6
12427         struct ip6_hdr *ip6 = NULL;
12428 #endif
12429 #ifdef INET
12430         struct ip *ip = NULL;
12431 #endif
12432         struct udphdr *udp = NULL;
12433
12434         /* Ok lets fill in the fast block, it can only be used with no IP options! */
12435 #ifdef INET6
12436         if (rack->r_is_v6) {
12437                 rack->r_ctl.fsb.tcp_ip_hdr_len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
12438                 ip6 = (struct ip6_hdr *)rack->r_ctl.fsb.tcp_ip_hdr;
12439                 if (tp->t_port) {
12440                         rack->r_ctl.fsb.tcp_ip_hdr_len += sizeof(struct udphdr);
12441                         udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
12442                         udp->uh_sport = htons(V_tcp_udp_tunneling_port);
12443                         udp->uh_dport = tp->t_port;
12444                         rack->r_ctl.fsb.udp = udp;
12445                         rack->r_ctl.fsb.th = (struct tcphdr *)(udp + 1);
12446                 } else
12447                 {
12448                         rack->r_ctl.fsb.th = (struct tcphdr *)(ip6 + 1);
12449                         rack->r_ctl.fsb.udp = NULL;
12450                 }
12451                 tcpip_fillheaders(rack->rc_inp,
12452                                   tp->t_port,
12453                                   ip6, rack->r_ctl.fsb.th);
12454         } else
12455 #endif                          /* INET6 */
12456         {
12457                 rack->r_ctl.fsb.tcp_ip_hdr_len = sizeof(struct tcpiphdr);
12458                 ip = (struct ip *)rack->r_ctl.fsb.tcp_ip_hdr;
12459                 if (tp->t_port) {
12460                         rack->r_ctl.fsb.tcp_ip_hdr_len += sizeof(struct udphdr);
12461                         udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
12462                         udp->uh_sport = htons(V_tcp_udp_tunneling_port);
12463                         udp->uh_dport = tp->t_port;
12464                         rack->r_ctl.fsb.udp = udp;
12465                         rack->r_ctl.fsb.th = (struct tcphdr *)(udp + 1);
12466                 } else
12467                 {
12468                         rack->r_ctl.fsb.udp = NULL;
12469                         rack->r_ctl.fsb.th = (struct tcphdr *)(ip + 1);
12470                 }
12471                 tcpip_fillheaders(rack->rc_inp,
12472                                   tp->t_port,
12473                                   ip, rack->r_ctl.fsb.th);
12474         }
12475         rack->r_fsb_inited = 1;
12476 }
12477
12478 static int
12479 rack_init_fsb(struct tcpcb *tp, struct tcp_rack *rack)
12480 {
12481         /*
12482          * Allocate the larger of spaces V6 if available else just
12483          * V4 and include udphdr (overbook)
12484          */
12485 #ifdef INET6
12486         rack->r_ctl.fsb.tcp_ip_hdr_len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr) + sizeof(struct udphdr);
12487 #else
12488         rack->r_ctl.fsb.tcp_ip_hdr_len = sizeof(struct tcpiphdr) + sizeof(struct udphdr);
12489 #endif
12490         rack->r_ctl.fsb.tcp_ip_hdr = malloc(rack->r_ctl.fsb.tcp_ip_hdr_len,
12491                                             M_TCPFSB, M_NOWAIT|M_ZERO);
12492         if (rack->r_ctl.fsb.tcp_ip_hdr == NULL) {
12493                 return (ENOMEM);
12494         }
12495         rack->r_fsb_inited = 0;
12496         return (0);
12497 }
12498
12499 static int
12500 rack_init(struct tcpcb *tp)
12501 {
12502         struct inpcb *inp = tptoinpcb(tp);
12503         struct tcp_rack *rack = NULL;
12504 #ifdef INVARIANTS
12505         struct rack_sendmap *insret;
12506 #endif
12507         uint32_t iwin, snt, us_cts;
12508         int err;
12509
12510         tp->t_fb_ptr = uma_zalloc(rack_pcb_zone, M_NOWAIT);
12511         if (tp->t_fb_ptr == NULL) {
12512                 /*
12513                  * We need to allocate memory but cant. The INP and INP_INFO
12514                  * locks and they are recursive (happens during setup. So a
12515                  * scheme to drop the locks fails :(
12516                  *
12517                  */
12518                 return (ENOMEM);
12519         }
12520         memset(tp->t_fb_ptr, 0, sizeof(struct tcp_rack));
12521
12522         rack = (struct tcp_rack *)tp->t_fb_ptr;
12523         RB_INIT(&rack->r_ctl.rc_mtree);
12524         TAILQ_INIT(&rack->r_ctl.rc_free);
12525         TAILQ_INIT(&rack->r_ctl.rc_tmap);
12526         rack->rc_tp = tp;
12527         rack->rc_inp = inp;
12528         /* Set the flag */
12529         rack->r_is_v6 = (inp->inp_vflag & INP_IPV6) != 0;
12530         /* Probably not needed but lets be sure */
12531         rack_clear_rate_sample(rack);
12532         /*
12533          * Save off the default values, socket options will poke
12534          * at these if pacing is not on or we have not yet
12535          * reached where pacing is on (gp_ready/fixed enabled).
12536          * When they get set into the CC module (when gp_ready
12537          * is enabled or we enable fixed) then we will set these
12538          * values into the CC and place in here the old values
12539          * so we have a restoral. Then we will set the flag
12540          * rc_pacing_cc_set. That way whenever we turn off pacing
12541          * or switch off this stack, we will know to go restore
12542          * the saved values.
12543          */
12544         rack->r_ctl.rc_saved_beta.beta = V_newreno_beta_ecn;
12545         rack->r_ctl.rc_saved_beta.beta_ecn = V_newreno_beta_ecn;
12546         /* We want abe like behavior as well */
12547         rack->r_ctl.rc_saved_beta.newreno_flags |= CC_NEWRENO_BETA_ECN_ENABLED;
12548         rack->r_ctl.rc_reorder_fade = rack_reorder_fade;
12549         rack->rc_allow_data_af_clo = rack_ignore_data_after_close;
12550         rack->r_ctl.rc_tlp_threshold = rack_tlp_thresh;
12551         rack->r_ctl.roundends = tp->snd_max;
12552         if (use_rack_rr)
12553                 rack->use_rack_rr = 1;
12554         if (V_tcp_delack_enabled)
12555                 tp->t_delayed_ack = 1;
12556         else
12557                 tp->t_delayed_ack = 0;
12558 #ifdef TCP_ACCOUNTING
12559         if (rack_tcp_accounting) {
12560                 tp->t_flags2 |= TF2_TCP_ACCOUNTING;
12561         }
12562 #endif
12563         if (rack_enable_shared_cwnd)
12564                 rack->rack_enable_scwnd = 1;
12565         rack->rc_user_set_max_segs = rack_hptsi_segments;
12566         rack->rc_force_max_seg = 0;
12567         if (rack_use_imac_dack)
12568                 rack->rc_dack_mode = 1;
12569         TAILQ_INIT(&rack->r_ctl.opt_list);
12570         rack->r_ctl.rc_reorder_shift = rack_reorder_thresh;
12571         rack->r_ctl.rc_pkt_delay = rack_pkt_delay;
12572         rack->r_ctl.rc_tlp_cwnd_reduce = rack_lower_cwnd_at_tlp;
12573         rack->r_ctl.rc_lowest_us_rtt = 0xffffffff;
12574         rack->r_ctl.rc_highest_us_rtt = 0;
12575         rack->r_ctl.bw_rate_cap = rack_bw_rate_cap;
12576         rack->r_ctl.timer_slop = TICKS_2_USEC(tcp_rexmit_slop);
12577         if (rack_use_cmp_acks)
12578                 rack->r_use_cmp_ack = 1;
12579         if (rack_disable_prr)
12580                 rack->rack_no_prr = 1;
12581         if (rack_gp_no_rec_chg)
12582                 rack->rc_gp_no_rec_chg = 1;
12583         if (rack_pace_every_seg && tcp_can_enable_pacing()) {
12584                 rack->rc_always_pace = 1;
12585                 if (rack->use_fixed_rate || rack->gp_ready)
12586                         rack_set_cc_pacing(rack);
12587         } else
12588                 rack->rc_always_pace = 0;
12589         if (rack_enable_mqueue_for_nonpaced || rack->r_use_cmp_ack)
12590                 rack->r_mbuf_queue = 1;
12591         else
12592                 rack->r_mbuf_queue = 0;
12593         if  (rack->r_mbuf_queue || rack->rc_always_pace || rack->r_use_cmp_ack)
12594                 inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
12595         else
12596                 inp->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
12597         rack_set_pace_segments(tp, rack, __LINE__, NULL);
12598         if (rack_limits_scwnd)
12599                 rack->r_limit_scw = 1;
12600         else
12601                 rack->r_limit_scw = 0;
12602         rack->rc_labc = V_tcp_abc_l_var;
12603         rack->r_ctl.rc_high_rwnd = tp->snd_wnd;
12604         rack->r_ctl.cwnd_to_use = tp->snd_cwnd;
12605         rack->r_ctl.rc_rate_sample_method = rack_rate_sample_method;
12606         rack->rack_tlp_threshold_use = rack_tlp_threshold_use;
12607         rack->r_ctl.rc_prr_sendalot = rack_send_a_lot_in_prr;
12608         rack->r_ctl.rc_min_to = rack_min_to;
12609         microuptime(&rack->r_ctl.act_rcv_time);
12610         rack->r_ctl.rc_last_time_decay = rack->r_ctl.act_rcv_time;
12611         rack->rc_init_win = rack_default_init_window;
12612         rack->r_ctl.rack_per_of_gp_ss = rack_per_of_gp_ss;
12613         if (rack_hw_up_only)
12614                 rack->r_up_only = 1;
12615         if (rack_do_dyn_mul) {
12616                 /* When dynamic adjustment is on CA needs to start at 100% */
12617                 rack->rc_gp_dyn_mul = 1;
12618                 if (rack_do_dyn_mul >= 100)
12619                         rack->r_ctl.rack_per_of_gp_ca = rack_do_dyn_mul;
12620         } else
12621                 rack->r_ctl.rack_per_of_gp_ca = rack_per_of_gp_ca;
12622         rack->r_ctl.rack_per_of_gp_rec = rack_per_of_gp_rec;
12623         rack->r_ctl.rack_per_of_gp_probertt = rack_per_of_gp_probertt;
12624         rack->r_ctl.rc_tlp_rxt_last_time = tcp_tv_to_mssectick(&rack->r_ctl.act_rcv_time);
12625         setup_time_filter_small(&rack->r_ctl.rc_gp_min_rtt, FILTER_TYPE_MIN,
12626                                 rack_probertt_filter_life);
12627         us_cts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
12628         rack->r_ctl.rc_lower_rtt_us_cts = us_cts;
12629         rack->r_ctl.rc_time_of_last_probertt = us_cts;
12630         rack->r_ctl.challenge_ack_ts = tcp_ts_getticks();
12631         rack->r_ctl.rc_time_probertt_starts = 0;
12632         if (rack_dsack_std_based & 0x1) {
12633                 /* Basically this means all rack timers are at least (srtt + 1/4 srtt) */
12634                 rack->rc_rack_tmr_std_based = 1;
12635         }
12636         if (rack_dsack_std_based & 0x2) {
12637                 /* Basically this means  rack timers are extended based on dsack by up to (2 * srtt) */
12638                 rack->rc_rack_use_dsack = 1;
12639         }
12640         /* We require at least one measurement, even if the sysctl is 0 */
12641         if (rack_req_measurements)
12642                 rack->r_ctl.req_measurements = rack_req_measurements;
12643         else
12644                 rack->r_ctl.req_measurements = 1;
12645         if (rack_enable_hw_pacing)
12646                 rack->rack_hdw_pace_ena = 1;
12647         if (rack_hw_rate_caps)
12648                 rack->r_rack_hw_rate_caps = 1;
12649         /* Do we force on detection? */
12650 #ifdef NETFLIX_EXP_DETECTION
12651         if (tcp_force_detection)
12652                 rack->do_detection = 1;
12653         else
12654 #endif
12655                 rack->do_detection = 0;
12656         if (rack_non_rxt_use_cr)
12657                 rack->rack_rec_nonrxt_use_cr = 1;
12658         err = rack_init_fsb(tp, rack);
12659         if (err) {
12660                 uma_zfree(rack_pcb_zone, tp->t_fb_ptr);
12661                 tp->t_fb_ptr = NULL;
12662                 return (err);
12663         }
12664         if (tp->snd_una != tp->snd_max) {
12665                 /* Create a send map for the current outstanding data */
12666                 struct rack_sendmap *rsm;
12667
12668                 rsm = rack_alloc(rack);
12669                 if (rsm == NULL) {
12670                         uma_zfree(rack_pcb_zone, tp->t_fb_ptr);
12671                         tp->t_fb_ptr = NULL;
12672                         return (ENOMEM);
12673                 }
12674                 rsm->r_no_rtt_allowed = 1;
12675                 rsm->r_tim_lastsent[0] = rack_to_usec_ts(&rack->r_ctl.act_rcv_time);
12676                 rsm->r_rtr_cnt = 1;
12677                 rsm->r_rtr_bytes = 0;
12678                 if (tp->t_flags & TF_SENTFIN)
12679                         rsm->r_flags |= RACK_HAS_FIN;
12680                 if ((tp->snd_una == tp->iss) &&
12681                     !TCPS_HAVEESTABLISHED(tp->t_state))
12682                         rsm->r_flags |= RACK_HAS_SYN;
12683                 rsm->r_start = tp->snd_una;
12684                 rsm->r_end = tp->snd_max;
12685                 rsm->r_dupack = 0;
12686                 if (rack->rc_inp->inp_socket->so_snd.sb_mb != NULL) {
12687                         rsm->m = sbsndmbuf(&rack->rc_inp->inp_socket->so_snd, 0, &rsm->soff);
12688                         if (rsm->m)
12689                                 rsm->orig_m_len = rsm->m->m_len;
12690                         else
12691                                 rsm->orig_m_len = 0;
12692                 } else {
12693                         /*
12694                          * This can happen if we have a stand-alone FIN or
12695                          *  SYN.
12696                          */
12697                         rsm->m = NULL;
12698                         rsm->orig_m_len = 0;
12699                         rsm->soff = 0;
12700                 }
12701 #ifndef INVARIANTS
12702                 (void)RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
12703 #else
12704                 insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
12705                 if (insret != NULL) {
12706                         panic("Insert in rb tree fails ret:%p rack:%p rsm:%p",
12707                               insret, rack, rsm);
12708                 }
12709 #endif
12710                 TAILQ_INSERT_TAIL(&rack->r_ctl.rc_tmap, rsm, r_tnext);
12711                 rsm->r_in_tmap = 1;
12712         }
12713         /*
12714          * Timers in Rack are kept in microseconds so lets
12715          * convert any initial incoming variables
12716          * from ticks into usecs. Note that we
12717          * also change the values of t_srtt and t_rttvar, if
12718          * they are non-zero. They are kept with a 5
12719          * bit decimal so we have to carefully convert
12720          * these to get the full precision.
12721          */
12722         rack_convert_rtts(tp);
12723         tp->t_rttlow = TICKS_2_USEC(tp->t_rttlow);
12724         if (rack_do_hystart) {
12725                 tp->ccv->flags |= CCF_HYSTART_ALLOWED;
12726                 if (rack_do_hystart > 1)
12727                         tp->ccv->flags |= CCF_HYSTART_CAN_SH_CWND;
12728                 if (rack_do_hystart > 2)
12729                         tp->ccv->flags |= CCF_HYSTART_CONS_SSTH;
12730         }
12731         if (rack_def_profile)
12732                 rack_set_profile(rack, rack_def_profile);
12733         /* Cancel the GP measurement in progress */
12734         tp->t_flags &= ~TF_GPUTINPROG;
12735         if (SEQ_GT(tp->snd_max, tp->iss))
12736                 snt = tp->snd_max - tp->iss;
12737         else
12738                 snt = 0;
12739         iwin = rc_init_window(rack);
12740         if (snt < iwin) {
12741                 /* We are not past the initial window
12742                  * so we need to make sure cwnd is
12743                  * correct.
12744                  */
12745                 if (tp->snd_cwnd < iwin)
12746                         tp->snd_cwnd = iwin;
12747                 /*
12748                  * If we are within the initial window
12749                  * we want ssthresh to be unlimited. Setting
12750                  * it to the rwnd (which the default stack does
12751                  * and older racks) is not really a good idea
12752                  * since we want to be in SS and grow both the
12753                  * cwnd and the rwnd (via dynamic rwnd growth). If
12754                  * we set it to the rwnd then as the peer grows its
12755                  * rwnd we will be stuck in CA and never hit SS.
12756                  *
12757                  * Its far better to raise it up high (this takes the
12758                  * risk that there as been a loss already, probably
12759                  * we should have an indicator in all stacks of loss
12760                  * but we don't), but considering the normal use this
12761                  * is a risk worth taking. The consequences of not
12762                  * hitting SS are far worse than going one more time
12763                  * into it early on (before we have sent even a IW).
12764                  * It is highly unlikely that we will have had a loss
12765                  * before getting the IW out.
12766                  */
12767                 tp->snd_ssthresh = 0xffffffff;
12768         }
12769         rack_stop_all_timers(tp);
12770         /* Lets setup the fsb block */
12771         rack_start_hpts_timer(rack, tp, tcp_get_usecs(NULL), 0, 0, 0);
12772         rack_log_rtt_shrinks(rack,  us_cts,  tp->t_rxtcur,
12773                              __LINE__, RACK_RTTS_INIT);
12774         return (0);
12775 }
12776
12777 static int
12778 rack_handoff_ok(struct tcpcb *tp)
12779 {
12780         if ((tp->t_state == TCPS_CLOSED) ||
12781             (tp->t_state == TCPS_LISTEN)) {
12782                 /* Sure no problem though it may not stick */
12783                 return (0);
12784         }
12785         if ((tp->t_state == TCPS_SYN_SENT) ||
12786             (tp->t_state == TCPS_SYN_RECEIVED)) {
12787                 /*
12788                  * We really don't know if you support sack,
12789                  * you have to get to ESTAB or beyond to tell.
12790                  */
12791                 return (EAGAIN);
12792         }
12793         if ((tp->t_flags & TF_SENTFIN) && ((tp->snd_max - tp->snd_una) > 1)) {
12794                 /*
12795                  * Rack will only send a FIN after all data is acknowledged.
12796                  * So in this case we have more data outstanding. We can't
12797                  * switch stacks until either all data and only the FIN
12798                  * is left (in which case rack_init() now knows how
12799                  * to deal with that) <or> all is acknowledged and we
12800                  * are only left with incoming data, though why you
12801                  * would want to switch to rack after all data is acknowledged
12802                  * I have no idea (rrs)!
12803                  */
12804                 return (EAGAIN);
12805         }
12806         if ((tp->t_flags & TF_SACK_PERMIT) || rack_sack_not_required){
12807                 return (0);
12808         }
12809         /*
12810          * If we reach here we don't do SACK on this connection so we can
12811          * never do rack.
12812          */
12813         return (EINVAL);
12814 }
12815
12816
12817 static void
12818 rack_fini(struct tcpcb *tp, int32_t tcb_is_purged)
12819 {
12820         struct inpcb *inp = tptoinpcb(tp);
12821
12822         if (tp->t_fb_ptr) {
12823                 struct tcp_rack *rack;
12824                 struct rack_sendmap *rsm, *nrsm;
12825 #ifdef INVARIANTS
12826                 struct rack_sendmap *rm;
12827 #endif
12828
12829                 rack = (struct tcp_rack *)tp->t_fb_ptr;
12830                 if (tp->t_in_pkt) {
12831                         /*
12832                          * It is unsafe to process the packets since a
12833                          * reset may be lurking in them (its rare but it
12834                          * can occur). If we were to find a RST, then we
12835                          * would end up dropping the connection and the
12836                          * INP lock, so when we return the caller (tcp_usrreq)
12837                          * will blow up when it trys to unlock the inp.
12838                          */
12839                         struct mbuf *save, *m;
12840
12841                         m = tp->t_in_pkt;
12842                         tp->t_in_pkt = NULL;
12843                         tp->t_tail_pkt = NULL;
12844                         while (m) {
12845                                 save = m->m_nextpkt;
12846                                 m->m_nextpkt = NULL;
12847                                 m_freem(m);
12848                                 m = save;
12849                         }
12850                 }
12851                 tp->t_flags &= ~TF_FORCEDATA;
12852 #ifdef NETFLIX_SHARED_CWND
12853                 if (rack->r_ctl.rc_scw) {
12854                         uint32_t limit;
12855
12856                         if (rack->r_limit_scw)
12857                                 limit = max(1, rack->r_ctl.rc_lowest_us_rtt);
12858                         else
12859                                 limit = 0;
12860                         tcp_shared_cwnd_free_full(tp, rack->r_ctl.rc_scw,
12861                                                   rack->r_ctl.rc_scw_index,
12862                                                   limit);
12863                         rack->r_ctl.rc_scw = NULL;
12864                 }
12865 #endif
12866                 if (rack->r_ctl.fsb.tcp_ip_hdr) {
12867                         free(rack->r_ctl.fsb.tcp_ip_hdr, M_TCPFSB);
12868                         rack->r_ctl.fsb.tcp_ip_hdr = NULL;
12869                         rack->r_ctl.fsb.th = NULL;
12870                 }
12871                 /* Convert back to ticks, with  */
12872                 if (tp->t_srtt > 1) {
12873                         uint32_t val, frac;
12874
12875                         val = USEC_2_TICKS(tp->t_srtt);
12876                         frac = tp->t_srtt % (HPTS_USEC_IN_SEC / hz);
12877                         tp->t_srtt = val << TCP_RTT_SHIFT;
12878                         /*
12879                          * frac is the fractional part here is left
12880                          * over from converting to hz and shifting.
12881                          * We need to convert this to the 5 bit
12882                          * remainder.
12883                          */
12884                         if (frac) {
12885                                 if (hz == 1000) {
12886                                         frac = (((uint64_t)frac *  (uint64_t)TCP_RTT_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC);
12887                                 } else {
12888                                         frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE) /(uint64_t)HPTS_USEC_IN_SEC);
12889                                 }
12890                                 tp->t_srtt += frac;
12891                         }
12892                 }
12893                 if (tp->t_rttvar) {
12894                         uint32_t val, frac;
12895
12896                         val = USEC_2_TICKS(tp->t_rttvar);
12897                         frac = tp->t_srtt % (HPTS_USEC_IN_SEC / hz);
12898                         tp->t_rttvar = val <<  TCP_RTTVAR_SHIFT;
12899                         /*
12900                          * frac is the fractional part here is left
12901                          * over from converting to hz and shifting.
12902                          * We need to convert this to the 5 bit
12903                          * remainder.
12904                          */
12905                         if (frac) {
12906                                 if (hz == 1000) {
12907                                         frac = (((uint64_t)frac *  (uint64_t)TCP_RTT_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC);
12908                                 } else {
12909                                         frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE) /(uint64_t)HPTS_USEC_IN_SEC);
12910                                 }
12911                                 tp->t_rttvar += frac;
12912                         }
12913                 }
12914                 tp->t_rxtcur = USEC_2_TICKS(tp->t_rxtcur);
12915                 tp->t_rttlow = USEC_2_TICKS(tp->t_rttlow);
12916                 if (rack->rc_always_pace) {
12917                         tcp_decrement_paced_conn();
12918                         rack_undo_cc_pacing(rack);
12919                         rack->rc_always_pace = 0;
12920                 }
12921                 /* Clean up any options if they were not applied */
12922                 while (!TAILQ_EMPTY(&rack->r_ctl.opt_list)) {
12923                         struct deferred_opt_list *dol;
12924
12925                         dol = TAILQ_FIRST(&rack->r_ctl.opt_list);
12926                         TAILQ_REMOVE(&rack->r_ctl.opt_list, dol, next);
12927                         free(dol, M_TCPDO);
12928                 }
12929                 /* rack does not use force data but other stacks may clear it */
12930                 if (rack->r_ctl.crte != NULL) {
12931                         tcp_rel_pacing_rate(rack->r_ctl.crte, tp);
12932                         rack->rack_hdrw_pacing = 0;
12933                         rack->r_ctl.crte = NULL;
12934                 }
12935 #ifdef TCP_BLACKBOX
12936                 tcp_log_flowend(tp);
12937 #endif
12938                 RB_FOREACH_SAFE(rsm, rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm) {
12939 #ifndef INVARIANTS
12940                         (void)RB_REMOVE(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
12941 #else
12942                         rm = RB_REMOVE(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
12943                         if (rm != rsm) {
12944                                 panic("At fini, rack:%p rsm:%p rm:%p",
12945                                       rack, rsm, rm);
12946                         }
12947 #endif
12948                         uma_zfree(rack_zone, rsm);
12949                 }
12950                 rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
12951                 while (rsm) {
12952                         TAILQ_REMOVE(&rack->r_ctl.rc_free, rsm, r_tnext);
12953                         uma_zfree(rack_zone, rsm);
12954                         rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
12955                 }
12956                 rack->rc_free_cnt = 0;
12957                 uma_zfree(rack_pcb_zone, tp->t_fb_ptr);
12958                 tp->t_fb_ptr = NULL;
12959         }
12960         inp->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
12961         inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
12962         inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
12963         inp->inp_flags2 &= ~INP_MBUF_ACKCMP;
12964         /* Cancel the GP measurement in progress */
12965         tp->t_flags &= ~TF_GPUTINPROG;
12966         inp->inp_flags2 &= ~INP_MBUF_L_ACKS;
12967         /* Make sure snd_nxt is correctly set */
12968         tp->snd_nxt = tp->snd_max;
12969 }
12970
12971 static void
12972 rack_set_state(struct tcpcb *tp, struct tcp_rack *rack)
12973 {
12974         if ((rack->r_state == TCPS_CLOSED) && (tp->t_state != TCPS_CLOSED)) {
12975                 rack->r_is_v6 = (tptoinpcb(tp)->inp_vflag & INP_IPV6) != 0;
12976         }
12977         switch (tp->t_state) {
12978         case TCPS_SYN_SENT:
12979                 rack->r_state = TCPS_SYN_SENT;
12980                 rack->r_substate = rack_do_syn_sent;
12981                 break;
12982         case TCPS_SYN_RECEIVED:
12983                 rack->r_state = TCPS_SYN_RECEIVED;
12984                 rack->r_substate = rack_do_syn_recv;
12985                 break;
12986         case TCPS_ESTABLISHED:
12987                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
12988                 rack->r_state = TCPS_ESTABLISHED;
12989                 rack->r_substate = rack_do_established;
12990                 break;
12991         case TCPS_CLOSE_WAIT:
12992                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
12993                 rack->r_state = TCPS_CLOSE_WAIT;
12994                 rack->r_substate = rack_do_close_wait;
12995                 break;
12996         case TCPS_FIN_WAIT_1:
12997                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
12998                 rack->r_state = TCPS_FIN_WAIT_1;
12999                 rack->r_substate = rack_do_fin_wait_1;
13000                 break;
13001         case TCPS_CLOSING:
13002                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
13003                 rack->r_state = TCPS_CLOSING;
13004                 rack->r_substate = rack_do_closing;
13005                 break;
13006         case TCPS_LAST_ACK:
13007                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
13008                 rack->r_state = TCPS_LAST_ACK;
13009                 rack->r_substate = rack_do_lastack;
13010                 break;
13011         case TCPS_FIN_WAIT_2:
13012                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
13013                 rack->r_state = TCPS_FIN_WAIT_2;
13014                 rack->r_substate = rack_do_fin_wait_2;
13015                 break;
13016         case TCPS_LISTEN:
13017         case TCPS_CLOSED:
13018         case TCPS_TIME_WAIT:
13019         default:
13020                 break;
13021         };
13022         if (rack->r_use_cmp_ack && TCPS_HAVEESTABLISHED(tp->t_state))
13023                 rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
13024
13025 }
13026
13027 static void
13028 rack_timer_audit(struct tcpcb *tp, struct tcp_rack *rack, struct sockbuf *sb)
13029 {
13030         /*
13031          * We received an ack, and then did not
13032          * call send or were bounced out due to the
13033          * hpts was running. Now a timer is up as well, is
13034          * it the right timer?
13035          */
13036         struct rack_sendmap *rsm;
13037         int tmr_up;
13038
13039         tmr_up = rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
13040         if (rack->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
13041                 return;
13042         rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
13043         if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
13044             (tmr_up == PACE_TMR_RXT)) {
13045                 /* Should be an RXT */
13046                 return;
13047         }
13048         if (rsm == NULL) {
13049                 /* Nothing outstanding? */
13050                 if (tp->t_flags & TF_DELACK) {
13051                         if (tmr_up == PACE_TMR_DELACK)
13052                                 /* We are supposed to have delayed ack up and we do */
13053                                 return;
13054                 } else if (sbavail(&tptosocket(tp)->so_snd) && (tmr_up == PACE_TMR_RXT)) {
13055                         /*
13056                          * if we hit enobufs then we would expect the possibility
13057                          * of nothing outstanding and the RXT up (and the hptsi timer).
13058                          */
13059                         return;
13060                 } else if (((V_tcp_always_keepalive ||
13061                              rack->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
13062                             (tp->t_state <= TCPS_CLOSING)) &&
13063                            (tmr_up == PACE_TMR_KEEP) &&
13064                            (tp->snd_max == tp->snd_una)) {
13065                         /* We should have keep alive up and we do */
13066                         return;
13067                 }
13068         }
13069         if (SEQ_GT(tp->snd_max, tp->snd_una) &&
13070                    ((tmr_up == PACE_TMR_TLP) ||
13071                     (tmr_up == PACE_TMR_RACK) ||
13072                     (tmr_up == PACE_TMR_RXT))) {
13073                 /*
13074                  * Either a Rack, TLP or RXT is fine if  we
13075                  * have outstanding data.
13076                  */
13077                 return;
13078         } else if (tmr_up == PACE_TMR_DELACK) {
13079                 /*
13080                  * If the delayed ack was going to go off
13081                  * before the rtx/tlp/rack timer were going to
13082                  * expire, then that would be the timer in control.
13083                  * Note we don't check the time here trusting the
13084                  * code is correct.
13085                  */
13086                 return;
13087         }
13088         /*
13089          * Ok the timer originally started is not what we want now.
13090          * We will force the hpts to be stopped if any, and restart
13091          * with the slot set to what was in the saved slot.
13092          */
13093         if (tcp_in_hpts(rack->rc_inp)) {
13094                 if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
13095                         uint32_t us_cts;
13096
13097                         us_cts = tcp_get_usecs(NULL);
13098                         if (TSTMP_GT(rack->r_ctl.rc_last_output_to, us_cts)) {
13099                                 rack->r_early = 1;
13100                                 rack->r_ctl.rc_agg_early += (rack->r_ctl.rc_last_output_to - us_cts);
13101                         }
13102                         rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
13103                 }
13104                 tcp_hpts_remove(rack->rc_inp);
13105         }
13106         rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
13107         rack_start_hpts_timer(rack, tp, tcp_get_usecs(NULL), 0, 0, 0);
13108 }
13109
13110
13111 static void
13112 rack_do_win_updates(struct tcpcb *tp, struct tcp_rack *rack, uint32_t tiwin, uint32_t seq, uint32_t ack, uint32_t cts, uint32_t high_seq)
13113 {
13114         if ((SEQ_LT(tp->snd_wl1, seq) ||
13115             (tp->snd_wl1 == seq && (SEQ_LT(tp->snd_wl2, ack) ||
13116             (tp->snd_wl2 == ack && tiwin > tp->snd_wnd))))) {
13117                 /* keep track of pure window updates */
13118                 if ((tp->snd_wl2 == ack) && (tiwin > tp->snd_wnd))
13119                         KMOD_TCPSTAT_INC(tcps_rcvwinupd);
13120                 tp->snd_wnd = tiwin;
13121                 rack_validate_fo_sendwin_up(tp, rack);
13122                 tp->snd_wl1 = seq;
13123                 tp->snd_wl2 = ack;
13124                 if (tp->snd_wnd > tp->max_sndwnd)
13125                         tp->max_sndwnd = tp->snd_wnd;
13126             rack->r_wanted_output = 1;
13127         } else if ((tp->snd_wl2 == ack) && (tiwin < tp->snd_wnd)) {
13128                 tp->snd_wnd = tiwin;
13129                 rack_validate_fo_sendwin_up(tp, rack);
13130                 tp->snd_wl1 = seq;
13131                 tp->snd_wl2 = ack;
13132         } else {
13133                 /* Not a valid win update */
13134                 return;
13135         }
13136         /* Do we exit persists? */
13137         if ((rack->rc_in_persist != 0) &&
13138             (tp->snd_wnd >= min((rack->r_ctl.rc_high_rwnd/2),
13139                                 rack->r_ctl.rc_pace_min_segs))) {
13140                 rack_exit_persist(tp, rack, cts);
13141         }
13142         /* Do we enter persists? */
13143         if ((rack->rc_in_persist == 0) &&
13144             (tp->snd_wnd < min((rack->r_ctl.rc_high_rwnd/2), rack->r_ctl.rc_pace_min_segs)) &&
13145             TCPS_HAVEESTABLISHED(tp->t_state) &&
13146             ((tp->snd_max == tp->snd_una) || rack->rc_has_collapsed) &&
13147             sbavail(&tptosocket(tp)->so_snd) &&
13148             (sbavail(&tptosocket(tp)->so_snd) > tp->snd_wnd)) {
13149                 /*
13150                  * Here the rwnd is less than
13151                  * the pacing size, we are established,
13152                  * nothing is outstanding, and there is
13153                  * data to send. Enter persists.
13154                  */
13155                 rack_enter_persist(tp, rack, rack->r_ctl.rc_rcvtime);
13156         }
13157 }
13158
13159 static void
13160 rack_log_input_packet(struct tcpcb *tp, struct tcp_rack *rack, struct tcp_ackent *ae, int ackval, uint32_t high_seq)
13161 {
13162
13163         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
13164                 struct inpcb *inp = tptoinpcb(tp);
13165                 union tcp_log_stackspecific log;
13166                 struct timeval ltv;
13167                 char tcp_hdr_buf[60];
13168                 struct tcphdr *th;
13169                 struct timespec ts;
13170                 uint32_t orig_snd_una;
13171                 uint8_t xx = 0;
13172
13173 #ifdef NETFLIX_HTTP_LOGGING
13174                 struct http_sendfile_track *http_req;
13175
13176                 if (SEQ_GT(ae->ack, tp->snd_una)) {
13177                         http_req = tcp_http_find_req_for_seq(tp, (ae->ack-1));
13178                 } else {
13179                         http_req = tcp_http_find_req_for_seq(tp, ae->ack);
13180                 }
13181 #endif
13182                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
13183                 log.u_bbr.inhpts = tcp_in_hpts(rack->rc_inp);
13184                 if (rack->rack_no_prr == 0)
13185                         log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
13186                 else
13187                         log.u_bbr.flex1 = 0;
13188                 log.u_bbr.use_lt_bw = rack->r_ent_rec_ns;
13189                 log.u_bbr.use_lt_bw <<= 1;
13190                 log.u_bbr.use_lt_bw |= rack->r_might_revert;
13191                 log.u_bbr.flex2 = rack->r_ctl.rc_num_maps_alloced;
13192                 log.u_bbr.inflight = ctf_flight_size(tp, rack->r_ctl.rc_sacked);
13193                 log.u_bbr.pkts_out = tp->t_maxseg;
13194                 log.u_bbr.flex4 = rack->r_ctl.rc_hpts_flags;
13195                 log.u_bbr.flex7 = 1;
13196                 log.u_bbr.lost = ae->flags;
13197                 log.u_bbr.cwnd_gain = ackval;
13198                 log.u_bbr.pacing_gain = 0x2;
13199                 if (ae->flags & TSTMP_HDWR) {
13200                         /* Record the hardware timestamp if present */
13201                         log.u_bbr.flex3 = M_TSTMP;
13202                         ts.tv_sec = ae->timestamp / 1000000000;
13203                         ts.tv_nsec = ae->timestamp % 1000000000;
13204                         ltv.tv_sec = ts.tv_sec;
13205                         ltv.tv_usec = ts.tv_nsec / 1000;
13206                         log.u_bbr.lt_epoch = tcp_tv_to_usectick(&ltv);
13207                 } else if (ae->flags & TSTMP_LRO) {
13208                         /* Record the LRO the arrival timestamp */
13209                         log.u_bbr.flex3 = M_TSTMP_LRO;
13210                         ts.tv_sec = ae->timestamp / 1000000000;
13211                         ts.tv_nsec = ae->timestamp % 1000000000;
13212                         ltv.tv_sec = ts.tv_sec;
13213                         ltv.tv_usec = ts.tv_nsec / 1000;
13214                         log.u_bbr.flex5 = tcp_tv_to_usectick(&ltv);
13215                 }
13216                 log.u_bbr.timeStamp = tcp_get_usecs(&ltv);
13217                 /* Log the rcv time */
13218                 log.u_bbr.delRate = ae->timestamp;
13219 #ifdef NETFLIX_HTTP_LOGGING
13220                 log.u_bbr.applimited = tp->t_http_closed;
13221                 log.u_bbr.applimited <<= 8;
13222                 log.u_bbr.applimited |= tp->t_http_open;
13223                 log.u_bbr.applimited <<= 8;
13224                 log.u_bbr.applimited |= tp->t_http_req;
13225                 if (http_req) {
13226                         /* Copy out any client req info */
13227                         /* seconds */
13228                         log.u_bbr.pkt_epoch = (http_req->localtime / HPTS_USEC_IN_SEC);
13229                         /* useconds */
13230                         log.u_bbr.delivered = (http_req->localtime % HPTS_USEC_IN_SEC);
13231                         log.u_bbr.rttProp = http_req->timestamp;
13232                         log.u_bbr.cur_del_rate = http_req->start;
13233                         if (http_req->flags & TCP_HTTP_TRACK_FLG_OPEN) {
13234                                 log.u_bbr.flex8 |= 1;
13235                         } else {
13236                                 log.u_bbr.flex8 |= 2;
13237                                 log.u_bbr.bw_inuse = http_req->end;
13238                         }
13239                         log.u_bbr.flex6 = http_req->start_seq;
13240                         if (http_req->flags & TCP_HTTP_TRACK_FLG_COMP) {
13241                                 log.u_bbr.flex8 |= 4;
13242                                 log.u_bbr.epoch = http_req->end_seq;
13243                         }
13244                 }
13245 #endif
13246                 memset(tcp_hdr_buf, 0, sizeof(tcp_hdr_buf));
13247                 th = (struct tcphdr *)tcp_hdr_buf;
13248                 th->th_seq = ae->seq;
13249                 th->th_ack = ae->ack;
13250                 th->th_win = ae->win;
13251                 /* Now fill in the ports */
13252                 th->th_sport = inp->inp_fport;
13253                 th->th_dport = inp->inp_lport;
13254                 tcp_set_flags(th, ae->flags);
13255                 /* Now do we have a timestamp option? */
13256                 if (ae->flags & HAS_TSTMP) {
13257                         u_char *cp;
13258                         uint32_t val;
13259
13260                         th->th_off = ((sizeof(struct tcphdr) + TCPOLEN_TSTAMP_APPA) >> 2);
13261                         cp = (u_char *)(th + 1);
13262                         *cp = TCPOPT_NOP;
13263                         cp++;
13264                         *cp = TCPOPT_NOP;
13265                         cp++;
13266                         *cp = TCPOPT_TIMESTAMP;
13267                         cp++;
13268                         *cp = TCPOLEN_TIMESTAMP;
13269                         cp++;
13270                         val = htonl(ae->ts_value);
13271                         bcopy((char *)&val,
13272                               (char *)cp, sizeof(uint32_t));
13273                         val = htonl(ae->ts_echo);
13274                         bcopy((char *)&val,
13275                               (char *)(cp + 4), sizeof(uint32_t));
13276                 } else
13277                         th->th_off = (sizeof(struct tcphdr) >> 2);
13278
13279                 /*
13280                  * For sane logging we need to play a little trick.
13281                  * If the ack were fully processed we would have moved
13282                  * snd_una to high_seq, but since compressed acks are
13283                  * processed in two phases, at this point (logging) snd_una
13284                  * won't be advanced. So we would see multiple acks showing
13285                  * the advancement. We can prevent that by "pretending" that
13286                  * snd_una was advanced and then un-advancing it so that the
13287                  * logging code has the right value for tlb_snd_una.
13288                  */
13289                 if (tp->snd_una != high_seq) {
13290                         orig_snd_una = tp->snd_una;
13291                         tp->snd_una = high_seq;
13292                         xx = 1;
13293                 } else
13294                         xx = 0;
13295                 TCP_LOG_EVENTP(tp, th,
13296                                &tptosocket(tp)->so_rcv,
13297                                &tptosocket(tp)->so_snd, TCP_LOG_IN, 0,
13298                                0, &log, true, &ltv);
13299                 if (xx) {
13300                         tp->snd_una = orig_snd_una;
13301                 }
13302         }
13303
13304 }
13305
13306 static void
13307 rack_handle_probe_response(struct tcp_rack *rack, uint32_t tiwin, uint32_t us_cts)
13308 {
13309         uint32_t us_rtt;
13310         /*
13311          * A persist or keep-alive was forced out, update our
13312          * min rtt time. Note now worry about lost responses.
13313          * When a subsequent keep-alive or persist times out
13314          * and forced_ack is still on, then the last probe
13315          * was not responded to. In such cases we have a
13316          * sysctl that controls the behavior. Either we apply
13317          * the rtt but with reduced confidence (0). Or we just
13318          * plain don't apply the rtt estimate. Having data flow
13319          * will clear the probe_not_answered flag i.e. cum-ack
13320          * move forward <or> exiting and reentering persists.
13321          */
13322
13323         rack->forced_ack = 0;
13324         rack->rc_tp->t_rxtshift = 0;
13325         if ((rack->rc_in_persist &&
13326              (tiwin == rack->rc_tp->snd_wnd)) ||
13327             (rack->rc_in_persist == 0)) {
13328                 /*
13329                  * In persists only apply the RTT update if this is
13330                  * a response to our window probe. And that
13331                  * means the rwnd sent must match the current
13332                  * snd_wnd. If it does not, then we got a
13333                  * window update ack instead. For keepalive
13334                  * we allow the answer no matter what the window.
13335                  *
13336                  * Note that if the probe_not_answered is set then
13337                  * the forced_ack_ts is the oldest one i.e. the first
13338                  * probe sent that might have been lost. This assures
13339                  * us that if we do calculate an RTT it is longer not
13340                  * some short thing.
13341                  */
13342                 if (rack->rc_in_persist)
13343                         counter_u64_add(rack_persists_acks, 1);
13344                 us_rtt = us_cts - rack->r_ctl.forced_ack_ts;
13345                 if (us_rtt == 0)
13346                         us_rtt = 1;
13347                 if (rack->probe_not_answered == 0) {
13348                         rack_apply_updated_usrtt(rack, us_rtt, us_cts);
13349                         tcp_rack_xmit_timer(rack, us_rtt, 0, us_rtt, 3, NULL, 1);
13350                 } else {
13351                         /* We have a retransmitted probe here too */
13352                         if (rack_apply_rtt_with_reduced_conf) {
13353                                 rack_apply_updated_usrtt(rack, us_rtt, us_cts);
13354                                 tcp_rack_xmit_timer(rack, us_rtt, 0, us_rtt, 0, NULL, 1);
13355                         }
13356                 }
13357         }
13358 }
13359
13360 static int
13361 rack_do_compressed_ack_processing(struct tcpcb *tp, struct socket *so, struct mbuf *m, int nxt_pkt, struct timeval *tv)
13362 {
13363         /*
13364          * Handle a "special" compressed ack mbuf. Each incoming
13365          * ack has only four possible dispositions:
13366          *
13367          * A) It moves the cum-ack forward
13368          * B) It is behind the cum-ack.
13369          * C) It is a window-update ack.
13370          * D) It is a dup-ack.
13371          *
13372          * Note that we can have between 1 -> TCP_COMP_ACK_ENTRIES
13373          * in the incoming mbuf. We also need to still pay attention
13374          * to nxt_pkt since there may be another packet after this
13375          * one.
13376          */
13377 #ifdef TCP_ACCOUNTING
13378         uint64_t ts_val;
13379         uint64_t rdstc;
13380 #endif
13381         int segsiz;
13382         struct timespec ts;
13383         struct tcp_rack *rack;
13384         struct tcp_ackent *ae;
13385         uint32_t tiwin, ms_cts, cts, acked, acked_amount, high_seq, win_seq, the_win, win_upd_ack;
13386         int cnt, i, did_out, ourfinisacked = 0;
13387         struct tcpopt to_holder, *to = NULL;
13388 #ifdef TCP_ACCOUNTING
13389         int win_up_req = 0;
13390 #endif
13391         int nsegs = 0;
13392         int under_pacing = 1;
13393         int recovery = 0;
13394 #ifdef TCP_ACCOUNTING
13395         sched_pin();
13396 #endif
13397         rack = (struct tcp_rack *)tp->t_fb_ptr;
13398         if (rack->gp_ready &&
13399             (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT))
13400                 under_pacing = 0;
13401         else
13402                 under_pacing = 1;
13403
13404         if (rack->r_state != tp->t_state)
13405                 rack_set_state(tp, rack);
13406         if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
13407             (tp->t_flags & TF_GPUTINPROG)) {
13408                 /*
13409                  * We have a goodput in progress
13410                  * and we have entered a late state.
13411                  * Do we have enough data in the sb
13412                  * to handle the GPUT request?
13413                  */
13414                 uint32_t bytes;
13415
13416                 bytes = tp->gput_ack - tp->gput_seq;
13417                 if (SEQ_GT(tp->gput_seq, tp->snd_una))
13418                         bytes += tp->gput_seq - tp->snd_una;
13419                 if (bytes > sbavail(&tptosocket(tp)->so_snd)) {
13420                         /*
13421                          * There are not enough bytes in the socket
13422                          * buffer that have been sent to cover this
13423                          * measurement. Cancel it.
13424                          */
13425                         rack_log_pacing_delay_calc(rack, (tp->gput_ack - tp->gput_seq) /*flex2*/,
13426                                                    rack->r_ctl.rc_gp_srtt /*flex1*/,
13427                                                    tp->gput_seq,
13428                                                    0, 0, 18, __LINE__, NULL, 0);
13429                         tp->t_flags &= ~TF_GPUTINPROG;
13430                 }
13431         }
13432         to = &to_holder;
13433         to->to_flags = 0;
13434         KASSERT((m->m_len >= sizeof(struct tcp_ackent)),
13435                 ("tp:%p m_cmpack:%p with invalid len:%u", tp, m, m->m_len));
13436         cnt = m->m_len / sizeof(struct tcp_ackent);
13437         counter_u64_add(rack_multi_single_eq, cnt);
13438         high_seq = tp->snd_una;
13439         the_win = tp->snd_wnd;
13440         win_seq = tp->snd_wl1;
13441         win_upd_ack = tp->snd_wl2;
13442         cts = tcp_tv_to_usectick(tv);
13443         ms_cts = tcp_tv_to_mssectick(tv);
13444         rack->r_ctl.rc_rcvtime = cts;
13445         segsiz = ctf_fixed_maxseg(tp);
13446         if ((rack->rc_gp_dyn_mul) &&
13447             (rack->use_fixed_rate == 0) &&
13448             (rack->rc_always_pace)) {
13449                 /* Check in on probertt */
13450                 rack_check_probe_rtt(rack, cts);
13451         }
13452         for (i = 0; i < cnt; i++) {
13453 #ifdef TCP_ACCOUNTING
13454                 ts_val = get_cyclecount();
13455 #endif
13456                 rack_clear_rate_sample(rack);
13457                 ae = ((mtod(m, struct tcp_ackent *)) + i);
13458                 /* Setup the window */
13459                 tiwin = ae->win << tp->snd_scale;
13460                 if (tiwin > rack->r_ctl.rc_high_rwnd)
13461                         rack->r_ctl.rc_high_rwnd = tiwin;
13462                 /* figure out the type of ack */
13463                 if (SEQ_LT(ae->ack, high_seq)) {
13464                         /* Case B*/
13465                         ae->ack_val_set = ACK_BEHIND;
13466                 } else if (SEQ_GT(ae->ack, high_seq)) {
13467                         /* Case A */
13468                         ae->ack_val_set = ACK_CUMACK;
13469                 } else if ((tiwin == the_win) && (rack->rc_in_persist == 0)){
13470                         /* Case D */
13471                         ae->ack_val_set = ACK_DUPACK;
13472                 } else {
13473                         /* Case C */
13474                         ae->ack_val_set = ACK_RWND;
13475                 }
13476                 rack_log_input_packet(tp, rack, ae, ae->ack_val_set, high_seq);
13477                 /* Validate timestamp */
13478                 if (ae->flags & HAS_TSTMP) {
13479                         /* Setup for a timestamp */
13480                         to->to_flags = TOF_TS;
13481                         ae->ts_echo -= tp->ts_offset;
13482                         to->to_tsecr = ae->ts_echo;
13483                         to->to_tsval = ae->ts_value;
13484                         /*
13485                          * If echoed timestamp is later than the current time, fall back to
13486                          * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
13487                          * were used when this connection was established.
13488                          */
13489                         if (TSTMP_GT(ae->ts_echo, ms_cts))
13490                                 to->to_tsecr = 0;
13491                         if (tp->ts_recent &&
13492                             TSTMP_LT(ae->ts_value, tp->ts_recent)) {
13493                                 if (ctf_ts_check_ac(tp, (ae->flags & 0xff))) {
13494 #ifdef TCP_ACCOUNTING
13495                                         rdstc = get_cyclecount();
13496                                         if (rdstc > ts_val) {
13497                                                 counter_u64_add(tcp_proc_time[ae->ack_val_set] ,
13498                                                                 (rdstc - ts_val));
13499                                                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13500                                                         tp->tcp_proc_time[ae->ack_val_set] += (rdstc - ts_val);
13501                                                 }
13502                                         }
13503 #endif
13504                                         continue;
13505                                 }
13506                         }
13507                         if (SEQ_LEQ(ae->seq, tp->last_ack_sent) &&
13508                             SEQ_LEQ(tp->last_ack_sent, ae->seq)) {
13509                                 tp->ts_recent_age = tcp_ts_getticks();
13510                                 tp->ts_recent = ae->ts_value;
13511                         }
13512                 } else {
13513                         /* Setup for a no options */
13514                         to->to_flags = 0;
13515                 }
13516                 /* Update the rcv time and perform idle reduction possibly */
13517                 if  (tp->t_idle_reduce &&
13518                      (tp->snd_max == tp->snd_una) &&
13519                      (TICKS_2_USEC(ticks - tp->t_rcvtime) >= tp->t_rxtcur)) {
13520                         counter_u64_add(rack_input_idle_reduces, 1);
13521                         rack_cc_after_idle(rack, tp);
13522                 }
13523                 tp->t_rcvtime = ticks;
13524                 /* Now what about ECN of a chain of pure ACKs? */
13525                 if (tcp_ecn_input_segment(tp, ae->flags, 0,
13526                         tcp_packets_this_ack(tp, ae->ack),
13527                         ae->codepoint))
13528                         rack_cong_signal(tp, CC_ECN, ae->ack, __LINE__);
13529 #ifdef TCP_ACCOUNTING
13530                 /* Count for the specific type of ack in */
13531                 counter_u64_add(tcp_cnt_counters[ae->ack_val_set], 1);
13532                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13533                         tp->tcp_cnt_counters[ae->ack_val_set]++;
13534                 }
13535 #endif
13536                 /*
13537                  * Note how we could move up these in the determination
13538                  * above, but we don't so that way the timestamp checks (and ECN)
13539                  * is done first before we do any processing on the ACK.
13540                  * The non-compressed path through the code has this
13541                  * weakness (noted by @jtl) that it actually does some
13542                  * processing before verifying the timestamp information.
13543                  * We don't take that path here which is why we set
13544                  * the ack_val_set first, do the timestamp and ecn
13545                  * processing, and then look at what we have setup.
13546                  */
13547                 if (ae->ack_val_set == ACK_BEHIND) {
13548                         /*
13549                          * Case B flag reordering, if window is not closed
13550                          * or it could be a keep-alive or persists
13551                          */
13552                         if (SEQ_LT(ae->ack, tp->snd_una) && (sbspace(&so->so_rcv) > segsiz)) {
13553                                 rack->r_ctl.rc_reorder_ts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
13554                         }
13555                 } else if (ae->ack_val_set == ACK_DUPACK) {
13556                         /* Case D */
13557                         rack_strike_dupack(rack);
13558                 } else if (ae->ack_val_set == ACK_RWND) {
13559                         /* Case C */
13560                         if ((ae->flags & TSTMP_LRO) || (ae->flags & TSTMP_HDWR)) {
13561                                 ts.tv_sec = ae->timestamp / 1000000000;
13562                                 ts.tv_nsec = ae->timestamp % 1000000000;
13563                                 rack->r_ctl.act_rcv_time.tv_sec = ts.tv_sec;
13564                                 rack->r_ctl.act_rcv_time.tv_usec = ts.tv_nsec/1000;
13565                         } else {
13566                                 rack->r_ctl.act_rcv_time = *tv;
13567                         }
13568                         if (rack->forced_ack) {
13569                                 rack_handle_probe_response(rack, tiwin,
13570                                                            tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time));
13571                         }
13572 #ifdef TCP_ACCOUNTING
13573                         win_up_req = 1;
13574 #endif
13575                         win_upd_ack = ae->ack;
13576                         win_seq = ae->seq;
13577                         the_win = tiwin;
13578                         rack_do_win_updates(tp, rack, the_win, win_seq, win_upd_ack, cts, high_seq);
13579                 } else {
13580                         /* Case A */
13581                         if (SEQ_GT(ae->ack, tp->snd_max)) {
13582                                 /*
13583                                  * We just send an ack since the incoming
13584                                  * ack is beyond the largest seq we sent.
13585                                  */
13586                                 if ((tp->t_flags & TF_ACKNOW) == 0) {
13587                                         ctf_ack_war_checks(tp, &rack->r_ctl.challenge_ack_ts, &rack->r_ctl.challenge_ack_cnt);
13588                                         if (tp->t_flags && TF_ACKNOW)
13589                                                 rack->r_wanted_output = 1;
13590                                 }
13591                         } else {
13592                                 nsegs++;
13593                                 /* If the window changed setup to update */
13594                                 if (tiwin != tp->snd_wnd) {
13595                                         win_upd_ack = ae->ack;
13596                                         win_seq = ae->seq;
13597                                         the_win = tiwin;
13598                                         rack_do_win_updates(tp, rack, the_win, win_seq, win_upd_ack, cts, high_seq);
13599                                 }
13600 #ifdef TCP_ACCOUNTING
13601                                 /* Account for the acks */
13602                                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13603                                         tp->tcp_cnt_counters[CNT_OF_ACKS_IN] += (((ae->ack - high_seq) + segsiz - 1) / segsiz);
13604                                 }
13605                                 counter_u64_add(tcp_cnt_counters[CNT_OF_ACKS_IN],
13606                                                 (((ae->ack - high_seq) + segsiz - 1) / segsiz));
13607 #endif
13608                                 high_seq = ae->ack;
13609                                 if (rack_verbose_logging && (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
13610                                         union tcp_log_stackspecific log;
13611                                         struct timeval tv;
13612
13613                                         memset(&log.u_bbr, 0, sizeof(log.u_bbr));
13614                                         log.u_bbr.timeStamp = tcp_get_usecs(&tv);
13615                                         log.u_bbr.flex1 = high_seq;
13616                                         log.u_bbr.flex2 = rack->r_ctl.roundends;
13617                                         log.u_bbr.flex3 = rack->r_ctl.current_round;
13618                                         log.u_bbr.rttProp = (uint64_t)CC_ALGO(tp)->newround;
13619                                         log.u_bbr.flex8 = 8;
13620                                         tcp_log_event_(tp, NULL, NULL, NULL, BBR_LOG_CWND, 0,
13621                                                        0, &log, false, NULL, NULL, 0, &tv);
13622                                 }
13623                                 /*
13624                                  * The draft (v3) calls for us to use SEQ_GEQ, but that
13625                                  * causes issues when we are just going app limited. Lets
13626                                  * instead use SEQ_GT <or> where its equal but more data
13627                                  * is outstanding.
13628                                  */
13629                                 if ((SEQ_GT(high_seq, rack->r_ctl.roundends)) ||
13630                                     ((high_seq == rack->r_ctl.roundends) &&
13631                                      SEQ_GT(tp->snd_max, tp->snd_una))) {
13632                                         rack->r_ctl.current_round++;
13633                                         rack->r_ctl.roundends = tp->snd_max;
13634                                         if (CC_ALGO(tp)->newround != NULL) {
13635                                                 CC_ALGO(tp)->newround(tp->ccv, rack->r_ctl.current_round);
13636                                         }
13637                                 }
13638                                 /* Setup our act_rcv_time */
13639                                 if ((ae->flags & TSTMP_LRO) || (ae->flags & TSTMP_HDWR)) {
13640                                         ts.tv_sec = ae->timestamp / 1000000000;
13641                                         ts.tv_nsec = ae->timestamp % 1000000000;
13642                                         rack->r_ctl.act_rcv_time.tv_sec = ts.tv_sec;
13643                                         rack->r_ctl.act_rcv_time.tv_usec = ts.tv_nsec/1000;
13644                                 } else {
13645                                         rack->r_ctl.act_rcv_time = *tv;
13646                                 }
13647                                 rack_process_to_cumack(tp, rack, ae->ack, cts, to);
13648                                 if (rack->rc_dsack_round_seen) {
13649                                         /* Is the dsack round over? */
13650                                         if (SEQ_GEQ(ae->ack, rack->r_ctl.dsack_round_end)) {
13651                                                 /* Yes it is */
13652                                                 rack->rc_dsack_round_seen = 0;
13653                                                 rack_log_dsack_event(rack, 3, __LINE__, 0, 0);
13654                                         }
13655                                 }
13656                         }
13657                 }
13658                 /* And lets be sure to commit the rtt measurements for this ack */
13659                 tcp_rack_xmit_timer_commit(rack, tp);
13660 #ifdef TCP_ACCOUNTING
13661                 rdstc = get_cyclecount();
13662                 if (rdstc > ts_val) {
13663                         counter_u64_add(tcp_proc_time[ae->ack_val_set] , (rdstc - ts_val));
13664                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13665                                 tp->tcp_proc_time[ae->ack_val_set] += (rdstc - ts_val);
13666                                 if (ae->ack_val_set == ACK_CUMACK)
13667                                         tp->tcp_proc_time[CYC_HANDLE_MAP] += (rdstc - ts_val);
13668                         }
13669                 }
13670 #endif
13671         }
13672 #ifdef TCP_ACCOUNTING
13673         ts_val = get_cyclecount();
13674 #endif
13675         /* Tend to any collapsed window */
13676         if (SEQ_GT(tp->snd_max, high_seq) && (tp->snd_wnd < (tp->snd_max - high_seq))) {
13677                 /* The peer collapsed the window */
13678                 rack_collapsed_window(rack, (tp->snd_max - high_seq), __LINE__);
13679         } else if (rack->rc_has_collapsed)
13680                 rack_un_collapse_window(rack, __LINE__);
13681         if ((rack->r_collapse_point_valid) &&
13682             (SEQ_GT(high_seq, rack->r_ctl.high_collapse_point)))
13683                 rack->r_collapse_point_valid = 0;
13684         acked_amount = acked = (high_seq - tp->snd_una);
13685         if (acked) {
13686                 /*
13687                  * Clear the probe not answered flag
13688                  * since cum-ack moved forward.
13689                  */
13690                 rack->probe_not_answered = 0;
13691                 if (rack->sack_attack_disable == 0)
13692                         rack_do_decay(rack);
13693                 if (acked >= segsiz) {
13694                         /*
13695                          * You only get credit for
13696                          * MSS and greater (and you get extra
13697                          * credit for larger cum-ack moves).
13698                          */
13699                         int ac;
13700
13701                         ac = acked / segsiz;
13702                         rack->r_ctl.ack_count += ac;
13703                         counter_u64_add(rack_ack_total, ac);
13704                 }
13705                 if (rack->r_ctl.ack_count > 0xfff00000) {
13706                         /*
13707                          * reduce the number to keep us under
13708                          * a uint32_t.
13709                          */
13710                         rack->r_ctl.ack_count /= 2;
13711                         rack->r_ctl.sack_count /= 2;
13712                 }
13713                 if (tp->t_flags & TF_NEEDSYN) {
13714                         /*
13715                          * T/TCP: Connection was half-synchronized, and our SYN has
13716                          * been ACK'd (so connection is now fully synchronized).  Go
13717                          * to non-starred state, increment snd_una for ACK of SYN,
13718                          * and check if we can do window scaling.
13719                          */
13720                         tp->t_flags &= ~TF_NEEDSYN;
13721                         tp->snd_una++;
13722                         acked_amount = acked = (high_seq - tp->snd_una);
13723                 }
13724                 if (acked > sbavail(&so->so_snd))
13725                         acked_amount = sbavail(&so->so_snd);
13726 #ifdef NETFLIX_EXP_DETECTION
13727                 /*
13728                  * We only care on a cum-ack move if we are in a sack-disabled
13729                  * state. We have already added in to the ack_count, and we never
13730                  * would disable on a cum-ack move, so we only care to do the
13731                  * detection if it may "undo" it, i.e. we were in disabled already.
13732                  */
13733                 if (rack->sack_attack_disable)
13734                         rack_do_detection(tp, rack, acked_amount, segsiz);
13735 #endif
13736                 if (IN_FASTRECOVERY(tp->t_flags) &&
13737                     (rack->rack_no_prr == 0))
13738                         rack_update_prr(tp, rack, acked_amount, high_seq);
13739                 if (IN_RECOVERY(tp->t_flags)) {
13740                         if (SEQ_LT(high_seq, tp->snd_recover) &&
13741                             (SEQ_LT(high_seq, tp->snd_max))) {
13742                                 tcp_rack_partialack(tp);
13743                         } else {
13744                                 rack_post_recovery(tp, high_seq);
13745                                 recovery = 1;
13746                         }
13747                 }
13748                 /* Handle the rack-log-ack part (sendmap) */
13749                 if ((sbused(&so->so_snd) == 0) &&
13750                     (acked > acked_amount) &&
13751                     (tp->t_state >= TCPS_FIN_WAIT_1) &&
13752                     (tp->t_flags & TF_SENTFIN)) {
13753                         /*
13754                          * We must be sure our fin
13755                          * was sent and acked (we can be
13756                          * in FIN_WAIT_1 without having
13757                          * sent the fin).
13758                          */
13759                         ourfinisacked = 1;
13760                         /*
13761                          * Lets make sure snd_una is updated
13762                          * since most likely acked_amount = 0 (it
13763                          * should be).
13764                          */
13765                         tp->snd_una = high_seq;
13766                 }
13767                 /* Did we make a RTO error? */
13768                 if ((tp->t_flags & TF_PREVVALID) &&
13769                     ((tp->t_flags & TF_RCVD_TSTMP) == 0)) {
13770                         tp->t_flags &= ~TF_PREVVALID;
13771                         if (tp->t_rxtshift == 1 &&
13772                             (int)(ticks - tp->t_badrxtwin) < 0)
13773                                 rack_cong_signal(tp, CC_RTO_ERR, high_seq, __LINE__);
13774                 }
13775                 /* Handle the data in the socket buffer */
13776                 KMOD_TCPSTAT_ADD(tcps_rcvackpack, 1);
13777                 KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
13778                 if (acked_amount > 0) {
13779                         struct mbuf *mfree;
13780
13781                         rack_ack_received(tp, rack, high_seq, nsegs, CC_ACK, recovery);
13782                         SOCKBUF_LOCK(&so->so_snd);
13783                         mfree = sbcut_locked(&so->so_snd, acked_amount);
13784                         tp->snd_una = high_seq;
13785                         /* Note we want to hold the sb lock through the sendmap adjust */
13786                         rack_adjust_sendmap(rack, &so->so_snd, tp->snd_una);
13787                         /* Wake up the socket if we have room to write more */
13788                         rack_log_wakeup(tp,rack, &so->so_snd, acked, 2);
13789                         sowwakeup_locked(so);
13790                         m_freem(mfree);
13791                 }
13792                 /* update progress */
13793                 tp->t_acktime = ticks;
13794                 rack_log_progress_event(rack, tp, tp->t_acktime,
13795                                         PROGRESS_UPDATE, __LINE__);
13796                 /* Clear out shifts and such */
13797                 tp->t_rxtshift = 0;
13798                 RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
13799                                    rack_rto_min, rack_rto_max, rack->r_ctl.timer_slop);
13800                 rack->rc_tlp_in_progress = 0;
13801                 rack->r_ctl.rc_tlp_cnt_out = 0;
13802                 /* Send recover and snd_nxt must be dragged along */
13803                 if (SEQ_GT(tp->snd_una, tp->snd_recover))
13804                         tp->snd_recover = tp->snd_una;
13805                 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
13806                         tp->snd_nxt = tp->snd_una;
13807                 /*
13808                  * If the RXT timer is running we want to
13809                  * stop it, so we can restart a TLP (or new RXT).
13810                  */
13811                 if (rack->r_ctl.rc_hpts_flags & PACE_TMR_RXT)
13812                         rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
13813 #ifdef NETFLIX_HTTP_LOGGING
13814                 tcp_http_check_for_comp(rack->rc_tp, high_seq);
13815 #endif
13816                 tp->snd_wl2 = high_seq;
13817                 tp->t_dupacks = 0;
13818                 if (under_pacing &&
13819                     (rack->use_fixed_rate == 0) &&
13820                     (rack->in_probe_rtt == 0) &&
13821                     rack->rc_gp_dyn_mul &&
13822                     rack->rc_always_pace) {
13823                         /* Check if we are dragging bottom */
13824                         rack_check_bottom_drag(tp, rack, so, acked);
13825                 }
13826                 if (tp->snd_una == tp->snd_max) {
13827                         tp->t_flags &= ~TF_PREVVALID;
13828                         rack->r_ctl.retran_during_recovery = 0;
13829                         rack->r_ctl.dsack_byte_cnt = 0;
13830                         rack->r_ctl.rc_went_idle_time = tcp_get_usecs(NULL);
13831                         if (rack->r_ctl.rc_went_idle_time == 0)
13832                                 rack->r_ctl.rc_went_idle_time = 1;
13833                         rack_log_progress_event(rack, tp, 0, PROGRESS_CLEAR, __LINE__);
13834                         if (sbavail(&tptosocket(tp)->so_snd) == 0)
13835                                 tp->t_acktime = 0;
13836                         /* Set so we might enter persists... */
13837                         rack->r_wanted_output = 1;
13838                         rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
13839                         sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
13840                         if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
13841                             (sbavail(&so->so_snd) == 0) &&
13842                             (tp->t_flags2 & TF2_DROP_AF_DATA)) {
13843                                 /*
13844                                  * The socket was gone and the
13845                                  * peer sent data (not now in the past), time to
13846                                  * reset him.
13847                                  */
13848                                 rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
13849                                 /* tcp_close will kill the inp pre-log the Reset */
13850                                 tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
13851 #ifdef TCP_ACCOUNTING
13852                                 rdstc = get_cyclecount();
13853                                 if (rdstc > ts_val) {
13854                                         counter_u64_add(tcp_proc_time[ACK_CUMACK] , (rdstc - ts_val));
13855                                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13856                                                 tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13857                                                 tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13858                                         }
13859                                 }
13860 #endif
13861                                 m_freem(m);
13862                                 tp = tcp_close(tp);
13863                                 if (tp == NULL) {
13864 #ifdef TCP_ACCOUNTING
13865                                         sched_unpin();
13866 #endif
13867                                         return (1);
13868                                 }
13869                                 /*
13870                                  * We would normally do drop-with-reset which would
13871                                  * send back a reset. We can't since we don't have
13872                                  * all the needed bits. Instead lets arrange for
13873                                  * a call to tcp_output(). That way since we
13874                                  * are in the closed state we will generate a reset.
13875                                  *
13876                                  * Note if tcp_accounting is on we don't unpin since
13877                                  * we do that after the goto label.
13878                                  */
13879                                 goto send_out_a_rst;
13880                         }
13881                         if ((sbused(&so->so_snd) == 0) &&
13882                             (tp->t_state >= TCPS_FIN_WAIT_1) &&
13883                             (tp->t_flags & TF_SENTFIN)) {
13884                                 /*
13885                                  * If we can't receive any more data, then closing user can
13886                                  * proceed. Starting the timer is contrary to the
13887                                  * specification, but if we don't get a FIN we'll hang
13888                                  * forever.
13889                                  *
13890                                  */
13891                                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
13892                                         soisdisconnected(so);
13893                                         tcp_timer_activate(tp, TT_2MSL,
13894                                                            (tcp_fast_finwait2_recycle ?
13895                                                             tcp_finwait2_timeout :
13896                                                             TP_MAXIDLE(tp)));
13897                                 }
13898                                 if (ourfinisacked == 0) {
13899                                         /*
13900                                          * We don't change to fin-wait-2 if we have our fin acked
13901                                          * which means we are probably in TCPS_CLOSING.
13902                                          */
13903                                         tcp_state_change(tp, TCPS_FIN_WAIT_2);
13904                                 }
13905                         }
13906                 }
13907                 /* Wake up the socket if we have room to write more */
13908                 if (sbavail(&so->so_snd)) {
13909                         rack->r_wanted_output = 1;
13910                         if (ctf_progress_timeout_check(tp, true)) {
13911                                 rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
13912                                                         tp, tick, PROGRESS_DROP, __LINE__);
13913                                 /*
13914                                  * We cheat here and don't send a RST, we should send one
13915                                  * when the pacer drops the connection.
13916                                  */
13917 #ifdef TCP_ACCOUNTING
13918                                 rdstc = get_cyclecount();
13919                                 if (rdstc > ts_val) {
13920                                         counter_u64_add(tcp_proc_time[ACK_CUMACK] , (rdstc - ts_val));
13921                                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13922                                                 tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13923                                                 tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13924                                         }
13925                                 }
13926                                 sched_unpin();
13927 #endif
13928                                 (void)tcp_drop(tp, ETIMEDOUT);
13929                                 m_freem(m);
13930                                 return (1);
13931                         }
13932                 }
13933                 if (ourfinisacked) {
13934                         switch(tp->t_state) {
13935                         case TCPS_CLOSING:
13936 #ifdef TCP_ACCOUNTING
13937                                 rdstc = get_cyclecount();
13938                                 if (rdstc > ts_val) {
13939                                         counter_u64_add(tcp_proc_time[ACK_CUMACK] ,
13940                                                         (rdstc - ts_val));
13941                                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13942                                                 tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13943                                                 tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13944                                         }
13945                                 }
13946                                 sched_unpin();
13947 #endif
13948                                 tcp_twstart(tp);
13949                                 m_freem(m);
13950                                 return (1);
13951                                 break;
13952                         case TCPS_LAST_ACK:
13953 #ifdef TCP_ACCOUNTING
13954                                 rdstc = get_cyclecount();
13955                                 if (rdstc > ts_val) {
13956                                         counter_u64_add(tcp_proc_time[ACK_CUMACK] ,
13957                                                         (rdstc - ts_val));
13958                                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13959                                                 tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13960                                                 tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13961                                         }
13962                                 }
13963                                 sched_unpin();
13964 #endif
13965                                 tp = tcp_close(tp);
13966                                 ctf_do_drop(m, tp);
13967                                 return (1);
13968                                 break;
13969                         case TCPS_FIN_WAIT_1:
13970 #ifdef TCP_ACCOUNTING
13971                                 rdstc = get_cyclecount();
13972                                 if (rdstc > ts_val) {
13973                                         counter_u64_add(tcp_proc_time[ACK_CUMACK] ,
13974                                                         (rdstc - ts_val));
13975                                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13976                                                 tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13977                                                 tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13978                                         }
13979                                 }
13980 #endif
13981                                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
13982                                         soisdisconnected(so);
13983                                         tcp_timer_activate(tp, TT_2MSL,
13984                                                            (tcp_fast_finwait2_recycle ?
13985                                                             tcp_finwait2_timeout :
13986                                                             TP_MAXIDLE(tp)));
13987                                 }
13988                                 tcp_state_change(tp, TCPS_FIN_WAIT_2);
13989                                 break;
13990                         default:
13991                                 break;
13992                         }
13993                 }
13994                 if (rack->r_fast_output) {
13995                         /*
13996                          * We re doing fast output.. can we expand that?
13997                          */
13998                         rack_gain_for_fastoutput(rack, tp, so, acked_amount);
13999                 }
14000 #ifdef TCP_ACCOUNTING
14001                 rdstc = get_cyclecount();
14002                 if (rdstc > ts_val) {
14003                         counter_u64_add(tcp_proc_time[ACK_CUMACK] , (rdstc - ts_val));
14004                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
14005                                 tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
14006                                 tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
14007                         }
14008                 }
14009
14010         } else if (win_up_req) {
14011                 rdstc = get_cyclecount();
14012                 if (rdstc > ts_val) {
14013                         counter_u64_add(tcp_proc_time[ACK_RWND] , (rdstc - ts_val));
14014                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
14015                                 tp->tcp_proc_time[ACK_RWND] += (rdstc - ts_val);
14016                         }
14017                 }
14018 #endif
14019         }
14020         /* Now is there a next packet, if so we are done */
14021         m_freem(m);
14022         did_out = 0;
14023         if (nxt_pkt) {
14024 #ifdef TCP_ACCOUNTING
14025                 sched_unpin();
14026 #endif
14027                 rack_log_doseg_done(rack, cts, nxt_pkt, did_out, 5, nsegs);
14028                 return (0);
14029         }
14030         rack_handle_might_revert(tp, rack);
14031         ctf_calc_rwin(so, tp);
14032         if ((rack->r_wanted_output != 0) || (rack->r_fast_output != 0)) {
14033         send_out_a_rst:
14034                 if (tcp_output(tp) < 0) {
14035 #ifdef TCP_ACCOUNTING
14036                         sched_unpin();
14037 #endif
14038                         return (1);
14039                 }
14040                 did_out = 1;
14041         }
14042         rack_free_trim(rack);
14043 #ifdef TCP_ACCOUNTING
14044         sched_unpin();
14045 #endif
14046         rack_timer_audit(tp, rack, &so->so_snd);
14047         rack_log_doseg_done(rack, cts, nxt_pkt, did_out, 6, nsegs);
14048         return (0);
14049 }
14050
14051
14052 static int
14053 rack_do_segment_nounlock(struct mbuf *m, struct tcphdr *th, struct socket *so,
14054     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos,
14055     int32_t nxt_pkt, struct timeval *tv)
14056 {
14057         struct inpcb *inp = tptoinpcb(tp);
14058 #ifdef TCP_ACCOUNTING
14059         uint64_t ts_val;
14060 #endif
14061         int32_t thflags, retval, did_out = 0;
14062         int32_t way_out = 0;
14063         /*
14064          * cts - is the current time from tv (caller gets ts) in microseconds.
14065          * ms_cts - is the current time from tv in milliseconds.
14066          * us_cts - is the time that LRO or hardware actually got the packet in microseconds.
14067          */
14068         uint32_t cts, us_cts, ms_cts;
14069         uint32_t tiwin, high_seq;
14070         struct timespec ts;
14071         struct tcpopt to;
14072         struct tcp_rack *rack;
14073         struct rack_sendmap *rsm;
14074         int32_t prev_state = 0;
14075 #ifdef TCP_ACCOUNTING
14076         int ack_val_set = 0xf;
14077 #endif
14078         int nsegs;
14079
14080         NET_EPOCH_ASSERT();
14081         INP_WLOCK_ASSERT(inp);
14082
14083         /*
14084          * tv passed from common code is from either M_TSTMP_LRO or
14085          * tcp_get_usecs() if no LRO m_pkthdr timestamp is present.
14086          */
14087         rack = (struct tcp_rack *)tp->t_fb_ptr;
14088         if (m->m_flags & M_ACKCMP) {
14089                 /*
14090                  * All compressed ack's are ack's by definition so
14091                  * remove any ack required flag and then do the processing.
14092                  */
14093                 rack->rc_ack_required = 0;
14094                 return (rack_do_compressed_ack_processing(tp, so, m, nxt_pkt, tv));
14095         }
14096         if (m->m_flags & M_ACKCMP) {
14097                 panic("Impossible reach m has ackcmp? m:%p tp:%p", m, tp);
14098         }
14099         cts = tcp_tv_to_usectick(tv);
14100         ms_cts =  tcp_tv_to_mssectick(tv);
14101         nsegs = m->m_pkthdr.lro_nsegs;
14102         counter_u64_add(rack_proc_non_comp_ack, 1);
14103         thflags = tcp_get_flags(th);
14104 #ifdef TCP_ACCOUNTING
14105         sched_pin();
14106         if (thflags & TH_ACK)
14107                 ts_val = get_cyclecount();
14108 #endif
14109         if ((m->m_flags & M_TSTMP) ||
14110             (m->m_flags & M_TSTMP_LRO)) {
14111                 mbuf_tstmp2timespec(m, &ts);
14112                 rack->r_ctl.act_rcv_time.tv_sec = ts.tv_sec;
14113                 rack->r_ctl.act_rcv_time.tv_usec = ts.tv_nsec/1000;
14114         } else
14115                 rack->r_ctl.act_rcv_time = *tv;
14116         kern_prefetch(rack, &prev_state);
14117         prev_state = 0;
14118         /*
14119          * Unscale the window into a 32-bit value. For the SYN_SENT state
14120          * the scale is zero.
14121          */
14122         tiwin = th->th_win << tp->snd_scale;
14123 #ifdef TCP_ACCOUNTING
14124         if (thflags & TH_ACK) {
14125                 /*
14126                  * We have a tradeoff here. We can either do what we are
14127                  * doing i.e. pinning to this CPU and then doing the accounting
14128                  * <or> we could do a critical enter, setup the rdtsc and cpu
14129                  * as in below, and then validate we are on the same CPU on
14130                  * exit. I have choosen to not do the critical enter since
14131                  * that often will gain you a context switch, and instead lock
14132                  * us (line above this if) to the same CPU with sched_pin(). This
14133                  * means we may be context switched out for a higher priority
14134                  * interupt but we won't be moved to another CPU.
14135                  *
14136                  * If this occurs (which it won't very often since we most likely
14137                  * are running this code in interupt context and only a higher
14138                  * priority will bump us ... clock?) we will falsely add in
14139                  * to the time the interupt processing time plus the ack processing
14140                  * time. This is ok since its a rare event.
14141                  */
14142                 ack_val_set = tcp_do_ack_accounting(tp, th, &to, tiwin,
14143                                                     ctf_fixed_maxseg(tp));
14144         }
14145 #endif
14146         /*
14147          * Parse options on any incoming segment.
14148          */
14149         memset(&to, 0, sizeof(to));
14150         tcp_dooptions(&to, (u_char *)(th + 1),
14151             (th->th_off << 2) - sizeof(struct tcphdr),
14152             (thflags & TH_SYN) ? TO_SYN : 0);
14153         KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
14154             __func__));
14155         KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
14156             __func__));
14157
14158         if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
14159             (tp->t_flags & TF_GPUTINPROG)) {
14160                 /*
14161                  * We have a goodput in progress
14162                  * and we have entered a late state.
14163                  * Do we have enough data in the sb
14164                  * to handle the GPUT request?
14165                  */
14166                 uint32_t bytes;
14167
14168                 bytes = tp->gput_ack - tp->gput_seq;
14169                 if (SEQ_GT(tp->gput_seq, tp->snd_una))
14170                         bytes += tp->gput_seq - tp->snd_una;
14171                 if (bytes > sbavail(&tptosocket(tp)->so_snd)) {
14172                         /*
14173                          * There are not enough bytes in the socket
14174                          * buffer that have been sent to cover this
14175                          * measurement. Cancel it.
14176                          */
14177                         rack_log_pacing_delay_calc(rack, (tp->gput_ack - tp->gput_seq) /*flex2*/,
14178                                                    rack->r_ctl.rc_gp_srtt /*flex1*/,
14179                                                    tp->gput_seq,
14180                                                    0, 0, 18, __LINE__, NULL, 0);
14181                         tp->t_flags &= ~TF_GPUTINPROG;
14182                 }
14183         }
14184         high_seq = th->th_ack;
14185         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
14186                 union tcp_log_stackspecific log;
14187                 struct timeval ltv;
14188 #ifdef NETFLIX_HTTP_LOGGING
14189                 struct http_sendfile_track *http_req;
14190
14191                 if (SEQ_GT(th->th_ack, tp->snd_una)) {
14192                         http_req = tcp_http_find_req_for_seq(tp, (th->th_ack-1));
14193                 } else {
14194                         http_req = tcp_http_find_req_for_seq(tp, th->th_ack);
14195                 }
14196 #endif
14197                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
14198                 log.u_bbr.inhpts = tcp_in_hpts(rack->rc_inp);
14199                 if (rack->rack_no_prr == 0)
14200                         log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
14201                 else
14202                         log.u_bbr.flex1 = 0;
14203                 log.u_bbr.use_lt_bw = rack->r_ent_rec_ns;
14204                 log.u_bbr.use_lt_bw <<= 1;
14205                 log.u_bbr.use_lt_bw |= rack->r_might_revert;
14206                 log.u_bbr.flex2 = rack->r_ctl.rc_num_maps_alloced;
14207                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
14208                 log.u_bbr.pkts_out = rack->rc_tp->t_maxseg;
14209                 log.u_bbr.flex3 = m->m_flags;
14210                 log.u_bbr.flex4 = rack->r_ctl.rc_hpts_flags;
14211                 log.u_bbr.lost = thflags;
14212                 log.u_bbr.pacing_gain = 0x1;
14213 #ifdef TCP_ACCOUNTING
14214                 log.u_bbr.cwnd_gain = ack_val_set;
14215 #endif
14216                 log.u_bbr.flex7 = 2;
14217                 if (m->m_flags & M_TSTMP) {
14218                         /* Record the hardware timestamp if present */
14219                         mbuf_tstmp2timespec(m, &ts);
14220                         ltv.tv_sec = ts.tv_sec;
14221                         ltv.tv_usec = ts.tv_nsec / 1000;
14222                         log.u_bbr.lt_epoch = tcp_tv_to_usectick(&ltv);
14223                 } else if (m->m_flags & M_TSTMP_LRO) {
14224                         /* Record the LRO the arrival timestamp */
14225                         mbuf_tstmp2timespec(m, &ts);
14226                         ltv.tv_sec = ts.tv_sec;
14227                         ltv.tv_usec = ts.tv_nsec / 1000;
14228                         log.u_bbr.flex5 = tcp_tv_to_usectick(&ltv);
14229                 }
14230                 log.u_bbr.timeStamp = tcp_get_usecs(&ltv);
14231                 /* Log the rcv time */
14232                 log.u_bbr.delRate = m->m_pkthdr.rcv_tstmp;
14233 #ifdef NETFLIX_HTTP_LOGGING
14234                 log.u_bbr.applimited = tp->t_http_closed;
14235                 log.u_bbr.applimited <<= 8;
14236                 log.u_bbr.applimited |= tp->t_http_open;
14237                 log.u_bbr.applimited <<= 8;
14238                 log.u_bbr.applimited |= tp->t_http_req;
14239                 if (http_req) {
14240                         /* Copy out any client req info */
14241                         /* seconds */
14242                         log.u_bbr.pkt_epoch = (http_req->localtime / HPTS_USEC_IN_SEC);
14243                         /* useconds */
14244                         log.u_bbr.delivered = (http_req->localtime % HPTS_USEC_IN_SEC);
14245                         log.u_bbr.rttProp = http_req->timestamp;
14246                         log.u_bbr.cur_del_rate = http_req->start;
14247                         if (http_req->flags & TCP_HTTP_TRACK_FLG_OPEN) {
14248                                 log.u_bbr.flex8 |= 1;
14249                         } else {
14250                                 log.u_bbr.flex8 |= 2;
14251                                 log.u_bbr.bw_inuse = http_req->end;
14252                         }
14253                         log.u_bbr.flex6 = http_req->start_seq;
14254                         if (http_req->flags & TCP_HTTP_TRACK_FLG_COMP) {
14255                                 log.u_bbr.flex8 |= 4;
14256                                 log.u_bbr.epoch = http_req->end_seq;
14257                         }
14258                 }
14259 #endif
14260                 TCP_LOG_EVENTP(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_IN, 0,
14261                     tlen, &log, true, &ltv);
14262         }
14263         /* Remove ack required flag if set, we have one  */
14264         if (thflags & TH_ACK)
14265                 rack->rc_ack_required = 0;
14266         if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
14267                 way_out = 4;
14268                 retval = 0;
14269                 m_freem(m);
14270                 goto done_with_input;
14271         }
14272         /*
14273          * If a segment with the ACK-bit set arrives in the SYN-SENT state
14274          * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
14275          */
14276         if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
14277             (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
14278                 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
14279                 ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
14280 #ifdef TCP_ACCOUNTING
14281                 sched_unpin();
14282 #endif
14283                 return (1);
14284         }
14285         /*
14286          * If timestamps were negotiated during SYN/ACK and a
14287          * segment without a timestamp is received, silently drop
14288          * the segment, unless it is a RST segment or missing timestamps are
14289          * tolerated.
14290          * See section 3.2 of RFC 7323.
14291          */
14292         if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
14293             ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
14294                 way_out = 5;
14295                 retval = 0;
14296                 m_freem(m);
14297                 goto done_with_input;
14298         }
14299
14300         /*
14301          * Segment received on connection. Reset idle time and keep-alive
14302          * timer. XXX: This should be done after segment validation to
14303          * ignore broken/spoofed segs.
14304          */
14305         if  (tp->t_idle_reduce &&
14306              (tp->snd_max == tp->snd_una) &&
14307              (TICKS_2_USEC(ticks - tp->t_rcvtime) >= tp->t_rxtcur)) {
14308                 counter_u64_add(rack_input_idle_reduces, 1);
14309                 rack_cc_after_idle(rack, tp);
14310         }
14311         tp->t_rcvtime = ticks;
14312 #ifdef STATS
14313         stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
14314 #endif
14315         if (tiwin > rack->r_ctl.rc_high_rwnd)
14316                 rack->r_ctl.rc_high_rwnd = tiwin;
14317         /*
14318          * TCP ECN processing. XXXJTL: If we ever use ECN, we need to move
14319          * this to occur after we've validated the segment.
14320          */
14321         if (tcp_ecn_input_segment(tp, thflags, tlen,
14322             tcp_packets_this_ack(tp, th->th_ack),
14323             iptos))
14324                 rack_cong_signal(tp, CC_ECN, th->th_ack, __LINE__);
14325
14326         /*
14327          * If echoed timestamp is later than the current time, fall back to
14328          * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
14329          * were used when this connection was established.
14330          */
14331         if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
14332                 to.to_tsecr -= tp->ts_offset;
14333                 if (TSTMP_GT(to.to_tsecr, ms_cts))
14334                         to.to_tsecr = 0;
14335         }
14336
14337         /*
14338          * If its the first time in we need to take care of options and
14339          * verify we can do SACK for rack!
14340          */
14341         if (rack->r_state == 0) {
14342                 /* Should be init'd by rack_init() */
14343                 KASSERT(rack->rc_inp != NULL,
14344                     ("%s: rack->rc_inp unexpectedly NULL", __func__));
14345                 if (rack->rc_inp == NULL) {
14346                         rack->rc_inp = inp;
14347                 }
14348
14349                 /*
14350                  * Process options only when we get SYN/ACK back. The SYN
14351                  * case for incoming connections is handled in tcp_syncache.
14352                  * According to RFC1323 the window field in a SYN (i.e., a
14353                  * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
14354                  * this is traditional behavior, may need to be cleaned up.
14355                  */
14356                 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
14357                         /* Handle parallel SYN for ECN */
14358                         tcp_ecn_input_parallel_syn(tp, thflags, iptos);
14359                         if ((to.to_flags & TOF_SCALE) &&
14360                             (tp->t_flags & TF_REQ_SCALE)) {
14361                                 tp->t_flags |= TF_RCVD_SCALE;
14362                                 tp->snd_scale = to.to_wscale;
14363                         } else
14364                                 tp->t_flags &= ~TF_REQ_SCALE;
14365                         /*
14366                          * Initial send window.  It will be updated with the
14367                          * next incoming segment to the scaled value.
14368                          */
14369                         tp->snd_wnd = th->th_win;
14370                         rack_validate_fo_sendwin_up(tp, rack);
14371                         if ((to.to_flags & TOF_TS) &&
14372                             (tp->t_flags & TF_REQ_TSTMP)) {
14373                                 tp->t_flags |= TF_RCVD_TSTMP;
14374                                 tp->ts_recent = to.to_tsval;
14375                                 tp->ts_recent_age = cts;
14376                         } else
14377                                 tp->t_flags &= ~TF_REQ_TSTMP;
14378                         if (to.to_flags & TOF_MSS) {
14379                                 tcp_mss(tp, to.to_mss);
14380                         }
14381                         if ((tp->t_flags & TF_SACK_PERMIT) &&
14382                             (to.to_flags & TOF_SACKPERM) == 0)
14383                                 tp->t_flags &= ~TF_SACK_PERMIT;
14384                         if (IS_FASTOPEN(tp->t_flags)) {
14385                                 if (to.to_flags & TOF_FASTOPEN) {
14386                                         uint16_t mss;
14387
14388                                         if (to.to_flags & TOF_MSS)
14389                                                 mss = to.to_mss;
14390                                         else
14391                                                 if ((inp->inp_vflag & INP_IPV6) != 0)
14392                                                         mss = TCP6_MSS;
14393                                                 else
14394                                                         mss = TCP_MSS;
14395                                         tcp_fastopen_update_cache(tp, mss,
14396                                             to.to_tfo_len, to.to_tfo_cookie);
14397                                 } else
14398                                         tcp_fastopen_disable_path(tp);
14399                         }
14400                 }
14401                 /*
14402                  * At this point we are at the initial call. Here we decide
14403                  * if we are doing RACK or not. We do this by seeing if
14404                  * TF_SACK_PERMIT is set and the sack-not-required is clear.
14405                  * The code now does do dup-ack counting so if you don't
14406                  * switch back you won't get rack & TLP, but you will still
14407                  * get this stack.
14408                  */
14409
14410                 if ((rack_sack_not_required == 0) &&
14411                     ((tp->t_flags & TF_SACK_PERMIT) == 0)) {
14412                         tcp_switch_back_to_default(tp);
14413                         (*tp->t_fb->tfb_tcp_do_segment) (m, th, so, tp, drop_hdrlen,
14414                             tlen, iptos);
14415 #ifdef TCP_ACCOUNTING
14416                         sched_unpin();
14417 #endif
14418                         return (1);
14419                 }
14420                 tcp_set_hpts(inp);
14421                 sack_filter_clear(&rack->r_ctl.rack_sf, th->th_ack);
14422         }
14423         if (thflags & TH_FIN)
14424                 tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
14425         us_cts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
14426         if ((rack->rc_gp_dyn_mul) &&
14427             (rack->use_fixed_rate == 0) &&
14428             (rack->rc_always_pace)) {
14429                 /* Check in on probertt */
14430                 rack_check_probe_rtt(rack, us_cts);
14431         }
14432         rack_clear_rate_sample(rack);
14433         if ((rack->forced_ack) &&
14434             ((tcp_get_flags(th) & TH_RST) == 0)) {
14435                 rack_handle_probe_response(rack, tiwin, us_cts);
14436         }
14437         /*
14438          * This is the one exception case where we set the rack state
14439          * always. All other times (timers etc) we must have a rack-state
14440          * set (so we assure we have done the checks above for SACK).
14441          */
14442         rack->r_ctl.rc_rcvtime = cts;
14443         if (rack->r_state != tp->t_state)
14444                 rack_set_state(tp, rack);
14445         if (SEQ_GT(th->th_ack, tp->snd_una) &&
14446             (rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree)) != NULL)
14447                 kern_prefetch(rsm, &prev_state);
14448         prev_state = rack->r_state;
14449         retval = (*rack->r_substate) (m, th, so,
14450             tp, &to, drop_hdrlen,
14451             tlen, tiwin, thflags, nxt_pkt, iptos);
14452         if (retval == 0) {
14453                 /*
14454                  * If retval is 1 the tcb is unlocked and most likely the tp
14455                  * is gone.
14456                  */
14457                 INP_WLOCK_ASSERT(inp);
14458                 if ((rack->rc_gp_dyn_mul) &&
14459                     (rack->rc_always_pace) &&
14460                     (rack->use_fixed_rate == 0) &&
14461                     rack->in_probe_rtt &&
14462                     (rack->r_ctl.rc_time_probertt_starts == 0)) {
14463                         /*
14464                          * If we are going for target, lets recheck before
14465                          * we output.
14466                          */
14467                         rack_check_probe_rtt(rack, us_cts);
14468                 }
14469                 if (rack->set_pacing_done_a_iw == 0) {
14470                         /* How much has been acked? */
14471                         if ((tp->snd_una - tp->iss) > (ctf_fixed_maxseg(tp) * 10)) {
14472                                 /* We have enough to set in the pacing segment size */
14473                                 rack->set_pacing_done_a_iw = 1;
14474                                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
14475                         }
14476                 }
14477                 tcp_rack_xmit_timer_commit(rack, tp);
14478 #ifdef TCP_ACCOUNTING
14479                 /*
14480                  * If we set the ack_val_se to what ack processing we are doing
14481                  * we also want to track how many cycles we burned. Note
14482                  * the bits after tcp_output we let be "free". This is because
14483                  * we are also tracking the tcp_output times as well. Note the
14484                  * use of 0xf here since we only have 11 counter (0 - 0xa) and
14485                  * 0xf cannot be returned and is what we initialize it too to
14486                  * indicate we are not doing the tabulations.
14487                  */
14488                 if (ack_val_set != 0xf) {
14489                         uint64_t crtsc;
14490
14491                         crtsc = get_cyclecount();
14492                         counter_u64_add(tcp_proc_time[ack_val_set] , (crtsc - ts_val));
14493                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
14494                                 tp->tcp_proc_time[ack_val_set] += (crtsc - ts_val);
14495                         }
14496                 }
14497 #endif
14498                 if (nxt_pkt == 0) {
14499                         if ((rack->r_wanted_output != 0) || (rack->r_fast_output != 0)) {
14500 do_output_now:
14501                                 if (tcp_output(tp) < 0)
14502                                         return (1);
14503                                 did_out = 1;
14504                         }
14505                         rack_start_hpts_timer(rack, tp, cts, 0, 0, 0);
14506                         rack_free_trim(rack);
14507                 }
14508                 /* Update any rounds needed */
14509                 if (rack_verbose_logging &&  (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
14510                         union tcp_log_stackspecific log;
14511                         struct timeval tv;
14512
14513                         memset(&log.u_bbr, 0, sizeof(log.u_bbr));
14514                         log.u_bbr.timeStamp = tcp_get_usecs(&tv);
14515                         log.u_bbr.flex1 = high_seq;
14516                         log.u_bbr.flex2 = rack->r_ctl.roundends;
14517                         log.u_bbr.flex3 = rack->r_ctl.current_round;
14518                         log.u_bbr.rttProp = (uint64_t)CC_ALGO(tp)->newround;
14519                         log.u_bbr.flex8 = 9;
14520                         tcp_log_event_(tp, NULL, NULL, NULL, BBR_LOG_CWND, 0,
14521                                        0, &log, false, NULL, NULL, 0, &tv);
14522                 }
14523                 /*
14524                  * The draft (v3) calls for us to use SEQ_GEQ, but that
14525                  * causes issues when we are just going app limited. Lets
14526                  * instead use SEQ_GT <or> where its equal but more data
14527                  * is outstanding.
14528                  */
14529                 if ((SEQ_GT(tp->snd_una, rack->r_ctl.roundends)) ||
14530                     ((tp->snd_una == rack->r_ctl.roundends) && SEQ_GT(tp->snd_max, tp->snd_una))) {
14531                         rack->r_ctl.current_round++;
14532                         rack->r_ctl.roundends = tp->snd_max;
14533                         if (CC_ALGO(tp)->newround != NULL) {
14534                                 CC_ALGO(tp)->newround(tp->ccv, rack->r_ctl.current_round);
14535                         }
14536                 }
14537                 if ((nxt_pkt == 0) &&
14538                     ((rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
14539                     (SEQ_GT(tp->snd_max, tp->snd_una) ||
14540                      (tp->t_flags & TF_DELACK) ||
14541                      ((V_tcp_always_keepalive || rack->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
14542                       (tp->t_state <= TCPS_CLOSING)))) {
14543                         /* We could not send (probably in the hpts but stopped the timer earlier)? */
14544                         if ((tp->snd_max == tp->snd_una) &&
14545                             ((tp->t_flags & TF_DELACK) == 0) &&
14546                             (tcp_in_hpts(rack->rc_inp)) &&
14547                             (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
14548                                 /* keep alive not needed if we are hptsi output yet */
14549                                 ;
14550                         } else {
14551                                 int late = 0;
14552                                 if (tcp_in_hpts(inp)) {
14553                                         if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
14554                                                 us_cts = tcp_get_usecs(NULL);
14555                                                 if (TSTMP_GT(rack->r_ctl.rc_last_output_to, us_cts)) {
14556                                                         rack->r_early = 1;
14557                                                         rack->r_ctl.rc_agg_early += (rack->r_ctl.rc_last_output_to - us_cts);
14558                                                 } else
14559                                                         late = 1;
14560                                                 rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
14561                                         }
14562                                         tcp_hpts_remove(inp);
14563                                 }
14564                                 if (late && (did_out == 0)) {
14565                                         /*
14566                                          * We are late in the sending
14567                                          * and we did not call the output
14568                                          * (this probably should not happen).
14569                                          */
14570                                         goto do_output_now;
14571                                 }
14572                                 rack_start_hpts_timer(rack, tp, tcp_get_usecs(NULL), 0, 0, 0);
14573                         }
14574                         way_out = 1;
14575                 } else if (nxt_pkt == 0) {
14576                         /* Do we have the correct timer running? */
14577                         rack_timer_audit(tp, rack, &so->so_snd);
14578                         way_out = 2;
14579                 }
14580         done_with_input:
14581                 rack_log_doseg_done(rack, cts, nxt_pkt, did_out, way_out, max(1, nsegs));
14582                 if (did_out)
14583                         rack->r_wanted_output = 0;
14584 #ifdef TCP_ACCOUNTING
14585         } else {
14586                 /*
14587                  * Track the time (see above).
14588                  */
14589                 if (ack_val_set != 0xf) {
14590                         uint64_t crtsc;
14591
14592                         crtsc = get_cyclecount();
14593                         counter_u64_add(tcp_proc_time[ack_val_set] , (crtsc - ts_val));
14594                         /*
14595                          * Note we *DO NOT* increment the per-tcb counters since
14596                          * in the else the TP may be gone!!
14597                          */
14598                 }
14599 #endif
14600         }
14601 #ifdef TCP_ACCOUNTING
14602         sched_unpin();
14603 #endif
14604         return (retval);
14605 }
14606
14607 void
14608 rack_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
14609     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
14610 {
14611         struct timeval tv;
14612
14613         /* First lets see if we have old packets */
14614         if (tp->t_in_pkt) {
14615                 if (ctf_do_queued_segments(so, tp, 1)) {
14616                         m_freem(m);
14617                         return;
14618                 }
14619         }
14620         if (m->m_flags & M_TSTMP_LRO) {
14621                 mbuf_tstmp2timeval(m, &tv);
14622         } else {
14623                 /* Should not be should we kassert instead? */
14624                 tcp_get_usecs(&tv);
14625         }
14626         if (rack_do_segment_nounlock(m, th, so, tp,
14627                                      drop_hdrlen, tlen, iptos, 0, &tv) == 0) {
14628                 INP_WUNLOCK(tptoinpcb(tp));
14629         }
14630 }
14631
14632 struct rack_sendmap *
14633 tcp_rack_output(struct tcpcb *tp, struct tcp_rack *rack, uint32_t tsused)
14634 {
14635         struct rack_sendmap *rsm = NULL;
14636         int32_t idx;
14637         uint32_t srtt = 0, thresh = 0, ts_low = 0;
14638
14639         /* Return the next guy to be re-transmitted */
14640         if (RB_EMPTY(&rack->r_ctl.rc_mtree)) {
14641                 return (NULL);
14642         }
14643         if (tp->t_flags & TF_SENTFIN) {
14644                 /* retran the end FIN? */
14645                 return (NULL);
14646         }
14647         /* ok lets look at this one */
14648         rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
14649         if (rack->r_must_retran && rsm && (rsm->r_flags & RACK_MUST_RXT)) {
14650                 return (rsm);
14651         }
14652         if (rsm && ((rsm->r_flags & RACK_ACKED) == 0)) {
14653                 goto check_it;
14654         }
14655         rsm = rack_find_lowest_rsm(rack);
14656         if (rsm == NULL) {
14657                 return (NULL);
14658         }
14659 check_it:
14660         if (((rack->rc_tp->t_flags & TF_SACK_PERMIT) == 0) &&
14661             (rsm->r_dupack >= DUP_ACK_THRESHOLD)) {
14662                 /*
14663                  * No sack so we automatically do the 3 strikes and
14664                  * retransmit (no rack timer would be started).
14665                  */
14666
14667                 return (rsm);
14668         }
14669         if (rsm->r_flags & RACK_ACKED) {
14670                 return (NULL);
14671         }
14672         if (((rsm->r_flags & RACK_SACK_PASSED) == 0) &&
14673             (rsm->r_dupack < DUP_ACK_THRESHOLD)) {
14674                 /* Its not yet ready */
14675                 return (NULL);
14676         }
14677         srtt = rack_grab_rtt(tp, rack);
14678         idx = rsm->r_rtr_cnt - 1;
14679         ts_low = (uint32_t)rsm->r_tim_lastsent[idx];
14680         thresh = rack_calc_thresh_rack(rack, srtt, tsused);
14681         if ((tsused == ts_low) ||
14682             (TSTMP_LT(tsused, ts_low))) {
14683                 /* No time since sending */
14684                 return (NULL);
14685         }
14686         if ((tsused - ts_low) < thresh) {
14687                 /* It has not been long enough yet */
14688                 return (NULL);
14689         }
14690         if ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
14691             ((rsm->r_flags & RACK_SACK_PASSED) &&
14692              (rack->sack_attack_disable == 0))) {
14693                 /*
14694                  * We have passed the dup-ack threshold <or>
14695                  * a SACK has indicated this is missing.
14696                  * Note that if you are a declared attacker
14697                  * it is only the dup-ack threshold that
14698                  * will cause retransmits.
14699                  */
14700                 /* log retransmit reason */
14701                 rack_log_retran_reason(rack, rsm, (tsused - ts_low), thresh, 1);
14702                 rack->r_fast_output = 0;
14703                 return (rsm);
14704         }
14705         return (NULL);
14706 }
14707
14708 static void
14709 rack_log_pacing_delay_calc(struct tcp_rack *rack, uint32_t len, uint32_t slot,
14710                            uint64_t bw_est, uint64_t bw, uint64_t len_time, int method,
14711                            int line, struct rack_sendmap *rsm, uint8_t quality)
14712 {
14713         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
14714                 union tcp_log_stackspecific log;
14715                 struct timeval tv;
14716
14717                 memset(&log, 0, sizeof(log));
14718                 log.u_bbr.flex1 = slot;
14719                 log.u_bbr.flex2 = len;
14720                 log.u_bbr.flex3 = rack->r_ctl.rc_pace_min_segs;
14721                 log.u_bbr.flex4 = rack->r_ctl.rc_pace_max_segs;
14722                 log.u_bbr.flex5 = rack->r_ctl.rack_per_of_gp_ss;
14723                 log.u_bbr.flex6 = rack->r_ctl.rack_per_of_gp_ca;
14724                 log.u_bbr.use_lt_bw = rack->rc_ack_can_sendout_data;
14725                 log.u_bbr.use_lt_bw <<= 1;
14726                 log.u_bbr.use_lt_bw |= rack->r_late;
14727                 log.u_bbr.use_lt_bw <<= 1;
14728                 log.u_bbr.use_lt_bw |= rack->r_early;
14729                 log.u_bbr.use_lt_bw <<= 1;
14730                 log.u_bbr.use_lt_bw |= rack->app_limited_needs_set;
14731                 log.u_bbr.use_lt_bw <<= 1;
14732                 log.u_bbr.use_lt_bw |= rack->rc_gp_filled;
14733                 log.u_bbr.use_lt_bw <<= 1;
14734                 log.u_bbr.use_lt_bw |= rack->measure_saw_probe_rtt;
14735                 log.u_bbr.use_lt_bw <<= 1;
14736                 log.u_bbr.use_lt_bw |= rack->in_probe_rtt;
14737                 log.u_bbr.use_lt_bw <<= 1;
14738                 log.u_bbr.use_lt_bw |= rack->gp_ready;
14739                 log.u_bbr.pkt_epoch = line;
14740                 log.u_bbr.epoch = rack->r_ctl.rc_agg_delayed;
14741                 log.u_bbr.lt_epoch = rack->r_ctl.rc_agg_early;
14742                 log.u_bbr.applimited = rack->r_ctl.rack_per_of_gp_rec;
14743                 log.u_bbr.bw_inuse = bw_est;
14744                 log.u_bbr.delRate = bw;
14745                 if (rack->r_ctl.gp_bw == 0)
14746                         log.u_bbr.cur_del_rate = 0;
14747                 else
14748                         log.u_bbr.cur_del_rate = rack_get_bw(rack);
14749                 log.u_bbr.rttProp = len_time;
14750                 log.u_bbr.pkts_out = rack->r_ctl.rc_rack_min_rtt;
14751                 log.u_bbr.lost = rack->r_ctl.rc_probertt_sndmax_atexit;
14752                 log.u_bbr.pacing_gain = rack_get_output_gain(rack, rsm);
14753                 if (rack->r_ctl.cwnd_to_use < rack->rc_tp->snd_ssthresh) {
14754                         /* We are in slow start */
14755                         log.u_bbr.flex7 = 1;
14756                 } else {
14757                         /* we are on congestion avoidance */
14758                         log.u_bbr.flex7 = 0;
14759                 }
14760                 log.u_bbr.flex8 = method;
14761                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
14762                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
14763                 log.u_bbr.cwnd_gain = rack->rc_gp_saw_rec;
14764                 log.u_bbr.cwnd_gain <<= 1;
14765                 log.u_bbr.cwnd_gain |= rack->rc_gp_saw_ss;
14766                 log.u_bbr.cwnd_gain <<= 1;
14767                 log.u_bbr.cwnd_gain |= rack->rc_gp_saw_ca;
14768                 log.u_bbr.bbr_substate = quality;
14769                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
14770                     &rack->rc_inp->inp_socket->so_rcv,
14771                     &rack->rc_inp->inp_socket->so_snd,
14772                     BBR_LOG_HPTSI_CALC, 0,
14773                     0, &log, false, &tv);
14774         }
14775 }
14776
14777 static uint32_t
14778 rack_get_pacing_len(struct tcp_rack *rack, uint64_t bw, uint32_t mss)
14779 {
14780         uint32_t new_tso, user_max;
14781
14782         user_max = rack->rc_user_set_max_segs * mss;
14783         if (rack->rc_force_max_seg) {
14784                 return (user_max);
14785         }
14786         if (rack->use_fixed_rate &&
14787             ((rack->r_ctl.crte == NULL) ||
14788              (bw != rack->r_ctl.crte->rate))) {
14789                 /* Use the user mss since we are not exactly matched */
14790                 return (user_max);
14791         }
14792         new_tso = tcp_get_pacing_burst_size(rack->rc_tp, bw, mss, rack_pace_one_seg, rack->r_ctl.crte, NULL);
14793         if (new_tso > user_max)
14794                 new_tso = user_max;
14795         return (new_tso);
14796 }
14797
14798 static int32_t
14799 pace_to_fill_cwnd(struct tcp_rack *rack, int32_t slot, uint32_t len, uint32_t segsiz, int *capped, uint64_t *rate_wanted, uint8_t non_paced)
14800 {
14801         uint64_t lentim, fill_bw;
14802
14803         /* Lets first see if we are full, if so continue with normal rate */
14804         rack->r_via_fill_cw = 0;
14805         if (ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked) > rack->r_ctl.cwnd_to_use)
14806                 return (slot);
14807         if ((ctf_outstanding(rack->rc_tp) + (segsiz-1)) > rack->rc_tp->snd_wnd)
14808                 return (slot);
14809         if (rack->r_ctl.rc_last_us_rtt == 0)
14810                 return (slot);
14811         if (rack->rc_pace_fill_if_rttin_range &&
14812             (rack->r_ctl.rc_last_us_rtt >=
14813              (get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) * rack->rtt_limit_mul))) {
14814                 /* The rtt is huge, N * smallest, lets not fill */
14815                 return (slot);
14816         }
14817         /*
14818          * first lets calculate the b/w based on the last us-rtt
14819          * and the sndwnd.
14820          */
14821         fill_bw = rack->r_ctl.cwnd_to_use;
14822         /* Take the rwnd if its smaller */
14823         if (fill_bw > rack->rc_tp->snd_wnd)
14824                 fill_bw = rack->rc_tp->snd_wnd;
14825         if (rack->r_fill_less_agg) {
14826                 /*
14827                  * Now take away the inflight (this will reduce our
14828                  * aggressiveness and yeah, if we get that much out in 1RTT
14829                  * we will have had acks come back and still be behind).
14830                  */
14831                 fill_bw -= ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
14832         }
14833         /* Now lets make it into a b/w */
14834         fill_bw *= (uint64_t)HPTS_USEC_IN_SEC;
14835         fill_bw /= (uint64_t)rack->r_ctl.rc_last_us_rtt;
14836         /* We are below the min b/w */
14837         if (non_paced)
14838                 *rate_wanted = fill_bw;
14839         if ((fill_bw < RACK_MIN_BW) || (fill_bw < *rate_wanted))
14840                 return (slot);
14841         if (rack->r_ctl.bw_rate_cap && (fill_bw > rack->r_ctl.bw_rate_cap))
14842                 fill_bw = rack->r_ctl.bw_rate_cap;
14843         rack->r_via_fill_cw = 1;
14844         if (rack->r_rack_hw_rate_caps &&
14845             (rack->r_ctl.crte != NULL)) {
14846                 uint64_t high_rate;
14847
14848                 high_rate = tcp_hw_highest_rate(rack->r_ctl.crte);
14849                 if (fill_bw > high_rate) {
14850                         /* We are capping bw at the highest rate table entry */
14851                         if (*rate_wanted > high_rate) {
14852                                 /* The original rate was also capped */
14853                                 rack->r_via_fill_cw = 0;
14854                         }
14855                         rack_log_hdwr_pacing(rack,
14856                                              fill_bw, high_rate, __LINE__,
14857                                              0, 3);
14858                         fill_bw = high_rate;
14859                         if (capped)
14860                                 *capped = 1;
14861                 }
14862         } else if ((rack->r_ctl.crte == NULL) &&
14863                    (rack->rack_hdrw_pacing == 0) &&
14864                    (rack->rack_hdw_pace_ena) &&
14865                    rack->r_rack_hw_rate_caps &&
14866                    (rack->rack_attempt_hdwr_pace == 0) &&
14867                    (rack->rc_inp->inp_route.ro_nh != NULL) &&
14868                    (rack->rc_inp->inp_route.ro_nh->nh_ifp != NULL)) {
14869                 /*
14870                  * Ok we may have a first attempt that is greater than our top rate
14871                  * lets check.
14872                  */
14873                 uint64_t high_rate;
14874
14875                 high_rate = tcp_hw_highest_rate_ifp(rack->rc_inp->inp_route.ro_nh->nh_ifp, rack->rc_inp);
14876                 if (high_rate) {
14877                         if (fill_bw > high_rate) {
14878                                 fill_bw = high_rate;
14879                                 if (capped)
14880                                         *capped = 1;
14881                         }
14882                 }
14883         }
14884         /*
14885          * Ok fill_bw holds our mythical b/w to fill the cwnd
14886          * in a rtt, what does that time wise equate too?
14887          */
14888         lentim = (uint64_t)(len) * (uint64_t)HPTS_USEC_IN_SEC;
14889         lentim /= fill_bw;
14890         *rate_wanted = fill_bw;
14891         if (non_paced || (lentim < slot)) {
14892                 rack_log_pacing_delay_calc(rack, len, slot, fill_bw,
14893                                            0, lentim, 12, __LINE__, NULL, 0);
14894                 return ((int32_t)lentim);
14895         } else
14896                 return (slot);
14897 }
14898
14899 static int32_t
14900 rack_get_pacing_delay(struct tcp_rack *rack, struct tcpcb *tp, uint32_t len, struct rack_sendmap *rsm, uint32_t segsiz)
14901 {
14902         uint64_t srtt;
14903         int32_t slot = 0;
14904         int can_start_hw_pacing = 1;
14905         int err;
14906
14907         if (rack->rc_always_pace == 0) {
14908                 /*
14909                  * We use the most optimistic possible cwnd/srtt for
14910                  * sending calculations. This will make our
14911                  * calculation anticipate getting more through
14912                  * quicker then possible. But thats ok we don't want
14913                  * the peer to have a gap in data sending.
14914                  */
14915                 uint64_t cwnd, tr_perms = 0;
14916                 int32_t reduce = 0;
14917
14918         old_method:
14919                 /*
14920                  * We keep no precise pacing with the old method
14921                  * instead we use the pacer to mitigate bursts.
14922                  */
14923                 if (rack->r_ctl.rc_rack_min_rtt)
14924                         srtt = rack->r_ctl.rc_rack_min_rtt;
14925                 else
14926                         srtt = max(tp->t_srtt, 1);
14927                 if (rack->r_ctl.rc_rack_largest_cwnd)
14928                         cwnd = rack->r_ctl.rc_rack_largest_cwnd;
14929                 else
14930                         cwnd = rack->r_ctl.cwnd_to_use;
14931                 /* Inflate cwnd by 1000 so srtt of usecs is in ms */
14932                 tr_perms = (cwnd * 1000) / srtt;
14933                 if (tr_perms == 0) {
14934                         tr_perms = ctf_fixed_maxseg(tp);
14935                 }
14936                 /*
14937                  * Calculate how long this will take to drain, if
14938                  * the calculation comes out to zero, thats ok we
14939                  * will use send_a_lot to possibly spin around for
14940                  * more increasing tot_len_this_send to the point
14941                  * that its going to require a pace, or we hit the
14942                  * cwnd. Which in that case we are just waiting for
14943                  * a ACK.
14944                  */
14945                 slot = len / tr_perms;
14946                 /* Now do we reduce the time so we don't run dry? */
14947                 if (slot && rack_slot_reduction) {
14948                         reduce = (slot / rack_slot_reduction);
14949                         if (reduce < slot) {
14950                                 slot -= reduce;
14951                         } else
14952                                 slot = 0;
14953                 }
14954                 slot *= HPTS_USEC_IN_MSEC;
14955                 if (rack->rc_pace_to_cwnd) {
14956                         uint64_t rate_wanted = 0;
14957
14958                         slot = pace_to_fill_cwnd(rack, slot, len, segsiz, NULL, &rate_wanted, 1);
14959                         rack->rc_ack_can_sendout_data = 1;
14960                         rack_log_pacing_delay_calc(rack, len, slot, rate_wanted, 0, 0, 14, __LINE__, NULL, 0);
14961                 } else
14962                         rack_log_pacing_delay_calc(rack, len, slot, tr_perms, reduce, 0, 7, __LINE__, NULL, 0);
14963         } else {
14964                 uint64_t bw_est, res, lentim, rate_wanted;
14965                 uint32_t orig_val, segs, oh;
14966                 int capped = 0;
14967                 int prev_fill;
14968
14969                 if ((rack->r_rr_config == 1) && rsm) {
14970                         return (rack->r_ctl.rc_min_to);
14971                 }
14972                 if (rack->use_fixed_rate) {
14973                         rate_wanted = bw_est = rack_get_fixed_pacing_bw(rack);
14974                 } else if ((rack->r_ctl.init_rate == 0) &&
14975 #ifdef NETFLIX_PEAKRATE
14976                            (rack->rc_tp->t_maxpeakrate == 0) &&
14977 #endif
14978                            (rack->r_ctl.gp_bw == 0)) {
14979                         /* no way to yet do an estimate */
14980                         bw_est = rate_wanted = 0;
14981                 } else {
14982                         bw_est = rack_get_bw(rack);
14983                         rate_wanted = rack_get_output_bw(rack, bw_est, rsm, &capped);
14984                 }
14985                 if ((bw_est == 0) || (rate_wanted == 0) ||
14986                     ((rack->gp_ready == 0) && (rack->use_fixed_rate == 0))) {
14987                         /*
14988                          * No way yet to make a b/w estimate or
14989                          * our raise is set incorrectly.
14990                          */
14991                         goto old_method;
14992                 }
14993                 /* We need to account for all the overheads */
14994                 segs = (len + segsiz - 1) / segsiz;
14995                 /*
14996                  * We need the diff between 1514 bytes (e-mtu with e-hdr)
14997                  * and how much data we put in each packet. Yes this
14998                  * means we may be off if we are larger than 1500 bytes
14999                  * or smaller. But this just makes us more conservative.
15000                  */
15001                 if (rack_hw_rate_min &&
15002                     (bw_est < rack_hw_rate_min))
15003                         can_start_hw_pacing = 0;
15004                 if (ETHERNET_SEGMENT_SIZE > segsiz)
15005                         oh = ETHERNET_SEGMENT_SIZE - segsiz;
15006                 else
15007                         oh = 0;
15008                 segs *= oh;
15009                 lentim = (uint64_t)(len + segs) * (uint64_t)HPTS_USEC_IN_SEC;
15010                 res = lentim / rate_wanted;
15011                 slot = (uint32_t)res;
15012                 orig_val = rack->r_ctl.rc_pace_max_segs;
15013                 if (rack->r_ctl.crte == NULL) {
15014                         /*
15015                          * Only do this if we are not hardware pacing
15016                          * since if we are doing hw-pacing below we will
15017                          * set make a call after setting up or changing
15018                          * the rate.
15019                          */
15020                         rack_set_pace_segments(rack->rc_tp, rack, __LINE__, NULL);
15021                 } else if (rack->rc_inp->inp_snd_tag == NULL) {
15022                         /*
15023                          * We lost our rate somehow, this can happen
15024                          * if the interface changed underneath us.
15025                          */
15026                         tcp_rel_pacing_rate(rack->r_ctl.crte, rack->rc_tp);
15027                         rack->r_ctl.crte = NULL;
15028                         /* Lets re-allow attempting to setup pacing */
15029                         rack->rack_hdrw_pacing = 0;
15030                         rack->rack_attempt_hdwr_pace = 0;
15031                         rack_log_hdwr_pacing(rack,
15032                                              rate_wanted, bw_est, __LINE__,
15033                                              0, 6);
15034                 }
15035                 /* Did we change the TSO size, if so log it */
15036                 if (rack->r_ctl.rc_pace_max_segs != orig_val)
15037                         rack_log_pacing_delay_calc(rack, len, slot, orig_val, 0, 0, 15, __LINE__, NULL, 0);
15038                 prev_fill = rack->r_via_fill_cw;
15039                 if ((rack->rc_pace_to_cwnd) &&
15040                     (capped == 0) &&
15041                     (rack->use_fixed_rate == 0) &&
15042                     (rack->in_probe_rtt == 0) &&
15043                     (IN_FASTRECOVERY(rack->rc_tp->t_flags) == 0)) {
15044                         /*
15045                          * We want to pace at our rate *or* faster to
15046                          * fill the cwnd to the max if its not full.
15047                          */
15048                         slot = pace_to_fill_cwnd(rack, slot, (len+segs), segsiz, &capped, &rate_wanted, 0);
15049                 }
15050                 if ((rack->rc_inp->inp_route.ro_nh != NULL) &&
15051                     (rack->rc_inp->inp_route.ro_nh->nh_ifp != NULL)) {
15052                         if ((rack->rack_hdw_pace_ena) &&
15053                             (can_start_hw_pacing > 0) &&
15054                             (rack->rack_hdrw_pacing == 0) &&
15055                             (rack->rack_attempt_hdwr_pace == 0)) {
15056                                 /*
15057                                  * Lets attempt to turn on hardware pacing
15058                                  * if we can.
15059                                  */
15060                                 rack->rack_attempt_hdwr_pace = 1;
15061                                 rack->r_ctl.crte = tcp_set_pacing_rate(rack->rc_tp,
15062                                                                        rack->rc_inp->inp_route.ro_nh->nh_ifp,
15063                                                                        rate_wanted,
15064                                                                        RS_PACING_GEQ,
15065                                                                        &err, &rack->r_ctl.crte_prev_rate);
15066                                 if (rack->r_ctl.crte) {
15067                                         rack->rack_hdrw_pacing = 1;
15068                                         rack->r_ctl.rc_pace_max_segs = tcp_get_pacing_burst_size(tp, rate_wanted, segsiz,
15069                                                                                                  0, rack->r_ctl.crte,
15070                                                                                                  NULL);
15071                                         rack_log_hdwr_pacing(rack,
15072                                                              rate_wanted, rack->r_ctl.crte->rate, __LINE__,
15073                                                              err, 0);
15074                                         rack->r_ctl.last_hw_bw_req = rate_wanted;
15075                                 } else {
15076                                         counter_u64_add(rack_hw_pace_init_fail, 1);
15077                                 }
15078                         } else if (rack->rack_hdrw_pacing &&
15079                                    (rack->r_ctl.last_hw_bw_req != rate_wanted)) {
15080                                 /* Do we need to adjust our rate? */
15081                                 const struct tcp_hwrate_limit_table *nrte;
15082
15083                                 if (rack->r_up_only &&
15084                                     (rate_wanted < rack->r_ctl.crte->rate)) {
15085                                         /**
15086                                          * We have four possible states here
15087                                          * having to do with the previous time
15088                                          * and this time.
15089                                          *   previous  |  this-time
15090                                          * A)     0      |     0   -- fill_cw not in the picture
15091                                          * B)     1      |     0   -- we were doing a fill-cw but now are not
15092                                          * C)     1      |     1   -- all rates from fill_cw
15093                                          * D)     0      |     1   -- we were doing non-fill and now we are filling
15094                                          *
15095                                          * For case A, C and D we don't allow a drop. But for
15096                                          * case B where we now our on our steady rate we do
15097                                          * allow a drop.
15098                                          *
15099                                          */
15100                                         if (!((prev_fill == 1) && (rack->r_via_fill_cw == 0)))
15101                                                 goto done_w_hdwr;
15102                                 }
15103                                 if ((rate_wanted > rack->r_ctl.crte->rate) ||
15104                                     (rate_wanted <= rack->r_ctl.crte_prev_rate)) {
15105                                         if (rack_hw_rate_to_low &&
15106                                             (bw_est < rack_hw_rate_to_low)) {
15107                                                 /*
15108                                                  * The pacing rate is too low for hardware, but
15109                                                  * do allow hardware pacing to be restarted.
15110                                                  */
15111                                                 rack_log_hdwr_pacing(rack,
15112                                                              bw_est, rack->r_ctl.crte->rate, __LINE__,
15113                                                              0, 5);
15114                                                 tcp_rel_pacing_rate(rack->r_ctl.crte, rack->rc_tp);
15115                                                 rack->r_ctl.crte = NULL;
15116                                                 rack->rack_attempt_hdwr_pace = 0;
15117                                                 rack->rack_hdrw_pacing = 0;
15118                                                 rack_set_pace_segments(rack->rc_tp, rack, __LINE__, &rate_wanted);
15119                                                 goto done_w_hdwr;
15120                                         }
15121                                         nrte = tcp_chg_pacing_rate(rack->r_ctl.crte,
15122                                                                    rack->rc_tp,
15123                                                                    rack->rc_inp->inp_route.ro_nh->nh_ifp,
15124                                                                    rate_wanted,
15125                                                                    RS_PACING_GEQ,
15126                                                                    &err, &rack->r_ctl.crte_prev_rate);
15127                                         if (nrte == NULL) {
15128                                                 /* Lost the rate */
15129                                                 rack->rack_hdrw_pacing = 0;
15130                                                 rack->r_ctl.crte = NULL;
15131                                                 rack_log_hdwr_pacing(rack,
15132                                                                      rate_wanted, 0, __LINE__,
15133                                                                      err, 1);
15134                                                 rack_set_pace_segments(rack->rc_tp, rack, __LINE__, &rate_wanted);
15135                                                 counter_u64_add(rack_hw_pace_lost, 1);
15136                                         } else if (nrte != rack->r_ctl.crte) {
15137                                                 rack->r_ctl.crte = nrte;
15138                                                 rack->r_ctl.rc_pace_max_segs = tcp_get_pacing_burst_size(tp, rate_wanted,
15139                                                                                                          segsiz, 0,
15140                                                                                                          rack->r_ctl.crte,
15141                                                                                                          NULL);
15142                                                 rack_log_hdwr_pacing(rack,
15143                                                                      rate_wanted, rack->r_ctl.crte->rate, __LINE__,
15144                                                                      err, 2);
15145                                                 rack->r_ctl.last_hw_bw_req = rate_wanted;
15146                                         }
15147                                 } else {
15148                                         /* We just need to adjust the segment size */
15149                                         rack_set_pace_segments(rack->rc_tp, rack, __LINE__, &rate_wanted);
15150                                         rack_log_hdwr_pacing(rack,
15151                                                              rate_wanted, rack->r_ctl.crte->rate, __LINE__,
15152                                                              0, 4);
15153                                         rack->r_ctl.last_hw_bw_req = rate_wanted;
15154                                 }
15155                         }
15156                 }
15157                 if ((rack->r_ctl.crte != NULL) &&
15158                     (rack->r_ctl.crte->rate == rate_wanted)) {
15159                         /*
15160                          * We need to add a extra if the rates
15161                          * are exactly matched. The idea is
15162                          * we want the software to make sure the
15163                          * queue is empty before adding more, this
15164                          * gives us N MSS extra pace times where
15165                          * N is our sysctl
15166                          */
15167                         slot += (rack->r_ctl.crte->time_between * rack_hw_pace_extra_slots);
15168                 }
15169 done_w_hdwr:
15170                 if (rack_limit_time_with_srtt &&
15171                     (rack->use_fixed_rate == 0) &&
15172 #ifdef NETFLIX_PEAKRATE
15173                     (rack->rc_tp->t_maxpeakrate == 0) &&
15174 #endif
15175                     (rack->rack_hdrw_pacing == 0)) {
15176                         /*
15177                          * Sanity check, we do not allow the pacing delay
15178                          * to be longer than the SRTT of the path. If it is
15179                          * a slow path, then adding a packet should increase
15180                          * the RTT and compensate for this i.e. the srtt will
15181                          * be greater so the allowed pacing time will be greater.
15182                          *
15183                          * Note this restriction is not for where a peak rate
15184                          * is set, we are doing fixed pacing or hardware pacing.
15185                          */
15186                         if (rack->rc_tp->t_srtt)
15187                                 srtt = rack->rc_tp->t_srtt;
15188                         else
15189                                 srtt = RACK_INITIAL_RTO * HPTS_USEC_IN_MSEC;    /* its in ms convert */
15190                         if (srtt < (uint64_t)slot) {
15191                                 rack_log_pacing_delay_calc(rack, srtt, slot, rate_wanted, bw_est, lentim, 99, __LINE__, NULL, 0);
15192                                 slot = srtt;
15193                         }
15194                 }
15195                 rack_log_pacing_delay_calc(rack, len, slot, rate_wanted, bw_est, lentim, 2, __LINE__, rsm, 0);
15196         }
15197         if (rack->r_ctl.crte && (rack->r_ctl.crte->rs_num_enobufs > 0)) {
15198                 /*
15199                  * If this rate is seeing enobufs when it
15200                  * goes to send then either the nic is out
15201                  * of gas or we are mis-estimating the time
15202                  * somehow and not letting the queue empty
15203                  * completely. Lets add to the pacing time.
15204                  */
15205                 int hw_boost_delay;
15206
15207                 hw_boost_delay = rack->r_ctl.crte->time_between * rack_enobuf_hw_boost_mult;
15208                 if (hw_boost_delay > rack_enobuf_hw_max)
15209                         hw_boost_delay = rack_enobuf_hw_max;
15210                 else if (hw_boost_delay < rack_enobuf_hw_min)
15211                         hw_boost_delay = rack_enobuf_hw_min;
15212                 slot += hw_boost_delay;
15213         }
15214         return (slot);
15215 }
15216
15217 static void
15218 rack_start_gp_measurement(struct tcpcb *tp, struct tcp_rack *rack,
15219     tcp_seq startseq, uint32_t sb_offset)
15220 {
15221         struct rack_sendmap *my_rsm = NULL;
15222         struct rack_sendmap fe;
15223
15224         if (tp->t_state < TCPS_ESTABLISHED) {
15225                 /*
15226                  * We don't start any measurements if we are
15227                  * not at least established.
15228                  */
15229                 return;
15230         }
15231         if (tp->t_state >= TCPS_FIN_WAIT_1) {
15232                 /*
15233                  * We will get no more data into the SB
15234                  * this means we need to have the data available
15235                  * before we start a measurement.
15236                  */
15237
15238                 if (sbavail(&tptosocket(tp)->so_snd) <
15239                     max(rc_init_window(rack),
15240                         (MIN_GP_WIN * ctf_fixed_maxseg(tp)))) {
15241                         /* Nope not enough data */
15242                         return;
15243                 }
15244         }
15245         tp->t_flags |= TF_GPUTINPROG;
15246         rack->r_ctl.rc_gp_lowrtt = 0xffffffff;
15247         rack->r_ctl.rc_gp_high_rwnd = rack->rc_tp->snd_wnd;
15248         tp->gput_seq = startseq;
15249         rack->app_limited_needs_set = 0;
15250         if (rack->in_probe_rtt)
15251                 rack->measure_saw_probe_rtt = 1;
15252         else if ((rack->measure_saw_probe_rtt) &&
15253                  (SEQ_GEQ(tp->gput_seq, rack->r_ctl.rc_probertt_sndmax_atexit)))
15254                 rack->measure_saw_probe_rtt = 0;
15255         if (rack->rc_gp_filled)
15256                 tp->gput_ts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
15257         else {
15258                 /* Special case initial measurement */
15259                 struct timeval tv;
15260
15261                 tp->gput_ts = tcp_get_usecs(&tv);
15262                 rack->r_ctl.rc_gp_output_ts = rack_to_usec_ts(&tv);
15263         }
15264         /*
15265          * We take a guess out into the future,
15266          * if we have no measurement and no
15267          * initial rate, we measure the first
15268          * initial-windows worth of data to
15269          * speed up getting some GP measurement and
15270          * thus start pacing.
15271          */
15272         if ((rack->rc_gp_filled == 0) && (rack->r_ctl.init_rate == 0)) {
15273                 rack->app_limited_needs_set = 1;
15274                 tp->gput_ack = startseq + max(rc_init_window(rack),
15275                                               (MIN_GP_WIN * ctf_fixed_maxseg(tp)));
15276                 rack_log_pacing_delay_calc(rack,
15277                                            tp->gput_seq,
15278                                            tp->gput_ack,
15279                                            0,
15280                                            tp->gput_ts,
15281                                            rack->r_ctl.rc_app_limited_cnt,
15282                                            9,
15283                                            __LINE__, NULL, 0);
15284                 return;
15285         }
15286         if (sb_offset) {
15287                 /*
15288                  * We are out somewhere in the sb
15289                  * can we use the already outstanding data?
15290                  */
15291                 if (rack->r_ctl.rc_app_limited_cnt == 0) {
15292                         /*
15293                          * Yes first one is good and in this case
15294                          * the tp->gput_ts is correctly set based on
15295                          * the last ack that arrived (no need to
15296                          * set things up when an ack comes in).
15297                          */
15298                         my_rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
15299                         if ((my_rsm == NULL) ||
15300                             (my_rsm->r_rtr_cnt != 1)) {
15301                                 /* retransmission? */
15302                                 goto use_latest;
15303                         }
15304                 } else {
15305                         if (rack->r_ctl.rc_first_appl == NULL) {
15306                                 /*
15307                                  * If rc_first_appl is NULL
15308                                  * then the cnt should be 0.
15309                                  * This is probably an error, maybe
15310                                  * a KASSERT would be approprate.
15311                                  */
15312                                 goto use_latest;
15313                         }
15314                         /*
15315                          * If we have a marker pointer to the last one that is
15316                          * app limited we can use that, but we need to set
15317                          * things up so that when it gets ack'ed we record
15318                          * the ack time (if its not already acked).
15319                          */
15320                         rack->app_limited_needs_set = 1;
15321                         /*
15322                          * We want to get to the rsm that is either
15323                          * next with space i.e. over 1 MSS or the one
15324                          * after that (after the app-limited).
15325                          */
15326                         my_rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree,
15327                                          rack->r_ctl.rc_first_appl);
15328                         if (my_rsm) {
15329                                 if ((my_rsm->r_end - my_rsm->r_start) <= ctf_fixed_maxseg(tp))
15330                                         /* Have to use the next one */
15331                                         my_rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree,
15332                                                          my_rsm);
15333                                 else {
15334                                         /* Use after the first MSS of it is acked */
15335                                         tp->gput_seq = my_rsm->r_start + ctf_fixed_maxseg(tp);
15336                                         goto start_set;
15337                                 }
15338                         }
15339                         if ((my_rsm == NULL) ||
15340                             (my_rsm->r_rtr_cnt != 1)) {
15341                                 /*
15342                                  * Either its a retransmit or
15343                                  * the last is the app-limited one.
15344                                  */
15345                                 goto use_latest;
15346                         }
15347                 }
15348                 tp->gput_seq = my_rsm->r_start;
15349 start_set:
15350                 if (my_rsm->r_flags & RACK_ACKED) {
15351                         /*
15352                          * This one has been acked use the arrival ack time
15353                          */
15354                         tp->gput_ts = (uint32_t)my_rsm->r_ack_arrival;
15355                         rack->app_limited_needs_set = 0;
15356                 }
15357                 rack->r_ctl.rc_gp_output_ts = my_rsm->r_tim_lastsent[(my_rsm->r_rtr_cnt-1)];
15358                 tp->gput_ack = tp->gput_seq + rack_get_measure_window(tp, rack);
15359                 rack_log_pacing_delay_calc(rack,
15360                                            tp->gput_seq,
15361                                            tp->gput_ack,
15362                                            (uint64_t)my_rsm,
15363                                            tp->gput_ts,
15364                                            rack->r_ctl.rc_app_limited_cnt,
15365                                            9,
15366                                            __LINE__, NULL, 0);
15367                 return;
15368         }
15369
15370 use_latest:
15371         /*
15372          * We don't know how long we may have been
15373          * idle or if this is the first-send. Lets
15374          * setup the flag so we will trim off
15375          * the first ack'd data so we get a true
15376          * measurement.
15377          */
15378         rack->app_limited_needs_set = 1;
15379         tp->gput_ack = startseq + rack_get_measure_window(tp, rack);
15380         /* Find this guy so we can pull the send time */
15381         fe.r_start = startseq;
15382         my_rsm = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
15383         if (my_rsm) {
15384                 rack->r_ctl.rc_gp_output_ts = my_rsm->r_tim_lastsent[(my_rsm->r_rtr_cnt-1)];
15385                 if (my_rsm->r_flags & RACK_ACKED) {
15386                         /*
15387                          * Unlikely since its probably what was
15388                          * just transmitted (but I am paranoid).
15389                          */
15390                         tp->gput_ts = (uint32_t)my_rsm->r_ack_arrival;
15391                         rack->app_limited_needs_set = 0;
15392                 }
15393                 if (SEQ_LT(my_rsm->r_start, tp->gput_seq)) {
15394                         /* This also is unlikely */
15395                         tp->gput_seq = my_rsm->r_start;
15396                 }
15397         } else {
15398                 /*
15399                  * TSNH unless we have some send-map limit,
15400                  * and even at that it should not be hitting
15401                  * that limit (we should have stopped sending).
15402                  */
15403                 struct timeval tv;
15404
15405                 microuptime(&tv);
15406                 rack->r_ctl.rc_gp_output_ts = rack_to_usec_ts(&tv);
15407         }
15408         rack_log_pacing_delay_calc(rack,
15409                                    tp->gput_seq,
15410                                    tp->gput_ack,
15411                                    (uint64_t)my_rsm,
15412                                    tp->gput_ts,
15413                                    rack->r_ctl.rc_app_limited_cnt,
15414                                    9, __LINE__, NULL, 0);
15415 }
15416
15417 static inline uint32_t
15418 rack_what_can_we_send(struct tcpcb *tp, struct tcp_rack *rack,  uint32_t cwnd_to_use,
15419     uint32_t avail, int32_t sb_offset)
15420 {
15421         uint32_t len;
15422         uint32_t sendwin;
15423
15424         if (tp->snd_wnd > cwnd_to_use)
15425                 sendwin = cwnd_to_use;
15426         else
15427                 sendwin = tp->snd_wnd;
15428         if (ctf_outstanding(tp) >= tp->snd_wnd) {
15429                 /* We never want to go over our peers rcv-window */
15430                 len = 0;
15431         } else {
15432                 uint32_t flight;
15433
15434                 flight = ctf_flight_size(tp, rack->r_ctl.rc_sacked);
15435                 if (flight >= sendwin) {
15436                         /*
15437                          * We have in flight what we are allowed by cwnd (if
15438                          * it was rwnd blocking it would have hit above out
15439                          * >= tp->snd_wnd).
15440                          */
15441                         return (0);
15442                 }
15443                 len = sendwin - flight;
15444                 if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
15445                         /* We would send too much (beyond the rwnd) */
15446                         len = tp->snd_wnd - ctf_outstanding(tp);
15447                 }
15448                 if ((len + sb_offset) > avail) {
15449                         /*
15450                          * We don't have that much in the SB, how much is
15451                          * there?
15452                          */
15453                         len = avail - sb_offset;
15454                 }
15455         }
15456         return (len);
15457 }
15458
15459 static void
15460 rack_log_fsb(struct tcp_rack *rack, struct tcpcb *tp, struct socket *so, uint32_t flags,
15461              unsigned ipoptlen, int32_t orig_len, int32_t len, int error,
15462              int rsm_is_null, int optlen, int line, uint16_t mode)
15463 {
15464         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
15465                 union tcp_log_stackspecific log;
15466                 struct timeval tv;
15467
15468                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
15469                 log.u_bbr.inhpts = tcp_in_hpts(rack->rc_inp);
15470                 log.u_bbr.flex1 = error;
15471                 log.u_bbr.flex2 = flags;
15472                 log.u_bbr.flex3 = rsm_is_null;
15473                 log.u_bbr.flex4 = ipoptlen;
15474                 log.u_bbr.flex5 = tp->rcv_numsacks;
15475                 log.u_bbr.flex6 = rack->r_ctl.rc_agg_early;
15476                 log.u_bbr.flex7 = optlen;
15477                 log.u_bbr.flex8 = rack->r_fsb_inited;
15478                 log.u_bbr.applimited = rack->r_fast_output;
15479                 log.u_bbr.bw_inuse = rack_get_bw(rack);
15480                 log.u_bbr.pacing_gain = rack_get_output_gain(rack, NULL);
15481                 log.u_bbr.cwnd_gain = mode;
15482                 log.u_bbr.pkts_out = orig_len;
15483                 log.u_bbr.lt_epoch = len;
15484                 log.u_bbr.delivered = line;
15485                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
15486                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
15487                 tcp_log_event_(tp, NULL, &so->so_rcv, &so->so_snd, TCP_LOG_FSB, 0,
15488                                len, &log, false, NULL, NULL, 0, &tv);
15489         }
15490 }
15491
15492
15493 static struct mbuf *
15494 rack_fo_base_copym(struct mbuf *the_m, uint32_t the_off, int32_t *plen,
15495                    struct rack_fast_send_blk *fsb,
15496                    int32_t seglimit, int32_t segsize, int hw_tls)
15497 {
15498 #ifdef KERN_TLS
15499         struct ktls_session *tls, *ntls;
15500 #ifdef INVARIANTS
15501         struct mbuf *start;
15502 #endif
15503 #endif
15504         struct mbuf *m, *n, **np, *smb;
15505         struct mbuf *top;
15506         int32_t off, soff;
15507         int32_t len = *plen;
15508         int32_t fragsize;
15509         int32_t len_cp = 0;
15510         uint32_t mlen, frags;
15511
15512         soff = off = the_off;
15513         smb = m = the_m;
15514         np = &top;
15515         top = NULL;
15516 #ifdef KERN_TLS
15517         if (hw_tls && (m->m_flags & M_EXTPG))
15518                 tls = m->m_epg_tls;
15519         else
15520                 tls = NULL;
15521 #ifdef INVARIANTS
15522         start = m;
15523 #endif
15524 #endif
15525         while (len > 0) {
15526                 if (m == NULL) {
15527                         *plen = len_cp;
15528                         break;
15529                 }
15530 #ifdef KERN_TLS
15531                 if (hw_tls) {
15532                         if (m->m_flags & M_EXTPG)
15533                                 ntls = m->m_epg_tls;
15534                         else
15535                                 ntls = NULL;
15536
15537                         /*
15538                          * Avoid mixing TLS records with handshake
15539                          * data or TLS records from different
15540                          * sessions.
15541                          */
15542                         if (tls != ntls) {
15543                                 MPASS(m != start);
15544                                 *plen = len_cp;
15545                                 break;
15546                         }
15547                 }
15548 #endif
15549                 mlen = min(len, m->m_len - off);
15550                 if (seglimit) {
15551                         /*
15552                          * For M_EXTPG mbufs, add 3 segments
15553                          * + 1 in case we are crossing page boundaries
15554                          * + 2 in case the TLS hdr/trailer are used
15555                          * It is cheaper to just add the segments
15556                          * than it is to take the cache miss to look
15557                          * at the mbuf ext_pgs state in detail.
15558                          */
15559                         if (m->m_flags & M_EXTPG) {
15560                                 fragsize = min(segsize, PAGE_SIZE);
15561                                 frags = 3;
15562                         } else {
15563                                 fragsize = segsize;
15564                                 frags = 0;
15565                         }
15566
15567                         /* Break if we really can't fit anymore. */
15568                         if ((frags + 1) >= seglimit) {
15569                                 *plen = len_cp;
15570                                 break;
15571                         }
15572
15573                         /*
15574                          * Reduce size if you can't copy the whole
15575                          * mbuf. If we can't copy the whole mbuf, also
15576                          * adjust len so the loop will end after this
15577                          * mbuf.
15578                          */
15579                         if ((frags + howmany(mlen, fragsize)) >= seglimit) {
15580                                 mlen = (seglimit - frags - 1) * fragsize;
15581                                 len = mlen;
15582                                 *plen = len_cp + len;
15583                         }
15584                         frags += howmany(mlen, fragsize);
15585                         if (frags == 0)
15586                                 frags++;
15587                         seglimit -= frags;
15588                         KASSERT(seglimit > 0,
15589                             ("%s: seglimit went too low", __func__));
15590                 }
15591                 n = m_get(M_NOWAIT, m->m_type);
15592                 *np = n;
15593                 if (n == NULL)
15594                         goto nospace;
15595                 n->m_len = mlen;
15596                 soff += mlen;
15597                 len_cp += n->m_len;
15598                 if (m->m_flags & (M_EXT|M_EXTPG)) {
15599                         n->m_data = m->m_data + off;
15600                         mb_dupcl(n, m);
15601                 } else {
15602                         bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
15603                             (u_int)n->m_len);
15604                 }
15605                 len -= n->m_len;
15606                 off = 0;
15607                 m = m->m_next;
15608                 np = &n->m_next;
15609                 if (len || (soff == smb->m_len)) {
15610                         /*
15611                          * We have more so we move forward  or
15612                          * we have consumed the entire mbuf and
15613                          * len has fell to 0.
15614                          */
15615                         soff = 0;
15616                         smb = m;
15617                 }
15618
15619         }
15620         if (fsb != NULL) {
15621                 fsb->m = smb;
15622                 fsb->off = soff;
15623                 if (smb) {
15624                         /*
15625                          * Save off the size of the mbuf. We do
15626                          * this so that we can recognize when it
15627                          * has been trimmed by sbcut() as acks
15628                          * come in.
15629                          */
15630                         fsb->o_m_len = smb->m_len;
15631                 } else {
15632                         /*
15633                          * This is the case where the next mbuf went to NULL. This
15634                          * means with this copy we have sent everything in the sb.
15635                          * In theory we could clear the fast_output flag, but lets
15636                          * not since its possible that we could get more added
15637                          * and acks that call the extend function which would let
15638                          * us send more.
15639                          */
15640                         fsb->o_m_len = 0;
15641                 }
15642         }
15643         return (top);
15644 nospace:
15645         if (top)
15646                 m_freem(top);
15647         return (NULL);
15648
15649 }
15650
15651 /*
15652  * This is a copy of m_copym(), taking the TSO segment size/limit
15653  * constraints into account, and advancing the sndptr as it goes.
15654  */
15655 static struct mbuf *
15656 rack_fo_m_copym(struct tcp_rack *rack, int32_t *plen,
15657                 int32_t seglimit, int32_t segsize, struct mbuf **s_mb, int *s_soff)
15658 {
15659         struct mbuf *m, *n;
15660         int32_t soff;
15661
15662         soff = rack->r_ctl.fsb.off;
15663         m = rack->r_ctl.fsb.m;
15664         if (rack->r_ctl.fsb.o_m_len > m->m_len) {
15665                 /*
15666                  * The mbuf had the front of it chopped off by an ack
15667                  * we need to adjust the soff/off by that difference.
15668                  */
15669                 uint32_t delta;
15670
15671                 delta = rack->r_ctl.fsb.o_m_len - m->m_len;
15672                 soff -= delta;
15673         } else if (rack->r_ctl.fsb.o_m_len < m->m_len) {
15674                 /*
15675                  * The mbuf was expanded probably by
15676                  * a m_compress. Just update o_m_len.
15677                  */
15678                 rack->r_ctl.fsb.o_m_len = m->m_len;
15679         }
15680         KASSERT(soff >= 0, ("%s, negative off %d", __FUNCTION__, soff));
15681         KASSERT(*plen >= 0, ("%s, negative len %d", __FUNCTION__, *plen));
15682         KASSERT(soff < m->m_len, ("%s rack:%p len:%u m:%p m->m_len:%u < off?",
15683                                  __FUNCTION__,
15684                                  rack, *plen, m, m->m_len));
15685         /* Save off the right location before we copy and advance */
15686         *s_soff = soff;
15687         *s_mb = rack->r_ctl.fsb.m;
15688         n = rack_fo_base_copym(m, soff, plen,
15689                                &rack->r_ctl.fsb,
15690                                seglimit, segsize, rack->r_ctl.fsb.hw_tls);
15691         return (n);
15692 }
15693
15694 static int
15695 rack_fast_rsm_output(struct tcpcb *tp, struct tcp_rack *rack, struct rack_sendmap *rsm,
15696                      uint64_t ts_val, uint32_t cts, uint32_t ms_cts, struct timeval *tv, int len, uint8_t doing_tlp)
15697 {
15698         /*
15699          * Enter the fast retransmit path. We are given that a sched_pin is
15700          * in place (if accounting is compliled in) and the cycle count taken
15701          * at the entry is in the ts_val. The concept her is that the rsm
15702          * now holds the mbuf offsets and such so we can directly transmit
15703          * without a lot of overhead, the len field is already set for
15704          * us to prohibit us from sending too much (usually its 1MSS).
15705          */
15706         struct ip *ip = NULL;
15707         struct udphdr *udp = NULL;
15708         struct tcphdr *th = NULL;
15709         struct mbuf *m = NULL;
15710         struct inpcb *inp;
15711         uint8_t *cpto;
15712         struct tcp_log_buffer *lgb;
15713 #ifdef TCP_ACCOUNTING
15714         uint64_t crtsc;
15715         int cnt_thru = 1;
15716 #endif
15717         struct tcpopt to;
15718         u_char opt[TCP_MAXOLEN];
15719         uint32_t hdrlen, optlen;
15720         int32_t slot, segsiz, max_val, tso = 0, error, ulen = 0;
15721         uint16_t flags;
15722         uint32_t if_hw_tsomaxsegcount = 0, startseq;
15723         uint32_t if_hw_tsomaxsegsize;
15724
15725 #ifdef INET6
15726         struct ip6_hdr *ip6 = NULL;
15727
15728         if (rack->r_is_v6) {
15729                 ip6 = (struct ip6_hdr *)rack->r_ctl.fsb.tcp_ip_hdr;
15730                 hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
15731         } else
15732 #endif                          /* INET6 */
15733         {
15734                 ip = (struct ip *)rack->r_ctl.fsb.tcp_ip_hdr;
15735                 hdrlen = sizeof(struct tcpiphdr);
15736         }
15737         if (tp->t_port && (V_tcp_udp_tunneling_port == 0)) {
15738                 goto failed;
15739         }
15740         if (doing_tlp) {
15741                 /* Its a TLP add the flag, it may already be there but be sure */
15742                 rsm->r_flags |= RACK_TLP;
15743         } else {
15744                 /* If it was a TLP it is not not on this retransmit */
15745                 rsm->r_flags &= ~RACK_TLP;
15746         }
15747         startseq = rsm->r_start;
15748         segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
15749         inp = rack->rc_inp;
15750         to.to_flags = 0;
15751         flags = tcp_outflags[tp->t_state];
15752         if (flags & (TH_SYN|TH_RST)) {
15753                 goto failed;
15754         }
15755         if (rsm->r_flags & RACK_HAS_FIN) {
15756                 /* We can't send a FIN here */
15757                 goto failed;
15758         }
15759         if (flags & TH_FIN) {
15760                 /* We never send a FIN */
15761                 flags &= ~TH_FIN;
15762         }
15763         if (tp->t_flags & TF_RCVD_TSTMP) {
15764                 to.to_tsval = ms_cts + tp->ts_offset;
15765                 to.to_tsecr = tp->ts_recent;
15766                 to.to_flags = TOF_TS;
15767         }
15768         optlen = tcp_addoptions(&to, opt);
15769         hdrlen += optlen;
15770         udp = rack->r_ctl.fsb.udp;
15771         if (udp)
15772                 hdrlen += sizeof(struct udphdr);
15773         if (rack->r_ctl.rc_pace_max_segs)
15774                 max_val = rack->r_ctl.rc_pace_max_segs;
15775         else if (rack->rc_user_set_max_segs)
15776                 max_val = rack->rc_user_set_max_segs * segsiz;
15777         else
15778                 max_val = len;
15779         if ((tp->t_flags & TF_TSO) &&
15780             V_tcp_do_tso &&
15781             (len > segsiz) &&
15782             (tp->t_port == 0))
15783                 tso = 1;
15784 #ifdef INET6
15785         if (MHLEN < hdrlen + max_linkhdr)
15786                 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
15787         else
15788 #endif
15789                 m = m_gethdr(M_NOWAIT, MT_DATA);
15790         if (m == NULL)
15791                 goto failed;
15792         m->m_data += max_linkhdr;
15793         m->m_len = hdrlen;
15794         th = rack->r_ctl.fsb.th;
15795         /* Establish the len to send */
15796         if (len > max_val)
15797                 len = max_val;
15798         if ((tso) && (len + optlen > tp->t_maxseg)) {
15799                 uint32_t if_hw_tsomax;
15800                 int32_t max_len;
15801
15802                 /* extract TSO information */
15803                 if_hw_tsomax = tp->t_tsomax;
15804                 if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
15805                 if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
15806                 /*
15807                  * Check if we should limit by maximum payload
15808                  * length:
15809                  */
15810                 if (if_hw_tsomax != 0) {
15811                         /* compute maximum TSO length */
15812                         max_len = (if_hw_tsomax - hdrlen -
15813                                    max_linkhdr);
15814                         if (max_len <= 0) {
15815                                 goto failed;
15816                         } else if (len > max_len) {
15817                                 len = max_len;
15818                         }
15819                 }
15820                 if (len <= segsiz) {
15821                         /*
15822                          * In case there are too many small fragments don't
15823                          * use TSO:
15824                          */
15825                         tso = 0;
15826                 }
15827         } else {
15828                 tso = 0;
15829         }
15830         if ((tso == 0) && (len > segsiz))
15831                 len = segsiz;
15832         if ((len == 0) ||
15833             (len <= MHLEN - hdrlen - max_linkhdr)) {
15834                 goto failed;
15835         }
15836         th->th_seq = htonl(rsm->r_start);
15837         th->th_ack = htonl(tp->rcv_nxt);
15838         /*
15839          * The PUSH bit should only be applied
15840          * if the full retransmission is made. If
15841          * we are sending less than this is the
15842          * left hand edge and should not have
15843          * the PUSH bit.
15844          */
15845         if ((rsm->r_flags & RACK_HAD_PUSH) &&
15846             (len == (rsm->r_end - rsm->r_start)))
15847                 flags |= TH_PUSH;
15848         th->th_win = htons((u_short)(rack->r_ctl.fsb.recwin >> tp->rcv_scale));
15849         if (th->th_win == 0) {
15850                 tp->t_sndzerowin++;
15851                 tp->t_flags |= TF_RXWIN0SENT;
15852         } else
15853                 tp->t_flags &= ~TF_RXWIN0SENT;
15854         if (rsm->r_flags & RACK_TLP) {
15855                 /*
15856                  * TLP should not count in retran count, but
15857                  * in its own bin
15858                  */
15859                 counter_u64_add(rack_tlp_retran, 1);
15860                 counter_u64_add(rack_tlp_retran_bytes, len);
15861         } else {
15862                 tp->t_sndrexmitpack++;
15863                 KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
15864                 KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
15865         }
15866 #ifdef STATS
15867         stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
15868                                  len);
15869 #endif
15870         if (rsm->m == NULL)
15871                 goto failed;
15872         if (rsm->orig_m_len != rsm->m->m_len) {
15873                 /* Fix up the orig_m_len and possibly the mbuf offset */
15874                 rack_adjust_orig_mlen(rsm);
15875         }
15876         m->m_next = rack_fo_base_copym(rsm->m, rsm->soff, &len, NULL, if_hw_tsomaxsegcount, if_hw_tsomaxsegsize, rsm->r_hw_tls);
15877         if (len <= segsiz) {
15878                 /*
15879                  * Must have ran out of mbufs for the copy
15880                  * shorten it to no longer need tso. Lets
15881                  * not put on sendalot since we are low on
15882                  * mbufs.
15883                  */
15884                 tso = 0;
15885         }
15886         if ((m->m_next == NULL) || (len <= 0)){
15887                 goto failed;
15888         }
15889         if (udp) {
15890                 if (rack->r_is_v6)
15891                         ulen = hdrlen + len - sizeof(struct ip6_hdr);
15892                 else
15893                         ulen = hdrlen + len - sizeof(struct ip);
15894                 udp->uh_ulen = htons(ulen);
15895         }
15896         m->m_pkthdr.rcvif = (struct ifnet *)0;
15897         if (TCPS_HAVERCVDSYN(tp->t_state) &&
15898             (tp->t_flags2 & (TF2_ECN_PERMIT | TF2_ACE_PERMIT))) {
15899                 int ect = tcp_ecn_output_established(tp, &flags, len, true);
15900                 if ((tp->t_state == TCPS_SYN_RECEIVED) &&
15901                     (tp->t_flags2 & TF2_ECN_SND_ECE))
15902                     tp->t_flags2 &= ~TF2_ECN_SND_ECE;
15903 #ifdef INET6
15904                 if (rack->r_is_v6) {
15905                     ip6->ip6_flow &= ~htonl(IPTOS_ECN_MASK << 20);
15906                     ip6->ip6_flow |= htonl(ect << 20);
15907                 }
15908                 else
15909 #endif
15910                 {
15911                     ip->ip_tos &= ~IPTOS_ECN_MASK;
15912                     ip->ip_tos |= ect;
15913                 }
15914         }
15915         tcp_set_flags(th, flags);
15916         m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
15917 #ifdef INET6
15918         if (rack->r_is_v6) {
15919                 if (tp->t_port) {
15920                         m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
15921                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
15922                         udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
15923                         th->th_sum = htons(0);
15924                         UDPSTAT_INC(udps_opackets);
15925                 } else {
15926                         m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
15927                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
15928                         th->th_sum = in6_cksum_pseudo(ip6,
15929                                                       sizeof(struct tcphdr) + optlen + len, IPPROTO_TCP,
15930                                                       0);
15931                 }
15932         }
15933 #endif
15934 #if defined(INET6) && defined(INET)
15935         else
15936 #endif
15937 #ifdef INET
15938         {
15939                 if (tp->t_port) {
15940                         m->m_pkthdr.csum_flags = CSUM_UDP;
15941                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
15942                         udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
15943                                                 ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
15944                         th->th_sum = htons(0);
15945                         UDPSTAT_INC(udps_opackets);
15946                 } else {
15947                         m->m_pkthdr.csum_flags = CSUM_TCP;
15948                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
15949                         th->th_sum = in_pseudo(ip->ip_src.s_addr,
15950                                                ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
15951                                                                         IPPROTO_TCP + len + optlen));
15952                 }
15953                 /* IP version must be set here for ipv4/ipv6 checking later */
15954                 KASSERT(ip->ip_v == IPVERSION,
15955                         ("%s: IP version incorrect: %d", __func__, ip->ip_v));
15956         }
15957 #endif
15958         if (tso) {
15959                 KASSERT(len > tp->t_maxseg - optlen,
15960                         ("%s: len <= tso_segsz tp:%p", __func__, tp));
15961                 m->m_pkthdr.csum_flags |= CSUM_TSO;
15962                 m->m_pkthdr.tso_segsz = tp->t_maxseg - optlen;
15963         }
15964 #ifdef INET6
15965         if (rack->r_is_v6) {
15966                 ip6->ip6_hlim = rack->r_ctl.fsb.hoplimit;
15967                 ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
15968                 if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss)
15969                         tp->t_flags2 |= TF2_PLPMTU_PMTUD;
15970                 else
15971                         tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
15972         }
15973 #endif
15974 #if defined(INET) && defined(INET6)
15975         else
15976 #endif
15977 #ifdef INET
15978         {
15979                 ip->ip_len = htons(m->m_pkthdr.len);
15980                 ip->ip_ttl = rack->r_ctl.fsb.hoplimit;
15981                 if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
15982                         tp->t_flags2 |= TF2_PLPMTU_PMTUD;
15983                         if (tp->t_port == 0 || len < V_tcp_minmss) {
15984                                 ip->ip_off |= htons(IP_DF);
15985                         }
15986                 } else {
15987                         tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
15988                 }
15989         }
15990 #endif
15991         /* Time to copy in our header */
15992         cpto = mtod(m, uint8_t *);
15993         memcpy(cpto, rack->r_ctl.fsb.tcp_ip_hdr, rack->r_ctl.fsb.tcp_ip_hdr_len);
15994         th = (struct tcphdr *)(cpto + ((uint8_t *)rack->r_ctl.fsb.th - rack->r_ctl.fsb.tcp_ip_hdr));
15995         if (optlen) {
15996                 bcopy(opt, th + 1, optlen);
15997                 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
15998         } else {
15999                 th->th_off = sizeof(struct tcphdr) >> 2;
16000         }
16001         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
16002                 union tcp_log_stackspecific log;
16003
16004                 if (rsm->r_flags & RACK_RWND_COLLAPSED) {
16005                         rack_log_collapse(rack, rsm->r_start, rsm->r_end, 0, __LINE__, 5, rsm->r_flags, rsm);
16006                         counter_u64_add(rack_collapsed_win_rxt, 1);
16007                         counter_u64_add(rack_collapsed_win_rxt_bytes, (rsm->r_end - rsm->r_start));
16008                 }
16009                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
16010                 log.u_bbr.inhpts = tcp_in_hpts(rack->rc_inp);
16011                 if (rack->rack_no_prr)
16012                         log.u_bbr.flex1 = 0;
16013                 else
16014                         log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
16015                 log.u_bbr.flex2 = rack->r_ctl.rc_pace_min_segs;
16016                 log.u_bbr.flex3 = rack->r_ctl.rc_pace_max_segs;
16017                 log.u_bbr.flex4 = max_val;
16018                 log.u_bbr.flex5 = 0;
16019                 /* Save off the early/late values */
16020                 log.u_bbr.flex6 = rack->r_ctl.rc_agg_early;
16021                 log.u_bbr.applimited = rack->r_ctl.rc_agg_delayed;
16022                 log.u_bbr.bw_inuse = rack_get_bw(rack);
16023                 if (doing_tlp == 0)
16024                         log.u_bbr.flex8 = 1;
16025                 else
16026                         log.u_bbr.flex8 = 2;
16027                 log.u_bbr.pacing_gain = rack_get_output_gain(rack, NULL);
16028                 log.u_bbr.flex7 = 55;
16029                 log.u_bbr.pkts_out = tp->t_maxseg;
16030                 log.u_bbr.timeStamp = cts;
16031                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
16032                 log.u_bbr.lt_epoch = rack->r_ctl.cwnd_to_use;
16033                 log.u_bbr.delivered = 0;
16034                 lgb = tcp_log_event_(tp, th, NULL, NULL, TCP_LOG_OUT, ERRNO_UNK,
16035                                      len, &log, false, NULL, NULL, 0, tv);
16036         } else
16037                 lgb = NULL;
16038 #ifdef INET6
16039         if (rack->r_is_v6) {
16040                 error = ip6_output(m, NULL,
16041                                    &inp->inp_route6,
16042                                    0, NULL, NULL, inp);
16043         }
16044 #endif
16045 #if defined(INET) && defined(INET6)
16046         else
16047 #endif
16048 #ifdef INET
16049         {
16050                 error = ip_output(m, NULL,
16051                                   &inp->inp_route,
16052                                   0, 0, inp);
16053         }
16054 #endif
16055         m = NULL;
16056         if (lgb) {
16057                 lgb->tlb_errno = error;
16058                 lgb = NULL;
16059         }
16060         if (error) {
16061                 goto failed;
16062         }
16063         rack_log_output(tp, &to, len, rsm->r_start, flags, error, rack_to_usec_ts(tv),
16064                         rsm, RACK_SENT_FP, rsm->m, rsm->soff, rsm->r_hw_tls);
16065         if (doing_tlp && (rack->fast_rsm_hack == 0)) {
16066                 rack->rc_tlp_in_progress = 1;
16067                 rack->r_ctl.rc_tlp_cnt_out++;
16068         }
16069         if (error == 0) {
16070                 tcp_account_for_send(tp, len, 1, doing_tlp, rsm->r_hw_tls);
16071                 if (doing_tlp) {
16072                         rack->rc_last_sent_tlp_past_cumack = 0;
16073                         rack->rc_last_sent_tlp_seq_valid = 1;
16074                         rack->r_ctl.last_sent_tlp_seq = rsm->r_start;
16075                         rack->r_ctl.last_sent_tlp_len = rsm->r_end - rsm->r_start;
16076                 }
16077         }
16078         tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
16079         rack->forced_ack = 0;   /* If we send something zap the FA flag */
16080         if (IN_FASTRECOVERY(tp->t_flags) && rsm)
16081                 rack->r_ctl.retran_during_recovery += len;
16082         {
16083                 int idx;
16084
16085                 idx = (len / segsiz) + 3;
16086                 if (idx >= TCP_MSS_ACCT_ATIMER)
16087                         counter_u64_add(rack_out_size[(TCP_MSS_ACCT_ATIMER-1)], 1);
16088                 else
16089                         counter_u64_add(rack_out_size[idx], 1);
16090         }
16091         if (tp->t_rtttime == 0) {
16092                 tp->t_rtttime = ticks;
16093                 tp->t_rtseq = startseq;
16094                 KMOD_TCPSTAT_INC(tcps_segstimed);
16095         }
16096         counter_u64_add(rack_fto_rsm_send, 1);
16097         if (error && (error == ENOBUFS)) {
16098                 if (rack->r_ctl.crte != NULL) {
16099                         rack_trace_point(rack, RACK_TP_HWENOBUF);
16100                 } else
16101                         rack_trace_point(rack, RACK_TP_ENOBUF);
16102                 slot = ((1 + rack->rc_enobuf) * HPTS_USEC_IN_MSEC);
16103                 if (rack->rc_enobuf < 0x7f)
16104                         rack->rc_enobuf++;
16105                 if (slot < (10 * HPTS_USEC_IN_MSEC))
16106                         slot = 10 * HPTS_USEC_IN_MSEC;
16107         } else
16108                 slot = rack_get_pacing_delay(rack, tp, len, NULL, segsiz);
16109         if ((slot == 0) ||
16110             (rack->rc_always_pace == 0) ||
16111             (rack->r_rr_config == 1)) {
16112                 /*
16113                  * We have no pacing set or we
16114                  * are using old-style rack or
16115                  * we are overridden to use the old 1ms pacing.
16116                  */
16117                 slot = rack->r_ctl.rc_min_to;
16118         }
16119         rack_start_hpts_timer(rack, tp, cts, slot, len, 0);
16120 #ifdef TCP_ACCOUNTING
16121         crtsc = get_cyclecount();
16122         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16123                 tp->tcp_cnt_counters[SND_OUT_DATA] += cnt_thru;
16124         }
16125         counter_u64_add(tcp_cnt_counters[SND_OUT_DATA], cnt_thru);
16126         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16127                 tp->tcp_proc_time[SND_OUT_DATA] += (crtsc - ts_val);
16128         }
16129         counter_u64_add(tcp_proc_time[SND_OUT_DATA], (crtsc - ts_val));
16130         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16131                 tp->tcp_cnt_counters[CNT_OF_MSS_OUT] += ((len + segsiz - 1) / segsiz);
16132         }
16133         counter_u64_add(tcp_cnt_counters[CNT_OF_MSS_OUT], ((len + segsiz - 1) / segsiz));
16134         sched_unpin();
16135 #endif
16136         return (0);
16137 failed:
16138         if (m)
16139                 m_free(m);
16140         return (-1);
16141 }
16142
16143 static void
16144 rack_sndbuf_autoscale(struct tcp_rack *rack)
16145 {
16146         /*
16147          * Automatic sizing of send socket buffer.  Often the send buffer
16148          * size is not optimally adjusted to the actual network conditions
16149          * at hand (delay bandwidth product).  Setting the buffer size too
16150          * small limits throughput on links with high bandwidth and high
16151          * delay (eg. trans-continental/oceanic links).  Setting the
16152          * buffer size too big consumes too much real kernel memory,
16153          * especially with many connections on busy servers.
16154          *
16155          * The criteria to step up the send buffer one notch are:
16156          *  1. receive window of remote host is larger than send buffer
16157          *     (with a fudge factor of 5/4th);
16158          *  2. send buffer is filled to 7/8th with data (so we actually
16159          *     have data to make use of it);
16160          *  3. send buffer fill has not hit maximal automatic size;
16161          *  4. our send window (slow start and cogestion controlled) is
16162          *     larger than sent but unacknowledged data in send buffer.
16163          *
16164          * Note that the rack version moves things much faster since
16165          * we want to avoid hitting cache lines in the rack_fast_output()
16166          * path so this is called much less often and thus moves
16167          * the SB forward by a percentage.
16168          */
16169         struct socket *so;
16170         struct tcpcb *tp;
16171         uint32_t sendwin, scaleup;
16172
16173         tp = rack->rc_tp;
16174         so = rack->rc_inp->inp_socket;
16175         sendwin = min(rack->r_ctl.cwnd_to_use, tp->snd_wnd);
16176         if (V_tcp_do_autosndbuf && so->so_snd.sb_flags & SB_AUTOSIZE) {
16177                 if ((tp->snd_wnd / 4 * 5) >= so->so_snd.sb_hiwat &&
16178                     sbused(&so->so_snd) >=
16179                     (so->so_snd.sb_hiwat / 8 * 7) &&
16180                     sbused(&so->so_snd) < V_tcp_autosndbuf_max &&
16181                     sendwin >= (sbused(&so->so_snd) -
16182                     (tp->snd_nxt - tp->snd_una))) {
16183                         if (rack_autosndbuf_inc)
16184                                 scaleup = (rack_autosndbuf_inc * so->so_snd.sb_hiwat) / 100;
16185                         else
16186                                 scaleup = V_tcp_autosndbuf_inc;
16187                         if (scaleup < V_tcp_autosndbuf_inc)
16188                                 scaleup = V_tcp_autosndbuf_inc;
16189                         scaleup += so->so_snd.sb_hiwat;
16190                         if (scaleup > V_tcp_autosndbuf_max)
16191                                 scaleup = V_tcp_autosndbuf_max;
16192                         if (!sbreserve_locked(so, SO_SND, scaleup, curthread))
16193                                 so->so_snd.sb_flags &= ~SB_AUTOSIZE;
16194                 }
16195         }
16196 }
16197
16198 static int
16199 rack_fast_output(struct tcpcb *tp, struct tcp_rack *rack, uint64_t ts_val,
16200                  uint32_t cts, uint32_t ms_cts, struct timeval *tv, long tot_len, int *send_err)
16201 {
16202         /*
16203          * Enter to do fast output. We are given that the sched_pin is
16204          * in place (if accounting is compiled in) and the cycle count taken
16205          * at entry is in place in ts_val. The idea here is that
16206          * we know how many more bytes needs to be sent (presumably either
16207          * during pacing or to fill the cwnd and that was greater than
16208          * the max-burst). We have how much to send and all the info we
16209          * need to just send.
16210          */
16211         struct ip *ip = NULL;
16212         struct udphdr *udp = NULL;
16213         struct tcphdr *th = NULL;
16214         struct mbuf *m, *s_mb;
16215         struct inpcb *inp;
16216         uint8_t *cpto;
16217         struct tcp_log_buffer *lgb;
16218 #ifdef TCP_ACCOUNTING
16219         uint64_t crtsc;
16220 #endif
16221         struct tcpopt to;
16222         u_char opt[TCP_MAXOLEN];
16223         uint32_t hdrlen, optlen;
16224 #ifdef TCP_ACCOUNTING
16225         int cnt_thru = 1;
16226 #endif
16227         int32_t slot, segsiz, len, max_val, tso = 0, sb_offset, error, ulen = 0;
16228         uint16_t flags;
16229         uint32_t s_soff;
16230         uint32_t if_hw_tsomaxsegcount = 0, startseq;
16231         uint32_t if_hw_tsomaxsegsize;
16232         uint16_t add_flag = RACK_SENT_FP;
16233 #ifdef INET6
16234         struct ip6_hdr *ip6 = NULL;
16235
16236         if (rack->r_is_v6) {
16237                 ip6 = (struct ip6_hdr *)rack->r_ctl.fsb.tcp_ip_hdr;
16238                 hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
16239         } else
16240 #endif                          /* INET6 */
16241         {
16242                 ip = (struct ip *)rack->r_ctl.fsb.tcp_ip_hdr;
16243                 hdrlen = sizeof(struct tcpiphdr);
16244         }
16245         if (tp->t_port && (V_tcp_udp_tunneling_port == 0)) {
16246                 m = NULL;
16247                 goto failed;
16248         }
16249         startseq = tp->snd_max;
16250         segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
16251         inp = rack->rc_inp;
16252         len = rack->r_ctl.fsb.left_to_send;
16253         to.to_flags = 0;
16254         flags = rack->r_ctl.fsb.tcp_flags;
16255         if (tp->t_flags & TF_RCVD_TSTMP) {
16256                 to.to_tsval = ms_cts + tp->ts_offset;
16257                 to.to_tsecr = tp->ts_recent;
16258                 to.to_flags = TOF_TS;
16259         }
16260         optlen = tcp_addoptions(&to, opt);
16261         hdrlen += optlen;
16262         udp = rack->r_ctl.fsb.udp;
16263         if (udp)
16264                 hdrlen += sizeof(struct udphdr);
16265         if (rack->r_ctl.rc_pace_max_segs)
16266                 max_val = rack->r_ctl.rc_pace_max_segs;
16267         else if (rack->rc_user_set_max_segs)
16268                 max_val = rack->rc_user_set_max_segs * segsiz;
16269         else
16270                 max_val = len;
16271         if ((tp->t_flags & TF_TSO) &&
16272             V_tcp_do_tso &&
16273             (len > segsiz) &&
16274             (tp->t_port == 0))
16275                 tso = 1;
16276 again:
16277 #ifdef INET6
16278         if (MHLEN < hdrlen + max_linkhdr)
16279                 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
16280         else
16281 #endif
16282                 m = m_gethdr(M_NOWAIT, MT_DATA);
16283         if (m == NULL)
16284                 goto failed;
16285         m->m_data += max_linkhdr;
16286         m->m_len = hdrlen;
16287         th = rack->r_ctl.fsb.th;
16288         /* Establish the len to send */
16289         if (len > max_val)
16290                 len = max_val;
16291         if ((tso) && (len + optlen > tp->t_maxseg)) {
16292                 uint32_t if_hw_tsomax;
16293                 int32_t max_len;
16294
16295                 /* extract TSO information */
16296                 if_hw_tsomax = tp->t_tsomax;
16297                 if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
16298                 if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
16299                 /*
16300                  * Check if we should limit by maximum payload
16301                  * length:
16302                  */
16303                 if (if_hw_tsomax != 0) {
16304                         /* compute maximum TSO length */
16305                         max_len = (if_hw_tsomax - hdrlen -
16306                                    max_linkhdr);
16307                         if (max_len <= 0) {
16308                                 goto failed;
16309                         } else if (len > max_len) {
16310                                 len = max_len;
16311                         }
16312                 }
16313                 if (len <= segsiz) {
16314                         /*
16315                          * In case there are too many small fragments don't
16316                          * use TSO:
16317                          */
16318                         tso = 0;
16319                 }
16320         } else {
16321                 tso = 0;
16322         }
16323         if ((tso == 0) && (len > segsiz))
16324                 len = segsiz;
16325         if ((len == 0) ||
16326             (len <= MHLEN - hdrlen - max_linkhdr)) {
16327                 goto failed;
16328         }
16329         sb_offset = tp->snd_max - tp->snd_una;
16330         th->th_seq = htonl(tp->snd_max);
16331         th->th_ack = htonl(tp->rcv_nxt);
16332         th->th_win = htons((u_short)(rack->r_ctl.fsb.recwin >> tp->rcv_scale));
16333         if (th->th_win == 0) {
16334                 tp->t_sndzerowin++;
16335                 tp->t_flags |= TF_RXWIN0SENT;
16336         } else
16337                 tp->t_flags &= ~TF_RXWIN0SENT;
16338         tp->snd_up = tp->snd_una;       /* drag it along, its deprecated */
16339         KMOD_TCPSTAT_INC(tcps_sndpack);
16340         KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
16341 #ifdef STATS
16342         stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
16343                                  len);
16344 #endif
16345         if (rack->r_ctl.fsb.m == NULL)
16346                 goto failed;
16347
16348         /* s_mb and s_soff are saved for rack_log_output */
16349         m->m_next = rack_fo_m_copym(rack, &len, if_hw_tsomaxsegcount, if_hw_tsomaxsegsize,
16350                                     &s_mb, &s_soff);
16351         if (len <= segsiz) {
16352                 /*
16353                  * Must have ran out of mbufs for the copy
16354                  * shorten it to no longer need tso. Lets
16355                  * not put on sendalot since we are low on
16356                  * mbufs.
16357                  */
16358                 tso = 0;
16359         }
16360         if (rack->r_ctl.fsb.rfo_apply_push &&
16361             (len == rack->r_ctl.fsb.left_to_send)) {
16362                 flags |= TH_PUSH;
16363                 add_flag |= RACK_HAD_PUSH;
16364         }
16365         if ((m->m_next == NULL) || (len <= 0)){
16366                 goto failed;
16367         }
16368         if (udp) {
16369                 if (rack->r_is_v6)
16370                         ulen = hdrlen + len - sizeof(struct ip6_hdr);
16371                 else
16372                         ulen = hdrlen + len - sizeof(struct ip);
16373                 udp->uh_ulen = htons(ulen);
16374         }
16375         m->m_pkthdr.rcvif = (struct ifnet *)0;
16376         if (TCPS_HAVERCVDSYN(tp->t_state) &&
16377             (tp->t_flags2 & (TF2_ECN_PERMIT | TF2_ACE_PERMIT))) {
16378                 int ect = tcp_ecn_output_established(tp, &flags, len, false);
16379                 if ((tp->t_state == TCPS_SYN_RECEIVED) &&
16380                     (tp->t_flags2 & TF2_ECN_SND_ECE))
16381                         tp->t_flags2 &= ~TF2_ECN_SND_ECE;
16382 #ifdef INET6
16383                 if (rack->r_is_v6) {
16384                         ip6->ip6_flow &= ~htonl(IPTOS_ECN_MASK << 20);
16385                         ip6->ip6_flow |= htonl(ect << 20);
16386                 }
16387                 else
16388 #endif
16389                 {
16390                         ip->ip_tos &= ~IPTOS_ECN_MASK;
16391                         ip->ip_tos |= ect;
16392                 }
16393         }
16394         tcp_set_flags(th, flags);
16395         m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
16396 #ifdef INET6
16397         if (rack->r_is_v6) {
16398                 if (tp->t_port) {
16399                         m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
16400                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
16401                         udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
16402                         th->th_sum = htons(0);
16403                         UDPSTAT_INC(udps_opackets);
16404                 } else {
16405                         m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
16406                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
16407                         th->th_sum = in6_cksum_pseudo(ip6,
16408                                                       sizeof(struct tcphdr) + optlen + len, IPPROTO_TCP,
16409                                                       0);
16410                 }
16411         }
16412 #endif
16413 #if defined(INET6) && defined(INET)
16414         else
16415 #endif
16416 #ifdef INET
16417         {
16418                 if (tp->t_port) {
16419                         m->m_pkthdr.csum_flags = CSUM_UDP;
16420                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
16421                         udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
16422                                                 ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
16423                         th->th_sum = htons(0);
16424                         UDPSTAT_INC(udps_opackets);
16425                 } else {
16426                         m->m_pkthdr.csum_flags = CSUM_TCP;
16427                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
16428                         th->th_sum = in_pseudo(ip->ip_src.s_addr,
16429                                                ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
16430                                                                         IPPROTO_TCP + len + optlen));
16431                 }
16432                 /* IP version must be set here for ipv4/ipv6 checking later */
16433                 KASSERT(ip->ip_v == IPVERSION,
16434                         ("%s: IP version incorrect: %d", __func__, ip->ip_v));
16435         }
16436 #endif
16437         if (tso) {
16438                 KASSERT(len > tp->t_maxseg - optlen,
16439                         ("%s: len <= tso_segsz tp:%p", __func__, tp));
16440                 m->m_pkthdr.csum_flags |= CSUM_TSO;
16441                 m->m_pkthdr.tso_segsz = tp->t_maxseg - optlen;
16442         }
16443 #ifdef INET6
16444         if (rack->r_is_v6) {
16445                 ip6->ip6_hlim = rack->r_ctl.fsb.hoplimit;
16446                 ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
16447                 if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss)
16448                         tp->t_flags2 |= TF2_PLPMTU_PMTUD;
16449                 else
16450                         tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
16451         }
16452 #endif
16453 #if defined(INET) && defined(INET6)
16454         else
16455 #endif
16456 #ifdef INET
16457         {
16458                 ip->ip_len = htons(m->m_pkthdr.len);
16459                 ip->ip_ttl = rack->r_ctl.fsb.hoplimit;
16460                 if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
16461                         tp->t_flags2 |= TF2_PLPMTU_PMTUD;
16462                         if (tp->t_port == 0 || len < V_tcp_minmss) {
16463                                 ip->ip_off |= htons(IP_DF);
16464                         }
16465                 } else {
16466                         tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
16467                 }
16468         }
16469 #endif
16470         /* Time to copy in our header */
16471         cpto = mtod(m, uint8_t *);
16472         memcpy(cpto, rack->r_ctl.fsb.tcp_ip_hdr, rack->r_ctl.fsb.tcp_ip_hdr_len);
16473         th = (struct tcphdr *)(cpto + ((uint8_t *)rack->r_ctl.fsb.th - rack->r_ctl.fsb.tcp_ip_hdr));
16474         if (optlen) {
16475                 bcopy(opt, th + 1, optlen);
16476                 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
16477         } else {
16478                 th->th_off = sizeof(struct tcphdr) >> 2;
16479         }
16480         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
16481                 union tcp_log_stackspecific log;
16482
16483                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
16484                 log.u_bbr.inhpts = tcp_in_hpts(rack->rc_inp);
16485                 if (rack->rack_no_prr)
16486                         log.u_bbr.flex1 = 0;
16487                 else
16488                         log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
16489                 log.u_bbr.flex2 = rack->r_ctl.rc_pace_min_segs;
16490                 log.u_bbr.flex3 = rack->r_ctl.rc_pace_max_segs;
16491                 log.u_bbr.flex4 = max_val;
16492                 log.u_bbr.flex5 = 0;
16493                 /* Save off the early/late values */
16494                 log.u_bbr.flex6 = rack->r_ctl.rc_agg_early;
16495                 log.u_bbr.applimited = rack->r_ctl.rc_agg_delayed;
16496                 log.u_bbr.bw_inuse = rack_get_bw(rack);
16497                 log.u_bbr.flex8 = 0;
16498                 log.u_bbr.pacing_gain = rack_get_output_gain(rack, NULL);
16499                 log.u_bbr.flex7 = 44;
16500                 log.u_bbr.pkts_out = tp->t_maxseg;
16501                 log.u_bbr.timeStamp = cts;
16502                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
16503                 log.u_bbr.lt_epoch = rack->r_ctl.cwnd_to_use;
16504                 log.u_bbr.delivered = 0;
16505                 lgb = tcp_log_event_(tp, th, NULL, NULL, TCP_LOG_OUT, ERRNO_UNK,
16506                                      len, &log, false, NULL, NULL, 0, tv);
16507         } else
16508                 lgb = NULL;
16509 #ifdef INET6
16510         if (rack->r_is_v6) {
16511                 error = ip6_output(m, NULL,
16512                                    &inp->inp_route6,
16513                                    0, NULL, NULL, inp);
16514         }
16515 #endif
16516 #if defined(INET) && defined(INET6)
16517         else
16518 #endif
16519 #ifdef INET
16520         {
16521                 error = ip_output(m, NULL,
16522                                   &inp->inp_route,
16523                                   0, 0, inp);
16524         }
16525 #endif
16526         if (lgb) {
16527                 lgb->tlb_errno = error;
16528                 lgb = NULL;
16529         }
16530         if (error) {
16531                 *send_err = error;
16532                 m = NULL;
16533                 goto failed;
16534         }
16535         rack_log_output(tp, &to, len, tp->snd_max, flags, error, rack_to_usec_ts(tv),
16536                         NULL, add_flag, s_mb, s_soff, rack->r_ctl.fsb.hw_tls);
16537         m = NULL;
16538         if (tp->snd_una == tp->snd_max) {
16539                 rack->r_ctl.rc_tlp_rxt_last_time = cts;
16540                 rack_log_progress_event(rack, tp, ticks, PROGRESS_START, __LINE__);
16541                 tp->t_acktime = ticks;
16542         }
16543         if (error == 0)
16544                 tcp_account_for_send(tp, len, 0, 0, rack->r_ctl.fsb.hw_tls);
16545
16546         rack->forced_ack = 0;   /* If we send something zap the FA flag */
16547         tot_len += len;
16548         if ((tp->t_flags & TF_GPUTINPROG) == 0)
16549                 rack_start_gp_measurement(tp, rack, tp->snd_max, sb_offset);
16550         tp->snd_max += len;
16551         tp->snd_nxt = tp->snd_max;
16552         {
16553                 int idx;
16554
16555                 idx = (len / segsiz) + 3;
16556                 if (idx >= TCP_MSS_ACCT_ATIMER)
16557                         counter_u64_add(rack_out_size[(TCP_MSS_ACCT_ATIMER-1)], 1);
16558                 else
16559                         counter_u64_add(rack_out_size[idx], 1);
16560         }
16561         if (len <= rack->r_ctl.fsb.left_to_send)
16562                 rack->r_ctl.fsb.left_to_send -= len;
16563         else
16564                 rack->r_ctl.fsb.left_to_send = 0;
16565         if (rack->r_ctl.fsb.left_to_send < segsiz) {
16566                 rack->r_fast_output = 0;
16567                 rack->r_ctl.fsb.left_to_send = 0;
16568                 /* At the end of fast_output scale up the sb */
16569                 SOCKBUF_LOCK(&rack->rc_inp->inp_socket->so_snd);
16570                 rack_sndbuf_autoscale(rack);
16571                 SOCKBUF_UNLOCK(&rack->rc_inp->inp_socket->so_snd);
16572         }
16573         if (tp->t_rtttime == 0) {
16574                 tp->t_rtttime = ticks;
16575                 tp->t_rtseq = startseq;
16576                 KMOD_TCPSTAT_INC(tcps_segstimed);
16577         }
16578         if ((rack->r_ctl.fsb.left_to_send >= segsiz) &&
16579             (max_val > len) &&
16580             (tso == 0)) {
16581                 max_val -= len;
16582                 len = segsiz;
16583                 th = rack->r_ctl.fsb.th;
16584 #ifdef TCP_ACCOUNTING
16585                 cnt_thru++;
16586 #endif
16587                 goto again;
16588         }
16589         tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
16590         counter_u64_add(rack_fto_send, 1);
16591         slot = rack_get_pacing_delay(rack, tp, tot_len, NULL, segsiz);
16592         rack_start_hpts_timer(rack, tp, cts, slot, tot_len, 0);
16593 #ifdef TCP_ACCOUNTING
16594         crtsc = get_cyclecount();
16595         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16596                 tp->tcp_cnt_counters[SND_OUT_DATA] += cnt_thru;
16597         }
16598         counter_u64_add(tcp_cnt_counters[SND_OUT_DATA], cnt_thru);
16599         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16600                 tp->tcp_proc_time[SND_OUT_DATA] += (crtsc - ts_val);
16601         }
16602         counter_u64_add(tcp_proc_time[SND_OUT_DATA], (crtsc - ts_val));
16603         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16604                 tp->tcp_cnt_counters[CNT_OF_MSS_OUT] += ((tot_len + segsiz - 1) / segsiz);
16605         }
16606         counter_u64_add(tcp_cnt_counters[CNT_OF_MSS_OUT], ((tot_len + segsiz - 1) / segsiz));
16607         sched_unpin();
16608 #endif
16609         return (0);
16610 failed:
16611         if (m)
16612                 m_free(m);
16613         rack->r_fast_output = 0;
16614         return (-1);
16615 }
16616
16617 static struct rack_sendmap *
16618 rack_check_collapsed(struct tcp_rack *rack, uint32_t cts)
16619 {
16620         struct rack_sendmap *rsm = NULL;
16621         struct rack_sendmap fe;
16622         int thresh;
16623
16624 restart:
16625         fe.r_start = rack->r_ctl.last_collapse_point;
16626         rsm = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
16627         if ((rsm == NULL) || ((rsm->r_flags & RACK_RWND_COLLAPSED) == 0)) {
16628                 /* Nothing, strange turn off validity  */
16629                 rack->r_collapse_point_valid = 0;
16630                 return (NULL);
16631         }
16632         /* Can we send it yet? */
16633         if (rsm->r_end > (rack->rc_tp->snd_una + rack->rc_tp->snd_wnd)) {
16634                 /*
16635                  * Receiver window has not grown enough for
16636                  * the segment to be put on the wire.
16637                  */
16638                 return (NULL);
16639         }
16640         if (rsm->r_flags & RACK_ACKED) {
16641                 /*
16642                  * It has been sacked, lets move to the
16643                  * next one if possible.
16644                  */
16645                 rack->r_ctl.last_collapse_point = rsm->r_end;
16646                 /* Are we done? */
16647                 if (SEQ_GEQ(rack->r_ctl.last_collapse_point,
16648                             rack->r_ctl.high_collapse_point)) {
16649                         rack->r_collapse_point_valid = 0;
16650                         return (NULL);
16651                 }
16652                 goto restart;
16653         }
16654         /* Now has it been long enough ? */
16655         thresh = rack_calc_thresh_rack(rack, rack_grab_rtt(rack->rc_tp, rack), cts);
16656         if ((cts - ((uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)])) > thresh) {
16657                 rack_log_collapse(rack, rsm->r_start,
16658                                   (cts - ((uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)])),
16659                                   thresh, __LINE__, 6, rsm->r_flags, rsm);
16660                 return (rsm);
16661         }
16662         /* Not enough time */
16663         rack_log_collapse(rack, rsm->r_start,
16664                           (cts - ((uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)])),
16665                           thresh, __LINE__, 7, rsm->r_flags, rsm);
16666         return (NULL);
16667 }
16668
16669 static int
16670 rack_output(struct tcpcb *tp)
16671 {
16672         struct socket *so;
16673         uint32_t recwin;
16674         uint32_t sb_offset, s_moff = 0;
16675         int32_t len, error = 0;
16676         uint16_t flags;
16677         struct mbuf *m, *s_mb = NULL;
16678         struct mbuf *mb;
16679         uint32_t if_hw_tsomaxsegcount = 0;
16680         uint32_t if_hw_tsomaxsegsize;
16681         int32_t segsiz, minseg;
16682         long tot_len_this_send = 0;
16683 #ifdef INET
16684         struct ip *ip = NULL;
16685 #endif
16686         struct udphdr *udp = NULL;
16687         struct tcp_rack *rack;
16688         struct tcphdr *th;
16689         uint8_t pass = 0;
16690         uint8_t mark = 0;
16691         uint8_t wanted_cookie = 0;
16692         u_char opt[TCP_MAXOLEN];
16693         unsigned ipoptlen, optlen, hdrlen, ulen=0;
16694         uint32_t rack_seq;
16695
16696 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
16697         unsigned ipsec_optlen = 0;
16698
16699 #endif
16700         int32_t idle, sendalot;
16701         int32_t sub_from_prr = 0;
16702         volatile int32_t sack_rxmit;
16703         struct rack_sendmap *rsm = NULL;
16704         int32_t tso, mtu;
16705         struct tcpopt to;
16706         int32_t slot = 0;
16707         int32_t sup_rack = 0;
16708         uint32_t cts, ms_cts, delayed, early;
16709         uint16_t add_flag = RACK_SENT_SP;
16710         /* The doing_tlp flag will be set by the actual rack_timeout_tlp() */
16711         uint8_t hpts_calling,  doing_tlp = 0;
16712         uint32_t cwnd_to_use, pace_max_seg;
16713         int32_t do_a_prefetch = 0;
16714         int32_t prefetch_rsm = 0;
16715         int32_t orig_len = 0;
16716         struct timeval tv;
16717         int32_t prefetch_so_done = 0;
16718         struct tcp_log_buffer *lgb;
16719         struct inpcb *inp = tptoinpcb(tp);
16720         struct sockbuf *sb;
16721         uint64_t ts_val = 0;
16722 #ifdef TCP_ACCOUNTING
16723         uint64_t crtsc;
16724 #endif
16725 #ifdef INET6
16726         struct ip6_hdr *ip6 = NULL;
16727         int32_t isipv6;
16728 #endif
16729         bool hw_tls = false;
16730
16731         NET_EPOCH_ASSERT();
16732         INP_WLOCK_ASSERT(inp);
16733
16734         /* setup and take the cache hits here */
16735         rack = (struct tcp_rack *)tp->t_fb_ptr;
16736 #ifdef TCP_ACCOUNTING
16737         sched_pin();
16738         ts_val = get_cyclecount();
16739 #endif
16740         hpts_calling = inp->inp_hpts_calls;
16741 #ifdef TCP_OFFLOAD
16742         if (tp->t_flags & TF_TOE) {
16743 #ifdef TCP_ACCOUNTING
16744                 sched_unpin();
16745 #endif
16746                 return (tcp_offload_output(tp));
16747         }
16748 #endif
16749         /*
16750          * For TFO connections in SYN_RECEIVED, only allow the initial
16751          * SYN|ACK and those sent by the retransmit timer.
16752          */
16753         if (IS_FASTOPEN(tp->t_flags) &&
16754             (tp->t_state == TCPS_SYN_RECEIVED) &&
16755             SEQ_GT(tp->snd_max, tp->snd_una) &&    /* initial SYN|ACK sent */
16756             (rack->r_ctl.rc_resend == NULL)) {         /* not a retransmit */
16757 #ifdef TCP_ACCOUNTING
16758                 sched_unpin();
16759 #endif
16760                 return (0);
16761         }
16762 #ifdef INET6
16763         if (rack->r_state) {
16764                 /* Use the cache line loaded if possible */
16765                 isipv6 = rack->r_is_v6;
16766         } else {
16767                 isipv6 = (rack->rc_inp->inp_vflag & INP_IPV6) != 0;
16768         }
16769 #endif
16770         early = 0;
16771         cts = tcp_get_usecs(&tv);
16772         ms_cts = tcp_tv_to_mssectick(&tv);
16773         if (((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
16774             tcp_in_hpts(rack->rc_inp)) {
16775                 /*
16776                  * We are on the hpts for some timer but not hptsi output.
16777                  * Remove from the hpts unconditionally.
16778                  */
16779                 rack_timer_cancel(tp, rack, cts, __LINE__);
16780         }
16781         /* Are we pacing and late? */
16782         if ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
16783             TSTMP_GEQ(cts, rack->r_ctl.rc_last_output_to)) {
16784                 /* We are delayed */
16785                 delayed = cts - rack->r_ctl.rc_last_output_to;
16786         } else {
16787                 delayed = 0;
16788         }
16789         /* Do the timers, which may override the pacer */
16790         if (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
16791                 int retval;
16792
16793                 retval = rack_process_timers(tp, rack, cts, hpts_calling,
16794                     &doing_tlp);
16795                 if (retval != 0) {
16796                         counter_u64_add(rack_out_size[TCP_MSS_ACCT_ATIMER], 1);
16797 #ifdef TCP_ACCOUNTING
16798                         sched_unpin();
16799 #endif
16800                         /*
16801                          * If timers want tcp_drop(), then pass error out,
16802                          * otherwise suppress it.
16803                          */
16804                         return (retval < 0 ? retval : 0);
16805                 }
16806         }
16807         if (rack->rc_in_persist) {
16808                 if (tcp_in_hpts(rack->rc_inp) == 0) {
16809                         /* Timer is not running */
16810                         rack_start_hpts_timer(rack, tp, cts, 0, 0, 0);
16811                 }
16812 #ifdef TCP_ACCOUNTING
16813                 sched_unpin();
16814 #endif
16815                 return (0);
16816         }
16817         if ((rack->rc_ack_required == 1) &&
16818             (rack->r_timer_override == 0)){
16819                 /* A timeout occurred and no ack has arrived */
16820                 if (tcp_in_hpts(rack->rc_inp) == 0) {
16821                         /* Timer is not running */
16822                         rack_start_hpts_timer(rack, tp, cts, 0, 0, 0);
16823                 }
16824 #ifdef TCP_ACCOUNTING
16825                 sched_unpin();
16826 #endif
16827                 return (0);
16828         }
16829         if ((rack->r_timer_override) ||
16830             (rack->rc_ack_can_sendout_data) ||
16831             (delayed) ||
16832             (tp->t_state < TCPS_ESTABLISHED)) {
16833                 rack->rc_ack_can_sendout_data = 0;
16834                 if (tcp_in_hpts(rack->rc_inp))
16835                         tcp_hpts_remove(rack->rc_inp);
16836         } else if (tcp_in_hpts(rack->rc_inp)) {
16837                 /*
16838                  * On the hpts you can't pass even if ACKNOW is on, we will
16839                  * when the hpts fires.
16840                  */
16841 #ifdef TCP_ACCOUNTING
16842                 crtsc = get_cyclecount();
16843                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16844                         tp->tcp_proc_time[SND_BLOCKED] += (crtsc - ts_val);
16845                 }
16846                 counter_u64_add(tcp_proc_time[SND_BLOCKED], (crtsc - ts_val));
16847                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16848                         tp->tcp_cnt_counters[SND_BLOCKED]++;
16849                 }
16850                 counter_u64_add(tcp_cnt_counters[SND_BLOCKED], 1);
16851                 sched_unpin();
16852 #endif
16853                 counter_u64_add(rack_out_size[TCP_MSS_ACCT_INPACE], 1);
16854                 return (0);
16855         }
16856         rack->rc_inp->inp_hpts_calls = 0;
16857         /* Finish out both pacing early and late accounting */
16858         if ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
16859             TSTMP_GT(rack->r_ctl.rc_last_output_to, cts)) {
16860                 early = rack->r_ctl.rc_last_output_to - cts;
16861         } else
16862                 early = 0;
16863         if (delayed) {
16864                 rack->r_ctl.rc_agg_delayed += delayed;
16865                 rack->r_late = 1;
16866         } else if (early) {
16867                 rack->r_ctl.rc_agg_early += early;
16868                 rack->r_early = 1;
16869         }
16870         /* Now that early/late accounting is done turn off the flag */
16871         rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
16872         rack->r_wanted_output = 0;
16873         rack->r_timer_override = 0;
16874         if ((tp->t_state != rack->r_state) &&
16875             TCPS_HAVEESTABLISHED(tp->t_state)) {
16876                 rack_set_state(tp, rack);
16877         }
16878         if ((rack->r_fast_output) &&
16879             (doing_tlp == 0) &&
16880             (tp->rcv_numsacks == 0)) {
16881                 int ret;
16882
16883                 error = 0;
16884                 ret = rack_fast_output(tp, rack, ts_val, cts, ms_cts, &tv, tot_len_this_send, &error);
16885                 if (ret >= 0)
16886                         return(ret);
16887                 else if (error) {
16888                         inp = rack->rc_inp;
16889                         so = inp->inp_socket;
16890                         sb = &so->so_snd;
16891                         goto nomore;
16892                 }
16893         }
16894         inp = rack->rc_inp;
16895         /*
16896          * For TFO connections in SYN_SENT or SYN_RECEIVED,
16897          * only allow the initial SYN or SYN|ACK and those sent
16898          * by the retransmit timer.
16899          */
16900         if (IS_FASTOPEN(tp->t_flags) &&
16901             ((tp->t_state == TCPS_SYN_RECEIVED) ||
16902              (tp->t_state == TCPS_SYN_SENT)) &&
16903             SEQ_GT(tp->snd_max, tp->snd_una) && /* initial SYN or SYN|ACK sent */
16904             (tp->t_rxtshift == 0)) {              /* not a retransmit */
16905                 cwnd_to_use = rack->r_ctl.cwnd_to_use = tp->snd_cwnd;
16906                 so = inp->inp_socket;
16907                 sb = &so->so_snd;
16908                 goto just_return_nolock;
16909         }
16910         /*
16911          * Determine length of data that should be transmitted, and flags
16912          * that will be used. If there is some data or critical controls
16913          * (SYN, RST) to send, then transmit; otherwise, investigate
16914          * further.
16915          */
16916         idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
16917         if (tp->t_idle_reduce) {
16918                 if (idle && (TICKS_2_USEC(ticks - tp->t_rcvtime) >= tp->t_rxtcur))
16919                         rack_cc_after_idle(rack, tp);
16920         }
16921         tp->t_flags &= ~TF_LASTIDLE;
16922         if (idle) {
16923                 if (tp->t_flags & TF_MORETOCOME) {
16924                         tp->t_flags |= TF_LASTIDLE;
16925                         idle = 0;
16926                 }
16927         }
16928         if ((tp->snd_una == tp->snd_max) &&
16929             rack->r_ctl.rc_went_idle_time &&
16930             TSTMP_GT(cts, rack->r_ctl.rc_went_idle_time)) {
16931                 idle = cts - rack->r_ctl.rc_went_idle_time;
16932                 if (idle > rack_min_probertt_hold) {
16933                         /* Count as a probe rtt */
16934                         if (rack->in_probe_rtt == 0) {
16935                                 rack->r_ctl.rc_lower_rtt_us_cts = cts;
16936                                 rack->r_ctl.rc_time_probertt_entered = rack->r_ctl.rc_lower_rtt_us_cts;
16937                                 rack->r_ctl.rc_time_probertt_starts = rack->r_ctl.rc_lower_rtt_us_cts;
16938                                 rack->r_ctl.rc_time_of_last_probertt = rack->r_ctl.rc_lower_rtt_us_cts;
16939                         } else {
16940                                 rack_exit_probertt(rack, cts);
16941                         }
16942                 }
16943                 idle = 0;
16944         }
16945         if (rack_use_fsb && (rack->r_fsb_inited == 0) && (rack->r_state != TCPS_CLOSED))
16946                 rack_init_fsb_block(tp, rack);
16947 again:
16948         /*
16949          * If we've recently taken a timeout, snd_max will be greater than
16950          * snd_nxt.  There may be SACK information that allows us to avoid
16951          * resending already delivered data.  Adjust snd_nxt accordingly.
16952          */
16953         sendalot = 0;
16954         cts = tcp_get_usecs(&tv);
16955         ms_cts = tcp_tv_to_mssectick(&tv);
16956         tso = 0;
16957         mtu = 0;
16958         segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
16959         minseg = segsiz;
16960         if (rack->r_ctl.rc_pace_max_segs == 0)
16961                 pace_max_seg = rack->rc_user_set_max_segs * segsiz;
16962         else
16963                 pace_max_seg = rack->r_ctl.rc_pace_max_segs;
16964         sb_offset = tp->snd_max - tp->snd_una;
16965         cwnd_to_use = rack->r_ctl.cwnd_to_use = tp->snd_cwnd;
16966         flags = tcp_outflags[tp->t_state];
16967         while (rack->rc_free_cnt < rack_free_cache) {
16968                 rsm = rack_alloc(rack);
16969                 if (rsm == NULL) {
16970                         if (inp->inp_hpts_calls)
16971                                 /* Retry in a ms */
16972                                 slot = (1 * HPTS_USEC_IN_MSEC);
16973                         so = inp->inp_socket;
16974                         sb = &so->so_snd;
16975                         goto just_return_nolock;
16976                 }
16977                 TAILQ_INSERT_TAIL(&rack->r_ctl.rc_free, rsm, r_tnext);
16978                 rack->rc_free_cnt++;
16979                 rsm = NULL;
16980         }
16981         if (inp->inp_hpts_calls)
16982                 inp->inp_hpts_calls = 0;
16983         sack_rxmit = 0;
16984         len = 0;
16985         rsm = NULL;
16986         if (flags & TH_RST) {
16987                 SOCKBUF_LOCK(&inp->inp_socket->so_snd);
16988                 so = inp->inp_socket;
16989                 sb = &so->so_snd;
16990                 goto send;
16991         }
16992         if (rack->r_ctl.rc_resend) {
16993                 /* Retransmit timer */
16994                 rsm = rack->r_ctl.rc_resend;
16995                 rack->r_ctl.rc_resend = NULL;
16996                 len = rsm->r_end - rsm->r_start;
16997                 sack_rxmit = 1;
16998                 sendalot = 0;
16999                 KASSERT(SEQ_LEQ(tp->snd_una, rsm->r_start),
17000                         ("%s:%d: r.start:%u < SND.UNA:%u; tp:%p, rack:%p, rsm:%p",
17001                          __func__, __LINE__,
17002                          rsm->r_start, tp->snd_una, tp, rack, rsm));
17003                 sb_offset = rsm->r_start - tp->snd_una;
17004                 if (len >= segsiz)
17005                         len = segsiz;
17006         } else if (rack->r_collapse_point_valid &&
17007                    ((rsm = rack_check_collapsed(rack, cts)) != NULL)) {
17008                 /*
17009                  * If an RSM is returned then enough time has passed
17010                  * for us to retransmit it. Move up the collapse point,
17011                  * since this rsm has its chance to retransmit now.
17012                  */
17013                 rack_trace_point(rack, RACK_TP_COLLAPSED_RXT);
17014                 rack->r_ctl.last_collapse_point = rsm->r_end;
17015                 /* Are we done? */
17016                 if (SEQ_GEQ(rack->r_ctl.last_collapse_point,
17017                             rack->r_ctl.high_collapse_point))
17018                         rack->r_collapse_point_valid = 0;
17019                 sack_rxmit = 1;
17020                 /* We are not doing a TLP */
17021                 doing_tlp = 0;
17022                 len = rsm->r_end - rsm->r_start;
17023                 sb_offset = rsm->r_start - tp->snd_una;
17024                 sendalot = 0;
17025                 if ((rack->full_size_rxt == 0) &&
17026                     (rack->shape_rxt_to_pacing_min == 0) &&
17027                     (len >= segsiz))
17028                         len = segsiz;
17029         } else if ((rsm = tcp_rack_output(tp, rack, cts)) != NULL) {
17030                 /* We have a retransmit that takes precedence */
17031                 if ((!IN_FASTRECOVERY(tp->t_flags)) &&
17032                     ((rsm->r_flags & RACK_MUST_RXT) == 0) &&
17033                     ((tp->t_flags & TF_WASFRECOVERY) == 0)) {
17034                         /* Enter recovery if not induced by a time-out */
17035                         rack_cong_signal(tp, CC_NDUPACK, tp->snd_una, __LINE__);
17036                 }
17037 #ifdef INVARIANTS
17038                 if (SEQ_LT(rsm->r_start, tp->snd_una)) {
17039                         panic("Huh, tp:%p rack:%p rsm:%p start:%u < snd_una:%u\n",
17040                               tp, rack, rsm, rsm->r_start, tp->snd_una);
17041                 }
17042 #endif
17043                 len = rsm->r_end - rsm->r_start;
17044                 KASSERT(SEQ_LEQ(tp->snd_una, rsm->r_start),
17045                         ("%s:%d: r.start:%u < SND.UNA:%u; tp:%p, rack:%p, rsm:%p",
17046                          __func__, __LINE__,
17047                          rsm->r_start, tp->snd_una, tp, rack, rsm));
17048                 sb_offset = rsm->r_start - tp->snd_una;
17049                 sendalot = 0;
17050                 if (len >= segsiz)
17051                         len = segsiz;
17052                 if (len > 0) {
17053                         sack_rxmit = 1;
17054                         KMOD_TCPSTAT_INC(tcps_sack_rexmits);
17055                         KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
17056                             min(len, segsiz));
17057                 }
17058         } else if (rack->r_ctl.rc_tlpsend) {
17059                 /* Tail loss probe */
17060                 long cwin;
17061                 long tlen;
17062
17063                 /*
17064                  * Check if we can do a TLP with a RACK'd packet
17065                  * this can happen if we are not doing the rack
17066                  * cheat and we skipped to a TLP and it
17067                  * went off.
17068                  */
17069                 rsm = rack->r_ctl.rc_tlpsend;
17070                 /* We are doing a TLP make sure the flag is preent */
17071                 rsm->r_flags |= RACK_TLP;
17072                 rack->r_ctl.rc_tlpsend = NULL;
17073                 sack_rxmit = 1;
17074                 tlen = rsm->r_end - rsm->r_start;
17075                 if (tlen > segsiz)
17076                         tlen = segsiz;
17077                 KASSERT(SEQ_LEQ(tp->snd_una, rsm->r_start),
17078                         ("%s:%d: r.start:%u < SND.UNA:%u; tp:%p, rack:%p, rsm:%p",
17079                          __func__, __LINE__,
17080                          rsm->r_start, tp->snd_una, tp, rack, rsm));
17081                 sb_offset = rsm->r_start - tp->snd_una;
17082                 cwin = min(tp->snd_wnd, tlen);
17083                 len = cwin;
17084         }
17085         if (rack->r_must_retran &&
17086             (doing_tlp == 0) &&
17087             (SEQ_GT(tp->snd_max, tp->snd_una)) &&
17088             (rsm == NULL)) {
17089                 /*
17090                  * There are two different ways that we
17091                  * can get into this block:
17092                  * a) This is a non-sack connection, we had a time-out
17093                  *    and thus r_must_retran was set and everything
17094                  *    left outstanding as been marked for retransmit.
17095                  * b) The MTU of the path shrank, so that everything
17096                  *    was marked to be retransmitted with the smaller
17097                  *    mtu and r_must_retran was set.
17098                  *
17099                  * This means that we expect the sendmap (outstanding)
17100                  * to all be marked must. We can use the tmap to
17101                  * look at them.
17102                  *
17103                  */
17104                 int sendwin, flight;
17105
17106                 sendwin = min(tp->snd_wnd, tp->snd_cwnd);
17107                 flight = ctf_flight_size(tp, rack->r_ctl.rc_out_at_rto);
17108                 if (flight >= sendwin) {
17109                         /*
17110                          * We can't send yet.
17111                          */
17112                         so = inp->inp_socket;
17113                         sb = &so->so_snd;
17114                         goto just_return_nolock;
17115                 }
17116                 /*
17117                  * This is the case a/b mentioned above. All
17118                  * outstanding/not-acked should be marked.
17119                  * We can use the tmap to find them.
17120                  */
17121                 rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
17122                 if (rsm == NULL) {
17123                         /* TSNH */
17124                         rack->r_must_retran = 0;
17125                         rack->r_ctl.rc_out_at_rto = 0;
17126                         so = inp->inp_socket;
17127                         sb = &so->so_snd;
17128                         goto just_return_nolock;
17129                 }
17130                 if ((rsm->r_flags & RACK_MUST_RXT) == 0) {
17131                         /*
17132                          * The first one does not have the flag, did we collapse
17133                          * further up in our list?
17134                          */
17135                         rack->r_must_retran = 0;
17136                         rack->r_ctl.rc_out_at_rto = 0;
17137                         rsm = NULL;
17138                         sack_rxmit = 0;
17139                 } else {
17140                         sack_rxmit = 1;
17141                         len = rsm->r_end - rsm->r_start;
17142                         sb_offset = rsm->r_start - tp->snd_una;
17143                         sendalot = 0;
17144                         if ((rack->full_size_rxt == 0) &&
17145                             (rack->shape_rxt_to_pacing_min == 0) &&
17146                             (len >= segsiz))
17147                                 len = segsiz;
17148                         /*
17149                          * Delay removing the flag RACK_MUST_RXT so
17150                          * that the fastpath for retransmit will
17151                          * work with this rsm.
17152                          */
17153                 }
17154         }
17155         /*
17156          * Enforce a connection sendmap count limit if set
17157          * as long as we are not retransmiting.
17158          */
17159         if ((rsm == NULL) &&
17160             (rack->do_detection == 0) &&
17161             (V_tcp_map_entries_limit > 0) &&
17162             (rack->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
17163                 counter_u64_add(rack_to_alloc_limited, 1);
17164                 if (!rack->alloc_limit_reported) {
17165                         rack->alloc_limit_reported = 1;
17166                         counter_u64_add(rack_alloc_limited_conns, 1);
17167                 }
17168                 so = inp->inp_socket;
17169                 sb = &so->so_snd;
17170                 goto just_return_nolock;
17171         }
17172         if (rsm && (rsm->r_flags & RACK_HAS_FIN)) {
17173                 /* we are retransmitting the fin */
17174                 len--;
17175                 if (len) {
17176                         /*
17177                          * When retransmitting data do *not* include the
17178                          * FIN. This could happen from a TLP probe.
17179                          */
17180                         flags &= ~TH_FIN;
17181                 }
17182         }
17183         if (rsm && rack->r_fsb_inited && rack_use_rsm_rfo &&
17184             ((rsm->r_flags & RACK_HAS_FIN) == 0)) {
17185                 int ret;
17186
17187                 ret = rack_fast_rsm_output(tp, rack, rsm, ts_val, cts, ms_cts, &tv, len, doing_tlp);
17188                 if (ret == 0)
17189                         return (0);
17190         }
17191         so = inp->inp_socket;
17192         sb = &so->so_snd;
17193         if (do_a_prefetch == 0) {
17194                 kern_prefetch(sb, &do_a_prefetch);
17195                 do_a_prefetch = 1;
17196         }
17197 #ifdef NETFLIX_SHARED_CWND
17198         if ((tp->t_flags2 & TF2_TCP_SCWND_ALLOWED) &&
17199             rack->rack_enable_scwnd) {
17200                 /* We are doing cwnd sharing */
17201                 if (rack->gp_ready &&
17202                     (rack->rack_attempted_scwnd == 0) &&
17203                     (rack->r_ctl.rc_scw == NULL) &&
17204                     tp->t_lib) {
17205                         /* The pcbid is in, lets make an attempt */
17206                         counter_u64_add(rack_try_scwnd, 1);
17207                         rack->rack_attempted_scwnd = 1;
17208                         rack->r_ctl.rc_scw = tcp_shared_cwnd_alloc(tp,
17209                                                                    &rack->r_ctl.rc_scw_index,
17210                                                                    segsiz);
17211                 }
17212                 if (rack->r_ctl.rc_scw &&
17213                     (rack->rack_scwnd_is_idle == 1) &&
17214                     sbavail(&so->so_snd)) {
17215                         /* we are no longer out of data */
17216                         tcp_shared_cwnd_active(rack->r_ctl.rc_scw, rack->r_ctl.rc_scw_index);
17217                         rack->rack_scwnd_is_idle = 0;
17218                 }
17219                 if (rack->r_ctl.rc_scw) {
17220                         /* First lets update and get the cwnd */
17221                         rack->r_ctl.cwnd_to_use = cwnd_to_use = tcp_shared_cwnd_update(rack->r_ctl.rc_scw,
17222                                                                     rack->r_ctl.rc_scw_index,
17223                                                                     tp->snd_cwnd, tp->snd_wnd, segsiz);
17224                 }
17225         }
17226 #endif
17227         /*
17228          * Get standard flags, and add SYN or FIN if requested by 'hidden'
17229          * state flags.
17230          */
17231         if (tp->t_flags & TF_NEEDFIN)
17232                 flags |= TH_FIN;
17233         if (tp->t_flags & TF_NEEDSYN)
17234                 flags |= TH_SYN;
17235         if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
17236                 void *end_rsm;
17237                 end_rsm = TAILQ_LAST_FAST(&rack->r_ctl.rc_tmap, rack_sendmap, r_tnext);
17238                 if (end_rsm)
17239                         kern_prefetch(end_rsm, &prefetch_rsm);
17240                 prefetch_rsm = 1;
17241         }
17242         SOCKBUF_LOCK(sb);
17243         /*
17244          * If snd_nxt == snd_max and we have transmitted a FIN, the
17245          * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
17246          * negative length.  This can also occur when TCP opens up its
17247          * congestion window while receiving additional duplicate acks after
17248          * fast-retransmit because TCP will reset snd_nxt to snd_max after
17249          * the fast-retransmit.
17250          *
17251          * In the normal retransmit-FIN-only case, however, snd_nxt will be
17252          * set to snd_una, the sb_offset will be 0, and the length may wind
17253          * up 0.
17254          *
17255          * If sack_rxmit is true we are retransmitting from the scoreboard
17256          * in which case len is already set.
17257          */
17258         if ((sack_rxmit == 0) &&
17259             (TCPS_HAVEESTABLISHED(tp->t_state) || IS_FASTOPEN(tp->t_flags))) {
17260                 uint32_t avail;
17261
17262                 avail = sbavail(sb);
17263                 if (SEQ_GT(tp->snd_nxt, tp->snd_una) && avail)
17264                         sb_offset = tp->snd_nxt - tp->snd_una;
17265                 else
17266                         sb_offset = 0;
17267                 if ((IN_FASTRECOVERY(tp->t_flags) == 0) || rack->rack_no_prr) {
17268                         if (rack->r_ctl.rc_tlp_new_data) {
17269                                 /* TLP is forcing out new data */
17270                                 if (rack->r_ctl.rc_tlp_new_data > (uint32_t) (avail - sb_offset)) {
17271                                         rack->r_ctl.rc_tlp_new_data = (uint32_t) (avail - sb_offset);
17272                                 }
17273                                 if ((rack->r_ctl.rc_tlp_new_data + sb_offset) > tp->snd_wnd) {
17274                                         if (tp->snd_wnd > sb_offset)
17275                                                 len = tp->snd_wnd - sb_offset;
17276                                         else
17277                                                 len = 0;
17278                                 } else {
17279                                         len = rack->r_ctl.rc_tlp_new_data;
17280                                 }
17281                                 rack->r_ctl.rc_tlp_new_data = 0;
17282                         }  else {
17283                                 len = rack_what_can_we_send(tp, rack, cwnd_to_use, avail, sb_offset);
17284                         }
17285                         if ((rack->r_ctl.crte == NULL) && IN_FASTRECOVERY(tp->t_flags) && (len > segsiz)) {
17286                                 /*
17287                                  * For prr=off, we need to send only 1 MSS
17288                                  * at a time. We do this because another sack could
17289                                  * be arriving that causes us to send retransmits and
17290                                  * we don't want to be on a long pace due to a larger send
17291                                  * that keeps us from sending out the retransmit.
17292                                  */
17293                                 len = segsiz;
17294                         }
17295                 } else {
17296                         uint32_t outstanding;
17297                         /*
17298                          * We are inside of a Fast recovery episode, this
17299                          * is caused by a SACK or 3 dup acks. At this point
17300                          * we have sent all the retransmissions and we rely
17301                          * on PRR to dictate what we will send in the form of
17302                          * new data.
17303                          */
17304
17305                         outstanding = tp->snd_max - tp->snd_una;
17306                         if ((rack->r_ctl.rc_prr_sndcnt + outstanding) > tp->snd_wnd) {
17307                                 if (tp->snd_wnd > outstanding) {
17308                                         len = tp->snd_wnd - outstanding;
17309                                         /* Check to see if we have the data */
17310                                         if ((sb_offset + len) > avail) {
17311                                                 /* It does not all fit */
17312                                                 if (avail > sb_offset)
17313                                                         len = avail - sb_offset;
17314                                                 else
17315                                                         len = 0;
17316                                         }
17317                                 } else {
17318                                         len = 0;
17319                                 }
17320                         } else if (avail > sb_offset) {
17321                                 len = avail - sb_offset;
17322                         } else {
17323                                 len = 0;
17324                         }
17325                         if (len > 0) {
17326                                 if (len > rack->r_ctl.rc_prr_sndcnt) {
17327                                         len = rack->r_ctl.rc_prr_sndcnt;
17328                                 }
17329                                 if (len > 0) {
17330                                         sub_from_prr = 1;
17331                                 }
17332                         }
17333                         if (len > segsiz) {
17334                                 /*
17335                                  * We should never send more than a MSS when
17336                                  * retransmitting or sending new data in prr
17337                                  * mode unless the override flag is on. Most
17338                                  * likely the PRR algorithm is not going to
17339                                  * let us send a lot as well :-)
17340                                  */
17341                                 if (rack->r_ctl.rc_prr_sendalot == 0) {
17342                                         len = segsiz;
17343                                 }
17344                         } else if (len < segsiz) {
17345                                 /*
17346                                  * Do we send any? The idea here is if the
17347                                  * send empty's the socket buffer we want to
17348                                  * do it. However if not then lets just wait
17349                                  * for our prr_sndcnt to get bigger.
17350                                  */
17351                                 long leftinsb;
17352
17353                                 leftinsb = sbavail(sb) - sb_offset;
17354                                 if (leftinsb > len) {
17355                                         /* This send does not empty the sb */
17356                                         len = 0;
17357                                 }
17358                         }
17359                 }
17360         } else if (!TCPS_HAVEESTABLISHED(tp->t_state)) {
17361                 /*
17362                  * If you have not established
17363                  * and are not doing FAST OPEN
17364                  * no data please.
17365                  */
17366                 if ((sack_rxmit == 0) &&
17367                     (!IS_FASTOPEN(tp->t_flags))){
17368                         len = 0;
17369                         sb_offset = 0;
17370                 }
17371         }
17372         if (prefetch_so_done == 0) {
17373                 kern_prefetch(so, &prefetch_so_done);
17374                 prefetch_so_done = 1;
17375         }
17376         /*
17377          * Lop off SYN bit if it has already been sent.  However, if this is
17378          * SYN-SENT state and if segment contains data and if we don't know
17379          * that foreign host supports TAO, suppress sending segment.
17380          */
17381         if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una) &&
17382             ((sack_rxmit == 0) && (tp->t_rxtshift == 0))) {
17383                 /*
17384                  * When sending additional segments following a TFO SYN|ACK,
17385                  * do not include the SYN bit.
17386                  */
17387                 if (IS_FASTOPEN(tp->t_flags) &&
17388                     (tp->t_state == TCPS_SYN_RECEIVED))
17389                         flags &= ~TH_SYN;
17390         }
17391         /*
17392          * Be careful not to send data and/or FIN on SYN segments. This
17393          * measure is needed to prevent interoperability problems with not
17394          * fully conformant TCP implementations.
17395          */
17396         if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
17397                 len = 0;
17398                 flags &= ~TH_FIN;
17399         }
17400         /*
17401          * On TFO sockets, ensure no data is sent in the following cases:
17402          *
17403          *  - When retransmitting SYN|ACK on a passively-created socket
17404          *
17405          *  - When retransmitting SYN on an actively created socket
17406          *
17407          *  - When sending a zero-length cookie (cookie request) on an
17408          *    actively created socket
17409          *
17410          *  - When the socket is in the CLOSED state (RST is being sent)
17411          */
17412         if (IS_FASTOPEN(tp->t_flags) &&
17413             (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
17414              ((tp->t_state == TCPS_SYN_SENT) &&
17415               (tp->t_tfo_client_cookie_len == 0)) ||
17416              (flags & TH_RST))) {
17417                 sack_rxmit = 0;
17418                 len = 0;
17419         }
17420         /* Without fast-open there should never be data sent on a SYN */
17421         if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags))) {
17422                 tp->snd_nxt = tp->iss;
17423                 len = 0;
17424         }
17425         if ((len > segsiz) && (tcp_dsack_block_exists(tp))) {
17426                 /* We only send 1 MSS if we have a DSACK block */
17427                 add_flag |= RACK_SENT_W_DSACK;
17428                 len = segsiz;
17429         }
17430         orig_len = len;
17431         if (len <= 0) {
17432                 /*
17433                  * If FIN has been sent but not acked, but we haven't been
17434                  * called to retransmit, len will be < 0.  Otherwise, window
17435                  * shrank after we sent into it.  If window shrank to 0,
17436                  * cancel pending retransmit, pull snd_nxt back to (closed)
17437                  * window, and set the persist timer if it isn't already
17438                  * going.  If the window didn't close completely, just wait
17439                  * for an ACK.
17440                  *
17441                  * We also do a general check here to ensure that we will
17442                  * set the persist timer when we have data to send, but a
17443                  * 0-byte window. This makes sure the persist timer is set
17444                  * even if the packet hits one of the "goto send" lines
17445                  * below.
17446                  */
17447                 len = 0;
17448                 if ((tp->snd_wnd == 0) &&
17449                     (TCPS_HAVEESTABLISHED(tp->t_state)) &&
17450                     (tp->snd_una == tp->snd_max) &&
17451                     (sb_offset < (int)sbavail(sb))) {
17452                         rack_enter_persist(tp, rack, cts);
17453                 }
17454         } else if ((rsm == NULL) &&
17455                    (doing_tlp == 0) &&
17456                    (len < pace_max_seg)) {
17457                 /*
17458                  * We are not sending a maximum sized segment for
17459                  * some reason. Should we not send anything (think
17460                  * sws or persists)?
17461                  */
17462                 if ((tp->snd_wnd < min((rack->r_ctl.rc_high_rwnd/2), minseg)) &&
17463                     (TCPS_HAVEESTABLISHED(tp->t_state)) &&
17464                     (len < minseg) &&
17465                     (len < (int)(sbavail(sb) - sb_offset))) {
17466                         /*
17467                          * Here the rwnd is less than
17468                          * the minimum pacing size, this is not a retransmit,
17469                          * we are established and
17470                          * the send is not the last in the socket buffer
17471                          * we send nothing, and we may enter persists
17472                          * if nothing is outstanding.
17473                          */
17474                         len = 0;
17475                         if (tp->snd_max == tp->snd_una) {
17476                                 /*
17477                                  * Nothing out we can
17478                                  * go into persists.
17479                                  */
17480                                 rack_enter_persist(tp, rack, cts);
17481                         }
17482                      } else if ((cwnd_to_use >= max(minseg, (segsiz * 4))) &&
17483                            (ctf_flight_size(tp, rack->r_ctl.rc_sacked) > (2 * segsiz)) &&
17484                            (len < (int)(sbavail(sb) - sb_offset)) &&
17485                            (len < minseg)) {
17486                         /*
17487                          * Here we are not retransmitting, and
17488                          * the cwnd is not so small that we could
17489                          * not send at least a min size (rxt timer
17490                          * not having gone off), We have 2 segments or
17491                          * more already in flight, its not the tail end
17492                          * of the socket buffer  and the cwnd is blocking
17493                          * us from sending out a minimum pacing segment size.
17494                          * Lets not send anything.
17495                          */
17496                         len = 0;
17497                 } else if (((tp->snd_wnd - ctf_outstanding(tp)) <
17498                             min((rack->r_ctl.rc_high_rwnd/2), minseg)) &&
17499                            (ctf_flight_size(tp, rack->r_ctl.rc_sacked) > (2 * segsiz)) &&
17500                            (len < (int)(sbavail(sb) - sb_offset)) &&
17501                            (TCPS_HAVEESTABLISHED(tp->t_state))) {
17502                         /*
17503                          * Here we have a send window but we have
17504                          * filled it up and we can't send another pacing segment.
17505                          * We also have in flight more than 2 segments
17506                          * and we are not completing the sb i.e. we allow
17507                          * the last bytes of the sb to go out even if
17508                          * its not a full pacing segment.
17509                          */
17510                         len = 0;
17511                 } else if ((rack->r_ctl.crte != NULL) &&
17512                            (tp->snd_wnd >= (pace_max_seg * max(1, rack_hw_rwnd_factor))) &&
17513                            (cwnd_to_use >= (pace_max_seg + (4 * segsiz))) &&
17514                            (ctf_flight_size(tp, rack->r_ctl.rc_sacked) >= (2 * segsiz)) &&
17515                            (len < (int)(sbavail(sb) - sb_offset))) {
17516                         /*
17517                          * Here we are doing hardware pacing, this is not a TLP,
17518                          * we are not sending a pace max segment size, there is rwnd
17519                          * room to send at least N pace_max_seg, the cwnd is greater
17520                          * than or equal to a full pacing segments plus 4 mss and we have 2 or
17521                          * more segments in flight and its not the tail of the socket buffer.
17522                          *
17523                          * We don't want to send instead we need to get more ack's in to
17524                          * allow us to send a full pacing segment. Normally, if we are pacing
17525                          * about the right speed, we should have finished our pacing
17526                          * send as most of the acks have come back if we are at the
17527                          * right rate. This is a bit fuzzy since return path delay
17528                          * can delay the acks, which is why we want to make sure we
17529                          * have cwnd space to have a bit more than a max pace segments in flight.
17530                          *
17531                          * If we have not gotten our acks back we are pacing at too high a
17532                          * rate delaying will not hurt and will bring our GP estimate down by
17533                          * injecting the delay. If we don't do this we will send
17534                          * 2 MSS out in response to the acks being clocked in which
17535                          * defeats the point of hw-pacing (i.e. to help us get
17536                          * larger TSO's out).
17537                          */
17538                         len = 0;
17539
17540                 }
17541
17542         }
17543         /* len will be >= 0 after this point. */
17544         KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
17545         rack_sndbuf_autoscale(rack);
17546         /*
17547          * Decide if we can use TCP Segmentation Offloading (if supported by
17548          * hardware).
17549          *
17550          * TSO may only be used if we are in a pure bulk sending state.  The
17551          * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
17552          * options prevent using TSO.  With TSO the TCP header is the same
17553          * (except for the sequence number) for all generated packets.  This
17554          * makes it impossible to transmit any options which vary per
17555          * generated segment or packet.
17556          *
17557          * IPv4 handling has a clear separation of ip options and ip header
17558          * flags while IPv6 combines both in in6p_outputopts. ip6_optlen() does
17559          * the right thing below to provide length of just ip options and thus
17560          * checking for ipoptlen is enough to decide if ip options are present.
17561          */
17562         ipoptlen = 0;
17563 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
17564         /*
17565          * Pre-calculate here as we save another lookup into the darknesses
17566          * of IPsec that way and can actually decide if TSO is ok.
17567          */
17568 #ifdef INET6
17569         if (isipv6 && IPSEC_ENABLED(ipv6))
17570                 ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
17571 #ifdef INET
17572         else
17573 #endif
17574 #endif                          /* INET6 */
17575 #ifdef INET
17576                 if (IPSEC_ENABLED(ipv4))
17577                         ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
17578 #endif                          /* INET */
17579 #endif
17580
17581 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
17582         ipoptlen += ipsec_optlen;
17583 #endif
17584         if ((tp->t_flags & TF_TSO) && V_tcp_do_tso && len > segsiz &&
17585             (tp->t_port == 0) &&
17586             ((tp->t_flags & TF_SIGNATURE) == 0) &&
17587             tp->rcv_numsacks == 0 && sack_rxmit == 0 &&
17588             ipoptlen == 0)
17589                 tso = 1;
17590         {
17591                 uint32_t outstanding __unused;
17592
17593                 outstanding = tp->snd_max - tp->snd_una;
17594                 if (tp->t_flags & TF_SENTFIN) {
17595                         /*
17596                          * If we sent a fin, snd_max is 1 higher than
17597                          * snd_una
17598                          */
17599                         outstanding--;
17600                 }
17601                 if (sack_rxmit) {
17602                         if ((rsm->r_flags & RACK_HAS_FIN) == 0)
17603                                 flags &= ~TH_FIN;
17604                 } else {
17605                         if (SEQ_LT(tp->snd_nxt + len, tp->snd_una +
17606                                    sbused(sb)))
17607                                 flags &= ~TH_FIN;
17608                 }
17609         }
17610         recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
17611             (long)TCP_MAXWIN << tp->rcv_scale);
17612
17613         /*
17614          * Sender silly window avoidance.   We transmit under the following
17615          * conditions when len is non-zero:
17616          *
17617          * - We have a full segment (or more with TSO) - This is the last
17618          * buffer in a write()/send() and we are either idle or running
17619          * NODELAY - we've timed out (e.g. persist timer) - we have more
17620          * then 1/2 the maximum send window's worth of data (receiver may be
17621          * limited the window size) - we need to retransmit
17622          */
17623         if (len) {
17624                 if (len >= segsiz) {
17625                         goto send;
17626                 }
17627                 /*
17628                  * NOTE! on localhost connections an 'ack' from the remote
17629                  * end may occur synchronously with the output and cause us
17630                  * to flush a buffer queued with moretocome.  XXX
17631                  *
17632                  */
17633                 if (!(tp->t_flags & TF_MORETOCOME) &&   /* normal case */
17634                     (idle || (tp->t_flags & TF_NODELAY)) &&
17635                     ((uint32_t)len + (uint32_t)sb_offset >= sbavail(sb)) &&
17636                     (tp->t_flags & TF_NOPUSH) == 0) {
17637                         pass = 2;
17638                         goto send;
17639                 }
17640                 if ((tp->snd_una == tp->snd_max) && len) {      /* Nothing outstanding */
17641                         pass = 22;
17642                         goto send;
17643                 }
17644                 if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
17645                         pass = 4;
17646                         goto send;
17647                 }
17648                 if (SEQ_LT(tp->snd_nxt, tp->snd_max)) { /* retransmit case */
17649                         pass = 5;
17650                         goto send;
17651                 }
17652                 if (sack_rxmit) {
17653                         pass = 6;
17654                         goto send;
17655                 }
17656                 if (((tp->snd_wnd - ctf_outstanding(tp)) < segsiz) &&
17657                     (ctf_outstanding(tp) < (segsiz * 2))) {
17658                         /*
17659                          * We have less than two MSS outstanding (delayed ack)
17660                          * and our rwnd will not let us send a full sized
17661                          * MSS. Lets go ahead and let this small segment
17662                          * out because we want to try to have at least two
17663                          * packets inflight to not be caught by delayed ack.
17664                          */
17665                         pass = 12;
17666                         goto send;
17667                 }
17668         }
17669         /*
17670          * Sending of standalone window updates.
17671          *
17672          * Window updates are important when we close our window due to a
17673          * full socket buffer and are opening it again after the application
17674          * reads data from it.  Once the window has opened again and the
17675          * remote end starts to send again the ACK clock takes over and
17676          * provides the most current window information.
17677          *
17678          * We must avoid the silly window syndrome whereas every read from
17679          * the receive buffer, no matter how small, causes a window update
17680          * to be sent.  We also should avoid sending a flurry of window
17681          * updates when the socket buffer had queued a lot of data and the
17682          * application is doing small reads.
17683          *
17684          * Prevent a flurry of pointless window updates by only sending an
17685          * update when we can increase the advertized window by more than
17686          * 1/4th of the socket buffer capacity.  When the buffer is getting
17687          * full or is very small be more aggressive and send an update
17688          * whenever we can increase by two mss sized segments. In all other
17689          * situations the ACK's to new incoming data will carry further
17690          * window increases.
17691          *
17692          * Don't send an independent window update if a delayed ACK is
17693          * pending (it will get piggy-backed on it) or the remote side
17694          * already has done a half-close and won't send more data.  Skip
17695          * this if the connection is in T/TCP half-open state.
17696          */
17697         if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
17698             !(tp->t_flags & TF_DELACK) &&
17699             !TCPS_HAVERCVDFIN(tp->t_state)) {
17700                 /*
17701                  * "adv" is the amount we could increase the window, taking
17702                  * into account that we are limited by TCP_MAXWIN <<
17703                  * tp->rcv_scale.
17704                  */
17705                 int32_t adv;
17706                 int oldwin;
17707
17708                 adv = recwin;
17709                 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
17710                         oldwin = (tp->rcv_adv - tp->rcv_nxt);
17711                         if (adv > oldwin)
17712                             adv -= oldwin;
17713                         else {
17714                                 /* We can't increase the window */
17715                                 adv = 0;
17716                         }
17717                 } else
17718                         oldwin = 0;
17719
17720                 /*
17721                  * If the new window size ends up being the same as or less
17722                  * than the old size when it is scaled, then don't force
17723                  * a window update.
17724                  */
17725                 if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
17726                         goto dontupdate;
17727
17728                 if (adv >= (int32_t)(2 * segsiz) &&
17729                     (adv >= (int32_t)(so->so_rcv.sb_hiwat / 4) ||
17730                      recwin <= (int32_t)(so->so_rcv.sb_hiwat / 8) ||
17731                      so->so_rcv.sb_hiwat <= 8 * segsiz)) {
17732                         pass = 7;
17733                         goto send;
17734                 }
17735                 if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat) {
17736                         pass = 23;
17737                         goto send;
17738                 }
17739         }
17740 dontupdate:
17741
17742         /*
17743          * Send if we owe the peer an ACK, RST, SYN, or urgent data.  ACKNOW
17744          * is also a catch-all for the retransmit timer timeout case.
17745          */
17746         if (tp->t_flags & TF_ACKNOW) {
17747                 pass = 8;
17748                 goto send;
17749         }
17750         if (((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0)) {
17751                 pass = 9;
17752                 goto send;
17753         }
17754         /*
17755          * If our state indicates that FIN should be sent and we have not
17756          * yet done so, then we need to send.
17757          */
17758         if ((flags & TH_FIN) &&
17759             (tp->snd_nxt == tp->snd_una)) {
17760                 pass = 11;
17761                 goto send;
17762         }
17763         /*
17764          * No reason to send a segment, just return.
17765          */
17766 just_return:
17767         SOCKBUF_UNLOCK(sb);
17768 just_return_nolock:
17769         {
17770                 int app_limited = CTF_JR_SENT_DATA;
17771
17772                 if (tot_len_this_send > 0) {
17773                         /* Make sure snd_nxt is up to max */
17774                         rack->r_ctl.fsb.recwin = recwin;
17775                         slot = rack_get_pacing_delay(rack, tp, tot_len_this_send, NULL, segsiz);
17776                         if ((error == 0) &&
17777                             rack_use_rfo &&
17778                             ((flags & (TH_SYN|TH_FIN)) == 0) &&
17779                             (ipoptlen == 0) &&
17780                             (tp->snd_nxt == tp->snd_max) &&
17781                             (tp->rcv_numsacks == 0) &&
17782                             rack->r_fsb_inited &&
17783                             TCPS_HAVEESTABLISHED(tp->t_state) &&
17784                             (rack->r_must_retran == 0) &&
17785                             ((tp->t_flags & TF_NEEDFIN) == 0) &&
17786                             (len > 0) && (orig_len > 0) &&
17787                             (orig_len > len) &&
17788                             ((orig_len - len) >= segsiz) &&
17789                             ((optlen == 0) ||
17790                              ((optlen == TCPOLEN_TSTAMP_APPA) && (to.to_flags & TOF_TS)))) {
17791                                 /* We can send at least one more MSS using our fsb */
17792
17793                                 rack->r_fast_output = 1;
17794                                 rack->r_ctl.fsb.m = sbsndmbuf(sb, (tp->snd_max - tp->snd_una), &rack->r_ctl.fsb.off);
17795                                 rack->r_ctl.fsb.o_m_len = rack->r_ctl.fsb.m->m_len;
17796                                 rack->r_ctl.fsb.tcp_flags = flags;
17797                                 rack->r_ctl.fsb.left_to_send = orig_len - len;
17798                                 if (hw_tls)
17799                                         rack->r_ctl.fsb.hw_tls = 1;
17800                                 else
17801                                         rack->r_ctl.fsb.hw_tls = 0;
17802                                 KASSERT((rack->r_ctl.fsb.left_to_send <= (sbavail(sb) - (tp->snd_max - tp->snd_una))),
17803                                         ("rack:%p left_to_send:%u sbavail:%u out:%u",
17804                                         rack, rack->r_ctl.fsb.left_to_send, sbavail(sb),
17805                                          (tp->snd_max - tp->snd_una)));
17806                                 if (rack->r_ctl.fsb.left_to_send < segsiz)
17807                                         rack->r_fast_output = 0;
17808                                 else {
17809                                         if (rack->r_ctl.fsb.left_to_send == (sbavail(sb) - (tp->snd_max - tp->snd_una)))
17810                                                 rack->r_ctl.fsb.rfo_apply_push = 1;
17811                                         else
17812                                                 rack->r_ctl.fsb.rfo_apply_push = 0;
17813                                 }
17814                         } else
17815                                 rack->r_fast_output = 0;
17816
17817
17818                         rack_log_fsb(rack, tp, so, flags,
17819                                      ipoptlen, orig_len, len, 0,
17820                                      1, optlen, __LINE__, 1);
17821                         if (SEQ_GT(tp->snd_max, tp->snd_nxt))
17822                                 tp->snd_nxt = tp->snd_max;
17823                 } else {
17824                         int end_window = 0;
17825                         uint32_t seq = tp->gput_ack;
17826
17827                         rsm = RB_MAX(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
17828                         if (rsm) {
17829                                 /*
17830                                  * Mark the last sent that we just-returned (hinting
17831                                  * that delayed ack may play a role in any rtt measurement).
17832                                  */
17833                                 rsm->r_just_ret = 1;
17834                         }
17835                         counter_u64_add(rack_out_size[TCP_MSS_ACCT_JUSTRET], 1);
17836                         rack->r_ctl.rc_agg_delayed = 0;
17837                         rack->r_early = 0;
17838                         rack->r_late = 0;
17839                         rack->r_ctl.rc_agg_early = 0;
17840                         if ((ctf_outstanding(tp) +
17841                              min(max(segsiz, (rack->r_ctl.rc_high_rwnd/2)),
17842                                  minseg)) >= tp->snd_wnd) {
17843                                 /* We are limited by the rwnd */
17844                                 app_limited = CTF_JR_RWND_LIMITED;
17845                                 if (IN_FASTRECOVERY(tp->t_flags))
17846                                     rack->r_ctl.rc_prr_sndcnt = 0;
17847                         } else if (ctf_outstanding(tp) >= sbavail(sb)) {
17848                                 /* We are limited by whats available -- app limited */
17849                                 app_limited = CTF_JR_APP_LIMITED;
17850                                 if (IN_FASTRECOVERY(tp->t_flags))
17851                                     rack->r_ctl.rc_prr_sndcnt = 0;
17852                         } else if ((idle == 0) &&
17853                                    ((tp->t_flags & TF_NODELAY) == 0) &&
17854                                    ((uint32_t)len + (uint32_t)sb_offset >= sbavail(sb)) &&
17855                                    (len < segsiz)) {
17856                                 /*
17857                                  * No delay is not on and the
17858                                  * user is sending less than 1MSS. This
17859                                  * brings out SWS avoidance so we
17860                                  * don't send. Another app-limited case.
17861                                  */
17862                                 app_limited = CTF_JR_APP_LIMITED;
17863                         } else if (tp->t_flags & TF_NOPUSH) {
17864                                 /*
17865                                  * The user has requested no push of
17866                                  * the last segment and we are
17867                                  * at the last segment. Another app
17868                                  * limited case.
17869                                  */
17870                                 app_limited = CTF_JR_APP_LIMITED;
17871                         } else if ((ctf_outstanding(tp) + minseg) > cwnd_to_use) {
17872                                 /* Its the cwnd */
17873                                 app_limited = CTF_JR_CWND_LIMITED;
17874                         } else if (IN_FASTRECOVERY(tp->t_flags) &&
17875                                    (rack->rack_no_prr == 0) &&
17876                                    (rack->r_ctl.rc_prr_sndcnt < segsiz)) {
17877                                 app_limited = CTF_JR_PRR;
17878                         } else {
17879                                 /* Now why here are we not sending? */
17880 #ifdef NOW
17881 #ifdef INVARIANTS
17882                                 panic("rack:%p hit JR_ASSESSING case cwnd_to_use:%u?", rack, cwnd_to_use);
17883 #endif
17884 #endif
17885                                 app_limited = CTF_JR_ASSESSING;
17886                         }
17887                         /*
17888                          * App limited in some fashion, for our pacing GP
17889                          * measurements we don't want any gap (even cwnd).
17890                          * Close  down the measurement window.
17891                          */
17892                         if (rack_cwnd_block_ends_measure &&
17893                             ((app_limited == CTF_JR_CWND_LIMITED) ||
17894                              (app_limited == CTF_JR_PRR))) {
17895                                 /*
17896                                  * The reason we are not sending is
17897                                  * the cwnd (or prr). We have been configured
17898                                  * to end the measurement window in
17899                                  * this case.
17900                                  */
17901                                 end_window = 1;
17902                         } else if (rack_rwnd_block_ends_measure &&
17903                                    (app_limited == CTF_JR_RWND_LIMITED)) {
17904                                 /*
17905                                  * We are rwnd limited and have been
17906                                  * configured to end the measurement
17907                                  * window in this case.
17908                                  */
17909                                 end_window = 1;
17910                         } else if (app_limited == CTF_JR_APP_LIMITED) {
17911                                 /*
17912                                  * A true application limited period, we have
17913                                  * ran out of data.
17914                                  */
17915                                 end_window = 1;
17916                         } else if (app_limited == CTF_JR_ASSESSING) {
17917                                 /*
17918                                  * In the assessing case we hit the end of
17919                                  * the if/else and had no known reason
17920                                  * This will panic us under invariants..
17921                                  *
17922                                  * If we get this out in logs we need to
17923                                  * investagate which reason we missed.
17924                                  */
17925                                 end_window = 1;
17926                         }
17927                         if (end_window) {
17928                                 uint8_t log = 0;
17929
17930                                 /* Adjust the Gput measurement */
17931                                 if ((tp->t_flags & TF_GPUTINPROG) &&
17932                                     SEQ_GT(tp->gput_ack, tp->snd_max)) {
17933                                         tp->gput_ack = tp->snd_max;
17934                                         if ((tp->gput_ack - tp->gput_seq) < (MIN_GP_WIN * segsiz)) {
17935                                                 /*
17936                                                  * There is not enough to measure.
17937                                                  */
17938                                                 tp->t_flags &= ~TF_GPUTINPROG;
17939                                                 rack_log_pacing_delay_calc(rack, (tp->gput_ack - tp->gput_seq) /*flex2*/,
17940                                                                            rack->r_ctl.rc_gp_srtt /*flex1*/,
17941                                                                            tp->gput_seq,
17942                                                                            0, 0, 18, __LINE__, NULL, 0);
17943                                         } else
17944                                                 log = 1;
17945                                 }
17946                                 /* Mark the last packet has app limited */
17947                                 rsm = RB_MAX(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
17948                                 if (rsm && ((rsm->r_flags & RACK_APP_LIMITED) == 0)) {
17949                                         if (rack->r_ctl.rc_app_limited_cnt == 0)
17950                                                 rack->r_ctl.rc_end_appl = rack->r_ctl.rc_first_appl = rsm;
17951                                         else {
17952                                                 /*
17953                                                  * Go out to the end app limited and mark
17954                                                  * this new one as next and move the end_appl up
17955                                                  * to this guy.
17956                                                  */
17957                                                 if (rack->r_ctl.rc_end_appl)
17958                                                         rack->r_ctl.rc_end_appl->r_nseq_appl = rsm->r_start;
17959                                                 rack->r_ctl.rc_end_appl = rsm;
17960                                         }
17961                                         rsm->r_flags |= RACK_APP_LIMITED;
17962                                         rack->r_ctl.rc_app_limited_cnt++;
17963                                 }
17964                                 if (log)
17965                                         rack_log_pacing_delay_calc(rack,
17966                                                                    rack->r_ctl.rc_app_limited_cnt, seq,
17967                                                                    tp->gput_ack, 0, 0, 4, __LINE__, NULL, 0);
17968                         }
17969                 }
17970                 /* Check if we need to go into persists or not */
17971                 if ((tp->snd_max == tp->snd_una) &&
17972                     TCPS_HAVEESTABLISHED(tp->t_state) &&
17973                     sbavail(sb) &&
17974                     (sbavail(sb) > tp->snd_wnd) &&
17975                     (tp->snd_wnd < min((rack->r_ctl.rc_high_rwnd/2), minseg))) {
17976                         /* Yes lets make sure to move to persist before timer-start */
17977                         rack_enter_persist(tp, rack, rack->r_ctl.rc_rcvtime);
17978                 }
17979                 rack_start_hpts_timer(rack, tp, cts, slot, tot_len_this_send, sup_rack);
17980                 rack_log_type_just_return(rack, cts, tot_len_this_send, slot, hpts_calling, app_limited, cwnd_to_use);
17981         }
17982 #ifdef NETFLIX_SHARED_CWND
17983         if ((sbavail(sb) == 0) &&
17984             rack->r_ctl.rc_scw) {
17985                 tcp_shared_cwnd_idle(rack->r_ctl.rc_scw, rack->r_ctl.rc_scw_index);
17986                 rack->rack_scwnd_is_idle = 1;
17987         }
17988 #endif
17989 #ifdef TCP_ACCOUNTING
17990         if (tot_len_this_send > 0) {
17991                 crtsc = get_cyclecount();
17992                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
17993                         tp->tcp_cnt_counters[SND_OUT_DATA]++;
17994                 }
17995                 counter_u64_add(tcp_cnt_counters[SND_OUT_DATA], 1);
17996                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
17997                         tp->tcp_proc_time[SND_OUT_DATA] += (crtsc - ts_val);
17998                 }
17999                 counter_u64_add(tcp_proc_time[SND_OUT_DATA], (crtsc - ts_val));
18000                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18001                         tp->tcp_cnt_counters[CNT_OF_MSS_OUT] += ((tot_len_this_send + segsiz - 1) / segsiz);
18002                 }
18003                 counter_u64_add(tcp_cnt_counters[CNT_OF_MSS_OUT], ((tot_len_this_send + segsiz - 1) / segsiz));
18004         } else {
18005                 crtsc = get_cyclecount();
18006                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18007                         tp->tcp_cnt_counters[SND_LIMITED]++;
18008                 }
18009                 counter_u64_add(tcp_cnt_counters[SND_LIMITED], 1);
18010                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18011                         tp->tcp_proc_time[SND_LIMITED] += (crtsc - ts_val);
18012                 }
18013                 counter_u64_add(tcp_proc_time[SND_LIMITED], (crtsc - ts_val));
18014         }
18015         sched_unpin();
18016 #endif
18017         return (0);
18018
18019 send:
18020         if (rsm || sack_rxmit)
18021                 counter_u64_add(rack_nfto_resend, 1);
18022         else
18023                 counter_u64_add(rack_non_fto_send, 1);
18024         if ((flags & TH_FIN) &&
18025             sbavail(sb)) {
18026                 /*
18027                  * We do not transmit a FIN
18028                  * with data outstanding. We
18029                  * need to make it so all data
18030                  * is acked first.
18031                  */
18032                 flags &= ~TH_FIN;
18033         }
18034         /* Enforce stack imposed max seg size if we have one */
18035         if (rack->r_ctl.rc_pace_max_segs &&
18036             (len > rack->r_ctl.rc_pace_max_segs)) {
18037                 mark = 1;
18038                 len = rack->r_ctl.rc_pace_max_segs;
18039         }
18040         SOCKBUF_LOCK_ASSERT(sb);
18041         if (len > 0) {
18042                 if (len >= segsiz)
18043                         tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
18044                 else
18045                         tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
18046         }
18047         /*
18048          * Before ESTABLISHED, force sending of initial options unless TCP
18049          * set not to do any options. NOTE: we assume that the IP/TCP header
18050          * plus TCP options always fit in a single mbuf, leaving room for a
18051          * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
18052          * + optlen <= MCLBYTES
18053          */
18054         optlen = 0;
18055 #ifdef INET6
18056         if (isipv6)
18057                 hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
18058         else
18059 #endif
18060                 hdrlen = sizeof(struct tcpiphdr);
18061
18062         /*
18063          * Compute options for segment. We only have to care about SYN and
18064          * established connection segments.  Options for SYN-ACK segments
18065          * are handled in TCP syncache.
18066          */
18067         to.to_flags = 0;
18068         if ((tp->t_flags & TF_NOOPT) == 0) {
18069                 /* Maximum segment size. */
18070                 if (flags & TH_SYN) {
18071                         tp->snd_nxt = tp->iss;
18072                         to.to_mss = tcp_mssopt(&inp->inp_inc);
18073                         if (tp->t_port)
18074                                 to.to_mss -= V_tcp_udp_tunneling_overhead;
18075                         to.to_flags |= TOF_MSS;
18076
18077                         /*
18078                          * On SYN or SYN|ACK transmits on TFO connections,
18079                          * only include the TFO option if it is not a
18080                          * retransmit, as the presence of the TFO option may
18081                          * have caused the original SYN or SYN|ACK to have
18082                          * been dropped by a middlebox.
18083                          */
18084                         if (IS_FASTOPEN(tp->t_flags) &&
18085                             (tp->t_rxtshift == 0)) {
18086                                 if (tp->t_state == TCPS_SYN_RECEIVED) {
18087                                         to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
18088                                         to.to_tfo_cookie =
18089                                                 (u_int8_t *)&tp->t_tfo_cookie.server;
18090                                         to.to_flags |= TOF_FASTOPEN;
18091                                         wanted_cookie = 1;
18092                                 } else if (tp->t_state == TCPS_SYN_SENT) {
18093                                         to.to_tfo_len =
18094                                                 tp->t_tfo_client_cookie_len;
18095                                         to.to_tfo_cookie =
18096                                                 tp->t_tfo_cookie.client;
18097                                         to.to_flags |= TOF_FASTOPEN;
18098                                         wanted_cookie = 1;
18099                                         /*
18100                                          * If we wind up having more data to
18101                                          * send with the SYN than can fit in
18102                                          * one segment, don't send any more
18103                                          * until the SYN|ACK comes back from
18104                                          * the other end.
18105                                          */
18106                                         sendalot = 0;
18107                                 }
18108                         }
18109                 }
18110                 /* Window scaling. */
18111                 if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
18112                         to.to_wscale = tp->request_r_scale;
18113                         to.to_flags |= TOF_SCALE;
18114                 }
18115                 /* Timestamps. */
18116                 if ((tp->t_flags & TF_RCVD_TSTMP) ||
18117                     ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
18118                         to.to_tsval = ms_cts + tp->ts_offset;
18119                         to.to_tsecr = tp->ts_recent;
18120                         to.to_flags |= TOF_TS;
18121                 }
18122                 /* Set receive buffer autosizing timestamp. */
18123                 if (tp->rfbuf_ts == 0 &&
18124                     (so->so_rcv.sb_flags & SB_AUTOSIZE))
18125                         tp->rfbuf_ts = tcp_ts_getticks();
18126                 /* Selective ACK's. */
18127                 if (tp->t_flags & TF_SACK_PERMIT) {
18128                         if (flags & TH_SYN)
18129                                 to.to_flags |= TOF_SACKPERM;
18130                         else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
18131                                  tp->rcv_numsacks > 0) {
18132                                 to.to_flags |= TOF_SACK;
18133                                 to.to_nsacks = tp->rcv_numsacks;
18134                                 to.to_sacks = (u_char *)tp->sackblks;
18135                         }
18136                 }
18137 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
18138                 /* TCP-MD5 (RFC2385). */
18139                 if (tp->t_flags & TF_SIGNATURE)
18140                         to.to_flags |= TOF_SIGNATURE;
18141 #endif                          /* TCP_SIGNATURE */
18142
18143                 /* Processing the options. */
18144                 hdrlen += optlen = tcp_addoptions(&to, opt);
18145                 /*
18146                  * If we wanted a TFO option to be added, but it was unable
18147                  * to fit, ensure no data is sent.
18148                  */
18149                 if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
18150                     !(to.to_flags & TOF_FASTOPEN))
18151                         len = 0;
18152         }
18153         if (tp->t_port) {
18154                 if (V_tcp_udp_tunneling_port == 0) {
18155                         /* The port was removed?? */
18156                         SOCKBUF_UNLOCK(&so->so_snd);
18157 #ifdef TCP_ACCOUNTING
18158                         crtsc = get_cyclecount();
18159                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18160                                 tp->tcp_cnt_counters[SND_OUT_FAIL]++;
18161                         }
18162                         counter_u64_add(tcp_cnt_counters[SND_OUT_FAIL], 1);
18163                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18164                                 tp->tcp_proc_time[SND_OUT_FAIL] += (crtsc - ts_val);
18165                         }
18166                         counter_u64_add(tcp_proc_time[SND_OUT_FAIL], (crtsc - ts_val));
18167                         sched_unpin();
18168 #endif
18169                         return (EHOSTUNREACH);
18170                 }
18171                 hdrlen += sizeof(struct udphdr);
18172         }
18173 #ifdef INET6
18174         if (isipv6)
18175                 ipoptlen = ip6_optlen(inp);
18176         else
18177 #endif
18178                 if (inp->inp_options)
18179                         ipoptlen = inp->inp_options->m_len -
18180                                 offsetof(struct ipoption, ipopt_list);
18181                 else
18182                         ipoptlen = 0;
18183 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
18184         ipoptlen += ipsec_optlen;
18185 #endif
18186
18187         /*
18188          * Adjust data length if insertion of options will bump the packet
18189          * length beyond the t_maxseg length. Clear the FIN bit because we
18190          * cut off the tail of the segment.
18191          */
18192         if (len + optlen + ipoptlen > tp->t_maxseg) {
18193                 if (tso) {
18194                         uint32_t if_hw_tsomax;
18195                         uint32_t moff;
18196                         int32_t max_len;
18197
18198                         /* extract TSO information */
18199                         if_hw_tsomax = tp->t_tsomax;
18200                         if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
18201                         if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
18202                         KASSERT(ipoptlen == 0,
18203                                 ("%s: TSO can't do IP options", __func__));
18204
18205                         /*
18206                          * Check if we should limit by maximum payload
18207                          * length:
18208                          */
18209                         if (if_hw_tsomax != 0) {
18210                                 /* compute maximum TSO length */
18211                                 max_len = (if_hw_tsomax - hdrlen -
18212                                            max_linkhdr);
18213                                 if (max_len <= 0) {
18214                                         len = 0;
18215                                 } else if (len > max_len) {
18216                                         sendalot = 1;
18217                                         len = max_len;
18218                                         mark = 2;
18219                                 }
18220                         }
18221                         /*
18222                          * Prevent the last segment from being fractional
18223                          * unless the send sockbuf can be emptied:
18224                          */
18225                         max_len = (tp->t_maxseg - optlen);
18226                         if ((sb_offset + len) < sbavail(sb)) {
18227                                 moff = len % (u_int)max_len;
18228                                 if (moff != 0) {
18229                                         mark = 3;
18230                                         len -= moff;
18231                                 }
18232                         }
18233                         /*
18234                          * In case there are too many small fragments don't
18235                          * use TSO:
18236                          */
18237                         if (len <= segsiz) {
18238                                 mark = 4;
18239                                 tso = 0;
18240                         }
18241                         /*
18242                          * Send the FIN in a separate segment after the bulk
18243                          * sending is done. We don't trust the TSO
18244                          * implementations to clear the FIN flag on all but
18245                          * the last segment.
18246                          */
18247                         if (tp->t_flags & TF_NEEDFIN) {
18248                                 sendalot = 4;
18249                         }
18250                 } else {
18251                         mark = 5;
18252                         if (optlen + ipoptlen >= tp->t_maxseg) {
18253                                 /*
18254                                  * Since we don't have enough space to put
18255                                  * the IP header chain and the TCP header in
18256                                  * one packet as required by RFC 7112, don't
18257                                  * send it. Also ensure that at least one
18258                                  * byte of the payload can be put into the
18259                                  * TCP segment.
18260                                  */
18261                                 SOCKBUF_UNLOCK(&so->so_snd);
18262                                 error = EMSGSIZE;
18263                                 sack_rxmit = 0;
18264                                 goto out;
18265                         }
18266                         len = tp->t_maxseg - optlen - ipoptlen;
18267                         sendalot = 5;
18268                 }
18269         } else {
18270                 tso = 0;
18271                 mark = 6;
18272         }
18273         KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
18274                 ("%s: len > IP_MAXPACKET", __func__));
18275 #ifdef DIAGNOSTIC
18276 #ifdef INET6
18277         if (max_linkhdr + hdrlen > MCLBYTES)
18278 #else
18279                 if (max_linkhdr + hdrlen > MHLEN)
18280 #endif
18281                         panic("tcphdr too big");
18282 #endif
18283
18284         /*
18285          * This KASSERT is here to catch edge cases at a well defined place.
18286          * Before, those had triggered (random) panic conditions further
18287          * down.
18288          */
18289         KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
18290         if ((len == 0) &&
18291             (flags & TH_FIN) &&
18292             (sbused(sb))) {
18293                 /*
18294                  * We have outstanding data, don't send a fin by itself!.
18295                  */
18296                 goto just_return;
18297         }
18298         /*
18299          * Grab a header mbuf, attaching a copy of data to be transmitted,
18300          * and initialize the header from the template for sends on this
18301          * connection.
18302          */
18303         hw_tls = (sb->sb_flags & SB_TLS_IFNET) != 0;
18304         if (len) {
18305                 uint32_t max_val;
18306                 uint32_t moff;
18307
18308                 if (rack->r_ctl.rc_pace_max_segs)
18309                         max_val = rack->r_ctl.rc_pace_max_segs;
18310                 else if (rack->rc_user_set_max_segs)
18311                         max_val = rack->rc_user_set_max_segs * segsiz;
18312                 else
18313                         max_val = len;
18314                 /*
18315                  * We allow a limit on sending with hptsi.
18316                  */
18317                 if (len > max_val) {
18318                         mark = 7;
18319                         len = max_val;
18320                 }
18321 #ifdef INET6
18322                 if (MHLEN < hdrlen + max_linkhdr)
18323                         m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
18324                 else
18325 #endif
18326                         m = m_gethdr(M_NOWAIT, MT_DATA);
18327
18328                 if (m == NULL) {
18329                         SOCKBUF_UNLOCK(sb);
18330                         error = ENOBUFS;
18331                         sack_rxmit = 0;
18332                         goto out;
18333                 }
18334                 m->m_data += max_linkhdr;
18335                 m->m_len = hdrlen;
18336
18337                 /*
18338                  * Start the m_copy functions from the closest mbuf to the
18339                  * sb_offset in the socket buffer chain.
18340                  */
18341                 mb = sbsndptr_noadv(sb, sb_offset, &moff);
18342                 s_mb = mb;
18343                 s_moff = moff;
18344                 if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
18345                         m_copydata(mb, moff, (int)len,
18346                                    mtod(m, caddr_t)+hdrlen);
18347                         if (SEQ_LT(tp->snd_nxt, tp->snd_max))
18348                                 sbsndptr_adv(sb, mb, len);
18349                         m->m_len += len;
18350                 } else {
18351                         struct sockbuf *msb;
18352
18353                         if (SEQ_LT(tp->snd_nxt, tp->snd_max))
18354                                 msb = NULL;
18355                         else
18356                                 msb = sb;
18357                         m->m_next = tcp_m_copym(
18358                                 mb, moff, &len,
18359                                 if_hw_tsomaxsegcount, if_hw_tsomaxsegsize, msb,
18360                                 ((rsm == NULL) ? hw_tls : 0)
18361 #ifdef NETFLIX_COPY_ARGS
18362                                 , &s_mb, &s_moff
18363 #endif
18364                                 );
18365                         if (len <= (tp->t_maxseg - optlen)) {
18366                                 /*
18367                                  * Must have ran out of mbufs for the copy
18368                                  * shorten it to no longer need tso. Lets
18369                                  * not put on sendalot since we are low on
18370                                  * mbufs.
18371                                  */
18372                                 tso = 0;
18373                         }
18374                         if (m->m_next == NULL) {
18375                                 SOCKBUF_UNLOCK(sb);
18376                                 (void)m_free(m);
18377                                 error = ENOBUFS;
18378                                 sack_rxmit = 0;
18379                                 goto out;
18380                         }
18381                 }
18382                 if (SEQ_LT(tp->snd_nxt, tp->snd_max) || sack_rxmit) {
18383                         if (rsm && (rsm->r_flags & RACK_TLP)) {
18384                                 /*
18385                                  * TLP should not count in retran count, but
18386                                  * in its own bin
18387                                  */
18388                                 counter_u64_add(rack_tlp_retran, 1);
18389                                 counter_u64_add(rack_tlp_retran_bytes, len);
18390                         } else {
18391                                 tp->t_sndrexmitpack++;
18392                                 KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
18393                                 KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
18394                         }
18395 #ifdef STATS
18396                         stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
18397                                                  len);
18398 #endif
18399                 } else {
18400                         KMOD_TCPSTAT_INC(tcps_sndpack);
18401                         KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
18402 #ifdef STATS
18403                         stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
18404                                                  len);
18405 #endif
18406                 }
18407                 /*
18408                  * If we're sending everything we've got, set PUSH. (This
18409                  * will keep happy those implementations which only give
18410                  * data to the user when a buffer fills or a PUSH comes in.)
18411                  */
18412                 if (sb_offset + len == sbused(sb) &&
18413                     sbused(sb) &&
18414                     !(flags & TH_SYN)) {
18415                         flags |= TH_PUSH;
18416                         add_flag |= RACK_HAD_PUSH;
18417                 }
18418
18419                 SOCKBUF_UNLOCK(sb);
18420         } else {
18421                 SOCKBUF_UNLOCK(sb);
18422                 if (tp->t_flags & TF_ACKNOW)
18423                         KMOD_TCPSTAT_INC(tcps_sndacks);
18424                 else if (flags & (TH_SYN | TH_FIN | TH_RST))
18425                         KMOD_TCPSTAT_INC(tcps_sndctrl);
18426                 else
18427                         KMOD_TCPSTAT_INC(tcps_sndwinup);
18428
18429                 m = m_gethdr(M_NOWAIT, MT_DATA);
18430                 if (m == NULL) {
18431                         error = ENOBUFS;
18432                         sack_rxmit = 0;
18433                         goto out;
18434                 }
18435 #ifdef INET6
18436                 if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
18437                     MHLEN >= hdrlen) {
18438                         M_ALIGN(m, hdrlen);
18439                 } else
18440 #endif
18441                         m->m_data += max_linkhdr;
18442                 m->m_len = hdrlen;
18443         }
18444         SOCKBUF_UNLOCK_ASSERT(sb);
18445         m->m_pkthdr.rcvif = (struct ifnet *)0;
18446 #ifdef MAC
18447         mac_inpcb_create_mbuf(inp, m);
18448 #endif
18449         if ((ipoptlen == 0) && (rack->r_ctl.fsb.tcp_ip_hdr) &&  rack->r_fsb_inited) {
18450 #ifdef INET6
18451                 if (isipv6)
18452                         ip6 = (struct ip6_hdr *)rack->r_ctl.fsb.tcp_ip_hdr;
18453                 else
18454 #endif                          /* INET6 */
18455                         ip = (struct ip *)rack->r_ctl.fsb.tcp_ip_hdr;
18456                 th = rack->r_ctl.fsb.th;
18457                 udp = rack->r_ctl.fsb.udp;
18458                 if (udp) {
18459 #ifdef INET6
18460                         if (isipv6)
18461                                 ulen = hdrlen + len - sizeof(struct ip6_hdr);
18462                         else
18463 #endif                          /* INET6 */
18464                                 ulen = hdrlen + len - sizeof(struct ip);
18465                         udp->uh_ulen = htons(ulen);
18466                 }
18467         } else {
18468 #ifdef INET6
18469                 if (isipv6) {
18470                         ip6 = mtod(m, struct ip6_hdr *);
18471                         if (tp->t_port) {
18472                                 udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
18473                                 udp->uh_sport = htons(V_tcp_udp_tunneling_port);
18474                                 udp->uh_dport = tp->t_port;
18475                                 ulen = hdrlen + len - sizeof(struct ip6_hdr);
18476                                 udp->uh_ulen = htons(ulen);
18477                                 th = (struct tcphdr *)(udp + 1);
18478                         } else
18479                                 th = (struct tcphdr *)(ip6 + 1);
18480                         tcpip_fillheaders(inp, tp->t_port, ip6, th);
18481                 } else
18482 #endif                          /* INET6 */
18483                 {
18484                         ip = mtod(m, struct ip *);
18485                         if (tp->t_port) {
18486                                 udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
18487                                 udp->uh_sport = htons(V_tcp_udp_tunneling_port);
18488                                 udp->uh_dport = tp->t_port;
18489                                 ulen = hdrlen + len - sizeof(struct ip);
18490                                 udp->uh_ulen = htons(ulen);
18491                                 th = (struct tcphdr *)(udp + 1);
18492                         } else
18493                                 th = (struct tcphdr *)(ip + 1);
18494                         tcpip_fillheaders(inp, tp->t_port, ip, th);
18495                 }
18496         }
18497         /*
18498          * Fill in fields, remembering maximum advertised window for use in
18499          * delaying messages about window sizes. If resending a FIN, be sure
18500          * not to use a new sequence number.
18501          */
18502         if (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&
18503             tp->snd_nxt == tp->snd_max)
18504                 tp->snd_nxt--;
18505         /*
18506          * If we are starting a connection, send ECN setup SYN packet. If we
18507          * are on a retransmit, we may resend those bits a number of times
18508          * as per RFC 3168.
18509          */
18510         if (tp->t_state == TCPS_SYN_SENT && V_tcp_do_ecn) {
18511                 flags |= tcp_ecn_output_syn_sent(tp);
18512         }
18513         /* Also handle parallel SYN for ECN */
18514         if (TCPS_HAVERCVDSYN(tp->t_state) &&
18515             (tp->t_flags2 & (TF2_ECN_PERMIT | TF2_ACE_PERMIT))) {
18516                 int ect = tcp_ecn_output_established(tp, &flags, len, sack_rxmit);
18517                 if ((tp->t_state == TCPS_SYN_RECEIVED) &&
18518                     (tp->t_flags2 & TF2_ECN_SND_ECE))
18519                         tp->t_flags2 &= ~TF2_ECN_SND_ECE;
18520 #ifdef INET6
18521                 if (isipv6) {
18522                         ip6->ip6_flow &= ~htonl(IPTOS_ECN_MASK << 20);
18523                         ip6->ip6_flow |= htonl(ect << 20);
18524                 }
18525                 else
18526 #endif
18527                 {
18528                         ip->ip_tos &= ~IPTOS_ECN_MASK;
18529                         ip->ip_tos |= ect;
18530                 }
18531         }
18532         /*
18533          * If we are doing retransmissions, then snd_nxt will not reflect
18534          * the first unsent octet.  For ACK only packets, we do not want the
18535          * sequence number of the retransmitted packet, we want the sequence
18536          * number of the next unsent octet.  So, if there is no data (and no
18537          * SYN or FIN), use snd_max instead of snd_nxt when filling in
18538          * ti_seq.  But if we are in persist state, snd_max might reflect
18539          * one byte beyond the right edge of the window, so use snd_nxt in
18540          * that case, since we know we aren't doing a retransmission.
18541          * (retransmit and persist are mutually exclusive...)
18542          */
18543         if (sack_rxmit == 0) {
18544                 if (len || (flags & (TH_SYN | TH_FIN))) {
18545                         th->th_seq = htonl(tp->snd_nxt);
18546                         rack_seq = tp->snd_nxt;
18547                 } else {
18548                         th->th_seq = htonl(tp->snd_max);
18549                         rack_seq = tp->snd_max;
18550                 }
18551         } else {
18552                 th->th_seq = htonl(rsm->r_start);
18553                 rack_seq = rsm->r_start;
18554         }
18555         th->th_ack = htonl(tp->rcv_nxt);
18556         tcp_set_flags(th, flags);
18557         /*
18558          * Calculate receive window.  Don't shrink window, but avoid silly
18559          * window syndrome.
18560          * If a RST segment is sent, advertise a window of zero.
18561          */
18562         if (flags & TH_RST) {
18563                 recwin = 0;
18564         } else {
18565                 if (recwin < (long)(so->so_rcv.sb_hiwat / 4) &&
18566                     recwin < (long)segsiz) {
18567                         recwin = 0;
18568                 }
18569                 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
18570                     recwin < (long)(tp->rcv_adv - tp->rcv_nxt))
18571                         recwin = (long)(tp->rcv_adv - tp->rcv_nxt);
18572         }
18573
18574         /*
18575          * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
18576          * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
18577          * handled in syncache.
18578          */
18579         if (flags & TH_SYN)
18580                 th->th_win = htons((u_short)
18581                                    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
18582         else {
18583                 /* Avoid shrinking window with window scaling. */
18584                 recwin = roundup2(recwin, 1 << tp->rcv_scale);
18585                 th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
18586         }
18587         /*
18588          * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
18589          * window.  This may cause the remote transmitter to stall.  This
18590          * flag tells soreceive() to disable delayed acknowledgements when
18591          * draining the buffer.  This can occur if the receiver is
18592          * attempting to read more data than can be buffered prior to
18593          * transmitting on the connection.
18594          */
18595         if (th->th_win == 0) {
18596                 tp->t_sndzerowin++;
18597                 tp->t_flags |= TF_RXWIN0SENT;
18598         } else
18599                 tp->t_flags &= ~TF_RXWIN0SENT;
18600         tp->snd_up = tp->snd_una;       /* drag it along, its deprecated */
18601         /* Now are we using fsb?, if so copy the template data to the mbuf */
18602         if ((ipoptlen == 0) && (rack->r_ctl.fsb.tcp_ip_hdr) && rack->r_fsb_inited) {
18603                 uint8_t *cpto;
18604
18605                 cpto = mtod(m, uint8_t *);
18606                 memcpy(cpto, rack->r_ctl.fsb.tcp_ip_hdr, rack->r_ctl.fsb.tcp_ip_hdr_len);
18607                 /*
18608                  * We have just copied in:
18609                  * IP/IP6
18610                  * <optional udphdr>
18611                  * tcphdr (no options)
18612                  *
18613                  * We need to grab the correct pointers into the mbuf
18614                  * for both the tcp header, and possibly the udp header (if tunneling).
18615                  * We do this by using the offset in the copy buffer and adding it
18616                  * to the mbuf base pointer (cpto).
18617                  */
18618 #ifdef INET6
18619                 if (isipv6)
18620                         ip6 = mtod(m, struct ip6_hdr *);
18621                 else
18622 #endif                          /* INET6 */
18623                         ip = mtod(m, struct ip *);
18624                 th = (struct tcphdr *)(cpto + ((uint8_t *)rack->r_ctl.fsb.th - rack->r_ctl.fsb.tcp_ip_hdr));
18625                 /* If we have a udp header lets set it into the mbuf as well */
18626                 if (udp)
18627                         udp = (struct udphdr *)(cpto + ((uint8_t *)rack->r_ctl.fsb.udp - rack->r_ctl.fsb.tcp_ip_hdr));
18628         }
18629 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
18630         if (to.to_flags & TOF_SIGNATURE) {
18631                 /*
18632                  * Calculate MD5 signature and put it into the place
18633                  * determined before.
18634                  * NOTE: since TCP options buffer doesn't point into
18635                  * mbuf's data, calculate offset and use it.
18636                  */
18637                 if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
18638                                                        (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
18639                         /*
18640                          * Do not send segment if the calculation of MD5
18641                          * digest has failed.
18642                          */
18643                         goto out;
18644                 }
18645         }
18646 #endif
18647         if (optlen) {
18648                 bcopy(opt, th + 1, optlen);
18649                 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
18650         }
18651         /*
18652          * Put TCP length in extended header, and then checksum extended
18653          * header and data.
18654          */
18655         m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
18656 #ifdef INET6
18657         if (isipv6) {
18658                 /*
18659                  * ip6_plen is not need to be filled now, and will be filled
18660                  * in ip6_output.
18661                  */
18662                 if (tp->t_port) {
18663                         m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
18664                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
18665                         udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
18666                         th->th_sum = htons(0);
18667                         UDPSTAT_INC(udps_opackets);
18668                 } else {
18669                         m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
18670                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
18671                         th->th_sum = in6_cksum_pseudo(ip6,
18672                                                       sizeof(struct tcphdr) + optlen + len, IPPROTO_TCP,
18673                                                       0);
18674                 }
18675         }
18676 #endif
18677 #if defined(INET6) && defined(INET)
18678         else
18679 #endif
18680 #ifdef INET
18681         {
18682                 if (tp->t_port) {
18683                         m->m_pkthdr.csum_flags = CSUM_UDP;
18684                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
18685                         udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
18686                                                 ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
18687                         th->th_sum = htons(0);
18688                         UDPSTAT_INC(udps_opackets);
18689                 } else {
18690                         m->m_pkthdr.csum_flags = CSUM_TCP;
18691                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
18692                         th->th_sum = in_pseudo(ip->ip_src.s_addr,
18693                                                ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
18694                                                                         IPPROTO_TCP + len + optlen));
18695                 }
18696                 /* IP version must be set here for ipv4/ipv6 checking later */
18697                 KASSERT(ip->ip_v == IPVERSION,
18698                         ("%s: IP version incorrect: %d", __func__, ip->ip_v));
18699         }
18700 #endif
18701         /*
18702          * Enable TSO and specify the size of the segments. The TCP pseudo
18703          * header checksum is always provided. XXX: Fixme: This is currently
18704          * not the case for IPv6.
18705          */
18706         if (tso) {
18707                 KASSERT(len > tp->t_maxseg - optlen,
18708                         ("%s: len <= tso_segsz", __func__));
18709                 m->m_pkthdr.csum_flags |= CSUM_TSO;
18710                 m->m_pkthdr.tso_segsz = tp->t_maxseg - optlen;
18711         }
18712         KASSERT(len + hdrlen == m_length(m, NULL),
18713                 ("%s: mbuf chain different than expected: %d + %u != %u",
18714                  __func__, len, hdrlen, m_length(m, NULL)));
18715
18716 #ifdef TCP_HHOOK
18717         /* Run HHOOK_TCP_ESTABLISHED_OUT helper hooks. */
18718         hhook_run_tcp_est_out(tp, th, &to, len, tso);
18719 #endif
18720         /* We're getting ready to send; log now. */
18721         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
18722                 union tcp_log_stackspecific log;
18723
18724                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
18725                 log.u_bbr.inhpts = tcp_in_hpts(rack->rc_inp);
18726                 if (rack->rack_no_prr)
18727                         log.u_bbr.flex1 = 0;
18728                 else
18729                         log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
18730                 log.u_bbr.flex2 = rack->r_ctl.rc_pace_min_segs;
18731                 log.u_bbr.flex3 = rack->r_ctl.rc_pace_max_segs;
18732                 log.u_bbr.flex4 = orig_len;
18733                 /* Save off the early/late values */
18734                 log.u_bbr.flex6 = rack->r_ctl.rc_agg_early;
18735                 log.u_bbr.applimited = rack->r_ctl.rc_agg_delayed;
18736                 log.u_bbr.bw_inuse = rack_get_bw(rack);
18737                 log.u_bbr.flex8 = 0;
18738                 if (rsm) {
18739                         if (rsm->r_flags & RACK_RWND_COLLAPSED) {
18740                                 rack_log_collapse(rack, rsm->r_start, rsm->r_end, 0, __LINE__, 5, rsm->r_flags, rsm);
18741                                 counter_u64_add(rack_collapsed_win_rxt, 1);
18742                                 counter_u64_add(rack_collapsed_win_rxt_bytes, (rsm->r_end - rsm->r_start));
18743                         }
18744                         if (doing_tlp)
18745                                 log.u_bbr.flex8 = 2;
18746                         else
18747                                 log.u_bbr.flex8 = 1;
18748                 } else {
18749                         if (doing_tlp)
18750                                 log.u_bbr.flex8 = 3;
18751                         else
18752                                 log.u_bbr.flex8 = 0;
18753                 }
18754                 log.u_bbr.pacing_gain = rack_get_output_gain(rack, rsm);
18755                 log.u_bbr.flex7 = mark;
18756                 log.u_bbr.flex7 <<= 8;
18757                 log.u_bbr.flex7 |= pass;
18758                 log.u_bbr.pkts_out = tp->t_maxseg;
18759                 log.u_bbr.timeStamp = cts;
18760                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
18761                 log.u_bbr.lt_epoch = cwnd_to_use;
18762                 log.u_bbr.delivered = sendalot;
18763                 lgb = tcp_log_event_(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
18764                                      len, &log, false, NULL, NULL, 0, &tv);
18765         } else
18766                 lgb = NULL;
18767
18768         /*
18769          * Fill in IP length and desired time to live and send to IP level.
18770          * There should be a better way to handle ttl and tos; we could keep
18771          * them in the template, but need a way to checksum without them.
18772          */
18773         /*
18774          * m->m_pkthdr.len should have been set before cksum calcuration,
18775          * because in6_cksum() need it.
18776          */
18777 #ifdef INET6
18778         if (isipv6) {
18779                 /*
18780                  * we separately set hoplimit for every segment, since the
18781                  * user might want to change the value via setsockopt. Also,
18782                  * desired default hop limit might be changed via Neighbor
18783                  * Discovery.
18784                  */
18785                 rack->r_ctl.fsb.hoplimit = ip6->ip6_hlim = in6_selecthlim(inp, NULL);
18786
18787                 /*
18788                  * Set the packet size here for the benefit of DTrace
18789                  * probes. ip6_output() will set it properly; it's supposed
18790                  * to include the option header lengths as well.
18791                  */
18792                 ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
18793
18794                 if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss)
18795                         tp->t_flags2 |= TF2_PLPMTU_PMTUD;
18796                 else
18797                         tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
18798
18799                 if (tp->t_state == TCPS_SYN_SENT)
18800                         TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
18801
18802                 TCP_PROBE5(send, NULL, tp, ip6, tp, th);
18803                 /* TODO: IPv6 IP6TOS_ECT bit on */
18804                 error = ip6_output(m,
18805 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
18806                                    inp->in6p_outputopts,
18807 #else
18808                                    NULL,
18809 #endif
18810                                    &inp->inp_route6,
18811                                    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
18812                                    NULL, NULL, inp);
18813
18814                 if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
18815                         mtu = inp->inp_route6.ro_nh->nh_mtu;
18816         }
18817 #endif                          /* INET6 */
18818 #if defined(INET) && defined(INET6)
18819         else
18820 #endif
18821 #ifdef INET
18822         {
18823                 ip->ip_len = htons(m->m_pkthdr.len);
18824 #ifdef INET6
18825                 if (inp->inp_vflag & INP_IPV6PROTO)
18826                         ip->ip_ttl = in6_selecthlim(inp, NULL);
18827 #endif                          /* INET6 */
18828                 rack->r_ctl.fsb.hoplimit = ip->ip_ttl;
18829                 /*
18830                  * If we do path MTU discovery, then we set DF on every
18831                  * packet. This might not be the best thing to do according
18832                  * to RFC3390 Section 2. However the tcp hostcache migitates
18833                  * the problem so it affects only the first tcp connection
18834                  * with a host.
18835                  *
18836                  * NB: Don't set DF on small MTU/MSS to have a safe
18837                  * fallback.
18838                  */
18839                 if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
18840                         tp->t_flags2 |= TF2_PLPMTU_PMTUD;
18841                         if (tp->t_port == 0 || len < V_tcp_minmss) {
18842                                 ip->ip_off |= htons(IP_DF);
18843                         }
18844                 } else {
18845                         tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
18846                 }
18847
18848                 if (tp->t_state == TCPS_SYN_SENT)
18849                         TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
18850
18851                 TCP_PROBE5(send, NULL, tp, ip, tp, th);
18852
18853                 error = ip_output(m,
18854 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
18855                                   inp->inp_options,
18856 #else
18857                                   NULL,
18858 #endif
18859                                   &inp->inp_route,
18860                                   ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
18861                                   inp);
18862                 if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
18863                         mtu = inp->inp_route.ro_nh->nh_mtu;
18864         }
18865 #endif                          /* INET */
18866
18867 out:
18868         if (lgb) {
18869                 lgb->tlb_errno = error;
18870                 lgb = NULL;
18871         }
18872         /*
18873          * In transmit state, time the transmission and arrange for the
18874          * retransmit.  In persist state, just set snd_max.
18875          */
18876         if (error == 0) {
18877                 tcp_account_for_send(tp, len, (rsm != NULL), doing_tlp, hw_tls);
18878                 if (rsm && doing_tlp) {
18879                         rack->rc_last_sent_tlp_past_cumack = 0;
18880                         rack->rc_last_sent_tlp_seq_valid = 1;
18881                         rack->r_ctl.last_sent_tlp_seq = rsm->r_start;
18882                         rack->r_ctl.last_sent_tlp_len = rsm->r_end - rsm->r_start;
18883                 }
18884                 rack->forced_ack = 0;   /* If we send something zap the FA flag */
18885                 if (rsm && (doing_tlp == 0)) {
18886                         /* Set we retransmitted */
18887                         rack->rc_gp_saw_rec = 1;
18888                 } else {
18889                         if (cwnd_to_use > tp->snd_ssthresh) {
18890                                 /* Set we sent in CA */
18891                                 rack->rc_gp_saw_ca = 1;
18892                         } else {
18893                                 /* Set we sent in SS */
18894                                 rack->rc_gp_saw_ss = 1;
18895                         }
18896                 }
18897                 if (TCPS_HAVEESTABLISHED(tp->t_state) &&
18898                     (tp->t_flags & TF_SACK_PERMIT) &&
18899                     tp->rcv_numsacks > 0)
18900                         tcp_clean_dsack_blocks(tp);
18901                 tot_len_this_send += len;
18902                 if (len == 0)
18903                         counter_u64_add(rack_out_size[TCP_MSS_ACCT_SNDACK], 1);
18904                 else if (len == 1) {
18905                         counter_u64_add(rack_out_size[TCP_MSS_ACCT_PERSIST], 1);
18906                 } else if (len > 1) {
18907                         int idx;
18908
18909                         idx = (len / segsiz) + 3;
18910                         if (idx >= TCP_MSS_ACCT_ATIMER)
18911                                 counter_u64_add(rack_out_size[(TCP_MSS_ACCT_ATIMER-1)], 1);
18912                         else
18913                                 counter_u64_add(rack_out_size[idx], 1);
18914                 }
18915         }
18916         if ((rack->rack_no_prr == 0) &&
18917             sub_from_prr &&
18918             (error == 0)) {
18919                 if (rack->r_ctl.rc_prr_sndcnt >= len)
18920                         rack->r_ctl.rc_prr_sndcnt -= len;
18921                 else
18922                         rack->r_ctl.rc_prr_sndcnt = 0;
18923         }
18924         sub_from_prr = 0;
18925         if (doing_tlp) {
18926                 /* Make sure the TLP is added */
18927                 add_flag |= RACK_TLP;
18928         } else if (rsm) {
18929                 /* If its a resend without TLP then it must not have the flag */
18930                 rsm->r_flags &= ~RACK_TLP;
18931         }
18932         rack_log_output(tp, &to, len, rack_seq, (uint8_t) flags, error,
18933                         rack_to_usec_ts(&tv),
18934                         rsm, add_flag, s_mb, s_moff, hw_tls);
18935
18936
18937         if ((error == 0) &&
18938             (len > 0) &&
18939             (tp->snd_una == tp->snd_max))
18940                 rack->r_ctl.rc_tlp_rxt_last_time = cts;
18941         {
18942                 tcp_seq startseq = tp->snd_nxt;
18943
18944                 /* Track our lost count */
18945                 if (rsm && (doing_tlp == 0))
18946                         rack->r_ctl.rc_loss_count += rsm->r_end - rsm->r_start;
18947                 /*
18948                  * Advance snd_nxt over sequence space of this segment.
18949                  */
18950                 if (error)
18951                         /* We don't log or do anything with errors */
18952                         goto nomore;
18953                 if (doing_tlp == 0) {
18954                         if (rsm == NULL) {
18955                                 /*
18956                                  * Not a retransmission of some
18957                                  * sort, new data is going out so
18958                                  * clear our TLP count and flag.
18959                                  */
18960                                 rack->rc_tlp_in_progress = 0;
18961                                 rack->r_ctl.rc_tlp_cnt_out = 0;
18962                         }
18963                 } else {
18964                         /*
18965                          * We have just sent a TLP, mark that it is true
18966                          * and make sure our in progress is set so we
18967                          * continue to check the count.
18968                          */
18969                         rack->rc_tlp_in_progress = 1;
18970                         rack->r_ctl.rc_tlp_cnt_out++;
18971                 }
18972                 if (flags & (TH_SYN | TH_FIN)) {
18973                         if (flags & TH_SYN)
18974                                 tp->snd_nxt++;
18975                         if (flags & TH_FIN) {
18976                                 tp->snd_nxt++;
18977                                 tp->t_flags |= TF_SENTFIN;
18978                         }
18979                 }
18980                 /* In the ENOBUFS case we do *not* update snd_max */
18981                 if (sack_rxmit)
18982                         goto nomore;
18983
18984                 tp->snd_nxt += len;
18985                 if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
18986                         if (tp->snd_una == tp->snd_max) {
18987                                 /*
18988                                  * Update the time we just added data since
18989                                  * none was outstanding.
18990                                  */
18991                                 rack_log_progress_event(rack, tp, ticks, PROGRESS_START, __LINE__);
18992                                 tp->t_acktime = ticks;
18993                         }
18994                         tp->snd_max = tp->snd_nxt;
18995                         /*
18996                          * Time this transmission if not a retransmission and
18997                          * not currently timing anything.
18998                          * This is only relevant in case of switching back to
18999                          * the base stack.
19000                          */
19001                         if (tp->t_rtttime == 0) {
19002                                 tp->t_rtttime = ticks;
19003                                 tp->t_rtseq = startseq;
19004                                 KMOD_TCPSTAT_INC(tcps_segstimed);
19005                         }
19006                         if (len &&
19007                             ((tp->t_flags & TF_GPUTINPROG) == 0))
19008                                 rack_start_gp_measurement(tp, rack, startseq, sb_offset);
19009                 }
19010                 /*
19011                  * If we are doing FO we need to update the mbuf position and subtract
19012                  * this happens when the peer sends us duplicate information and
19013                  * we thus want to send a DSACK.
19014                  *
19015                  * XXXRRS: This brings to mind a ?, when we send a DSACK block is TSO
19016                  * turned off? If not then we are going to echo multiple DSACK blocks
19017                  * out (with the TSO), which we should not be doing.
19018                  */
19019                 if (rack->r_fast_output && len) {
19020                         if (rack->r_ctl.fsb.left_to_send > len)
19021                                 rack->r_ctl.fsb.left_to_send -= len;
19022                         else
19023                                 rack->r_ctl.fsb.left_to_send = 0;
19024                         if (rack->r_ctl.fsb.left_to_send < segsiz)
19025                                 rack->r_fast_output = 0;
19026                         if (rack->r_fast_output) {
19027                                 rack->r_ctl.fsb.m = sbsndmbuf(sb, (tp->snd_max - tp->snd_una), &rack->r_ctl.fsb.off);
19028                                 rack->r_ctl.fsb.o_m_len = rack->r_ctl.fsb.m->m_len;
19029                         }
19030                 }
19031         }
19032 nomore:
19033         if (error) {
19034                 rack->r_ctl.rc_agg_delayed = 0;
19035                 rack->r_early = 0;
19036                 rack->r_late = 0;
19037                 rack->r_ctl.rc_agg_early = 0;
19038                 SOCKBUF_UNLOCK_ASSERT(sb);      /* Check gotos. */
19039                 /*
19040                  * Failures do not advance the seq counter above. For the
19041                  * case of ENOBUFS we will fall out and retry in 1ms with
19042                  * the hpts. Everything else will just have to retransmit
19043                  * with the timer.
19044                  *
19045                  * In any case, we do not want to loop around for another
19046                  * send without a good reason.
19047                  */
19048                 sendalot = 0;
19049                 switch (error) {
19050                 case EPERM:
19051                         tp->t_softerror = error;
19052 #ifdef TCP_ACCOUNTING
19053                         crtsc = get_cyclecount();
19054                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
19055                                 tp->tcp_cnt_counters[SND_OUT_FAIL]++;
19056                         }
19057                         counter_u64_add(tcp_cnt_counters[SND_OUT_FAIL], 1);
19058                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
19059                                 tp->tcp_proc_time[SND_OUT_FAIL] += (crtsc - ts_val);
19060                         }
19061                         counter_u64_add(tcp_proc_time[SND_OUT_FAIL], (crtsc - ts_val));
19062                         sched_unpin();
19063 #endif
19064                         return (error);
19065                 case ENOBUFS:
19066                         /*
19067                          * Pace us right away to retry in a some
19068                          * time
19069                          */
19070                         if (rack->r_ctl.crte != NULL) {
19071                                 rack_trace_point(rack, RACK_TP_HWENOBUF);
19072                         } else
19073                                 rack_trace_point(rack, RACK_TP_ENOBUF);
19074                         slot = ((1 + rack->rc_enobuf) * HPTS_USEC_IN_MSEC);
19075                         if (rack->rc_enobuf < 0x7f)
19076                                 rack->rc_enobuf++;
19077                         if (slot < (10 * HPTS_USEC_IN_MSEC))
19078                                 slot = 10 * HPTS_USEC_IN_MSEC;
19079                         if (rack->r_ctl.crte != NULL) {
19080                                 counter_u64_add(rack_saw_enobuf_hw, 1);
19081                                 tcp_rl_log_enobuf(rack->r_ctl.crte);
19082                         }
19083                         counter_u64_add(rack_saw_enobuf, 1);
19084                         goto enobufs;
19085                 case EMSGSIZE:
19086                         /*
19087                          * For some reason the interface we used initially
19088                          * to send segments changed to another or lowered
19089                          * its MTU. If TSO was active we either got an
19090                          * interface without TSO capabilits or TSO was
19091                          * turned off. If we obtained mtu from ip_output()
19092                          * then update it and try again.
19093                          */
19094                         if (tso)
19095                                 tp->t_flags &= ~TF_TSO;
19096                         if (mtu != 0) {
19097                                 tcp_mss_update(tp, -1, mtu, NULL, NULL);
19098                                 goto again;
19099                         }
19100                         slot = 10 * HPTS_USEC_IN_MSEC;
19101                         rack_start_hpts_timer(rack, tp, cts, slot, 0, 0);
19102 #ifdef TCP_ACCOUNTING
19103                         crtsc = get_cyclecount();
19104                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
19105                                 tp->tcp_cnt_counters[SND_OUT_FAIL]++;
19106                         }
19107                         counter_u64_add(tcp_cnt_counters[SND_OUT_FAIL], 1);
19108                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
19109                                 tp->tcp_proc_time[SND_OUT_FAIL] += (crtsc - ts_val);
19110                         }
19111                         counter_u64_add(tcp_proc_time[SND_OUT_FAIL], (crtsc - ts_val));
19112                         sched_unpin();
19113 #endif
19114                         return (error);
19115                 case ENETUNREACH:
19116                         counter_u64_add(rack_saw_enetunreach, 1);
19117                 case EHOSTDOWN:
19118                 case EHOSTUNREACH:
19119                 case ENETDOWN:
19120                         if (TCPS_HAVERCVDSYN(tp->t_state)) {
19121                                 tp->t_softerror = error;
19122                         }
19123                         /* FALLTHROUGH */
19124                 default:
19125                         slot = 10 * HPTS_USEC_IN_MSEC;
19126                         rack_start_hpts_timer(rack, tp, cts, slot, 0, 0);
19127 #ifdef TCP_ACCOUNTING
19128                         crtsc = get_cyclecount();
19129                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
19130                                 tp->tcp_cnt_counters[SND_OUT_FAIL]++;
19131                         }
19132                         counter_u64_add(tcp_cnt_counters[SND_OUT_FAIL], 1);
19133                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
19134                                 tp->tcp_proc_time[SND_OUT_FAIL] += (crtsc - ts_val);
19135                         }
19136                         counter_u64_add(tcp_proc_time[SND_OUT_FAIL], (crtsc - ts_val));
19137                         sched_unpin();
19138 #endif
19139                         return (error);
19140                 }
19141         } else {
19142                 rack->rc_enobuf = 0;
19143                 if (IN_FASTRECOVERY(tp->t_flags) && rsm)
19144                         rack->r_ctl.retran_during_recovery += len;
19145         }
19146         KMOD_TCPSTAT_INC(tcps_sndtotal);
19147
19148         /*
19149          * Data sent (as far as we can tell). If this advertises a larger
19150          * window than any other segment, then remember the size of the
19151          * advertised window. Any pending ACK has now been sent.
19152          */
19153         if (recwin > 0 && SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
19154                 tp->rcv_adv = tp->rcv_nxt + recwin;
19155
19156         tp->last_ack_sent = tp->rcv_nxt;
19157         tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
19158 enobufs:
19159         if (sendalot) {
19160                 /* Do we need to turn off sendalot? */
19161                 if (rack->r_ctl.rc_pace_max_segs &&
19162                     (tot_len_this_send >= rack->r_ctl.rc_pace_max_segs)) {
19163                         /* We hit our max. */
19164                         sendalot = 0;
19165                 } else if ((rack->rc_user_set_max_segs) &&
19166                            (tot_len_this_send >= (rack->rc_user_set_max_segs * segsiz))) {
19167                         /* We hit the user defined max */
19168                         sendalot = 0;
19169                 }
19170         }
19171         if ((error == 0) && (flags & TH_FIN))
19172                 tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
19173         if (flags & TH_RST) {
19174                 /*
19175                  * We don't send again after sending a RST.
19176                  */
19177                 slot = 0;
19178                 sendalot = 0;
19179                 if (error == 0)
19180                         tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
19181         } else if ((slot == 0) && (sendalot == 0) && tot_len_this_send) {
19182                 /*
19183                  * Get our pacing rate, if an error
19184                  * occurred in sending (ENOBUF) we would
19185                  * hit the else if with slot preset. Other
19186                  * errors return.
19187                  */
19188                 slot = rack_get_pacing_delay(rack, tp, tot_len_this_send, rsm, segsiz);
19189         }
19190         if (rsm &&
19191             (rsm->r_flags & RACK_HAS_SYN) == 0 &&
19192             rack->use_rack_rr) {
19193                 /* Its a retransmit and we use the rack cheat? */
19194                 if ((slot == 0) ||
19195                     (rack->rc_always_pace == 0) ||
19196                     (rack->r_rr_config == 1)) {
19197                         /*
19198                          * We have no pacing set or we
19199                          * are using old-style rack or
19200                          * we are overridden to use the old 1ms pacing.
19201                          */
19202                         slot = rack->r_ctl.rc_min_to;
19203                 }
19204         }
19205         /* We have sent clear the flag */
19206         rack->r_ent_rec_ns = 0;
19207         if (rack->r_must_retran) {
19208                 if (rsm) {
19209                         rack->r_ctl.rc_out_at_rto -= (rsm->r_end - rsm->r_start);
19210                         if (SEQ_GEQ(rsm->r_end, rack->r_ctl.rc_snd_max_at_rto)) {
19211                                 /*
19212                                  * We have retransmitted all.
19213                                  */
19214                                 rack->r_must_retran = 0;
19215                                 rack->r_ctl.rc_out_at_rto = 0;
19216                         }
19217                 } else if (SEQ_GEQ(tp->snd_max, rack->r_ctl.rc_snd_max_at_rto)) {
19218                         /*
19219                          * Sending new data will also kill
19220                          * the loop.
19221                          */
19222                         rack->r_must_retran = 0;
19223                         rack->r_ctl.rc_out_at_rto = 0;
19224                 }
19225         }
19226         rack->r_ctl.fsb.recwin = recwin;
19227         if ((tp->t_flags & (TF_WASCRECOVERY|TF_WASFRECOVERY)) &&
19228             SEQ_GT(tp->snd_max, rack->r_ctl.rc_snd_max_at_rto)) {
19229                 /*
19230                  * We hit an RTO and now have past snd_max at the RTO
19231                  * clear all the WAS flags.
19232                  */
19233                 tp->t_flags &= ~(TF_WASCRECOVERY|TF_WASFRECOVERY);
19234         }
19235         if (slot) {
19236                 /* set the rack tcb into the slot N */
19237                 if ((error == 0) &&
19238                     rack_use_rfo &&
19239                     ((flags & (TH_SYN|TH_FIN)) == 0) &&
19240                     (rsm == NULL) &&
19241                     (tp->snd_nxt == tp->snd_max) &&
19242                     (ipoptlen == 0) &&
19243                     (tp->rcv_numsacks == 0) &&
19244                     rack->r_fsb_inited &&
19245                     TCPS_HAVEESTABLISHED(tp->t_state) &&
19246                     (rack->r_must_retran == 0) &&
19247                     ((tp->t_flags & TF_NEEDFIN) == 0) &&
19248                     (len > 0) && (orig_len > 0) &&
19249                     (orig_len > len) &&
19250                     ((orig_len - len) >= segsiz) &&
19251                     ((optlen == 0) ||
19252                      ((optlen == TCPOLEN_TSTAMP_APPA) && (to.to_flags & TOF_TS)))) {
19253                         /* We can send at least one more MSS using our fsb */
19254
19255                         rack->r_fast_output = 1;
19256                         rack->r_ctl.fsb.m = sbsndmbuf(sb, (tp->snd_max - tp->snd_una), &rack->r_ctl.fsb.off);
19257                         rack->r_ctl.fsb.o_m_len = rack->r_ctl.fsb.m->m_len;
19258                         rack->r_ctl.fsb.tcp_flags = flags;
19259                         rack->r_ctl.fsb.left_to_send = orig_len - len;
19260                         if (hw_tls)
19261                                 rack->r_ctl.fsb.hw_tls = 1;
19262                         else
19263                                 rack->r_ctl.fsb.hw_tls = 0;
19264                         KASSERT((rack->r_ctl.fsb.left_to_send <= (sbavail(sb) - (tp->snd_max - tp->snd_una))),
19265                                 ("rack:%p left_to_send:%u sbavail:%u out:%u",
19266                                  rack, rack->r_ctl.fsb.left_to_send, sbavail(sb),
19267                                  (tp->snd_max - tp->snd_una)));
19268                         if (rack->r_ctl.fsb.left_to_send < segsiz)
19269                                 rack->r_fast_output = 0;
19270                         else {
19271                                 if (rack->r_ctl.fsb.left_to_send == (sbavail(sb) - (tp->snd_max - tp->snd_una)))
19272                                         rack->r_ctl.fsb.rfo_apply_push = 1;
19273                                 else
19274                                         rack->r_ctl.fsb.rfo_apply_push = 0;
19275                         }
19276                 } else
19277                         rack->r_fast_output = 0;
19278                 rack_log_fsb(rack, tp, so, flags,
19279                              ipoptlen, orig_len, len, error,
19280                              (rsm == NULL), optlen, __LINE__, 2);
19281         } else if (sendalot) {
19282                 int ret;
19283
19284                 sack_rxmit = 0;
19285                 if ((error == 0) &&
19286                     rack_use_rfo &&
19287                     ((flags & (TH_SYN|TH_FIN)) == 0) &&
19288                     (rsm == NULL) &&
19289                     (ipoptlen == 0) &&
19290                     (tp->rcv_numsacks == 0) &&
19291                     (tp->snd_nxt == tp->snd_max) &&
19292                     (rack->r_must_retran == 0) &&
19293                     rack->r_fsb_inited &&
19294                     TCPS_HAVEESTABLISHED(tp->t_state) &&
19295                     ((tp->t_flags & TF_NEEDFIN) == 0) &&
19296                     (len > 0) && (orig_len > 0) &&
19297                     (orig_len > len) &&
19298                     ((orig_len - len) >= segsiz) &&
19299                     ((optlen == 0) ||
19300                      ((optlen == TCPOLEN_TSTAMP_APPA) && (to.to_flags & TOF_TS)))) {
19301                         /* we can use fast_output for more */
19302
19303                         rack->r_fast_output = 1;
19304                         rack->r_ctl.fsb.m = sbsndmbuf(sb, (tp->snd_max - tp->snd_una), &rack->r_ctl.fsb.off);
19305                         rack->r_ctl.fsb.o_m_len = rack->r_ctl.fsb.m->m_len;
19306                         rack->r_ctl.fsb.tcp_flags = flags;
19307                         rack->r_ctl.fsb.left_to_send = orig_len - len;
19308                         if (hw_tls)
19309                                 rack->r_ctl.fsb.hw_tls = 1;
19310                         else
19311                                 rack->r_ctl.fsb.hw_tls = 0;
19312                         KASSERT((rack->r_ctl.fsb.left_to_send <= (sbavail(sb) - (tp->snd_max - tp->snd_una))),
19313                                 ("rack:%p left_to_send:%u sbavail:%u out:%u",
19314                                  rack, rack->r_ctl.fsb.left_to_send, sbavail(sb),
19315                                  (tp->snd_max - tp->snd_una)));
19316                         if (rack->r_ctl.fsb.left_to_send < segsiz) {
19317                                 rack->r_fast_output = 0;
19318                         }
19319                         if (rack->r_fast_output) {
19320                                 if (rack->r_ctl.fsb.left_to_send == (sbavail(sb) - (tp->snd_max - tp->snd_una)))
19321                                         rack->r_ctl.fsb.rfo_apply_push = 1;
19322                                 else
19323                                         rack->r_ctl.fsb.rfo_apply_push = 0;
19324                                 rack_log_fsb(rack, tp, so, flags,
19325                                              ipoptlen, orig_len, len, error,
19326                                              (rsm == NULL), optlen, __LINE__, 3);
19327                                 error = 0;
19328                                 ret = rack_fast_output(tp, rack, ts_val, cts, ms_cts, &tv, tot_len_this_send, &error);
19329                                 if (ret >= 0)
19330                                         return (ret);
19331                                 else if (error)
19332                                         goto nomore;
19333
19334                         }
19335                 }
19336                 goto again;
19337         }
19338         /* Assure when we leave that snd_nxt will point to top */
19339         if (SEQ_GT(tp->snd_max, tp->snd_nxt))
19340                 tp->snd_nxt = tp->snd_max;
19341         rack_start_hpts_timer(rack, tp, cts, slot, tot_len_this_send, 0);
19342 #ifdef TCP_ACCOUNTING
19343         crtsc = get_cyclecount() - ts_val;
19344         if (tot_len_this_send) {
19345                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
19346                         tp->tcp_cnt_counters[SND_OUT_DATA]++;
19347                 }
19348                 counter_u64_add(tcp_cnt_counters[SND_OUT_DATA], 1);
19349                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
19350                         tp->tcp_proc_time[SND_OUT_DATA] += crtsc;
19351                 }
19352                 counter_u64_add(tcp_proc_time[SND_OUT_DATA], crtsc);
19353                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
19354                         tp->tcp_cnt_counters[CNT_OF_MSS_OUT] += ((tot_len_this_send + segsiz - 1) /segsiz);
19355                 }
19356                 counter_u64_add(tcp_cnt_counters[CNT_OF_MSS_OUT], ((tot_len_this_send + segsiz - 1) /segsiz));
19357         } else {
19358                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
19359                         tp->tcp_cnt_counters[SND_OUT_ACK]++;
19360                 }
19361                 counter_u64_add(tcp_cnt_counters[SND_OUT_ACK], 1);
19362                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
19363                         tp->tcp_proc_time[SND_OUT_ACK] += crtsc;
19364                 }
19365                 counter_u64_add(tcp_proc_time[SND_OUT_ACK], crtsc);
19366         }
19367         sched_unpin();
19368 #endif
19369         if (error == ENOBUFS)
19370                 error = 0;
19371         return (error);
19372 }
19373
19374 static void
19375 rack_update_seg(struct tcp_rack *rack)
19376 {
19377         uint32_t orig_val;
19378
19379         orig_val = rack->r_ctl.rc_pace_max_segs;
19380         rack_set_pace_segments(rack->rc_tp, rack, __LINE__, NULL);
19381         if (orig_val != rack->r_ctl.rc_pace_max_segs)
19382                 rack_log_pacing_delay_calc(rack, 0, 0, orig_val, 0, 0, 15, __LINE__, NULL, 0);
19383 }
19384
19385 static void
19386 rack_mtu_change(struct tcpcb *tp)
19387 {
19388         /*
19389          * The MSS may have changed
19390          */
19391         struct tcp_rack *rack;
19392         struct rack_sendmap *rsm;
19393
19394         rack = (struct tcp_rack *)tp->t_fb_ptr;
19395         if (rack->r_ctl.rc_pace_min_segs != ctf_fixed_maxseg(tp)) {
19396                 /*
19397                  * The MTU has changed we need to resend everything
19398                  * since all we have sent is lost. We first fix
19399                  * up the mtu though.
19400                  */
19401                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
19402                 /* We treat this like a full retransmit timeout without the cwnd adjustment */
19403                 rack_remxt_tmr(tp);
19404                 rack->r_fast_output = 0;
19405                 rack->r_ctl.rc_out_at_rto = ctf_flight_size(tp,
19406                                                 rack->r_ctl.rc_sacked);
19407                 rack->r_ctl.rc_snd_max_at_rto = tp->snd_max;
19408                 rack->r_must_retran = 1;
19409                 /* Mark all inflight to needing to be rxt'd */
19410                 TAILQ_FOREACH(rsm, &rack->r_ctl.rc_tmap, r_tnext) {
19411                         rsm->r_flags |= RACK_MUST_RXT;
19412                 }
19413         }
19414         sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
19415         /* We don't use snd_nxt to retransmit */
19416         tp->snd_nxt = tp->snd_max;
19417 }
19418
19419 static int
19420 rack_set_profile(struct tcp_rack *rack, int prof)
19421 {
19422         int err = EINVAL;
19423         if (prof == 1) {
19424                 /* pace_always=1 */
19425                 if (rack->rc_always_pace == 0) {
19426                         if (tcp_can_enable_pacing() == 0)
19427                                 return (EBUSY);
19428                 }
19429                 rack->rc_always_pace = 1;
19430                 if (rack->use_fixed_rate || rack->gp_ready)
19431                         rack_set_cc_pacing(rack);
19432                 rack->rc_inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
19433                 rack->rack_attempt_hdwr_pace = 0;
19434                 /* cmpack=1 */
19435                 if (rack_use_cmp_acks)
19436                         rack->r_use_cmp_ack = 1;
19437                 if (TCPS_HAVEESTABLISHED(rack->rc_tp->t_state) &&
19438                     rack->r_use_cmp_ack)
19439                         rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
19440                 /* scwnd=1 */
19441                 rack->rack_enable_scwnd = 1;
19442                 /* dynamic=100 */
19443                 rack->rc_gp_dyn_mul = 1;
19444                 /* gp_inc_ca */
19445                 rack->r_ctl.rack_per_of_gp_ca = 100;
19446                 /* rrr_conf=3 */
19447                 rack->r_rr_config = 3;
19448                 /* npush=2 */
19449                 rack->r_ctl.rc_no_push_at_mrtt = 2;
19450                 /* fillcw=1 */
19451                 rack->rc_pace_to_cwnd = 1;
19452                 rack->rc_pace_fill_if_rttin_range = 0;
19453                 rack->rtt_limit_mul = 0;
19454                 /* noprr=1 */
19455                 rack->rack_no_prr = 1;
19456                 /* lscwnd=1 */
19457                 rack->r_limit_scw = 1;
19458                 /* gp_inc_rec */
19459                 rack->r_ctl.rack_per_of_gp_rec = 90;
19460                 err = 0;
19461
19462         } else if (prof == 3) {
19463                 /* Same as profile one execept fill_cw becomes 2 (less aggressive set) */
19464                 /* pace_always=1 */
19465                 if (rack->rc_always_pace == 0) {
19466                         if (tcp_can_enable_pacing() == 0)
19467                                 return (EBUSY);
19468                 }
19469                 rack->rc_always_pace = 1;
19470                 if (rack->use_fixed_rate || rack->gp_ready)
19471                         rack_set_cc_pacing(rack);
19472                 rack->rc_inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
19473                 rack->rack_attempt_hdwr_pace = 0;
19474                 /* cmpack=1 */
19475                 if (rack_use_cmp_acks)
19476                         rack->r_use_cmp_ack = 1;
19477                 if (TCPS_HAVEESTABLISHED(rack->rc_tp->t_state) &&
19478                     rack->r_use_cmp_ack)
19479                         rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
19480                 /* scwnd=1 */
19481                 rack->rack_enable_scwnd = 1;
19482                 /* dynamic=100 */
19483                 rack->rc_gp_dyn_mul = 1;
19484                 /* gp_inc_ca */
19485                 rack->r_ctl.rack_per_of_gp_ca = 100;
19486                 /* rrr_conf=3 */
19487                 rack->r_rr_config = 3;
19488                 /* npush=2 */
19489                 rack->r_ctl.rc_no_push_at_mrtt = 2;
19490                 /* fillcw=2 */
19491                 rack->rc_pace_to_cwnd = 1;
19492                 rack->r_fill_less_agg = 1;
19493                 rack->rc_pace_fill_if_rttin_range = 0;
19494                 rack->rtt_limit_mul = 0;
19495                 /* noprr=1 */
19496                 rack->rack_no_prr = 1;
19497                 /* lscwnd=1 */
19498                 rack->r_limit_scw = 1;
19499                 /* gp_inc_rec */
19500                 rack->r_ctl.rack_per_of_gp_rec = 90;
19501                 err = 0;
19502
19503
19504         } else if (prof == 2) {
19505                 /* cmpack=1 */
19506                 if (rack->rc_always_pace == 0) {
19507                         if (tcp_can_enable_pacing() == 0)
19508                                 return (EBUSY);
19509                 }
19510                 rack->rc_always_pace = 1;
19511                 if (rack->use_fixed_rate || rack->gp_ready)
19512                         rack_set_cc_pacing(rack);
19513                 rack->r_use_cmp_ack = 1;
19514                 if (TCPS_HAVEESTABLISHED(rack->rc_tp->t_state))
19515                         rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
19516                 /* pace_always=1 */
19517                 rack->rc_inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
19518                 /* scwnd=1 */
19519                 rack->rack_enable_scwnd = 1;
19520                 /* dynamic=100 */
19521                 rack->rc_gp_dyn_mul = 1;
19522                 rack->r_ctl.rack_per_of_gp_ca = 100;
19523                 /* rrr_conf=3 */
19524                 rack->r_rr_config = 3;
19525                 /* npush=2 */
19526                 rack->r_ctl.rc_no_push_at_mrtt = 2;
19527                 /* fillcw=1 */
19528                 rack->rc_pace_to_cwnd = 1;
19529                 rack->rc_pace_fill_if_rttin_range = 0;
19530                 rack->rtt_limit_mul = 0;
19531                 /* noprr=1 */
19532                 rack->rack_no_prr = 1;
19533                 /* lscwnd=0 */
19534                 rack->r_limit_scw = 0;
19535                 err = 0;
19536         } else if (prof == 0) {
19537                 /* This changes things back to the default settings */
19538                 err = 0;
19539                 if (rack->rc_always_pace) {
19540                         tcp_decrement_paced_conn();
19541                         rack_undo_cc_pacing(rack);
19542                         rack->rc_always_pace = 0;
19543                 }
19544                 if (rack_pace_every_seg && tcp_can_enable_pacing()) {
19545                         rack->rc_always_pace = 1;
19546                         if (rack->use_fixed_rate || rack->gp_ready)
19547                                 rack_set_cc_pacing(rack);
19548                 } else
19549                         rack->rc_always_pace = 0;
19550                 if (rack_dsack_std_based & 0x1) {
19551                         /* Basically this means all rack timers are at least (srtt + 1/4 srtt) */
19552                         rack->rc_rack_tmr_std_based = 1;
19553                 }
19554                 if (rack_dsack_std_based & 0x2) {
19555                         /* Basically this means  rack timers are extended based on dsack by up to (2 * srtt) */
19556                         rack->rc_rack_use_dsack = 1;
19557                 }
19558                 if (rack_use_cmp_acks)
19559                         rack->r_use_cmp_ack = 1;
19560                 else
19561                         rack->r_use_cmp_ack = 0;
19562                 if (rack_disable_prr)
19563                         rack->rack_no_prr = 1;
19564                 else
19565                         rack->rack_no_prr = 0;
19566                 if (rack_gp_no_rec_chg)
19567                         rack->rc_gp_no_rec_chg = 1;
19568                 else
19569                         rack->rc_gp_no_rec_chg = 0;
19570                 if (rack_enable_mqueue_for_nonpaced || rack->r_use_cmp_ack) {
19571                         rack->r_mbuf_queue = 1;
19572                         if (TCPS_HAVEESTABLISHED(rack->rc_tp->t_state))
19573                                 rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
19574                         rack->rc_inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
19575                 } else {
19576                         rack->r_mbuf_queue = 0;
19577                         rack->rc_inp->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
19578                 }
19579                 if (rack_enable_shared_cwnd)
19580                         rack->rack_enable_scwnd = 1;
19581                 else
19582                         rack->rack_enable_scwnd = 0;
19583                 if (rack_do_dyn_mul) {
19584                         /* When dynamic adjustment is on CA needs to start at 100% */
19585                         rack->rc_gp_dyn_mul = 1;
19586                         if (rack_do_dyn_mul >= 100)
19587                                 rack->r_ctl.rack_per_of_gp_ca = rack_do_dyn_mul;
19588                 } else {
19589                         rack->r_ctl.rack_per_of_gp_ca = rack_per_of_gp_ca;
19590                         rack->rc_gp_dyn_mul = 0;
19591                 }
19592                 rack->r_rr_config = 0;
19593                 rack->r_ctl.rc_no_push_at_mrtt = 0;
19594                 rack->rc_pace_to_cwnd = 0;
19595                 rack->rc_pace_fill_if_rttin_range = 0;
19596                 rack->rtt_limit_mul = 0;
19597
19598                 if (rack_enable_hw_pacing)
19599                         rack->rack_hdw_pace_ena = 1;
19600                 else
19601                         rack->rack_hdw_pace_ena = 0;
19602                 if (rack_disable_prr)
19603                         rack->rack_no_prr = 1;
19604                 else
19605                         rack->rack_no_prr = 0;
19606                 if (rack_limits_scwnd)
19607                         rack->r_limit_scw  = 1;
19608                 else
19609                         rack->r_limit_scw  = 0;
19610                 err = 0;
19611         }
19612         return (err);
19613 }
19614
19615 static int
19616 rack_add_deferred_option(struct tcp_rack *rack, int sopt_name, uint64_t loptval)
19617 {
19618         struct deferred_opt_list *dol;
19619
19620         dol = malloc(sizeof(struct deferred_opt_list),
19621                      M_TCPFSB, M_NOWAIT|M_ZERO);
19622         if (dol == NULL) {
19623                 /*
19624                  * No space yikes -- fail out..
19625                  */
19626                 return (0);
19627         }
19628         dol->optname = sopt_name;
19629         dol->optval = loptval;
19630         TAILQ_INSERT_TAIL(&rack->r_ctl.opt_list, dol, next);
19631         return (1);
19632 }
19633
19634 static int
19635 rack_process_option(struct tcpcb *tp, struct tcp_rack *rack, int sopt_name,
19636                     uint32_t optval, uint64_t loptval)
19637 {
19638         struct epoch_tracker et;
19639         struct sockopt sopt;
19640         struct cc_newreno_opts opt;
19641         struct inpcb *inp = tptoinpcb(tp);
19642         uint64_t val;
19643         int error = 0;
19644         uint16_t ca, ss;
19645
19646         switch (sopt_name) {
19647
19648         case TCP_RACK_DSACK_OPT:
19649                 RACK_OPTS_INC(tcp_rack_dsack_opt);
19650                 if (optval & 0x1) {
19651                         rack->rc_rack_tmr_std_based = 1;
19652                 } else {
19653                         rack->rc_rack_tmr_std_based = 0;
19654                 }
19655                 if (optval & 0x2) {
19656                         rack->rc_rack_use_dsack = 1;
19657                 } else {
19658                         rack->rc_rack_use_dsack = 0;
19659                 }
19660                 rack_log_dsack_event(rack, 5, __LINE__, 0, 0);
19661                 break;
19662         case TCP_RACK_PACING_BETA:
19663                 RACK_OPTS_INC(tcp_rack_beta);
19664                 if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0) {
19665                         /* This only works for newreno. */
19666                         error = EINVAL;
19667                         break;
19668                 }
19669                 if (rack->rc_pacing_cc_set) {
19670                         /*
19671                          * Set them into the real CC module
19672                          * whats in the rack pcb is the old values
19673                          * to be used on restoral/
19674                          */
19675                         sopt.sopt_dir = SOPT_SET;
19676                         opt.name = CC_NEWRENO_BETA;
19677                         opt.val = optval;
19678                         if (CC_ALGO(tp)->ctl_output != NULL)
19679                                 error = CC_ALGO(tp)->ctl_output(tp->ccv, &sopt, &opt);
19680                         else {
19681                                 error = ENOENT;
19682                                 break;
19683                         }
19684                 } else {
19685                         /*
19686                          * Not pacing yet so set it into our local
19687                          * rack pcb storage.
19688                          */
19689                         rack->r_ctl.rc_saved_beta.beta = optval;
19690                 }
19691                 break;
19692         case TCP_RACK_TIMER_SLOP:
19693                 RACK_OPTS_INC(tcp_rack_timer_slop);
19694                 rack->r_ctl.timer_slop = optval;
19695                 if (rack->rc_tp->t_srtt) {
19696                         /*
19697                          * If we have an SRTT lets update t_rxtcur
19698                          * to have the new slop.
19699                          */
19700                         RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
19701                                            rack_rto_min, rack_rto_max,
19702                                            rack->r_ctl.timer_slop);
19703                 }
19704                 break;
19705         case TCP_RACK_PACING_BETA_ECN:
19706                 RACK_OPTS_INC(tcp_rack_beta_ecn);
19707                 if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0) {
19708                         /* This only works for newreno. */
19709                         error = EINVAL;
19710                         break;
19711                 }
19712                 if (rack->rc_pacing_cc_set) {
19713                         /*
19714                          * Set them into the real CC module
19715                          * whats in the rack pcb is the old values
19716                          * to be used on restoral/
19717                          */
19718                         sopt.sopt_dir = SOPT_SET;
19719                         opt.name = CC_NEWRENO_BETA_ECN;
19720                         opt.val = optval;
19721                         if (CC_ALGO(tp)->ctl_output != NULL)
19722                                 error = CC_ALGO(tp)->ctl_output(tp->ccv, &sopt, &opt);
19723                         else
19724                                 error = ENOENT;
19725                 } else {
19726                         /*
19727                          * Not pacing yet so set it into our local
19728                          * rack pcb storage.
19729                          */
19730                         rack->r_ctl.rc_saved_beta.beta_ecn = optval;
19731                         rack->r_ctl.rc_saved_beta.newreno_flags = CC_NEWRENO_BETA_ECN_ENABLED;
19732                 }
19733                 break;
19734         case TCP_DEFER_OPTIONS:
19735                 RACK_OPTS_INC(tcp_defer_opt);
19736                 if (optval) {
19737                         if (rack->gp_ready) {
19738                                 /* Too late */
19739                                 error = EINVAL;
19740                                 break;
19741                         }
19742                         rack->defer_options = 1;
19743                 } else
19744                         rack->defer_options = 0;
19745                 break;
19746         case TCP_RACK_MEASURE_CNT:
19747                 RACK_OPTS_INC(tcp_rack_measure_cnt);
19748                 if (optval && (optval <= 0xff)) {
19749                         rack->r_ctl.req_measurements = optval;
19750                 } else
19751                         error = EINVAL;
19752                 break;
19753         case TCP_REC_ABC_VAL:
19754                 RACK_OPTS_INC(tcp_rec_abc_val);
19755                 if (optval > 0)
19756                         rack->r_use_labc_for_rec = 1;
19757                 else
19758                         rack->r_use_labc_for_rec = 0;
19759                 break;
19760         case TCP_RACK_ABC_VAL:
19761                 RACK_OPTS_INC(tcp_rack_abc_val);
19762                 if ((optval > 0) && (optval < 255))
19763                         rack->rc_labc = optval;
19764                 else
19765                         error = EINVAL;
19766                 break;
19767         case TCP_HDWR_UP_ONLY:
19768                 RACK_OPTS_INC(tcp_pacing_up_only);
19769                 if (optval)
19770                         rack->r_up_only = 1;
19771                 else
19772                         rack->r_up_only = 0;
19773                 break;
19774         case TCP_PACING_RATE_CAP:
19775                 RACK_OPTS_INC(tcp_pacing_rate_cap);
19776                 rack->r_ctl.bw_rate_cap = loptval;
19777                 break;
19778         case TCP_RACK_PROFILE:
19779                 RACK_OPTS_INC(tcp_profile);
19780                 error = rack_set_profile(rack, optval);
19781                 break;
19782         case TCP_USE_CMP_ACKS:
19783                 RACK_OPTS_INC(tcp_use_cmp_acks);
19784                 if ((optval == 0) && (rack->rc_inp->inp_flags2 & INP_MBUF_ACKCMP)) {
19785                         /* You can't turn it off once its on! */
19786                         error = EINVAL;
19787                 } else if ((optval == 1) && (rack->r_use_cmp_ack == 0)) {
19788                         rack->r_use_cmp_ack = 1;
19789                         rack->r_mbuf_queue = 1;
19790                         inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
19791                 }
19792                 if (rack->r_use_cmp_ack && TCPS_HAVEESTABLISHED(tp->t_state))
19793                         inp->inp_flags2 |= INP_MBUF_ACKCMP;
19794                 break;
19795         case TCP_SHARED_CWND_TIME_LIMIT:
19796                 RACK_OPTS_INC(tcp_lscwnd);
19797                 if (optval)
19798                         rack->r_limit_scw = 1;
19799                 else
19800                         rack->r_limit_scw = 0;
19801                 break;
19802         case TCP_RACK_PACE_TO_FILL:
19803                 RACK_OPTS_INC(tcp_fillcw);
19804                 if (optval == 0)
19805                         rack->rc_pace_to_cwnd = 0;
19806                 else {
19807                         rack->rc_pace_to_cwnd = 1;
19808                         if (optval > 1)
19809                                 rack->r_fill_less_agg = 1;
19810                 }
19811                 if ((optval >= rack_gp_rtt_maxmul) &&
19812                     rack_gp_rtt_maxmul &&
19813                     (optval < 0xf)) {
19814                         rack->rc_pace_fill_if_rttin_range = 1;
19815                         rack->rtt_limit_mul = optval;
19816                 } else {
19817                         rack->rc_pace_fill_if_rttin_range = 0;
19818                         rack->rtt_limit_mul = 0;
19819                 }
19820                 break;
19821         case TCP_RACK_NO_PUSH_AT_MAX:
19822                 RACK_OPTS_INC(tcp_npush);
19823                 if (optval == 0)
19824                         rack->r_ctl.rc_no_push_at_mrtt = 0;
19825                 else if (optval < 0xff)
19826                         rack->r_ctl.rc_no_push_at_mrtt = optval;
19827                 else
19828                         error = EINVAL;
19829                 break;
19830         case TCP_SHARED_CWND_ENABLE:
19831                 RACK_OPTS_INC(tcp_rack_scwnd);
19832                 if (optval == 0)
19833                         rack->rack_enable_scwnd = 0;
19834                 else
19835                         rack->rack_enable_scwnd = 1;
19836                 break;
19837         case TCP_RACK_MBUF_QUEUE:
19838                 /* Now do we use the LRO mbuf-queue feature */
19839                 RACK_OPTS_INC(tcp_rack_mbufq);
19840                 if (optval || rack->r_use_cmp_ack)
19841                         rack->r_mbuf_queue = 1;
19842                 else
19843                         rack->r_mbuf_queue = 0;
19844                 if  (rack->r_mbuf_queue || rack->rc_always_pace || rack->r_use_cmp_ack)
19845                         inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
19846                 else
19847                         inp->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
19848                 break;
19849         case TCP_RACK_NONRXT_CFG_RATE:
19850                 RACK_OPTS_INC(tcp_rack_cfg_rate);
19851                 if (optval == 0)
19852                         rack->rack_rec_nonrxt_use_cr = 0;
19853                 else
19854                         rack->rack_rec_nonrxt_use_cr = 1;
19855                 break;
19856         case TCP_NO_PRR:
19857                 RACK_OPTS_INC(tcp_rack_noprr);
19858                 if (optval == 0)
19859                         rack->rack_no_prr = 0;
19860                 else if (optval == 1)
19861                         rack->rack_no_prr = 1;
19862                 else if (optval == 2)
19863                         rack->no_prr_addback = 1;
19864                 else
19865                         error = EINVAL;
19866                 break;
19867         case TCP_TIMELY_DYN_ADJ:
19868                 RACK_OPTS_INC(tcp_timely_dyn);
19869                 if (optval == 0)
19870                         rack->rc_gp_dyn_mul = 0;
19871                 else {
19872                         rack->rc_gp_dyn_mul = 1;
19873                         if (optval >= 100) {
19874                                 /*
19875                                  * If the user sets something 100 or more
19876                                  * its the gp_ca value.
19877                                  */
19878                                 rack->r_ctl.rack_per_of_gp_ca  = optval;
19879                         }
19880                 }
19881                 break;
19882         case TCP_RACK_DO_DETECTION:
19883                 RACK_OPTS_INC(tcp_rack_do_detection);
19884                 if (optval == 0)
19885                         rack->do_detection = 0;
19886                 else
19887                         rack->do_detection = 1;
19888                 break;
19889         case TCP_RACK_TLP_USE:
19890                 if ((optval < TLP_USE_ID) || (optval > TLP_USE_TWO_TWO)) {
19891                         error = EINVAL;
19892                         break;
19893                 }
19894                 RACK_OPTS_INC(tcp_tlp_use);
19895                 rack->rack_tlp_threshold_use = optval;
19896                 break;
19897         case TCP_RACK_TLP_REDUCE:
19898                 /* RACK TLP cwnd reduction (bool) */
19899                 RACK_OPTS_INC(tcp_rack_tlp_reduce);
19900                 rack->r_ctl.rc_tlp_cwnd_reduce = optval;
19901                 break;
19902         /*  Pacing related ones */
19903         case TCP_RACK_PACE_ALWAYS:
19904                 /*
19905                  * zero is old rack method, 1 is new
19906                  * method using a pacing rate.
19907                  */
19908                 RACK_OPTS_INC(tcp_rack_pace_always);
19909                 if (optval > 0) {
19910                         if (rack->rc_always_pace) {
19911                                 error = EALREADY;
19912                                 break;
19913                         } else if (tcp_can_enable_pacing()) {
19914                                 rack->rc_always_pace = 1;
19915                                 if (rack->use_fixed_rate || rack->gp_ready)
19916                                         rack_set_cc_pacing(rack);
19917                         }
19918                         else {
19919                                 error = ENOSPC;
19920                                 break;
19921                         }
19922                 } else {
19923                         if (rack->rc_always_pace) {
19924                                 tcp_decrement_paced_conn();
19925                                 rack->rc_always_pace = 0;
19926                                 rack_undo_cc_pacing(rack);
19927                         }
19928                 }
19929                 if  (rack->r_mbuf_queue || rack->rc_always_pace || rack->r_use_cmp_ack)
19930                         inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
19931                 else
19932                         inp->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
19933                 /* A rate may be set irate or other, if so set seg size */
19934                 rack_update_seg(rack);
19935                 break;
19936         case TCP_BBR_RACK_INIT_RATE:
19937                 RACK_OPTS_INC(tcp_initial_rate);
19938                 val = optval;
19939                 /* Change from kbits per second to bytes per second */
19940                 val *= 1000;
19941                 val /= 8;
19942                 rack->r_ctl.init_rate = val;
19943                 if (rack->rc_init_win != rack_default_init_window) {
19944                         uint32_t win, snt;
19945
19946                         /*
19947                          * Options don't always get applied
19948                          * in the order you think. So in order
19949                          * to assure we update a cwnd we need
19950                          * to check and see if we are still
19951                          * where we should raise the cwnd.
19952                          */
19953                         win = rc_init_window(rack);
19954                         if (SEQ_GT(tp->snd_max, tp->iss))
19955                                 snt = tp->snd_max - tp->iss;
19956                         else
19957                                 snt = 0;
19958                         if ((snt < win) &&
19959                             (tp->snd_cwnd < win))
19960                                 tp->snd_cwnd = win;
19961                 }
19962                 if (rack->rc_always_pace)
19963                         rack_update_seg(rack);
19964                 break;
19965         case TCP_BBR_IWINTSO:
19966                 RACK_OPTS_INC(tcp_initial_win);
19967                 if (optval && (optval <= 0xff)) {
19968                         uint32_t win, snt;
19969
19970                         rack->rc_init_win = optval;
19971                         win = rc_init_window(rack);
19972                         if (SEQ_GT(tp->snd_max, tp->iss))
19973                                 snt = tp->snd_max - tp->iss;
19974                         else
19975                                 snt = 0;
19976                         if ((snt < win) &&
19977                             (tp->t_srtt |
19978 #ifdef NETFLIX_PEAKRATE
19979                              tp->t_maxpeakrate |
19980 #endif
19981                              rack->r_ctl.init_rate)) {
19982                                 /*
19983                                  * We are not past the initial window
19984                                  * and we have some bases for pacing,
19985                                  * so we need to possibly adjust up
19986                                  * the cwnd. Note even if we don't set
19987                                  * the cwnd, its still ok to raise the rc_init_win
19988                                  * which can be used coming out of idle when we
19989                                  * would have a rate.
19990                                  */
19991                                 if (tp->snd_cwnd < win)
19992                                         tp->snd_cwnd = win;
19993                         }
19994                         if (rack->rc_always_pace)
19995                                 rack_update_seg(rack);
19996                 } else
19997                         error = EINVAL;
19998                 break;
19999         case TCP_RACK_FORCE_MSEG:
20000                 RACK_OPTS_INC(tcp_rack_force_max_seg);
20001                 if (optval)
20002                         rack->rc_force_max_seg = 1;
20003                 else
20004                         rack->rc_force_max_seg = 0;
20005                 break;
20006         case TCP_RACK_PACE_MAX_SEG:
20007                 /* Max segments size in a pace in bytes */
20008                 RACK_OPTS_INC(tcp_rack_max_seg);
20009                 rack->rc_user_set_max_segs = optval;
20010                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
20011                 break;
20012         case TCP_RACK_PACE_RATE_REC:
20013                 /* Set the fixed pacing rate in Bytes per second ca */
20014                 RACK_OPTS_INC(tcp_rack_pace_rate_rec);
20015                 rack->r_ctl.rc_fixed_pacing_rate_rec = optval;
20016                 if (rack->r_ctl.rc_fixed_pacing_rate_ca == 0)
20017                         rack->r_ctl.rc_fixed_pacing_rate_ca = optval;
20018                 if (rack->r_ctl.rc_fixed_pacing_rate_ss == 0)
20019                         rack->r_ctl.rc_fixed_pacing_rate_ss = optval;
20020                 rack->use_fixed_rate = 1;
20021                 if (rack->rc_always_pace)
20022                         rack_set_cc_pacing(rack);
20023                 rack_log_pacing_delay_calc(rack,
20024                                            rack->r_ctl.rc_fixed_pacing_rate_ss,
20025                                            rack->r_ctl.rc_fixed_pacing_rate_ca,
20026                                            rack->r_ctl.rc_fixed_pacing_rate_rec, 0, 0, 8,
20027                                            __LINE__, NULL,0);
20028                 break;
20029
20030         case TCP_RACK_PACE_RATE_SS:
20031                 /* Set the fixed pacing rate in Bytes per second ca */
20032                 RACK_OPTS_INC(tcp_rack_pace_rate_ss);
20033                 rack->r_ctl.rc_fixed_pacing_rate_ss = optval;
20034                 if (rack->r_ctl.rc_fixed_pacing_rate_ca == 0)
20035                         rack->r_ctl.rc_fixed_pacing_rate_ca = optval;
20036                 if (rack->r_ctl.rc_fixed_pacing_rate_rec == 0)
20037                         rack->r_ctl.rc_fixed_pacing_rate_rec = optval;
20038                 rack->use_fixed_rate = 1;
20039                 if (rack->rc_always_pace)
20040                         rack_set_cc_pacing(rack);
20041                 rack_log_pacing_delay_calc(rack,
20042                                            rack->r_ctl.rc_fixed_pacing_rate_ss,
20043                                            rack->r_ctl.rc_fixed_pacing_rate_ca,
20044                                            rack->r_ctl.rc_fixed_pacing_rate_rec, 0, 0, 8,
20045                                            __LINE__, NULL, 0);
20046                 break;
20047
20048         case TCP_RACK_PACE_RATE_CA:
20049                 /* Set the fixed pacing rate in Bytes per second ca */
20050                 RACK_OPTS_INC(tcp_rack_pace_rate_ca);
20051                 rack->r_ctl.rc_fixed_pacing_rate_ca = optval;
20052                 if (rack->r_ctl.rc_fixed_pacing_rate_ss == 0)
20053                         rack->r_ctl.rc_fixed_pacing_rate_ss = optval;
20054                 if (rack->r_ctl.rc_fixed_pacing_rate_rec == 0)
20055                         rack->r_ctl.rc_fixed_pacing_rate_rec = optval;
20056                 rack->use_fixed_rate = 1;
20057                 if (rack->rc_always_pace)
20058                         rack_set_cc_pacing(rack);
20059                 rack_log_pacing_delay_calc(rack,
20060                                            rack->r_ctl.rc_fixed_pacing_rate_ss,
20061                                            rack->r_ctl.rc_fixed_pacing_rate_ca,
20062                                            rack->r_ctl.rc_fixed_pacing_rate_rec, 0, 0, 8,
20063                                            __LINE__, NULL, 0);
20064                 break;
20065         case TCP_RACK_GP_INCREASE_REC:
20066                 RACK_OPTS_INC(tcp_gp_inc_rec);
20067                 rack->r_ctl.rack_per_of_gp_rec = optval;
20068                 rack_log_pacing_delay_calc(rack,
20069                                            rack->r_ctl.rack_per_of_gp_ss,
20070                                            rack->r_ctl.rack_per_of_gp_ca,
20071                                            rack->r_ctl.rack_per_of_gp_rec, 0, 0, 1,
20072                                            __LINE__, NULL, 0);
20073                 break;
20074         case TCP_RACK_GP_INCREASE_CA:
20075                 RACK_OPTS_INC(tcp_gp_inc_ca);
20076                 ca = optval;
20077                 if (ca < 100) {
20078                         /*
20079                          * We don't allow any reduction
20080                          * over the GP b/w.
20081                          */
20082                         error = EINVAL;
20083                         break;
20084                 }
20085                 rack->r_ctl.rack_per_of_gp_ca = ca;
20086                 rack_log_pacing_delay_calc(rack,
20087                                            rack->r_ctl.rack_per_of_gp_ss,
20088                                            rack->r_ctl.rack_per_of_gp_ca,
20089                                            rack->r_ctl.rack_per_of_gp_rec, 0, 0, 1,
20090                                            __LINE__, NULL, 0);
20091                 break;
20092         case TCP_RACK_GP_INCREASE_SS:
20093                 RACK_OPTS_INC(tcp_gp_inc_ss);
20094                 ss = optval;
20095                 if (ss < 100) {
20096                         /*
20097                          * We don't allow any reduction
20098                          * over the GP b/w.
20099                          */
20100                         error = EINVAL;
20101                         break;
20102                 }
20103                 rack->r_ctl.rack_per_of_gp_ss = ss;
20104                 rack_log_pacing_delay_calc(rack,
20105                                            rack->r_ctl.rack_per_of_gp_ss,
20106                                            rack->r_ctl.rack_per_of_gp_ca,
20107                                            rack->r_ctl.rack_per_of_gp_rec, 0, 0, 1,
20108                                            __LINE__, NULL, 0);
20109                 break;
20110         case TCP_RACK_RR_CONF:
20111                 RACK_OPTS_INC(tcp_rack_rrr_no_conf_rate);
20112                 if (optval && optval <= 3)
20113                         rack->r_rr_config = optval;
20114                 else
20115                         rack->r_rr_config = 0;
20116                 break;
20117         case TCP_HDWR_RATE_CAP:
20118                 RACK_OPTS_INC(tcp_hdwr_rate_cap);
20119                 if (optval) {
20120                         if (rack->r_rack_hw_rate_caps == 0)
20121                                 rack->r_rack_hw_rate_caps = 1;
20122                         else
20123                                 error = EALREADY;
20124                 } else {
20125                         rack->r_rack_hw_rate_caps = 0;
20126                 }
20127                 break;
20128         case TCP_BBR_HDWR_PACE:
20129                 RACK_OPTS_INC(tcp_hdwr_pacing);
20130                 if (optval){
20131                         if (rack->rack_hdrw_pacing == 0) {
20132                                 rack->rack_hdw_pace_ena = 1;
20133                                 rack->rack_attempt_hdwr_pace = 0;
20134                         } else
20135                                 error = EALREADY;
20136                 } else {
20137                         rack->rack_hdw_pace_ena = 0;
20138 #ifdef RATELIMIT
20139                         if (rack->r_ctl.crte != NULL) {
20140                                 rack->rack_hdrw_pacing = 0;
20141                                 rack->rack_attempt_hdwr_pace = 0;
20142                                 tcp_rel_pacing_rate(rack->r_ctl.crte, tp);
20143                                 rack->r_ctl.crte = NULL;
20144                         }
20145 #endif
20146                 }
20147                 break;
20148         /*  End Pacing related ones */
20149         case TCP_RACK_PRR_SENDALOT:
20150                 /* Allow PRR to send more than one seg */
20151                 RACK_OPTS_INC(tcp_rack_prr_sendalot);
20152                 rack->r_ctl.rc_prr_sendalot = optval;
20153                 break;
20154         case TCP_RACK_MIN_TO:
20155                 /* Minimum time between rack t-o's in ms */
20156                 RACK_OPTS_INC(tcp_rack_min_to);
20157                 rack->r_ctl.rc_min_to = optval;
20158                 break;
20159         case TCP_RACK_EARLY_SEG:
20160                 /* If early recovery max segments */
20161                 RACK_OPTS_INC(tcp_rack_early_seg);
20162                 rack->r_ctl.rc_early_recovery_segs = optval;
20163                 break;
20164         case TCP_RACK_ENABLE_HYSTART:
20165         {
20166                 if (optval) {
20167                         tp->ccv->flags |= CCF_HYSTART_ALLOWED;
20168                         if (rack_do_hystart > RACK_HYSTART_ON)
20169                                 tp->ccv->flags |= CCF_HYSTART_CAN_SH_CWND;
20170                         if (rack_do_hystart > RACK_HYSTART_ON_W_SC)
20171                                 tp->ccv->flags |= CCF_HYSTART_CONS_SSTH;
20172                 } else {
20173                         tp->ccv->flags &= ~(CCF_HYSTART_ALLOWED|CCF_HYSTART_CAN_SH_CWND|CCF_HYSTART_CONS_SSTH);
20174                 }
20175         }
20176         break;
20177         case TCP_RACK_REORD_THRESH:
20178                 /* RACK reorder threshold (shift amount) */
20179                 RACK_OPTS_INC(tcp_rack_reord_thresh);
20180                 if ((optval > 0) && (optval < 31))
20181                         rack->r_ctl.rc_reorder_shift = optval;
20182                 else
20183                         error = EINVAL;
20184                 break;
20185         case TCP_RACK_REORD_FADE:
20186                 /* Does reordering fade after ms time */
20187                 RACK_OPTS_INC(tcp_rack_reord_fade);
20188                 rack->r_ctl.rc_reorder_fade = optval;
20189                 break;
20190         case TCP_RACK_TLP_THRESH:
20191                 /* RACK TLP theshold i.e. srtt+(srtt/N) */
20192                 RACK_OPTS_INC(tcp_rack_tlp_thresh);
20193                 if (optval)
20194                         rack->r_ctl.rc_tlp_threshold = optval;
20195                 else
20196                         error = EINVAL;
20197                 break;
20198         case TCP_BBR_USE_RACK_RR:
20199                 RACK_OPTS_INC(tcp_rack_rr);
20200                 if (optval)
20201                         rack->use_rack_rr = 1;
20202                 else
20203                         rack->use_rack_rr = 0;
20204                 break;
20205         case TCP_FAST_RSM_HACK:
20206                 RACK_OPTS_INC(tcp_rack_fastrsm_hack);
20207                 if (optval)
20208                         rack->fast_rsm_hack = 1;
20209                 else
20210                         rack->fast_rsm_hack = 0;
20211                 break;
20212         case TCP_RACK_PKT_DELAY:
20213                 /* RACK added ms i.e. rack-rtt + reord + N */
20214                 RACK_OPTS_INC(tcp_rack_pkt_delay);
20215                 rack->r_ctl.rc_pkt_delay = optval;
20216                 break;
20217         case TCP_DELACK:
20218                 RACK_OPTS_INC(tcp_rack_delayed_ack);
20219                 if (optval == 0)
20220                         tp->t_delayed_ack = 0;
20221                 else
20222                         tp->t_delayed_ack = 1;
20223                 if (tp->t_flags & TF_DELACK) {
20224                         tp->t_flags &= ~TF_DELACK;
20225                         tp->t_flags |= TF_ACKNOW;
20226                         NET_EPOCH_ENTER(et);
20227                         rack_output(tp);
20228                         NET_EPOCH_EXIT(et);
20229                 }
20230                 break;
20231
20232         case TCP_BBR_RACK_RTT_USE:
20233                 RACK_OPTS_INC(tcp_rack_rtt_use);
20234                 if ((optval != USE_RTT_HIGH) &&
20235                     (optval != USE_RTT_LOW) &&
20236                     (optval != USE_RTT_AVG))
20237                         error = EINVAL;
20238                 else
20239                         rack->r_ctl.rc_rate_sample_method = optval;
20240                 break;
20241         case TCP_DATA_AFTER_CLOSE:
20242                 RACK_OPTS_INC(tcp_data_after_close);
20243                 if (optval)
20244                         rack->rc_allow_data_af_clo = 1;
20245                 else
20246                         rack->rc_allow_data_af_clo = 0;
20247                 break;
20248         default:
20249                 break;
20250         }
20251 #ifdef NETFLIX_STATS
20252         tcp_log_socket_option(tp, sopt_name, optval, error);
20253 #endif
20254         return (error);
20255 }
20256
20257
20258 static void
20259 rack_apply_deferred_options(struct tcp_rack *rack)
20260 {
20261         struct deferred_opt_list *dol, *sdol;
20262         uint32_t s_optval;
20263
20264         TAILQ_FOREACH_SAFE(dol, &rack->r_ctl.opt_list, next, sdol) {
20265                 TAILQ_REMOVE(&rack->r_ctl.opt_list, dol, next);
20266                 /* Disadvantage of deferal is you loose the error return */
20267                 s_optval = (uint32_t)dol->optval;
20268                 (void)rack_process_option(rack->rc_tp, rack, dol->optname, s_optval, dol->optval);
20269                 free(dol, M_TCPDO);
20270         }
20271 }
20272
20273 static void
20274 rack_hw_tls_change(struct tcpcb *tp, int chg)
20275 {
20276         /*
20277          * HW tls state has changed.. fix all
20278          * rsm's in flight.
20279          */
20280         struct tcp_rack *rack;
20281         struct rack_sendmap *rsm;
20282
20283         rack = (struct tcp_rack *)tp->t_fb_ptr;
20284         RB_FOREACH(rsm, rack_rb_tree_head, &rack->r_ctl.rc_mtree) {
20285                 if (chg)
20286                         rsm->r_hw_tls = 1;
20287                 else
20288                         rsm->r_hw_tls = 0;
20289         }
20290         if (chg)
20291                 rack->r_ctl.fsb.hw_tls = 1;
20292         else
20293                 rack->r_ctl.fsb.hw_tls = 0;
20294 }
20295
20296 static int
20297 rack_pru_options(struct tcpcb *tp, int flags)
20298 {
20299         if (flags & PRUS_OOB)
20300                 return (EOPNOTSUPP);
20301         return (0);
20302 }
20303
20304 static struct tcp_function_block __tcp_rack = {
20305         .tfb_tcp_block_name = __XSTRING(STACKNAME),
20306         .tfb_tcp_output = rack_output,
20307         .tfb_do_queued_segments = ctf_do_queued_segments,
20308         .tfb_do_segment_nounlock = rack_do_segment_nounlock,
20309         .tfb_tcp_do_segment = rack_do_segment,
20310         .tfb_tcp_ctloutput = rack_ctloutput,
20311         .tfb_tcp_fb_init = rack_init,
20312         .tfb_tcp_fb_fini = rack_fini,
20313         .tfb_tcp_timer_stop_all = rack_stopall,
20314         .tfb_tcp_timer_activate = rack_timer_activate,
20315         .tfb_tcp_timer_active = rack_timer_active,
20316         .tfb_tcp_timer_stop = rack_timer_stop,
20317         .tfb_tcp_rexmit_tmr = rack_remxt_tmr,
20318         .tfb_tcp_handoff_ok = rack_handoff_ok,
20319         .tfb_tcp_mtu_chg = rack_mtu_change,
20320         .tfb_pru_options = rack_pru_options,
20321         .tfb_hwtls_change = rack_hw_tls_change,
20322         .tfb_compute_pipe = rack_compute_pipe,
20323         .tfb_flags = TCP_FUNC_OUTPUT_CANDROP,
20324 };
20325
20326 /*
20327  * rack_ctloutput() must drop the inpcb lock before performing copyin on
20328  * socket option arguments.  When it re-acquires the lock after the copy, it
20329  * has to revalidate that the connection is still valid for the socket
20330  * option.
20331  */
20332 static int
20333 rack_set_sockopt(struct inpcb *inp, struct sockopt *sopt)
20334 {
20335 #ifdef INET6
20336         struct ip6_hdr *ip6;
20337 #endif
20338 #ifdef INET
20339         struct ip *ip;
20340 #endif
20341         struct tcpcb *tp;
20342         struct tcp_rack *rack;
20343         uint64_t loptval;
20344         int32_t error = 0, optval;
20345
20346         tp = intotcpcb(inp);
20347         rack = (struct tcp_rack *)tp->t_fb_ptr;
20348         if (rack == NULL) {
20349                 INP_WUNLOCK(inp);
20350                 return (EINVAL);
20351         }
20352 #ifdef INET6
20353         ip6 = (struct ip6_hdr *)rack->r_ctl.fsb.tcp_ip_hdr;
20354 #endif
20355 #ifdef INET
20356         ip = (struct ip *)rack->r_ctl.fsb.tcp_ip_hdr;
20357 #endif
20358
20359         switch (sopt->sopt_level) {
20360 #ifdef INET6
20361         case IPPROTO_IPV6:
20362                 MPASS(inp->inp_vflag & INP_IPV6PROTO);
20363                 switch (sopt->sopt_name) {
20364                 case IPV6_USE_MIN_MTU:
20365                         tcp6_use_min_mtu(tp);
20366                         break;
20367                 case IPV6_TCLASS:
20368                         /*
20369                          * The DSCP codepoint has changed, update the fsb.
20370                          */
20371                         ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
20372                             (rack->rc_inp->inp_flow & IPV6_FLOWINFO_MASK);
20373                         break;
20374                 }
20375                 INP_WUNLOCK(inp);
20376                 return (0);
20377 #endif
20378 #ifdef INET
20379         case IPPROTO_IP:
20380                 switch (sopt->sopt_name) {
20381                 case IP_TOS:
20382                         /*
20383                          * The DSCP codepoint has changed, update the fsb.
20384                          */
20385                         ip->ip_tos = rack->rc_inp->inp_ip_tos;
20386                         break;
20387                 case IP_TTL:
20388                         /*
20389                          * The TTL has changed, update the fsb.
20390                          */
20391                         ip->ip_ttl = rack->rc_inp->inp_ip_ttl;
20392                         break;
20393                 }
20394                 INP_WUNLOCK(inp);
20395                 return (0);
20396 #endif
20397         }
20398
20399         switch (sopt->sopt_name) {
20400         case TCP_RACK_TLP_REDUCE:               /*  URL:tlp_reduce */
20401         /*  Pacing related ones */
20402         case TCP_RACK_PACE_ALWAYS:              /*  URL:pace_always */
20403         case TCP_BBR_RACK_INIT_RATE:            /*  URL:irate */
20404         case TCP_BBR_IWINTSO:                   /*  URL:tso_iwin */
20405         case TCP_RACK_PACE_MAX_SEG:             /*  URL:pace_max_seg */
20406         case TCP_RACK_FORCE_MSEG:               /*  URL:force_max_seg */
20407         case TCP_RACK_PACE_RATE_CA:             /*  URL:pr_ca */
20408         case TCP_RACK_PACE_RATE_SS:             /*  URL:pr_ss*/
20409         case TCP_RACK_PACE_RATE_REC:            /*  URL:pr_rec */
20410         case TCP_RACK_GP_INCREASE_CA:           /*  URL:gp_inc_ca */
20411         case TCP_RACK_GP_INCREASE_SS:           /*  URL:gp_inc_ss */
20412         case TCP_RACK_GP_INCREASE_REC:          /*  URL:gp_inc_rec */
20413         case TCP_RACK_RR_CONF:                  /*  URL:rrr_conf */
20414         case TCP_BBR_HDWR_PACE:                 /*  URL:hdwrpace */
20415         case TCP_HDWR_RATE_CAP:                 /*  URL:hdwrcap boolean */
20416         case TCP_PACING_RATE_CAP:               /*  URL:cap  -- used by side-channel */
20417         case TCP_HDWR_UP_ONLY:                  /*  URL:uponly -- hardware pacing  boolean */
20418        /* End pacing related */
20419         case TCP_FAST_RSM_HACK:                 /*  URL:frsm_hack */
20420         case TCP_DELACK:                        /*  URL:delack (in base TCP i.e. tcp_hints along with cc etc ) */
20421         case TCP_RACK_PRR_SENDALOT:             /*  URL:prr_sendalot */
20422         case TCP_RACK_MIN_TO:                   /*  URL:min_to */
20423         case TCP_RACK_EARLY_SEG:                /*  URL:early_seg */
20424         case TCP_RACK_REORD_THRESH:             /*  URL:reord_thresh */
20425         case TCP_RACK_REORD_FADE:               /*  URL:reord_fade */
20426         case TCP_RACK_TLP_THRESH:               /*  URL:tlp_thresh */
20427         case TCP_RACK_PKT_DELAY:                /*  URL:pkt_delay */
20428         case TCP_RACK_TLP_USE:                  /*  URL:tlp_use */
20429         case TCP_BBR_RACK_RTT_USE:              /*  URL:rttuse */
20430         case TCP_BBR_USE_RACK_RR:               /*  URL:rackrr */
20431         case TCP_RACK_DO_DETECTION:             /*  URL:detect */
20432         case TCP_NO_PRR:                        /*  URL:noprr */
20433         case TCP_TIMELY_DYN_ADJ:                /*  URL:dynamic */
20434         case TCP_DATA_AFTER_CLOSE:              /*  no URL */
20435         case TCP_RACK_NONRXT_CFG_RATE:          /*  URL:nonrxtcr */
20436         case TCP_SHARED_CWND_ENABLE:            /*  URL:scwnd */
20437         case TCP_RACK_MBUF_QUEUE:               /*  URL:mqueue */
20438         case TCP_RACK_NO_PUSH_AT_MAX:           /*  URL:npush */
20439         case TCP_RACK_PACE_TO_FILL:             /*  URL:fillcw */
20440         case TCP_SHARED_CWND_TIME_LIMIT:        /*  URL:lscwnd */
20441         case TCP_RACK_PROFILE:                  /*  URL:profile */
20442         case TCP_USE_CMP_ACKS:                  /*  URL:cmpack */
20443         case TCP_RACK_ABC_VAL:                  /*  URL:labc */
20444         case TCP_REC_ABC_VAL:                   /*  URL:reclabc */
20445         case TCP_RACK_MEASURE_CNT:              /*  URL:measurecnt */
20446         case TCP_DEFER_OPTIONS:                 /*  URL:defer */
20447         case TCP_RACK_DSACK_OPT:                /*  URL:dsack */
20448         case TCP_RACK_PACING_BETA:              /*  URL:pacing_beta */
20449         case TCP_RACK_PACING_BETA_ECN:          /*  URL:pacing_beta_ecn */
20450         case TCP_RACK_TIMER_SLOP:               /*  URL:timer_slop */
20451         case TCP_RACK_ENABLE_HYSTART:           /*  URL:hystart */
20452                 break;
20453         default:
20454                 /* Filter off all unknown options to the base stack */
20455                 return (tcp_default_ctloutput(inp, sopt));
20456                 break;
20457         }
20458         INP_WUNLOCK(inp);
20459         if (sopt->sopt_name == TCP_PACING_RATE_CAP) {
20460                 error = sooptcopyin(sopt, &loptval, sizeof(loptval), sizeof(loptval));
20461                 /*
20462                  * We truncate it down to 32 bits for the socket-option trace this
20463                  * means rates > 34Gbps won't show right, but thats probably ok.
20464                  */
20465                 optval = (uint32_t)loptval;
20466         } else {
20467                 error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
20468                 /* Save it in 64 bit form too */
20469                 loptval = optval;
20470         }
20471         if (error)
20472                 return (error);
20473         INP_WLOCK(inp);
20474         if (inp->inp_flags & INP_DROPPED) {
20475                 INP_WUNLOCK(inp);
20476                 return (ECONNRESET);
20477         }
20478         if (tp->t_fb != &__tcp_rack) {
20479                 INP_WUNLOCK(inp);
20480                 return (ENOPROTOOPT);
20481         }
20482         if (rack->defer_options && (rack->gp_ready == 0) &&
20483             (sopt->sopt_name != TCP_DEFER_OPTIONS) &&
20484             (sopt->sopt_name != TCP_RACK_PACING_BETA) &&
20485             (sopt->sopt_name != TCP_RACK_PACING_BETA_ECN) &&
20486             (sopt->sopt_name != TCP_RACK_MEASURE_CNT)) {
20487                 /* Options are beind deferred */
20488                 if (rack_add_deferred_option(rack, sopt->sopt_name, loptval)) {
20489                         INP_WUNLOCK(inp);
20490                         return (0);
20491                 } else {
20492                         /* No memory to defer, fail */
20493                         INP_WUNLOCK(inp);
20494                         return (ENOMEM);
20495                 }
20496         }
20497         error = rack_process_option(tp, rack, sopt->sopt_name, optval, loptval);
20498         INP_WUNLOCK(inp);
20499         return (error);
20500 }
20501
20502 static void
20503 rack_fill_info(struct tcpcb *tp, struct tcp_info *ti)
20504 {
20505
20506         INP_WLOCK_ASSERT(tptoinpcb(tp));
20507         bzero(ti, sizeof(*ti));
20508
20509         ti->tcpi_state = tp->t_state;
20510         if ((tp->t_flags & TF_REQ_TSTMP) && (tp->t_flags & TF_RCVD_TSTMP))
20511                 ti->tcpi_options |= TCPI_OPT_TIMESTAMPS;
20512         if (tp->t_flags & TF_SACK_PERMIT)
20513                 ti->tcpi_options |= TCPI_OPT_SACK;
20514         if ((tp->t_flags & TF_REQ_SCALE) && (tp->t_flags & TF_RCVD_SCALE)) {
20515                 ti->tcpi_options |= TCPI_OPT_WSCALE;
20516                 ti->tcpi_snd_wscale = tp->snd_scale;
20517                 ti->tcpi_rcv_wscale = tp->rcv_scale;
20518         }
20519         if (tp->t_flags2 & (TF2_ECN_PERMIT | TF2_ACE_PERMIT))
20520                 ti->tcpi_options |= TCPI_OPT_ECN;
20521         if (tp->t_flags & TF_FASTOPEN)
20522                 ti->tcpi_options |= TCPI_OPT_TFO;
20523         /* still kept in ticks is t_rcvtime */
20524         ti->tcpi_last_data_recv = ((uint32_t)ticks - tp->t_rcvtime) * tick;
20525         /* Since we hold everything in precise useconds this is easy */
20526         ti->tcpi_rtt = tp->t_srtt;
20527         ti->tcpi_rttvar = tp->t_rttvar;
20528         ti->tcpi_rto = tp->t_rxtcur;
20529         ti->tcpi_snd_ssthresh = tp->snd_ssthresh;
20530         ti->tcpi_snd_cwnd = tp->snd_cwnd;
20531         /*
20532          * FreeBSD-specific extension fields for tcp_info.
20533          */
20534         ti->tcpi_rcv_space = tp->rcv_wnd;
20535         ti->tcpi_rcv_nxt = tp->rcv_nxt;
20536         ti->tcpi_snd_wnd = tp->snd_wnd;
20537         ti->tcpi_snd_bwnd = 0;          /* Unused, kept for compat. */
20538         ti->tcpi_snd_nxt = tp->snd_nxt;
20539         ti->tcpi_snd_mss = tp->t_maxseg;
20540         ti->tcpi_rcv_mss = tp->t_maxseg;
20541         ti->tcpi_snd_rexmitpack = tp->t_sndrexmitpack;
20542         ti->tcpi_rcv_ooopack = tp->t_rcvoopack;
20543         ti->tcpi_snd_zerowin = tp->t_sndzerowin;
20544 #ifdef NETFLIX_STATS
20545         ti->tcpi_total_tlp = tp->t_sndtlppack;
20546         ti->tcpi_total_tlp_bytes = tp->t_sndtlpbyte;
20547         memcpy(&ti->tcpi_rxsyninfo, &tp->t_rxsyninfo, sizeof(struct tcpsyninfo));
20548 #endif
20549 #ifdef TCP_OFFLOAD
20550         if (tp->t_flags & TF_TOE) {
20551                 ti->tcpi_options |= TCPI_OPT_TOE;
20552                 tcp_offload_tcp_info(tp, ti);
20553         }
20554 #endif
20555 }
20556
20557 static int
20558 rack_get_sockopt(struct inpcb *inp, struct sockopt *sopt)
20559 {
20560         struct tcpcb *tp;
20561         struct tcp_rack *rack;
20562         int32_t error, optval;
20563         uint64_t val, loptval;
20564         struct  tcp_info ti;
20565         /*
20566          * Because all our options are either boolean or an int, we can just
20567          * pull everything into optval and then unlock and copy. If we ever
20568          * add a option that is not a int, then this will have quite an
20569          * impact to this routine.
20570          */
20571         error = 0;
20572         tp = intotcpcb(inp);
20573         rack = (struct tcp_rack *)tp->t_fb_ptr;
20574         if (rack == NULL) {
20575                 INP_WUNLOCK(inp);
20576                 return (EINVAL);
20577         }
20578         switch (sopt->sopt_name) {
20579         case TCP_INFO:
20580                 /* First get the info filled */
20581                 rack_fill_info(tp, &ti);
20582                 /* Fix up the rtt related fields if needed */
20583                 INP_WUNLOCK(inp);
20584                 error = sooptcopyout(sopt, &ti, sizeof ti);
20585                 return (error);
20586         /*
20587          * Beta is the congestion control value for NewReno that influences how
20588          * much of a backoff happens when loss is detected. It is normally set
20589          * to 50 for 50% i.e. the cwnd is reduced to 50% of its previous value
20590          * when you exit recovery.
20591          */
20592         case TCP_RACK_PACING_BETA:
20593                 if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0)
20594                         error = EINVAL;
20595                 else if (rack->rc_pacing_cc_set == 0)
20596                         optval = rack->r_ctl.rc_saved_beta.beta;
20597                 else {
20598                         /*
20599                          * Reach out into the CC data and report back what
20600                          * I have previously set. Yeah it looks hackish but
20601                          * we don't want to report the saved values.
20602                          */
20603                         if (tp->ccv->cc_data)
20604                                 optval = ((struct newreno *)tp->ccv->cc_data)->beta;
20605                         else
20606                                 error = EINVAL;
20607                 }
20608                 break;
20609                 /*
20610                  * Beta_ecn is the congestion control value for NewReno that influences how
20611                  * much of a backoff happens when a ECN mark is detected. It is normally set
20612                  * to 80 for 80% i.e. the cwnd is reduced by 20% of its previous value when
20613                  * you exit recovery. Note that classic ECN has a beta of 50, it is only
20614                  * ABE Ecn that uses this "less" value, but we do too with pacing :)
20615                  */
20616
20617         case TCP_RACK_PACING_BETA_ECN:
20618                 if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0)
20619                         error = EINVAL;
20620                 else if (rack->rc_pacing_cc_set == 0)
20621                         optval = rack->r_ctl.rc_saved_beta.beta_ecn;
20622                 else {
20623                         /*
20624                          * Reach out into the CC data and report back what
20625                          * I have previously set. Yeah it looks hackish but
20626                          * we don't want to report the saved values.
20627                          */
20628                         if (tp->ccv->cc_data)
20629                                 optval = ((struct newreno *)tp->ccv->cc_data)->beta_ecn;
20630                         else
20631                                 error = EINVAL;
20632                 }
20633                 break;
20634         case TCP_RACK_DSACK_OPT:
20635                 optval = 0;
20636                 if (rack->rc_rack_tmr_std_based) {
20637                         optval |= 1;
20638                 }
20639                 if (rack->rc_rack_use_dsack) {
20640                         optval |= 2;
20641                 }
20642                 break;
20643         case TCP_RACK_ENABLE_HYSTART:
20644         {
20645                 if (tp->ccv->flags & CCF_HYSTART_ALLOWED) {
20646                         optval = RACK_HYSTART_ON;
20647                         if (tp->ccv->flags & CCF_HYSTART_CAN_SH_CWND)
20648                                 optval = RACK_HYSTART_ON_W_SC;
20649                         if (tp->ccv->flags & CCF_HYSTART_CONS_SSTH)
20650                                 optval = RACK_HYSTART_ON_W_SC_C;
20651                 } else {
20652                         optval = RACK_HYSTART_OFF;
20653                 }
20654         }
20655         break;
20656         case TCP_FAST_RSM_HACK:
20657                 optval = rack->fast_rsm_hack;
20658                 break;
20659         case TCP_DEFER_OPTIONS:
20660                 optval = rack->defer_options;
20661                 break;
20662         case TCP_RACK_MEASURE_CNT:
20663                 optval = rack->r_ctl.req_measurements;
20664                 break;
20665         case TCP_REC_ABC_VAL:
20666                 optval = rack->r_use_labc_for_rec;
20667                 break;
20668         case TCP_RACK_ABC_VAL:
20669                 optval = rack->rc_labc;
20670                 break;
20671         case TCP_HDWR_UP_ONLY:
20672                 optval= rack->r_up_only;
20673                 break;
20674         case TCP_PACING_RATE_CAP:
20675                 loptval = rack->r_ctl.bw_rate_cap;
20676                 break;
20677         case TCP_RACK_PROFILE:
20678                 /* You cannot retrieve a profile, its write only */
20679                 error = EINVAL;
20680                 break;
20681         case TCP_USE_CMP_ACKS:
20682                 optval = rack->r_use_cmp_ack;
20683                 break;
20684         case TCP_RACK_PACE_TO_FILL:
20685                 optval = rack->rc_pace_to_cwnd;
20686                 if (optval && rack->r_fill_less_agg)
20687                         optval++;
20688                 break;
20689         case TCP_RACK_NO_PUSH_AT_MAX:
20690                 optval = rack->r_ctl.rc_no_push_at_mrtt;
20691                 break;
20692         case TCP_SHARED_CWND_ENABLE:
20693                 optval = rack->rack_enable_scwnd;
20694                 break;
20695         case TCP_RACK_NONRXT_CFG_RATE:
20696                 optval = rack->rack_rec_nonrxt_use_cr;
20697                 break;
20698         case TCP_NO_PRR:
20699                 if (rack->rack_no_prr  == 1)
20700                         optval = 1;
20701                 else if (rack->no_prr_addback == 1)
20702                         optval = 2;
20703                 else
20704                         optval = 0;
20705                 break;
20706         case TCP_RACK_DO_DETECTION:
20707                 optval = rack->do_detection;
20708                 break;
20709         case TCP_RACK_MBUF_QUEUE:
20710                 /* Now do we use the LRO mbuf-queue feature */
20711                 optval = rack->r_mbuf_queue;
20712                 break;
20713         case TCP_TIMELY_DYN_ADJ:
20714                 optval = rack->rc_gp_dyn_mul;
20715                 break;
20716         case TCP_BBR_IWINTSO:
20717                 optval = rack->rc_init_win;
20718                 break;
20719         case TCP_RACK_TLP_REDUCE:
20720                 /* RACK TLP cwnd reduction (bool) */
20721                 optval = rack->r_ctl.rc_tlp_cwnd_reduce;
20722                 break;
20723         case TCP_BBR_RACK_INIT_RATE:
20724                 val = rack->r_ctl.init_rate;
20725                 /* convert to kbits per sec */
20726                 val *= 8;
20727                 val /= 1000;
20728                 optval = (uint32_t)val;
20729                 break;
20730         case TCP_RACK_FORCE_MSEG:
20731                 optval = rack->rc_force_max_seg;
20732                 break;
20733         case TCP_RACK_PACE_MAX_SEG:
20734                 /* Max segments in a pace */
20735                 optval = rack->rc_user_set_max_segs;
20736                 break;
20737         case TCP_RACK_PACE_ALWAYS:
20738                 /* Use the always pace method */
20739                 optval = rack->rc_always_pace;
20740                 break;
20741         case TCP_RACK_PRR_SENDALOT:
20742                 /* Allow PRR to send more than one seg */
20743                 optval = rack->r_ctl.rc_prr_sendalot;
20744                 break;
20745         case TCP_RACK_MIN_TO:
20746                 /* Minimum time between rack t-o's in ms */
20747                 optval = rack->r_ctl.rc_min_to;
20748                 break;
20749         case TCP_RACK_EARLY_SEG:
20750                 /* If early recovery max segments */
20751                 optval = rack->r_ctl.rc_early_recovery_segs;
20752                 break;
20753         case TCP_RACK_REORD_THRESH:
20754                 /* RACK reorder threshold (shift amount) */
20755                 optval = rack->r_ctl.rc_reorder_shift;
20756                 break;
20757         case TCP_RACK_REORD_FADE:
20758                 /* Does reordering fade after ms time */
20759                 optval = rack->r_ctl.rc_reorder_fade;
20760                 break;
20761         case TCP_BBR_USE_RACK_RR:
20762                 /* Do we use the rack cheat for rxt */
20763                 optval = rack->use_rack_rr;
20764                 break;
20765         case TCP_RACK_RR_CONF:
20766                 optval = rack->r_rr_config;
20767                 break;
20768         case TCP_HDWR_RATE_CAP:
20769                 optval = rack->r_rack_hw_rate_caps;
20770                 break;
20771         case TCP_BBR_HDWR_PACE:
20772                 optval = rack->rack_hdw_pace_ena;
20773                 break;
20774         case TCP_RACK_TLP_THRESH:
20775                 /* RACK TLP theshold i.e. srtt+(srtt/N) */
20776                 optval = rack->r_ctl.rc_tlp_threshold;
20777                 break;
20778         case TCP_RACK_PKT_DELAY:
20779                 /* RACK added ms i.e. rack-rtt + reord + N */
20780                 optval = rack->r_ctl.rc_pkt_delay;
20781                 break;
20782         case TCP_RACK_TLP_USE:
20783                 optval = rack->rack_tlp_threshold_use;
20784                 break;
20785         case TCP_RACK_PACE_RATE_CA:
20786                 optval = rack->r_ctl.rc_fixed_pacing_rate_ca;
20787                 break;
20788         case TCP_RACK_PACE_RATE_SS:
20789                 optval = rack->r_ctl.rc_fixed_pacing_rate_ss;
20790                 break;
20791         case TCP_RACK_PACE_RATE_REC:
20792                 optval = rack->r_ctl.rc_fixed_pacing_rate_rec;
20793                 break;
20794         case TCP_RACK_GP_INCREASE_SS:
20795                 optval = rack->r_ctl.rack_per_of_gp_ca;
20796                 break;
20797         case TCP_RACK_GP_INCREASE_CA:
20798                 optval = rack->r_ctl.rack_per_of_gp_ss;
20799                 break;
20800         case TCP_BBR_RACK_RTT_USE:
20801                 optval = rack->r_ctl.rc_rate_sample_method;
20802                 break;
20803         case TCP_DELACK:
20804                 optval = tp->t_delayed_ack;
20805                 break;
20806         case TCP_DATA_AFTER_CLOSE:
20807                 optval = rack->rc_allow_data_af_clo;
20808                 break;
20809         case TCP_SHARED_CWND_TIME_LIMIT:
20810                 optval = rack->r_limit_scw;
20811                 break;
20812         case TCP_RACK_TIMER_SLOP:
20813                 optval = rack->r_ctl.timer_slop;
20814                 break;
20815         default:
20816                 return (tcp_default_ctloutput(inp, sopt));
20817                 break;
20818         }
20819         INP_WUNLOCK(inp);
20820         if (error == 0) {
20821                 if (TCP_PACING_RATE_CAP)
20822                         error = sooptcopyout(sopt, &loptval, sizeof loptval);
20823                 else
20824                         error = sooptcopyout(sopt, &optval, sizeof optval);
20825         }
20826         return (error);
20827 }
20828
20829 static int
20830 rack_ctloutput(struct inpcb *inp, struct sockopt *sopt)
20831 {
20832         if (sopt->sopt_dir == SOPT_SET) {
20833                 return (rack_set_sockopt(inp, sopt));
20834         } else if (sopt->sopt_dir == SOPT_GET) {
20835                 return (rack_get_sockopt(inp, sopt));
20836         } else {
20837                 panic("%s: sopt_dir $%d", __func__, sopt->sopt_dir);
20838         }
20839 }
20840
20841 static const char *rack_stack_names[] = {
20842         __XSTRING(STACKNAME),
20843 #ifdef STACKALIAS
20844         __XSTRING(STACKALIAS),
20845 #endif
20846 };
20847
20848 static int
20849 rack_ctor(void *mem, int32_t size, void *arg, int32_t how)
20850 {
20851         memset(mem, 0, size);
20852         return (0);
20853 }
20854
20855 static void
20856 rack_dtor(void *mem, int32_t size, void *arg)
20857 {
20858
20859 }
20860
20861 static bool rack_mod_inited = false;
20862
20863 static int
20864 tcp_addrack(module_t mod, int32_t type, void *data)
20865 {
20866         int32_t err = 0;
20867         int num_stacks;
20868
20869         switch (type) {
20870         case MOD_LOAD:
20871                 rack_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
20872                     sizeof(struct rack_sendmap),
20873                     rack_ctor, rack_dtor, NULL, NULL, UMA_ALIGN_PTR, 0);
20874
20875                 rack_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
20876                     sizeof(struct tcp_rack),
20877                     rack_ctor, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
20878
20879                 sysctl_ctx_init(&rack_sysctl_ctx);
20880                 rack_sysctl_root = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
20881                     SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
20882                     OID_AUTO,
20883 #ifdef STACKALIAS
20884                     __XSTRING(STACKALIAS),
20885 #else
20886                     __XSTRING(STACKNAME),
20887 #endif
20888                     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
20889                     "");
20890                 if (rack_sysctl_root == NULL) {
20891                         printf("Failed to add sysctl node\n");
20892                         err = EFAULT;
20893                         goto free_uma;
20894                 }
20895                 rack_init_sysctls();
20896                 num_stacks = nitems(rack_stack_names);
20897                 err = register_tcp_functions_as_names(&__tcp_rack, M_WAITOK,
20898                     rack_stack_names, &num_stacks);
20899                 if (err) {
20900                         printf("Failed to register %s stack name for "
20901                             "%s module\n", rack_stack_names[num_stacks],
20902                             __XSTRING(MODNAME));
20903                         sysctl_ctx_free(&rack_sysctl_ctx);
20904 free_uma:
20905                         uma_zdestroy(rack_zone);
20906                         uma_zdestroy(rack_pcb_zone);
20907                         rack_counter_destroy();
20908                         printf("Failed to register rack module -- err:%d\n", err);
20909                         return (err);
20910                 }
20911                 tcp_lro_reg_mbufq();
20912                 rack_mod_inited = true;
20913                 break;
20914         case MOD_QUIESCE:
20915                 err = deregister_tcp_functions(&__tcp_rack, true, false);
20916                 break;
20917         case MOD_UNLOAD:
20918                 err = deregister_tcp_functions(&__tcp_rack, false, true);
20919                 if (err == EBUSY)
20920                         break;
20921                 if (rack_mod_inited) {
20922                         uma_zdestroy(rack_zone);
20923                         uma_zdestroy(rack_pcb_zone);
20924                         sysctl_ctx_free(&rack_sysctl_ctx);
20925                         rack_counter_destroy();
20926                         rack_mod_inited = false;
20927                 }
20928                 tcp_lro_dereg_mbufq();
20929                 err = 0;
20930                 break;
20931         default:
20932                 return (EOPNOTSUPP);
20933         }
20934         return (err);
20935 }
20936
20937 static moduledata_t tcp_rack = {
20938         .name = __XSTRING(MODNAME),
20939         .evhand = tcp_addrack,
20940         .priv = 0
20941 };
20942
20943 MODULE_VERSION(MODNAME, 1);
20944 DECLARE_MODULE(MODNAME, tcp_rack, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
20945 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);