]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/tcp_stacks/rack.c
tcp: Fix sending of TCP segments with IP level options
[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 <sys/param.h>
36 #include <sys/arb.h>
37 #include <sys/module.h>
38 #include <sys/kernel.h>
39 #ifdef TCP_HHOOK
40 #include <sys/hhook.h>
41 #endif
42 #include <sys/lock.h>
43 #include <sys/malloc.h>
44 #include <sys/lock.h>
45 #include <sys/mutex.h>
46 #include <sys/mbuf.h>
47 #include <sys/proc.h>           /* for proc0 declaration */
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/sysctl.h>
51 #include <sys/systm.h>
52 #ifdef STATS
53 #include <sys/qmath.h>
54 #include <sys/tree.h>
55 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
56 #else
57 #include <sys/tree.h>
58 #endif
59 #include <sys/refcount.h>
60 #include <sys/queue.h>
61 #include <sys/tim_filter.h>
62 #include <sys/smp.h>
63 #include <sys/kthread.h>
64 #include <sys/kern_prefetch.h>
65 #include <sys/protosw.h>
66 #ifdef TCP_ACCOUNTING
67 #include <sys/sched.h>
68 #include <machine/cpu.h>
69 #endif
70 #include <vm/uma.h>
71
72 #include <net/route.h>
73 #include <net/route/nhop.h>
74 #include <net/vnet.h>
75
76 #define TCPSTATES               /* for logging */
77
78 #include <netinet/in.h>
79 #include <netinet/in_kdtrace.h>
80 #include <netinet/in_pcb.h>
81 #include <netinet/ip.h>
82 #include <netinet/ip_icmp.h>    /* required for icmp_var.h */
83 #include <netinet/icmp_var.h>   /* for ICMP_BANDLIM */
84 #include <netinet/ip_var.h>
85 #include <netinet/ip6.h>
86 #include <netinet6/in6_pcb.h>
87 #include <netinet6/ip6_var.h>
88 #include <netinet/tcp.h>
89 #define TCPOUTFLAGS
90 #include <netinet/tcp_fsm.h>
91 #include <netinet/tcp_log_buf.h>
92 #include <netinet/tcp_seq.h>
93 #include <netinet/tcp_timer.h>
94 #include <netinet/tcp_var.h>
95 #include <netinet/tcp_hpts.h>
96 #include <netinet/tcp_ratelimit.h>
97 #include <netinet/tcp_accounting.h>
98 #include <netinet/tcpip.h>
99 #include <netinet/cc/cc.h>
100 #include <netinet/cc/cc_newreno.h>
101 #include <netinet/tcp_fastopen.h>
102 #include <netinet/tcp_lro.h>
103 #ifdef NETFLIX_SHARED_CWND
104 #include <netinet/tcp_shared_cwnd.h>
105 #endif
106 #ifdef TCPDEBUG
107 #include <netinet/tcp_debug.h>
108 #endif                          /* TCPDEBUG */
109 #ifdef TCP_OFFLOAD
110 #include <netinet/tcp_offload.h>
111 #endif
112 #ifdef INET6
113 #include <netinet6/tcp6_var.h>
114 #endif
115
116 #include <netipsec/ipsec_support.h>
117
118 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
119 #include <netipsec/ipsec.h>
120 #include <netipsec/ipsec6.h>
121 #endif                          /* IPSEC */
122
123 #include <netinet/udp.h>
124 #include <netinet/udp_var.h>
125 #include <machine/in_cksum.h>
126
127 #ifdef MAC
128 #include <security/mac/mac_framework.h>
129 #endif
130 #include "sack_filter.h"
131 #include "tcp_rack.h"
132 #include "rack_bbr_common.h"
133
134 uma_zone_t rack_zone;
135 uma_zone_t rack_pcb_zone;
136
137 #ifndef TICKS2SBT
138 #define TICKS2SBT(__t)  (tick_sbt * ((sbintime_t)(__t)))
139 #endif
140
141 VNET_DECLARE(uint32_t, newreno_beta);
142 VNET_DECLARE(uint32_t, newreno_beta_ecn);
143 #define V_newreno_beta VNET(newreno_beta)
144 #define V_newreno_beta_ecn VNET(newreno_beta_ecn)
145
146
147 MALLOC_DEFINE(M_TCPFSB, "tcp_fsb", "TCP fast send block");
148 MALLOC_DEFINE(M_TCPDO, "tcp_do", "TCP deferred options");
149
150 struct sysctl_ctx_list rack_sysctl_ctx;
151 struct sysctl_oid *rack_sysctl_root;
152
153 #define CUM_ACKED 1
154 #define SACKED 2
155
156 /*
157  * The RACK module incorporates a number of
158  * TCP ideas that have been put out into the IETF
159  * over the last few years:
160  * - Matt Mathis's Rate Halving which slowly drops
161  *    the congestion window so that the ack clock can
162  *    be maintained during a recovery.
163  * - Yuchung Cheng's RACK TCP (for which its named) that
164  *    will stop us using the number of dup acks and instead
165  *    use time as the gage of when we retransmit.
166  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
167  *    of Dukkipati et.al.
168  * RACK depends on SACK, so if an endpoint arrives that
169  * cannot do SACK the state machine below will shuttle the
170  * connection back to using the "default" TCP stack that is
171  * in FreeBSD.
172  *
173  * To implement RACK the original TCP stack was first decomposed
174  * into a functional state machine with individual states
175  * for each of the possible TCP connection states. The do_segement
176  * functions role in life is to mandate the connection supports SACK
177  * initially and then assure that the RACK state matches the conenction
178  * state before calling the states do_segment function. Each
179  * state is simplified due to the fact that the original do_segment
180  * has been decomposed and we *know* what state we are in (no
181  * switches on the state) and all tests for SACK are gone. This
182  * greatly simplifies what each state does.
183  *
184  * TCP output is also over-written with a new version since it
185  * must maintain the new rack scoreboard.
186  *
187  */
188 static int32_t rack_tlp_thresh = 1;
189 static int32_t rack_tlp_limit = 2;      /* No more than 2 TLPs w-out new data */
190 static int32_t rack_tlp_use_greater = 1;
191 static int32_t rack_reorder_thresh = 2;
192 static int32_t rack_reorder_fade = 60000000;    /* 0 - never fade, def 60,000,000
193                                                  * - 60 seconds */
194 static uint8_t rack_req_measurements = 1;
195 /* Attack threshold detections */
196 static uint32_t rack_highest_sack_thresh_seen = 0;
197 static uint32_t rack_highest_move_thresh_seen = 0;
198 static int32_t rack_enable_hw_pacing = 0; /* Due to CCSP keep it off by default */
199 static int32_t rack_hw_pace_extra_slots = 2;    /* 2 extra MSS time betweens */
200 static int32_t rack_hw_rate_caps = 1; /* 1; */
201 static int32_t rack_hw_rate_min = 0; /* 1500000;*/
202 static int32_t rack_hw_rate_to_low = 0; /* 1200000; */
203 static int32_t rack_hw_up_only = 1;
204 static int32_t rack_stats_gets_ms_rtt = 1;
205 static int32_t rack_prr_addbackmax = 2;
206
207 static int32_t rack_pkt_delay = 1000;
208 static int32_t rack_send_a_lot_in_prr = 1;
209 static int32_t rack_min_to = 1000;      /* Number of microsecond  min timeout */
210 static int32_t rack_verbose_logging = 0;
211 static int32_t rack_ignore_data_after_close = 1;
212 static int32_t rack_enable_shared_cwnd = 1;
213 static int32_t rack_use_cmp_acks = 1;
214 static int32_t rack_use_fsb = 1;
215 static int32_t rack_use_rfo = 1;
216 static int32_t rack_use_rsm_rfo = 1;
217 static int32_t rack_max_abc_post_recovery = 2;
218 static int32_t rack_client_low_buf = 0;
219 #ifdef TCP_ACCOUNTING
220 static int32_t rack_tcp_accounting = 0;
221 #endif
222 static int32_t rack_limits_scwnd = 1;
223 static int32_t rack_enable_mqueue_for_nonpaced = 0;
224 static int32_t rack_disable_prr = 0;
225 static int32_t use_rack_rr = 1;
226 static int32_t rack_non_rxt_use_cr = 0; /* does a non-rxt in recovery use the configured rate (ss/ca)? */
227 static int32_t rack_persist_min = 250000;       /* 250usec */
228 static int32_t rack_persist_max = 2000000;      /* 2 Second in usec's */
229 static int32_t rack_sack_not_required = 1;      /* set to one to allow non-sack to use rack */
230 static int32_t rack_default_init_window = 0;    /* Use system default */
231 static int32_t rack_limit_time_with_srtt = 0;
232 static int32_t rack_autosndbuf_inc = 20;        /* In percentage form */
233 static int32_t rack_enobuf_hw_boost_mult = 2;   /* How many times the hw rate we boost slot using time_between */
234 static int32_t rack_enobuf_hw_max = 12000;      /* 12 ms in usecs */
235 static int32_t rack_enobuf_hw_min = 10000;      /* 10 ms in usecs */
236 static int32_t rack_hw_rwnd_factor = 2;         /* How many max_segs the rwnd must be before we hold off sending */
237 /*
238  * Currently regular tcp has a rto_min of 30ms
239  * the backoff goes 12 times so that ends up
240  * being a total of 122.850 seconds before a
241  * connection is killed.
242  */
243 static uint32_t rack_def_data_window = 20;
244 static uint32_t rack_goal_bdp = 2;
245 static uint32_t rack_min_srtts = 1;
246 static uint32_t rack_min_measure_usec = 0;
247 static int32_t rack_tlp_min = 10000;    /* 10ms */
248 static int32_t rack_rto_min = 30000;    /* 30,000 usec same as main freebsd */
249 static int32_t rack_rto_max = 4000000;  /* 4 seconds in usec's */
250 static const int32_t rack_free_cache = 2;
251 static int32_t rack_hptsi_segments = 40;
252 static int32_t rack_rate_sample_method = USE_RTT_LOW;
253 static int32_t rack_pace_every_seg = 0;
254 static int32_t rack_delayed_ack_time = 40000;   /* 40ms in usecs */
255 static int32_t rack_slot_reduction = 4;
256 static int32_t rack_wma_divisor = 8;            /* For WMA calculation */
257 static int32_t rack_cwnd_block_ends_measure = 0;
258 static int32_t rack_rwnd_block_ends_measure = 0;
259 static int32_t rack_def_profile = 0;
260
261 static int32_t rack_lower_cwnd_at_tlp = 0;
262 static int32_t rack_limited_retran = 0;
263 static int32_t rack_always_send_oldest = 0;
264 static int32_t rack_tlp_threshold_use = TLP_USE_TWO_ONE;
265
266 static uint16_t rack_per_of_gp_ss = 250;        /* 250 % slow-start */
267 static uint16_t rack_per_of_gp_ca = 200;        /* 200 % congestion-avoidance */
268 static uint16_t rack_per_of_gp_rec = 200;       /* 200 % of bw */
269
270 /* Probertt */
271 static uint16_t rack_per_of_gp_probertt = 60;   /* 60% of bw */
272 static uint16_t rack_per_of_gp_lowthresh = 40;  /* 40% is bottom */
273 static uint16_t rack_per_of_gp_probertt_reduce = 10; /* 10% reduction */
274 static uint16_t rack_atexit_prtt_hbp = 130;     /* Clamp to 130% on exit prtt if highly buffered path */
275 static uint16_t rack_atexit_prtt = 130; /* Clamp to 100% on exit prtt if non highly buffered path */
276
277 static uint32_t rack_max_drain_wait = 2;        /* How man gp srtt's before we give up draining */
278 static uint32_t rack_must_drain = 1;            /* How many GP srtt's we *must* wait */
279 static uint32_t rack_probertt_use_min_rtt_entry = 1;    /* Use the min to calculate the goal else gp_srtt */
280 static uint32_t rack_probertt_use_min_rtt_exit = 0;
281 static uint32_t rack_probe_rtt_sets_cwnd = 0;
282 static uint32_t rack_probe_rtt_safety_val = 2000000;    /* No more than 2 sec in probe-rtt */
283 static uint32_t rack_time_between_probertt = 9600000;   /* 9.6 sec in usecs */
284 static uint32_t rack_probertt_gpsrtt_cnt_mul = 0;       /* How many srtt periods does probe-rtt last top fraction */
285 static uint32_t rack_probertt_gpsrtt_cnt_div = 0;       /* How many srtt periods does probe-rtt last bottom fraction */
286 static uint32_t rack_min_probertt_hold = 40000;         /* Equal to delayed ack time */
287 static uint32_t rack_probertt_filter_life = 10000000;
288 static uint32_t rack_probertt_lower_within = 10;
289 static uint32_t rack_min_rtt_movement = 250000; /* Must move at least 250ms (in microseconds)  to count as a lowering */
290 static int32_t rack_pace_one_seg = 0;           /* Shall we pace for less than 1.4Meg 1MSS at a time */
291 static int32_t rack_probertt_clear_is = 1;
292 static int32_t rack_max_drain_hbp = 1;          /* Extra drain times gpsrtt for highly buffered paths */
293 static int32_t rack_hbp_thresh = 3;             /* what is the divisor max_rtt/min_rtt to decided a hbp */
294
295 /* Part of pacing */
296 static int32_t rack_max_per_above = 30;         /* When we go to increment stop if above 100+this% */
297
298 /* Timely information */
299 /* Combine these two gives the range of 'no change' to bw */
300 /* ie the up/down provide the upper and lower bound */
301 static int32_t rack_gp_per_bw_mul_up = 2;       /* 2% */
302 static int32_t rack_gp_per_bw_mul_down = 4;     /* 4% */
303 static int32_t rack_gp_rtt_maxmul = 3;          /* 3 x maxmin */
304 static int32_t rack_gp_rtt_minmul = 1;          /* minrtt + (minrtt/mindiv) is lower rtt */
305 static int32_t rack_gp_rtt_mindiv = 4;          /* minrtt + (minrtt * minmul/mindiv) is lower rtt */
306 static int32_t rack_gp_decrease_per = 20;       /* 20% decrease in multipler */
307 static int32_t rack_gp_increase_per = 2;        /* 2% increase in multipler */
308 static int32_t rack_per_lower_bound = 50;       /* Don't allow to drop below this multiplier */
309 static int32_t rack_per_upper_bound_ss = 0;     /* Don't allow SS to grow above this */
310 static int32_t rack_per_upper_bound_ca = 0;     /* Don't allow CA to grow above this */
311 static int32_t rack_do_dyn_mul = 0;             /* Are the rack gp multipliers dynamic */
312 static int32_t rack_gp_no_rec_chg = 1;          /* Prohibit recovery from reducing it's multiplier */
313 static int32_t rack_timely_dec_clear = 6;       /* Do we clear decrement count at a value (6)? */
314 static int32_t rack_timely_max_push_rise = 3;   /* One round of pushing */
315 static int32_t rack_timely_max_push_drop = 3;   /* Three round of pushing */
316 static int32_t rack_timely_min_segs = 4;        /* 4 segment minimum */
317 static int32_t rack_use_max_for_nobackoff = 0;
318 static int32_t rack_timely_int_timely_only = 0; /* do interim timely's only use the timely algo (no b/w changes)? */
319 static int32_t rack_timely_no_stopping = 0;
320 static int32_t rack_down_raise_thresh = 100;
321 static int32_t rack_req_segs = 1;
322 static uint64_t rack_bw_rate_cap = 0;
323
324 /* Weird delayed ack mode */
325 static int32_t rack_use_imac_dack = 0;
326 /* Rack specific counters */
327 counter_u64_t rack_badfr;
328 counter_u64_t rack_badfr_bytes;
329 counter_u64_t rack_rtm_prr_retran;
330 counter_u64_t rack_rtm_prr_newdata;
331 counter_u64_t rack_timestamp_mismatch;
332 counter_u64_t rack_reorder_seen;
333 counter_u64_t rack_paced_segments;
334 counter_u64_t rack_unpaced_segments;
335 counter_u64_t rack_calc_zero;
336 counter_u64_t rack_calc_nonzero;
337 counter_u64_t rack_saw_enobuf;
338 counter_u64_t rack_saw_enobuf_hw;
339 counter_u64_t rack_saw_enetunreach;
340 counter_u64_t rack_per_timer_hole;
341 counter_u64_t rack_large_ackcmp;
342 counter_u64_t rack_small_ackcmp;
343 #ifdef INVARIANTS
344 counter_u64_t rack_adjust_map_bw;
345 #endif
346 /* Tail loss probe counters */
347 counter_u64_t rack_tlp_tot;
348 counter_u64_t rack_tlp_newdata;
349 counter_u64_t rack_tlp_retran;
350 counter_u64_t rack_tlp_retran_bytes;
351 counter_u64_t rack_tlp_retran_fail;
352 counter_u64_t rack_to_tot;
353 counter_u64_t rack_to_arm_rack;
354 counter_u64_t rack_to_arm_tlp;
355 counter_u64_t rack_hot_alloc;
356 counter_u64_t rack_to_alloc;
357 counter_u64_t rack_to_alloc_hard;
358 counter_u64_t rack_to_alloc_emerg;
359 counter_u64_t rack_to_alloc_limited;
360 counter_u64_t rack_alloc_limited_conns;
361 counter_u64_t rack_split_limited;
362
363 #define MAX_NUM_OF_CNTS 13
364 counter_u64_t rack_proc_comp_ack[MAX_NUM_OF_CNTS];
365 counter_u64_t rack_multi_single_eq;
366 counter_u64_t rack_proc_non_comp_ack;
367
368 counter_u64_t rack_fto_send;
369 counter_u64_t rack_fto_rsm_send;
370 counter_u64_t rack_nfto_resend;
371 counter_u64_t rack_non_fto_send;
372 counter_u64_t rack_extended_rfo;
373
374 counter_u64_t rack_sack_proc_all;
375 counter_u64_t rack_sack_proc_short;
376 counter_u64_t rack_sack_proc_restart;
377 counter_u64_t rack_sack_attacks_detected;
378 counter_u64_t rack_sack_attacks_reversed;
379 counter_u64_t rack_sack_used_next_merge;
380 counter_u64_t rack_sack_splits;
381 counter_u64_t rack_sack_used_prev_merge;
382 counter_u64_t rack_sack_skipped_acked;
383 counter_u64_t rack_ack_total;
384 counter_u64_t rack_express_sack;
385 counter_u64_t rack_sack_total;
386 counter_u64_t rack_move_none;
387 counter_u64_t rack_move_some;
388
389 counter_u64_t rack_used_tlpmethod;
390 counter_u64_t rack_used_tlpmethod2;
391 counter_u64_t rack_enter_tlp_calc;
392 counter_u64_t rack_input_idle_reduces;
393 counter_u64_t rack_collapsed_win;
394 counter_u64_t rack_tlp_does_nada;
395 counter_u64_t rack_try_scwnd;
396 counter_u64_t rack_hw_pace_init_fail;
397 counter_u64_t rack_hw_pace_lost;
398 counter_u64_t rack_sbsndptr_right;
399 counter_u64_t rack_sbsndptr_wrong;
400
401 /* Temp CPU counters */
402 counter_u64_t rack_find_high;
403
404 counter_u64_t rack_progress_drops;
405 counter_u64_t rack_out_size[TCP_MSS_ACCT_SIZE];
406 counter_u64_t rack_opts_arry[RACK_OPTS_SIZE];
407
408
409 #define RACK_REXMTVAL(tp) max(rack_rto_min, ((tp)->t_srtt + ((tp)->t_rttvar << 2)))
410
411 #define RACK_TCPT_RANGESET(tv, value, tvmin, tvmax) do { \
412         (tv) = (value) + TICKS_2_USEC(tcp_rexmit_slop);  \
413         if ((u_long)(tv) < (u_long)(tvmin)) \
414                 (tv) = (tvmin); \
415         if ((u_long)(tv) > (u_long)(tvmax)) \
416                 (tv) = (tvmax); \
417 } while (0)
418
419 static void
420 rack_log_progress_event(struct tcp_rack *rack, struct tcpcb *tp, uint32_t tick,  int event, int line);
421
422 static int
423 rack_process_ack(struct mbuf *m, struct tcphdr *th,
424     struct socket *so, struct tcpcb *tp, struct tcpopt *to,
425     uint32_t tiwin, int32_t tlen, int32_t * ofia, int32_t thflags, int32_t * ret_val);
426 static int
427 rack_process_data(struct mbuf *m, struct tcphdr *th,
428     struct socket *so, struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
429     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
430 static void
431 rack_ack_received(struct tcpcb *tp, struct tcp_rack *rack,
432    uint32_t th_ack, uint16_t nsegs, uint16_t type, int32_t recovery);
433 static struct rack_sendmap *rack_alloc(struct tcp_rack *rack);
434 static struct rack_sendmap *rack_alloc_limit(struct tcp_rack *rack,
435     uint8_t limit_type);
436 static struct rack_sendmap *
437 rack_check_recovery_mode(struct tcpcb *tp,
438     uint32_t tsused);
439 static void
440 rack_cong_signal(struct tcpcb *tp,
441                  uint32_t type, uint32_t ack);
442 static void rack_counter_destroy(void);
443 static int
444 rack_ctloutput(struct socket *so, struct sockopt *sopt,
445     struct inpcb *inp, struct tcpcb *tp);
446 static int32_t rack_ctor(void *mem, int32_t size, void *arg, int32_t how);
447 static void
448 rack_set_pace_segments(struct tcpcb *tp, struct tcp_rack *rack, uint32_t line, uint64_t *fill_override);
449 static void
450 rack_do_segment(struct mbuf *m, struct tcphdr *th,
451     struct socket *so, struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
452     uint8_t iptos);
453 static void rack_dtor(void *mem, int32_t size, void *arg);
454 static void
455 rack_log_alt_to_to_cancel(struct tcp_rack *rack,
456     uint32_t flex1, uint32_t flex2,
457     uint32_t flex3, uint32_t flex4,
458     uint32_t flex5, uint32_t flex6,
459     uint16_t flex7, uint8_t mod);
460 static void
461 rack_log_pacing_delay_calc(struct tcp_rack *rack, uint32_t len, uint32_t slot,
462    uint64_t bw_est, uint64_t bw, uint64_t len_time, int method, int line, struct rack_sendmap *rsm);
463 static struct rack_sendmap *
464 rack_find_high_nonack(struct tcp_rack *rack,
465     struct rack_sendmap *rsm);
466 static struct rack_sendmap *rack_find_lowest_rsm(struct tcp_rack *rack);
467 static void rack_free(struct tcp_rack *rack, struct rack_sendmap *rsm);
468 static void rack_fini(struct tcpcb *tp, int32_t tcb_is_purged);
469 static int
470 rack_get_sockopt(struct socket *so, struct sockopt *sopt,
471     struct inpcb *inp, struct tcpcb *tp, struct tcp_rack *rack);
472 static void
473 rack_do_goodput_measurement(struct tcpcb *tp, struct tcp_rack *rack,
474                             tcp_seq th_ack, int line);
475 static uint32_t
476 rack_get_pacing_len(struct tcp_rack *rack, uint64_t bw, uint32_t mss);
477 static int32_t rack_handoff_ok(struct tcpcb *tp);
478 static int32_t rack_init(struct tcpcb *tp);
479 static void rack_init_sysctls(void);
480 static void
481 rack_log_ack(struct tcpcb *tp, struct tcpopt *to,
482     struct tcphdr *th, int entered_rec, int dup_ack_struck);
483 static void
484 rack_log_output(struct tcpcb *tp, struct tcpopt *to, int32_t len,
485     uint32_t seq_out, uint8_t th_flags, int32_t err, uint64_t ts,
486     struct rack_sendmap *hintrsm, uint16_t add_flags, struct mbuf *s_mb, uint32_t s_moff);
487
488 static void
489 rack_log_sack_passed(struct tcpcb *tp, struct tcp_rack *rack,
490     struct rack_sendmap *rsm);
491 static void rack_log_to_event(struct tcp_rack *rack, int32_t to_num, struct rack_sendmap *rsm);
492 static int32_t rack_output(struct tcpcb *tp);
493
494 static uint32_t
495 rack_proc_sack_blk(struct tcpcb *tp, struct tcp_rack *rack,
496     struct sackblk *sack, struct tcpopt *to, struct rack_sendmap **prsm,
497     uint32_t cts, int *moved_two);
498 static void rack_post_recovery(struct tcpcb *tp, uint32_t th_seq);
499 static void rack_remxt_tmr(struct tcpcb *tp);
500 static int
501 rack_set_sockopt(struct socket *so, struct sockopt *sopt,
502     struct inpcb *inp, struct tcpcb *tp, struct tcp_rack *rack);
503 static void rack_set_state(struct tcpcb *tp, struct tcp_rack *rack);
504 static int32_t rack_stopall(struct tcpcb *tp);
505 static void
506 rack_timer_activate(struct tcpcb *tp, uint32_t timer_type,
507     uint32_t delta);
508 static int32_t rack_timer_active(struct tcpcb *tp, uint32_t timer_type);
509 static void rack_timer_cancel(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, int line);
510 static void rack_timer_stop(struct tcpcb *tp, uint32_t timer_type);
511 static uint32_t
512 rack_update_entry(struct tcpcb *tp, struct tcp_rack *rack,
513     struct rack_sendmap *rsm, uint64_t ts, int32_t * lenp, uint16_t add_flag);
514 static void
515 rack_update_rsm(struct tcpcb *tp, struct tcp_rack *rack,
516     struct rack_sendmap *rsm, uint64_t ts, uint16_t add_flag);
517 static int
518 rack_update_rtt(struct tcpcb *tp, struct tcp_rack *rack,
519     struct rack_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, tcp_seq th_ack);
520 static int32_t tcp_addrack(module_t mod, int32_t type, void *data);
521 static int
522 rack_do_close_wait(struct mbuf *m, struct tcphdr *th,
523     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
524     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
525 static int
526 rack_do_closing(struct mbuf *m, struct tcphdr *th,
527     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
528     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
529 static int
530 rack_do_established(struct mbuf *m, struct tcphdr *th,
531     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
532     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
533 static int
534 rack_do_fastnewdata(struct mbuf *m, struct tcphdr *th,
535     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
536     int32_t tlen, uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos);
537 static int
538 rack_do_fin_wait_1(struct mbuf *m, struct tcphdr *th,
539     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
540     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
541 static int
542 rack_do_fin_wait_2(struct mbuf *m, struct tcphdr *th,
543     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
544     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
545 static int
546 rack_do_lastack(struct mbuf *m, struct tcphdr *th,
547     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
548     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
549 static int
550 rack_do_syn_recv(struct mbuf *m, struct tcphdr *th,
551     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
552     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
553 static int
554 rack_do_syn_sent(struct mbuf *m, struct tcphdr *th,
555     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
556     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
557 struct rack_sendmap *
558 tcp_rack_output(struct tcpcb *tp, struct tcp_rack *rack,
559     uint32_t tsused);
560 static void tcp_rack_xmit_timer(struct tcp_rack *rack, int32_t rtt,
561     uint32_t len, uint32_t us_tim, int confidence, struct rack_sendmap *rsm, uint16_t rtrcnt);
562 static void
563      tcp_rack_partialack(struct tcpcb *tp);
564 static int
565 rack_set_profile(struct tcp_rack *rack, int prof);
566 static void
567 rack_apply_deferred_options(struct tcp_rack *rack);
568
569 int32_t rack_clear_counter=0;
570
571 static void
572 rack_set_cc_pacing(struct tcp_rack *rack)
573 {
574         struct sockopt sopt;
575         struct cc_newreno_opts opt;
576         struct newreno old, *ptr;
577         struct tcpcb *tp;
578         int error;
579
580         if (rack->rc_pacing_cc_set)
581                 return;
582
583         tp = rack->rc_tp;
584         if (tp->cc_algo == NULL) {
585                 /* Tcb is leaving */
586                 printf("No cc algorithm?\n");
587                 return;
588         }
589         rack->rc_pacing_cc_set = 1;
590         if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0) {
591                 /* Not new-reno we can't play games with beta! */
592                 printf("cc_algo:%s is not NEWRENO:%s\n",
593                        tp->cc_algo->name, CCALGONAME_NEWRENO);
594                 goto out;
595         }
596         ptr = ((struct newreno *)tp->ccv->cc_data);
597         if (CC_ALGO(tp)->ctl_output == NULL)  {
598                 /* Huh, why does new_reno no longer have a set function? */
599                 printf("no ctl_output for algo:%s\n", tp->cc_algo->name);
600                 goto out;
601         }
602         if (ptr == NULL) {
603                 /* Just the default values */
604                 old.beta = V_newreno_beta_ecn;
605                 old.beta_ecn = V_newreno_beta_ecn;
606                 old.newreno_flags = 0;
607         } else {
608                 old.beta = ptr->beta;
609                 old.beta_ecn = ptr->beta_ecn;
610                 old.newreno_flags = ptr->newreno_flags;
611         }
612         sopt.sopt_valsize = sizeof(struct cc_newreno_opts);
613         sopt.sopt_dir = SOPT_SET;
614         opt.name = CC_NEWRENO_BETA;
615         opt.val = rack->r_ctl.rc_saved_beta.beta;
616         error = CC_ALGO(tp)->ctl_output(tp->ccv, &sopt, &opt);
617         if (error)  {
618                 printf("Error returned by ctl_output %d\n", error);
619                 goto out;
620         }
621         /*
622          * Hack alert we need to set in our newreno_flags
623          * so that Abe behavior is also applied.
624          */
625         ((struct newreno *)tp->ccv->cc_data)->newreno_flags = CC_NEWRENO_BETA_ECN;
626         opt.name = CC_NEWRENO_BETA_ECN;
627         opt.val = rack->r_ctl.rc_saved_beta.beta_ecn;
628         error = CC_ALGO(tp)->ctl_output(tp->ccv, &sopt, &opt);
629         if (error) {
630                 printf("Error returned by ctl_output %d\n", 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         int i;
739
740         error = SYSCTL_OUT(req, &rack_clear_counter, sizeof(uint32_t));
741         if (error || req->newptr == NULL)
742                 return error;
743
744         error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
745         if (error)
746                 return (error);
747         if (stat == 1) {
748 #ifdef INVARIANTS
749                 printf("Clearing RACK counters\n");
750 #endif
751                 counter_u64_zero(rack_badfr);
752                 counter_u64_zero(rack_badfr_bytes);
753                 counter_u64_zero(rack_rtm_prr_retran);
754                 counter_u64_zero(rack_rtm_prr_newdata);
755                 counter_u64_zero(rack_timestamp_mismatch);
756                 counter_u64_zero(rack_reorder_seen);
757                 counter_u64_zero(rack_tlp_tot);
758                 counter_u64_zero(rack_tlp_newdata);
759                 counter_u64_zero(rack_tlp_retran);
760                 counter_u64_zero(rack_tlp_retran_bytes);
761                 counter_u64_zero(rack_tlp_retran_fail);
762                 counter_u64_zero(rack_to_tot);
763                 counter_u64_zero(rack_to_arm_rack);
764                 counter_u64_zero(rack_to_arm_tlp);
765                 counter_u64_zero(rack_paced_segments);
766                 counter_u64_zero(rack_calc_zero);
767                 counter_u64_zero(rack_calc_nonzero);
768                 counter_u64_zero(rack_unpaced_segments);
769                 counter_u64_zero(rack_saw_enobuf);
770                 counter_u64_zero(rack_saw_enobuf_hw);
771                 counter_u64_zero(rack_saw_enetunreach);
772                 counter_u64_zero(rack_per_timer_hole);
773                 counter_u64_zero(rack_large_ackcmp);
774                 counter_u64_zero(rack_small_ackcmp);
775 #ifdef INVARIANTS
776                 counter_u64_zero(rack_adjust_map_bw);
777 #endif
778                 counter_u64_zero(rack_to_alloc_hard);
779                 counter_u64_zero(rack_to_alloc_emerg);
780                 counter_u64_zero(rack_sack_proc_all);
781                 counter_u64_zero(rack_fto_send);
782                 counter_u64_zero(rack_fto_rsm_send);
783                 counter_u64_zero(rack_extended_rfo);
784                 counter_u64_zero(rack_hw_pace_init_fail);
785                 counter_u64_zero(rack_hw_pace_lost);
786                 counter_u64_zero(rack_sbsndptr_wrong);
787                 counter_u64_zero(rack_sbsndptr_right);
788                 counter_u64_zero(rack_non_fto_send);
789                 counter_u64_zero(rack_nfto_resend);
790                 counter_u64_zero(rack_sack_proc_short);
791                 counter_u64_zero(rack_sack_proc_restart);
792                 counter_u64_zero(rack_to_alloc);
793                 counter_u64_zero(rack_to_alloc_limited);
794                 counter_u64_zero(rack_alloc_limited_conns);
795                 counter_u64_zero(rack_split_limited);
796                 for (i = 0; i < MAX_NUM_OF_CNTS; i++) {
797                         counter_u64_zero(rack_proc_comp_ack[i]);
798                 }
799                 counter_u64_zero(rack_multi_single_eq);
800                 counter_u64_zero(rack_proc_non_comp_ack);
801                 counter_u64_zero(rack_find_high);
802                 counter_u64_zero(rack_sack_attacks_detected);
803                 counter_u64_zero(rack_sack_attacks_reversed);
804                 counter_u64_zero(rack_sack_used_next_merge);
805                 counter_u64_zero(rack_sack_used_prev_merge);
806                 counter_u64_zero(rack_sack_splits);
807                 counter_u64_zero(rack_sack_skipped_acked);
808                 counter_u64_zero(rack_ack_total);
809                 counter_u64_zero(rack_express_sack);
810                 counter_u64_zero(rack_sack_total);
811                 counter_u64_zero(rack_move_none);
812                 counter_u64_zero(rack_move_some);
813                 counter_u64_zero(rack_used_tlpmethod);
814                 counter_u64_zero(rack_used_tlpmethod2);
815                 counter_u64_zero(rack_enter_tlp_calc);
816                 counter_u64_zero(rack_progress_drops);
817                 counter_u64_zero(rack_tlp_does_nada);
818                 counter_u64_zero(rack_try_scwnd);
819                 counter_u64_zero(rack_collapsed_win);
820         }
821         rack_clear_counter = 0;
822         return (0);
823 }
824
825 static void
826 rack_init_sysctls(void)
827 {
828         int i;
829         struct sysctl_oid *rack_counters;
830         struct sysctl_oid *rack_attack;
831         struct sysctl_oid *rack_pacing;
832         struct sysctl_oid *rack_timely;
833         struct sysctl_oid *rack_timers;
834         struct sysctl_oid *rack_tlp;
835         struct sysctl_oid *rack_misc;
836         struct sysctl_oid *rack_measure;
837         struct sysctl_oid *rack_probertt;
838         struct sysctl_oid *rack_hw_pacing;
839
840         rack_attack = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
841             SYSCTL_CHILDREN(rack_sysctl_root),
842             OID_AUTO,
843             "sack_attack",
844             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
845             "Rack Sack Attack Counters and Controls");
846         rack_counters = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
847             SYSCTL_CHILDREN(rack_sysctl_root),
848             OID_AUTO,
849             "stats",
850             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
851             "Rack Counters");
852         SYSCTL_ADD_S32(&rack_sysctl_ctx,
853             SYSCTL_CHILDREN(rack_sysctl_root),
854             OID_AUTO, "rate_sample_method", CTLFLAG_RW,
855             &rack_rate_sample_method , USE_RTT_LOW,
856             "What method should we use for rate sampling 0=high, 1=low ");
857         /* Probe rtt related controls */
858         rack_probertt = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
859             SYSCTL_CHILDREN(rack_sysctl_root),
860             OID_AUTO,
861             "probertt",
862             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
863             "ProbeRTT related Controls");
864         SYSCTL_ADD_U16(&rack_sysctl_ctx,
865             SYSCTL_CHILDREN(rack_probertt),
866             OID_AUTO, "exit_per_hpb", CTLFLAG_RW,
867             &rack_atexit_prtt_hbp, 130,
868             "What percentage above goodput do we clamp CA/SS to at exit on high-BDP path 110%");
869         SYSCTL_ADD_U16(&rack_sysctl_ctx,
870             SYSCTL_CHILDREN(rack_probertt),
871             OID_AUTO, "exit_per_nonhpb", CTLFLAG_RW,
872             &rack_atexit_prtt, 130,
873             "What percentage above goodput do we clamp CA/SS to at exit on a non high-BDP path 100%");
874         SYSCTL_ADD_U16(&rack_sysctl_ctx,
875             SYSCTL_CHILDREN(rack_probertt),
876             OID_AUTO, "gp_per_mul", CTLFLAG_RW,
877             &rack_per_of_gp_probertt, 60,
878             "What percentage of goodput do we pace at in probertt");
879         SYSCTL_ADD_U16(&rack_sysctl_ctx,
880             SYSCTL_CHILDREN(rack_probertt),
881             OID_AUTO, "gp_per_reduce", CTLFLAG_RW,
882             &rack_per_of_gp_probertt_reduce, 10,
883             "What percentage of goodput do we reduce every gp_srtt");
884         SYSCTL_ADD_U16(&rack_sysctl_ctx,
885             SYSCTL_CHILDREN(rack_probertt),
886             OID_AUTO, "gp_per_low", CTLFLAG_RW,
887             &rack_per_of_gp_lowthresh, 40,
888             "What percentage of goodput do we allow the multiplier to fall to");
889         SYSCTL_ADD_U32(&rack_sysctl_ctx,
890             SYSCTL_CHILDREN(rack_probertt),
891             OID_AUTO, "time_between", CTLFLAG_RW,
892             & rack_time_between_probertt, 96000000,
893             "How many useconds between the lowest rtt falling must past before we enter probertt");
894         SYSCTL_ADD_U32(&rack_sysctl_ctx,
895             SYSCTL_CHILDREN(rack_probertt),
896             OID_AUTO, "safety", CTLFLAG_RW,
897             &rack_probe_rtt_safety_val, 2000000,
898             "If not zero, provides a maximum usecond that you can stay in probertt (2sec = 2000000)");
899         SYSCTL_ADD_U32(&rack_sysctl_ctx,
900             SYSCTL_CHILDREN(rack_probertt),
901             OID_AUTO, "sets_cwnd", CTLFLAG_RW,
902             &rack_probe_rtt_sets_cwnd, 0,
903             "Do we set the cwnd too (if always_lower is on)");
904         SYSCTL_ADD_U32(&rack_sysctl_ctx,
905             SYSCTL_CHILDREN(rack_probertt),
906             OID_AUTO, "maxdrainsrtts", CTLFLAG_RW,
907             &rack_max_drain_wait, 2,
908             "Maximum number of gp_srtt's to hold in drain waiting for flight to reach goal");
909         SYSCTL_ADD_U32(&rack_sysctl_ctx,
910             SYSCTL_CHILDREN(rack_probertt),
911             OID_AUTO, "mustdrainsrtts", CTLFLAG_RW,
912             &rack_must_drain, 1,
913             "We must drain this many gp_srtt's waiting for flight to reach goal");
914         SYSCTL_ADD_U32(&rack_sysctl_ctx,
915             SYSCTL_CHILDREN(rack_probertt),
916             OID_AUTO, "goal_use_min_entry", CTLFLAG_RW,
917             &rack_probertt_use_min_rtt_entry, 1,
918             "Should we use the min-rtt to calculate the goal rtt (else gp_srtt) at entry");
919         SYSCTL_ADD_U32(&rack_sysctl_ctx,
920             SYSCTL_CHILDREN(rack_probertt),
921             OID_AUTO, "goal_use_min_exit", CTLFLAG_RW,
922             &rack_probertt_use_min_rtt_exit, 0,
923             "How to set cwnd at exit, 0 - dynamic, 1 - use min-rtt, 2 - use curgprtt, 3 - entry gp-rtt");
924         SYSCTL_ADD_U32(&rack_sysctl_ctx,
925             SYSCTL_CHILDREN(rack_probertt),
926             OID_AUTO, "length_div", CTLFLAG_RW,
927             &rack_probertt_gpsrtt_cnt_div, 0,
928             "How many recent goodput srtt periods plus hold tim does probertt last (bottom of fraction)");
929         SYSCTL_ADD_U32(&rack_sysctl_ctx,
930             SYSCTL_CHILDREN(rack_probertt),
931             OID_AUTO, "length_mul", CTLFLAG_RW,
932             &rack_probertt_gpsrtt_cnt_mul, 0,
933             "How many recent goodput srtt periods plus hold tim does probertt last (top of fraction)");
934         SYSCTL_ADD_U32(&rack_sysctl_ctx,
935             SYSCTL_CHILDREN(rack_probertt),
936             OID_AUTO, "holdtim_at_target", CTLFLAG_RW,
937             &rack_min_probertt_hold, 200000,
938             "What is the minimum time we hold probertt at target");
939         SYSCTL_ADD_U32(&rack_sysctl_ctx,
940             SYSCTL_CHILDREN(rack_probertt),
941             OID_AUTO, "filter_life", CTLFLAG_RW,
942             &rack_probertt_filter_life, 10000000,
943             "What is the time for the filters life in useconds");
944         SYSCTL_ADD_U32(&rack_sysctl_ctx,
945             SYSCTL_CHILDREN(rack_probertt),
946             OID_AUTO, "lower_within", CTLFLAG_RW,
947             &rack_probertt_lower_within, 10,
948             "If the rtt goes lower within this percentage of the time, go into probe-rtt");
949         SYSCTL_ADD_U32(&rack_sysctl_ctx,
950             SYSCTL_CHILDREN(rack_probertt),
951             OID_AUTO, "must_move", CTLFLAG_RW,
952             &rack_min_rtt_movement, 250,
953             "How much is the minimum movement in rtt to count as a drop for probertt purposes");
954         SYSCTL_ADD_U32(&rack_sysctl_ctx,
955             SYSCTL_CHILDREN(rack_probertt),
956             OID_AUTO, "clear_is_cnts", CTLFLAG_RW,
957             &rack_probertt_clear_is, 1,
958             "Do we clear I/S counts on exiting probe-rtt");
959         SYSCTL_ADD_S32(&rack_sysctl_ctx,
960             SYSCTL_CHILDREN(rack_probertt),
961             OID_AUTO, "hbp_extra_drain", CTLFLAG_RW,
962             &rack_max_drain_hbp, 1,
963             "How many extra drain gpsrtt's do we get in highly buffered paths");
964         SYSCTL_ADD_S32(&rack_sysctl_ctx,
965             SYSCTL_CHILDREN(rack_probertt),
966             OID_AUTO, "hbp_threshold", CTLFLAG_RW,
967             &rack_hbp_thresh, 3,
968             "We are highly buffered if min_rtt_seen / max_rtt_seen > this-threshold");
969         /* Pacing related sysctls */
970         rack_pacing = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
971             SYSCTL_CHILDREN(rack_sysctl_root),
972             OID_AUTO,
973             "pacing",
974             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
975             "Pacing related Controls");
976         SYSCTL_ADD_S32(&rack_sysctl_ctx,
977             SYSCTL_CHILDREN(rack_pacing),
978             OID_AUTO, "max_pace_over", CTLFLAG_RW,
979             &rack_max_per_above, 30,
980             "What is the maximum allowable percentage that we can pace above (so 30 = 130% of our goal)");
981         SYSCTL_ADD_S32(&rack_sysctl_ctx,
982             SYSCTL_CHILDREN(rack_pacing),
983             OID_AUTO, "pace_to_one", CTLFLAG_RW,
984             &rack_pace_one_seg, 0,
985             "Do we allow low b/w pacing of 1MSS instead of two");
986         SYSCTL_ADD_S32(&rack_sysctl_ctx,
987             SYSCTL_CHILDREN(rack_pacing),
988             OID_AUTO, "limit_wsrtt", CTLFLAG_RW,
989             &rack_limit_time_with_srtt, 0,
990             "Do we limit pacing time based on srtt");
991         SYSCTL_ADD_S32(&rack_sysctl_ctx,
992             SYSCTL_CHILDREN(rack_pacing),
993             OID_AUTO, "init_win", CTLFLAG_RW,
994             &rack_default_init_window, 0,
995             "Do we have a rack initial window 0 = system default");
996         SYSCTL_ADD_U16(&rack_sysctl_ctx,
997             SYSCTL_CHILDREN(rack_pacing),
998             OID_AUTO, "gp_per_ss", CTLFLAG_RW,
999             &rack_per_of_gp_ss, 250,
1000             "If non zero, what percentage of goodput to pace at in slow start");
1001         SYSCTL_ADD_U16(&rack_sysctl_ctx,
1002             SYSCTL_CHILDREN(rack_pacing),
1003             OID_AUTO, "gp_per_ca", CTLFLAG_RW,
1004             &rack_per_of_gp_ca, 150,
1005             "If non zero, what percentage of goodput to pace at in congestion avoidance");
1006         SYSCTL_ADD_U16(&rack_sysctl_ctx,
1007             SYSCTL_CHILDREN(rack_pacing),
1008             OID_AUTO, "gp_per_rec", CTLFLAG_RW,
1009             &rack_per_of_gp_rec, 200,
1010             "If non zero, what percentage of goodput to pace at in recovery");
1011         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1012             SYSCTL_CHILDREN(rack_pacing),
1013             OID_AUTO, "pace_max_seg", CTLFLAG_RW,
1014             &rack_hptsi_segments, 40,
1015             "What size is the max for TSO segments in pacing and burst mitigation");
1016         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1017             SYSCTL_CHILDREN(rack_pacing),
1018             OID_AUTO, "burst_reduces", CTLFLAG_RW,
1019             &rack_slot_reduction, 4,
1020             "When doing only burst mitigation what is the reduce divisor");
1021         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1022             SYSCTL_CHILDREN(rack_sysctl_root),
1023             OID_AUTO, "use_pacing", CTLFLAG_RW,
1024             &rack_pace_every_seg, 0,
1025             "If set we use pacing, if clear we use only the original burst mitigation");
1026         SYSCTL_ADD_U64(&rack_sysctl_ctx,
1027             SYSCTL_CHILDREN(rack_pacing),
1028             OID_AUTO, "rate_cap", CTLFLAG_RW,
1029             &rack_bw_rate_cap, 0,
1030             "If set we apply this value to the absolute rate cap used by pacing");
1031         SYSCTL_ADD_U8(&rack_sysctl_ctx,
1032             SYSCTL_CHILDREN(rack_sysctl_root),
1033             OID_AUTO, "req_measure_cnt", CTLFLAG_RW,
1034             &rack_req_measurements, 1,
1035             "If doing dynamic pacing, how many measurements must be in before we start pacing?");
1036         /* Hardware pacing */
1037         rack_hw_pacing = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1038             SYSCTL_CHILDREN(rack_sysctl_root),
1039             OID_AUTO,
1040             "hdwr_pacing",
1041             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1042             "Pacing related Controls");
1043         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1044             SYSCTL_CHILDREN(rack_hw_pacing),
1045             OID_AUTO, "rwnd_factor", CTLFLAG_RW,
1046             &rack_hw_rwnd_factor, 2,
1047             "How many times does snd_wnd need to be bigger than pace_max_seg so we will hold off and get more acks?");
1048         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1049             SYSCTL_CHILDREN(rack_hw_pacing),
1050             OID_AUTO, "pace_enobuf_mult", CTLFLAG_RW,
1051             &rack_enobuf_hw_boost_mult, 2,
1052             "By how many time_betweens should we boost the pacing time if we see a ENOBUFS?");
1053         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1054             SYSCTL_CHILDREN(rack_hw_pacing),
1055             OID_AUTO, "pace_enobuf_max", CTLFLAG_RW,
1056             &rack_enobuf_hw_max, 2,
1057             "What is the max boost the pacing time if we see a ENOBUFS?");
1058         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1059             SYSCTL_CHILDREN(rack_hw_pacing),
1060             OID_AUTO, "pace_enobuf_min", CTLFLAG_RW,
1061             &rack_enobuf_hw_min, 2,
1062             "What is the min boost the pacing time if we see a ENOBUFS?");
1063         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1064             SYSCTL_CHILDREN(rack_hw_pacing),
1065             OID_AUTO, "enable", CTLFLAG_RW,
1066             &rack_enable_hw_pacing, 0,
1067             "Should RACK attempt to use hw pacing?");
1068         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1069             SYSCTL_CHILDREN(rack_hw_pacing),
1070             OID_AUTO, "rate_cap", CTLFLAG_RW,
1071             &rack_hw_rate_caps, 1,
1072             "Does the highest hardware pacing rate cap the rate we will send at??");
1073         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1074             SYSCTL_CHILDREN(rack_hw_pacing),
1075             OID_AUTO, "rate_min", CTLFLAG_RW,
1076             &rack_hw_rate_min, 0,
1077             "Do we need a minimum estimate of this many bytes per second in order to engage hw pacing?");
1078         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1079             SYSCTL_CHILDREN(rack_hw_pacing),
1080             OID_AUTO, "rate_to_low", CTLFLAG_RW,
1081             &rack_hw_rate_to_low, 0,
1082             "If we fall below this rate, dis-engage hw pacing?");
1083         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1084             SYSCTL_CHILDREN(rack_hw_pacing),
1085             OID_AUTO, "up_only", CTLFLAG_RW,
1086             &rack_hw_up_only, 1,
1087             "Do we allow hw pacing to lower the rate selected?");
1088         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1089             SYSCTL_CHILDREN(rack_hw_pacing),
1090             OID_AUTO, "extra_mss_precise", CTLFLAG_RW,
1091             &rack_hw_pace_extra_slots, 2,
1092             "If the rates between software and hardware match precisely how many extra time_betweens do we get?");
1093         rack_timely = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1094             SYSCTL_CHILDREN(rack_sysctl_root),
1095             OID_AUTO,
1096             "timely",
1097             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1098             "Rack Timely RTT Controls");
1099         /* Timely based GP dynmics */
1100         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1101             SYSCTL_CHILDREN(rack_timely),
1102             OID_AUTO, "upper", CTLFLAG_RW,
1103             &rack_gp_per_bw_mul_up, 2,
1104             "Rack timely upper range for equal b/w (in percentage)");
1105         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1106             SYSCTL_CHILDREN(rack_timely),
1107             OID_AUTO, "lower", CTLFLAG_RW,
1108             &rack_gp_per_bw_mul_down, 4,
1109             "Rack timely lower range for equal b/w (in percentage)");
1110         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1111             SYSCTL_CHILDREN(rack_timely),
1112             OID_AUTO, "rtt_max_mul", CTLFLAG_RW,
1113             &rack_gp_rtt_maxmul, 3,
1114             "Rack timely multipler of lowest rtt for rtt_max");
1115         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1116             SYSCTL_CHILDREN(rack_timely),
1117             OID_AUTO, "rtt_min_div", CTLFLAG_RW,
1118             &rack_gp_rtt_mindiv, 4,
1119             "Rack timely divisor used for rtt + (rtt * mul/divisor) for check for lower rtt");
1120         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1121             SYSCTL_CHILDREN(rack_timely),
1122             OID_AUTO, "rtt_min_mul", CTLFLAG_RW,
1123             &rack_gp_rtt_minmul, 1,
1124             "Rack timely multiplier used for rtt + (rtt * mul/divisor) for check for lower rtt");
1125         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1126             SYSCTL_CHILDREN(rack_timely),
1127             OID_AUTO, "decrease", CTLFLAG_RW,
1128             &rack_gp_decrease_per, 20,
1129             "Rack timely decrease percentage of our GP multiplication factor");
1130         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1131             SYSCTL_CHILDREN(rack_timely),
1132             OID_AUTO, "increase", CTLFLAG_RW,
1133             &rack_gp_increase_per, 2,
1134             "Rack timely increase perentage of our GP multiplication factor");
1135         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1136             SYSCTL_CHILDREN(rack_timely),
1137             OID_AUTO, "lowerbound", CTLFLAG_RW,
1138             &rack_per_lower_bound, 50,
1139             "Rack timely lowest percentage we allow GP multiplier to fall to");
1140         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1141             SYSCTL_CHILDREN(rack_timely),
1142             OID_AUTO, "upperboundss", CTLFLAG_RW,
1143             &rack_per_upper_bound_ss, 0,
1144             "Rack timely higest percentage we allow GP multiplier in SS to raise to (0 is no upperbound)");
1145         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1146             SYSCTL_CHILDREN(rack_timely),
1147             OID_AUTO, "upperboundca", CTLFLAG_RW,
1148             &rack_per_upper_bound_ca, 0,
1149             "Rack timely higest percentage we allow GP multiplier to CA raise to (0 is no upperbound)");
1150         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1151             SYSCTL_CHILDREN(rack_timely),
1152             OID_AUTO, "dynamicgp", CTLFLAG_RW,
1153             &rack_do_dyn_mul, 0,
1154             "Rack timely do we enable dynmaic timely goodput by default");
1155         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1156             SYSCTL_CHILDREN(rack_timely),
1157             OID_AUTO, "no_rec_red", CTLFLAG_RW,
1158             &rack_gp_no_rec_chg, 1,
1159             "Rack timely do we prohibit the recovery multiplier from being lowered");
1160         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1161             SYSCTL_CHILDREN(rack_timely),
1162             OID_AUTO, "red_clear_cnt", CTLFLAG_RW,
1163             &rack_timely_dec_clear, 6,
1164             "Rack timely what threshold do we count to before another boost during b/w decent");
1165         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1166             SYSCTL_CHILDREN(rack_timely),
1167             OID_AUTO, "max_push_rise", CTLFLAG_RW,
1168             &rack_timely_max_push_rise, 3,
1169             "Rack timely how many times do we push up with b/w increase");
1170         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1171             SYSCTL_CHILDREN(rack_timely),
1172             OID_AUTO, "max_push_drop", CTLFLAG_RW,
1173             &rack_timely_max_push_drop, 3,
1174             "Rack timely how many times do we push back on b/w decent");
1175         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1176             SYSCTL_CHILDREN(rack_timely),
1177             OID_AUTO, "min_segs", CTLFLAG_RW,
1178             &rack_timely_min_segs, 4,
1179             "Rack timely when setting the cwnd what is the min num segments");
1180         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1181             SYSCTL_CHILDREN(rack_timely),
1182             OID_AUTO, "noback_max", CTLFLAG_RW,
1183             &rack_use_max_for_nobackoff, 0,
1184             "Rack timely when deciding if to backoff on a loss, do we use under max rtt else min");
1185         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1186             SYSCTL_CHILDREN(rack_timely),
1187             OID_AUTO, "interim_timely_only", CTLFLAG_RW,
1188             &rack_timely_int_timely_only, 0,
1189             "Rack timely when doing interim timely's do we only do timely (no b/w consideration)");
1190         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1191             SYSCTL_CHILDREN(rack_timely),
1192             OID_AUTO, "nonstop", CTLFLAG_RW,
1193             &rack_timely_no_stopping, 0,
1194             "Rack timely don't stop increase");
1195         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1196             SYSCTL_CHILDREN(rack_timely),
1197             OID_AUTO, "dec_raise_thresh", CTLFLAG_RW,
1198             &rack_down_raise_thresh, 100,
1199             "If the CA or SS is below this threshold raise on the first 3 b/w lowers (0=always)");
1200         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1201             SYSCTL_CHILDREN(rack_timely),
1202             OID_AUTO, "bottom_drag_segs", CTLFLAG_RW,
1203             &rack_req_segs, 1,
1204             "Bottom dragging if not these many segments outstanding and room");
1205
1206         /* TLP and Rack related parameters */
1207         rack_tlp = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1208             SYSCTL_CHILDREN(rack_sysctl_root),
1209             OID_AUTO,
1210             "tlp",
1211             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1212             "TLP and Rack related Controls");
1213         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1214             SYSCTL_CHILDREN(rack_tlp),
1215             OID_AUTO, "use_rrr", CTLFLAG_RW,
1216             &use_rack_rr, 1,
1217             "Do we use Rack Rapid Recovery");
1218         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1219             SYSCTL_CHILDREN(rack_tlp),
1220             OID_AUTO, "post_rec_labc", CTLFLAG_RW,
1221             &rack_max_abc_post_recovery, 2,
1222             "Since we do early recovery, do we override the l_abc to a value, if so what?");
1223         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1224             SYSCTL_CHILDREN(rack_tlp),
1225             OID_AUTO, "nonrxt_use_cr", CTLFLAG_RW,
1226             &rack_non_rxt_use_cr, 0,
1227             "Do we use ss/ca rate if in recovery we are transmitting a new data chunk");
1228         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1229             SYSCTL_CHILDREN(rack_tlp),
1230             OID_AUTO, "tlpmethod", CTLFLAG_RW,
1231             &rack_tlp_threshold_use, TLP_USE_TWO_ONE,
1232             "What method do we do for TLP time calc 0=no-de-ack-comp, 1=ID, 2=2.1, 3=2.2");
1233         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1234             SYSCTL_CHILDREN(rack_tlp),
1235             OID_AUTO, "limit", CTLFLAG_RW,
1236             &rack_tlp_limit, 2,
1237             "How many TLP's can be sent without sending new data");
1238         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1239             SYSCTL_CHILDREN(rack_tlp),
1240             OID_AUTO, "use_greater", CTLFLAG_RW,
1241             &rack_tlp_use_greater, 1,
1242             "Should we use the rack_rtt time if its greater than srtt");
1243         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1244             SYSCTL_CHILDREN(rack_tlp),
1245             OID_AUTO, "tlpminto", CTLFLAG_RW,
1246             &rack_tlp_min, 10000,
1247             "TLP minimum timeout per the specification (in microseconds)");
1248         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1249             SYSCTL_CHILDREN(rack_tlp),
1250             OID_AUTO, "send_oldest", CTLFLAG_RW,
1251             &rack_always_send_oldest, 0,
1252             "Should we always send the oldest TLP and RACK-TLP");
1253         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1254             SYSCTL_CHILDREN(rack_tlp),
1255             OID_AUTO, "rack_tlimit", CTLFLAG_RW,
1256             &rack_limited_retran, 0,
1257             "How many times can a rack timeout drive out sends");
1258         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1259             SYSCTL_CHILDREN(rack_tlp),
1260             OID_AUTO, "tlp_cwnd_flag", CTLFLAG_RW,
1261             &rack_lower_cwnd_at_tlp, 0,
1262             "When a TLP completes a retran should we enter recovery");
1263         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1264             SYSCTL_CHILDREN(rack_tlp),
1265             OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1266             &rack_reorder_thresh, 2,
1267             "What factor for rack will be added when seeing reordering (shift right)");
1268         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1269             SYSCTL_CHILDREN(rack_tlp),
1270             OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1271             &rack_tlp_thresh, 1,
1272             "What divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1273         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1274             SYSCTL_CHILDREN(rack_tlp),
1275             OID_AUTO, "reorder_fade", CTLFLAG_RW,
1276             &rack_reorder_fade, 60000000,
1277             "Does reorder detection fade, if so how many microseconds (0 means never)");
1278         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1279             SYSCTL_CHILDREN(rack_tlp),
1280             OID_AUTO, "pktdelay", CTLFLAG_RW,
1281             &rack_pkt_delay, 1000,
1282             "Extra RACK time (in microseconds) besides reordering thresh");
1283
1284         /* Timer related controls */
1285         rack_timers = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1286             SYSCTL_CHILDREN(rack_sysctl_root),
1287             OID_AUTO,
1288             "timers",
1289             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1290             "Timer related controls");
1291         SYSCTL_ADD_U32(&rack_sysctl_ctx,
1292             SYSCTL_CHILDREN(rack_timers),
1293             OID_AUTO, "persmin", CTLFLAG_RW,
1294             &rack_persist_min, 250000,
1295             "What is the minimum time in microseconds between persists");
1296         SYSCTL_ADD_U32(&rack_sysctl_ctx,
1297             SYSCTL_CHILDREN(rack_timers),
1298             OID_AUTO, "persmax", CTLFLAG_RW,
1299             &rack_persist_max, 2000000,
1300             "What is the largest delay in microseconds between persists");
1301         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1302             SYSCTL_CHILDREN(rack_timers),
1303             OID_AUTO, "delayed_ack", CTLFLAG_RW,
1304             &rack_delayed_ack_time, 40000,
1305             "Delayed ack time (40ms in microseconds)");
1306         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1307             SYSCTL_CHILDREN(rack_timers),
1308             OID_AUTO, "minrto", CTLFLAG_RW,
1309             &rack_rto_min, 30000,
1310             "Minimum RTO in microseconds -- set with caution below 1000 due to TLP");
1311         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1312             SYSCTL_CHILDREN(rack_timers),
1313             OID_AUTO, "maxrto", CTLFLAG_RW,
1314             &rack_rto_max, 4000000,
1315             "Maxiumum RTO in microseconds -- should be at least as large as min_rto");
1316         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1317             SYSCTL_CHILDREN(rack_timers),
1318             OID_AUTO, "minto", CTLFLAG_RW,
1319             &rack_min_to, 1000,
1320             "Minimum rack timeout in microseconds");
1321         /* Measure controls */
1322         rack_measure = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1323             SYSCTL_CHILDREN(rack_sysctl_root),
1324             OID_AUTO,
1325             "measure",
1326             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1327             "Measure related controls");
1328         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1329             SYSCTL_CHILDREN(rack_measure),
1330             OID_AUTO, "wma_divisor", CTLFLAG_RW,
1331             &rack_wma_divisor, 8,
1332             "When doing b/w calculation what is the  divisor for the WMA");
1333         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1334             SYSCTL_CHILDREN(rack_measure),
1335             OID_AUTO, "end_cwnd", CTLFLAG_RW,
1336             &rack_cwnd_block_ends_measure, 0,
1337             "Does a cwnd just-return end the measurement window (app limited)");
1338         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1339             SYSCTL_CHILDREN(rack_measure),
1340             OID_AUTO, "end_rwnd", CTLFLAG_RW,
1341             &rack_rwnd_block_ends_measure, 0,
1342             "Does an rwnd just-return end the measurement window (app limited -- not persists)");
1343         SYSCTL_ADD_U32(&rack_sysctl_ctx,
1344             SYSCTL_CHILDREN(rack_measure),
1345             OID_AUTO, "min_target", CTLFLAG_RW,
1346             &rack_def_data_window, 20,
1347             "What is the minimum target window (in mss) for a GP measurements");
1348         SYSCTL_ADD_U32(&rack_sysctl_ctx,
1349             SYSCTL_CHILDREN(rack_measure),
1350             OID_AUTO, "goal_bdp", CTLFLAG_RW,
1351             &rack_goal_bdp, 2,
1352             "What is the goal BDP to measure");
1353         SYSCTL_ADD_U32(&rack_sysctl_ctx,
1354             SYSCTL_CHILDREN(rack_measure),
1355             OID_AUTO, "min_srtts", CTLFLAG_RW,
1356             &rack_min_srtts, 1,
1357             "What is the goal BDP to measure");
1358         SYSCTL_ADD_U32(&rack_sysctl_ctx,
1359             SYSCTL_CHILDREN(rack_measure),
1360             OID_AUTO, "min_measure_tim", CTLFLAG_RW,
1361             &rack_min_measure_usec, 0,
1362             "What is the Minimum time time for a measurement if 0, this is off");
1363         /* Misc rack controls */
1364         rack_misc = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1365             SYSCTL_CHILDREN(rack_sysctl_root),
1366             OID_AUTO,
1367             "misc",
1368             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1369             "Misc related controls");
1370 #ifdef TCP_ACCOUNTING
1371         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1372             SYSCTL_CHILDREN(rack_misc),
1373             OID_AUTO, "tcp_acct", CTLFLAG_RW,
1374             &rack_tcp_accounting, 0,
1375             "Should we turn on TCP accounting for all rack sessions?");
1376 #endif
1377         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1378             SYSCTL_CHILDREN(rack_misc),
1379             OID_AUTO, "prr_addback_max", CTLFLAG_RW,
1380             &rack_prr_addbackmax, 2,
1381             "What is the maximum number of MSS we allow to be added back if prr can't send all its data?");
1382         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1383             SYSCTL_CHILDREN(rack_misc),
1384             OID_AUTO, "stats_gets_ms", CTLFLAG_RW,
1385             &rack_stats_gets_ms_rtt, 1,
1386             "What do we feed the stats framework (1 = ms_rtt, 0 = us_rtt, 2 = ms_rtt from hdwr, > 2 usec rtt from hdwr)?");
1387         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1388             SYSCTL_CHILDREN(rack_misc),
1389             OID_AUTO, "clientlowbuf", CTLFLAG_RW,
1390             &rack_client_low_buf, 0,
1391             "Client low buffer level (below this we are more aggressive in DGP exiting recovery (0 = off)?");
1392         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1393             SYSCTL_CHILDREN(rack_misc),
1394             OID_AUTO, "defprofile", CTLFLAG_RW,
1395             &rack_def_profile, 0,
1396             "Should RACK use a default profile (0=no, num == profile num)?");
1397         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1398             SYSCTL_CHILDREN(rack_misc),
1399             OID_AUTO, "cmpack", CTLFLAG_RW,
1400             &rack_use_cmp_acks, 1,
1401             "Should RACK have LRO send compressed acks");
1402         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1403             SYSCTL_CHILDREN(rack_misc),
1404             OID_AUTO, "fsb", CTLFLAG_RW,
1405             &rack_use_fsb, 1,
1406             "Should RACK use the fast send block?");
1407         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1408             SYSCTL_CHILDREN(rack_misc),
1409             OID_AUTO, "rfo", CTLFLAG_RW,
1410             &rack_use_rfo, 1,
1411             "Should RACK use rack_fast_output()?");
1412         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1413             SYSCTL_CHILDREN(rack_misc),
1414             OID_AUTO, "rsmrfo", CTLFLAG_RW,
1415             &rack_use_rsm_rfo, 1,
1416             "Should RACK use rack_fast_rsm_output()?");
1417         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1418             SYSCTL_CHILDREN(rack_misc),
1419             OID_AUTO, "shared_cwnd", CTLFLAG_RW,
1420             &rack_enable_shared_cwnd, 1,
1421             "Should RACK try to use the shared cwnd on connections where allowed");
1422         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1423             SYSCTL_CHILDREN(rack_misc),
1424             OID_AUTO, "limits_on_scwnd", CTLFLAG_RW,
1425             &rack_limits_scwnd, 1,
1426             "Should RACK place low end time limits on the shared cwnd feature");
1427         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1428             SYSCTL_CHILDREN(rack_misc),
1429             OID_AUTO, "non_paced_lro_queue", CTLFLAG_RW,
1430             &rack_enable_mqueue_for_nonpaced, 0,
1431             "Should RACK use mbuf queuing for non-paced connections");
1432         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1433             SYSCTL_CHILDREN(rack_misc),
1434             OID_AUTO, "iMac_dack", CTLFLAG_RW,
1435             &rack_use_imac_dack, 0,
1436             "Should RACK try to emulate iMac delayed ack");
1437         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1438             SYSCTL_CHILDREN(rack_misc),
1439             OID_AUTO, "no_prr", CTLFLAG_RW,
1440             &rack_disable_prr, 0,
1441             "Should RACK not use prr and only pace (must have pacing on)");
1442         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1443             SYSCTL_CHILDREN(rack_misc),
1444             OID_AUTO, "bb_verbose", CTLFLAG_RW,
1445             &rack_verbose_logging, 0,
1446             "Should RACK black box logging be verbose");
1447         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1448             SYSCTL_CHILDREN(rack_misc),
1449             OID_AUTO, "data_after_close", CTLFLAG_RW,
1450             &rack_ignore_data_after_close, 1,
1451             "Do we hold off sending a RST until all pending data is ack'd");
1452         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1453             SYSCTL_CHILDREN(rack_misc),
1454             OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1455             &rack_sack_not_required, 1,
1456             "Do we allow rack to run on connections not supporting SACK");
1457         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1458             SYSCTL_CHILDREN(rack_misc),
1459             OID_AUTO, "prr_sendalot", CTLFLAG_RW,
1460             &rack_send_a_lot_in_prr, 1,
1461             "Send a lot in prr");
1462         SYSCTL_ADD_S32(&rack_sysctl_ctx,
1463             SYSCTL_CHILDREN(rack_misc),
1464             OID_AUTO, "autoscale", CTLFLAG_RW,
1465             &rack_autosndbuf_inc, 20,
1466             "What percentage should rack scale up its snd buffer by?");
1467         /* Sack Attacker detection stuff */
1468         SYSCTL_ADD_U32(&rack_sysctl_ctx,
1469             SYSCTL_CHILDREN(rack_attack),
1470             OID_AUTO, "detect_highsackratio", CTLFLAG_RW,
1471             &rack_highest_sack_thresh_seen, 0,
1472             "Highest sack to ack ratio seen");
1473         SYSCTL_ADD_U32(&rack_sysctl_ctx,
1474             SYSCTL_CHILDREN(rack_attack),
1475             OID_AUTO, "detect_highmoveratio", CTLFLAG_RW,
1476             &rack_highest_move_thresh_seen, 0,
1477             "Highest move to non-move ratio seen");
1478         rack_ack_total = counter_u64_alloc(M_WAITOK);
1479         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1480             SYSCTL_CHILDREN(rack_attack),
1481             OID_AUTO, "acktotal", CTLFLAG_RD,
1482             &rack_ack_total,
1483             "Total number of Ack's");
1484         rack_express_sack = counter_u64_alloc(M_WAITOK);
1485         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1486             SYSCTL_CHILDREN(rack_attack),
1487             OID_AUTO, "exp_sacktotal", CTLFLAG_RD,
1488             &rack_express_sack,
1489             "Total expresss number of Sack's");
1490         rack_sack_total = counter_u64_alloc(M_WAITOK);
1491         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1492             SYSCTL_CHILDREN(rack_attack),
1493             OID_AUTO, "sacktotal", CTLFLAG_RD,
1494             &rack_sack_total,
1495             "Total number of SACKs");
1496         rack_move_none = counter_u64_alloc(M_WAITOK);
1497         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1498             SYSCTL_CHILDREN(rack_attack),
1499             OID_AUTO, "move_none", CTLFLAG_RD,
1500             &rack_move_none,
1501             "Total number of SACK index reuse of postions under threshold");
1502         rack_move_some = counter_u64_alloc(M_WAITOK);
1503         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1504             SYSCTL_CHILDREN(rack_attack),
1505             OID_AUTO, "move_some", CTLFLAG_RD,
1506             &rack_move_some,
1507             "Total number of SACK index reuse of postions over threshold");
1508         rack_sack_attacks_detected = counter_u64_alloc(M_WAITOK);
1509         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1510             SYSCTL_CHILDREN(rack_attack),
1511             OID_AUTO, "attacks", CTLFLAG_RD,
1512             &rack_sack_attacks_detected,
1513             "Total number of SACK attackers that had sack disabled");
1514         rack_sack_attacks_reversed = counter_u64_alloc(M_WAITOK);
1515         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1516             SYSCTL_CHILDREN(rack_attack),
1517             OID_AUTO, "reversed", CTLFLAG_RD,
1518             &rack_sack_attacks_reversed,
1519             "Total number of SACK attackers that were later determined false positive");
1520         rack_sack_used_next_merge = counter_u64_alloc(M_WAITOK);
1521         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1522             SYSCTL_CHILDREN(rack_attack),
1523             OID_AUTO, "nextmerge", CTLFLAG_RD,
1524             &rack_sack_used_next_merge,
1525             "Total number of times we used the next merge");
1526         rack_sack_used_prev_merge = counter_u64_alloc(M_WAITOK);
1527         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1528             SYSCTL_CHILDREN(rack_attack),
1529             OID_AUTO, "prevmerge", CTLFLAG_RD,
1530             &rack_sack_used_prev_merge,
1531             "Total number of times we used the prev merge");
1532         /* Counters */
1533         rack_fto_send = counter_u64_alloc(M_WAITOK);
1534         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1535             SYSCTL_CHILDREN(rack_counters),
1536             OID_AUTO, "fto_send", CTLFLAG_RD,
1537             &rack_fto_send, "Total number of rack_fast_output sends");
1538         rack_fto_rsm_send = counter_u64_alloc(M_WAITOK);
1539         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1540             SYSCTL_CHILDREN(rack_counters),
1541             OID_AUTO, "fto_rsm_send", CTLFLAG_RD,
1542             &rack_fto_rsm_send, "Total number of rack_fast_rsm_output sends");
1543         rack_nfto_resend = counter_u64_alloc(M_WAITOK);
1544         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1545             SYSCTL_CHILDREN(rack_counters),
1546             OID_AUTO, "nfto_resend", CTLFLAG_RD,
1547             &rack_nfto_resend, "Total number of rack_output retransmissions");
1548         rack_non_fto_send = counter_u64_alloc(M_WAITOK);
1549         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1550             SYSCTL_CHILDREN(rack_counters),
1551             OID_AUTO, "nfto_send", CTLFLAG_RD,
1552             &rack_non_fto_send, "Total number of rack_output first sends");
1553         rack_extended_rfo = counter_u64_alloc(M_WAITOK);
1554         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1555             SYSCTL_CHILDREN(rack_counters),
1556             OID_AUTO, "rfo_extended", CTLFLAG_RD,
1557             &rack_extended_rfo, "Total number of times we extended rfo");
1558
1559         rack_hw_pace_init_fail = counter_u64_alloc(M_WAITOK);
1560         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1561             SYSCTL_CHILDREN(rack_counters),
1562             OID_AUTO, "hwpace_init_fail", CTLFLAG_RD,
1563             &rack_hw_pace_init_fail, "Total number of times we failed to initialize hw pacing");
1564         rack_hw_pace_lost = counter_u64_alloc(M_WAITOK);
1565
1566         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1567             SYSCTL_CHILDREN(rack_counters),
1568             OID_AUTO, "hwpace_lost", CTLFLAG_RD,
1569             &rack_hw_pace_lost, "Total number of times we failed to initialize hw pacing");
1570
1571
1572
1573         rack_badfr = counter_u64_alloc(M_WAITOK);
1574         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1575             SYSCTL_CHILDREN(rack_counters),
1576             OID_AUTO, "badfr", CTLFLAG_RD,
1577             &rack_badfr, "Total number of bad FRs");
1578         rack_badfr_bytes = counter_u64_alloc(M_WAITOK);
1579         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1580             SYSCTL_CHILDREN(rack_counters),
1581             OID_AUTO, "badfr_bytes", CTLFLAG_RD,
1582             &rack_badfr_bytes, "Total number of bad FRs");
1583         rack_rtm_prr_retran = counter_u64_alloc(M_WAITOK);
1584         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1585             SYSCTL_CHILDREN(rack_counters),
1586             OID_AUTO, "prrsndret", CTLFLAG_RD,
1587             &rack_rtm_prr_retran,
1588             "Total number of prr based retransmits");
1589         rack_rtm_prr_newdata = counter_u64_alloc(M_WAITOK);
1590         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1591             SYSCTL_CHILDREN(rack_counters),
1592             OID_AUTO, "prrsndnew", CTLFLAG_RD,
1593             &rack_rtm_prr_newdata,
1594             "Total number of prr based new transmits");
1595         rack_timestamp_mismatch = counter_u64_alloc(M_WAITOK);
1596         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1597             SYSCTL_CHILDREN(rack_counters),
1598             OID_AUTO, "tsnf", CTLFLAG_RD,
1599             &rack_timestamp_mismatch,
1600             "Total number of timestamps that we could not find the reported ts");
1601         rack_find_high = counter_u64_alloc(M_WAITOK);
1602         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1603             SYSCTL_CHILDREN(rack_counters),
1604             OID_AUTO, "findhigh", CTLFLAG_RD,
1605             &rack_find_high,
1606             "Total number of FIN causing find-high");
1607         rack_reorder_seen = counter_u64_alloc(M_WAITOK);
1608         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1609             SYSCTL_CHILDREN(rack_counters),
1610             OID_AUTO, "reordering", CTLFLAG_RD,
1611             &rack_reorder_seen,
1612             "Total number of times we added delay due to reordering");
1613         rack_tlp_tot = counter_u64_alloc(M_WAITOK);
1614         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1615             SYSCTL_CHILDREN(rack_counters),
1616             OID_AUTO, "tlp_to_total", CTLFLAG_RD,
1617             &rack_tlp_tot,
1618             "Total number of tail loss probe expirations");
1619         rack_tlp_newdata = counter_u64_alloc(M_WAITOK);
1620         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1621             SYSCTL_CHILDREN(rack_counters),
1622             OID_AUTO, "tlp_new", CTLFLAG_RD,
1623             &rack_tlp_newdata,
1624             "Total number of tail loss probe sending new data");
1625         rack_tlp_retran = counter_u64_alloc(M_WAITOK);
1626         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1627             SYSCTL_CHILDREN(rack_counters),
1628             OID_AUTO, "tlp_retran", CTLFLAG_RD,
1629             &rack_tlp_retran,
1630             "Total number of tail loss probe sending retransmitted data");
1631         rack_tlp_retran_bytes = counter_u64_alloc(M_WAITOK);
1632         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1633             SYSCTL_CHILDREN(rack_counters),
1634             OID_AUTO, "tlp_retran_bytes", CTLFLAG_RD,
1635             &rack_tlp_retran_bytes,
1636             "Total bytes of tail loss probe sending retransmitted data");
1637         rack_tlp_retran_fail = counter_u64_alloc(M_WAITOK);
1638         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1639             SYSCTL_CHILDREN(rack_counters),
1640             OID_AUTO, "tlp_retran_fail", CTLFLAG_RD,
1641             &rack_tlp_retran_fail,
1642             "Total number of tail loss probe sending retransmitted data that failed (wait for t3)");
1643         rack_to_tot = counter_u64_alloc(M_WAITOK);
1644         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1645             SYSCTL_CHILDREN(rack_counters),
1646             OID_AUTO, "rack_to_tot", CTLFLAG_RD,
1647             &rack_to_tot,
1648             "Total number of times the rack to expired");
1649         rack_to_arm_rack = counter_u64_alloc(M_WAITOK);
1650         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1651             SYSCTL_CHILDREN(rack_counters),
1652             OID_AUTO, "arm_rack", CTLFLAG_RD,
1653             &rack_to_arm_rack,
1654             "Total number of times the rack timer armed");
1655         rack_to_arm_tlp = counter_u64_alloc(M_WAITOK);
1656         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1657             SYSCTL_CHILDREN(rack_counters),
1658             OID_AUTO, "arm_tlp", CTLFLAG_RD,
1659             &rack_to_arm_tlp,
1660             "Total number of times the tlp timer armed");
1661         rack_calc_zero = counter_u64_alloc(M_WAITOK);
1662         rack_calc_nonzero = counter_u64_alloc(M_WAITOK);
1663         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1664             SYSCTL_CHILDREN(rack_counters),
1665             OID_AUTO, "calc_zero", CTLFLAG_RD,
1666             &rack_calc_zero,
1667             "Total number of times pacing time worked out to zero");
1668         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1669             SYSCTL_CHILDREN(rack_counters),
1670             OID_AUTO, "calc_nonzero", CTLFLAG_RD,
1671             &rack_calc_nonzero,
1672             "Total number of times pacing time worked out to non-zero");
1673         rack_paced_segments = counter_u64_alloc(M_WAITOK);
1674         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1675             SYSCTL_CHILDREN(rack_counters),
1676             OID_AUTO, "paced", CTLFLAG_RD,
1677             &rack_paced_segments,
1678             "Total number of times a segment send caused hptsi");
1679         rack_unpaced_segments = counter_u64_alloc(M_WAITOK);
1680         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1681             SYSCTL_CHILDREN(rack_counters),
1682             OID_AUTO, "unpaced", CTLFLAG_RD,
1683             &rack_unpaced_segments,
1684             "Total number of times a segment did not cause hptsi");
1685         rack_saw_enobuf = counter_u64_alloc(M_WAITOK);
1686         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1687             SYSCTL_CHILDREN(rack_counters),
1688             OID_AUTO, "saw_enobufs", CTLFLAG_RD,
1689             &rack_saw_enobuf,
1690             "Total number of times a sends returned enobuf for non-hdwr paced connections");
1691         rack_saw_enobuf_hw = counter_u64_alloc(M_WAITOK);
1692         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1693             SYSCTL_CHILDREN(rack_counters),
1694             OID_AUTO, "saw_enobufs_hw", CTLFLAG_RD,
1695             &rack_saw_enobuf_hw,
1696             "Total number of times a send returned enobuf for hdwr paced connections");
1697         rack_saw_enetunreach = counter_u64_alloc(M_WAITOK);
1698         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1699             SYSCTL_CHILDREN(rack_counters),
1700             OID_AUTO, "saw_enetunreach", CTLFLAG_RD,
1701             &rack_saw_enetunreach,
1702             "Total number of times a send received a enetunreachable");
1703         rack_hot_alloc = counter_u64_alloc(M_WAITOK);
1704         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1705             SYSCTL_CHILDREN(rack_counters),
1706             OID_AUTO, "alloc_hot", CTLFLAG_RD,
1707             &rack_hot_alloc,
1708             "Total allocations from the top of our list");
1709         rack_to_alloc = counter_u64_alloc(M_WAITOK);
1710         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1711             SYSCTL_CHILDREN(rack_counters),
1712             OID_AUTO, "allocs", CTLFLAG_RD,
1713             &rack_to_alloc,
1714             "Total allocations of tracking structures");
1715         rack_to_alloc_hard = counter_u64_alloc(M_WAITOK);
1716         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1717             SYSCTL_CHILDREN(rack_counters),
1718             OID_AUTO, "allochard", CTLFLAG_RD,
1719             &rack_to_alloc_hard,
1720             "Total allocations done with sleeping the hard way");
1721         rack_to_alloc_emerg = counter_u64_alloc(M_WAITOK);
1722         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1723             SYSCTL_CHILDREN(rack_counters),
1724             OID_AUTO, "allocemerg", CTLFLAG_RD,
1725             &rack_to_alloc_emerg,
1726             "Total allocations done from emergency cache");
1727         rack_to_alloc_limited = counter_u64_alloc(M_WAITOK);
1728         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1729             SYSCTL_CHILDREN(rack_counters),
1730             OID_AUTO, "alloc_limited", CTLFLAG_RD,
1731             &rack_to_alloc_limited,
1732             "Total allocations dropped due to limit");
1733         rack_alloc_limited_conns = counter_u64_alloc(M_WAITOK);
1734         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1735             SYSCTL_CHILDREN(rack_counters),
1736             OID_AUTO, "alloc_limited_conns", CTLFLAG_RD,
1737             &rack_alloc_limited_conns,
1738             "Connections with allocations dropped due to limit");
1739         rack_split_limited = counter_u64_alloc(M_WAITOK);
1740         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1741             SYSCTL_CHILDREN(rack_counters),
1742             OID_AUTO, "split_limited", CTLFLAG_RD,
1743             &rack_split_limited,
1744             "Split allocations dropped due to limit");
1745
1746         for (i = 0; i < MAX_NUM_OF_CNTS; i++) {
1747                 char name[32];
1748                 sprintf(name, "cmp_ack_cnt_%d", i);
1749                 rack_proc_comp_ack[i] = counter_u64_alloc(M_WAITOK);
1750                 SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1751                                        SYSCTL_CHILDREN(rack_counters),
1752                                        OID_AUTO, name, CTLFLAG_RD,
1753                                        &rack_proc_comp_ack[i],
1754                                        "Number of compressed acks we processed");
1755         }
1756         rack_large_ackcmp = counter_u64_alloc(M_WAITOK);
1757         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1758             SYSCTL_CHILDREN(rack_counters),
1759             OID_AUTO, "cmp_large_mbufs", CTLFLAG_RD,
1760             &rack_large_ackcmp,
1761             "Number of TCP connections with large mbuf's for compressed acks");
1762         rack_small_ackcmp = counter_u64_alloc(M_WAITOK);
1763         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1764             SYSCTL_CHILDREN(rack_counters),
1765             OID_AUTO, "cmp_small_mbufs", CTLFLAG_RD,
1766             &rack_small_ackcmp,
1767             "Number of TCP connections with small mbuf's for compressed acks");
1768 #ifdef INVARIANTS
1769         rack_adjust_map_bw = counter_u64_alloc(M_WAITOK);
1770         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1771             SYSCTL_CHILDREN(rack_counters),
1772             OID_AUTO, "map_adjust_req", CTLFLAG_RD,
1773             &rack_adjust_map_bw,
1774             "Number of times we hit the case where the sb went up and down on a sendmap entry");
1775 #endif
1776         rack_multi_single_eq = counter_u64_alloc(M_WAITOK);
1777         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1778             SYSCTL_CHILDREN(rack_counters),
1779             OID_AUTO, "cmp_ack_equiv", CTLFLAG_RD,
1780             &rack_multi_single_eq,
1781             "Number of compressed acks total represented");
1782         rack_proc_non_comp_ack = counter_u64_alloc(M_WAITOK);
1783         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1784             SYSCTL_CHILDREN(rack_counters),
1785             OID_AUTO, "cmp_ack_not", CTLFLAG_RD,
1786             &rack_proc_non_comp_ack,
1787             "Number of non compresseds acks that we processed");
1788
1789
1790         rack_sack_proc_all = counter_u64_alloc(M_WAITOK);
1791         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1792             SYSCTL_CHILDREN(rack_counters),
1793             OID_AUTO, "sack_long", CTLFLAG_RD,
1794             &rack_sack_proc_all,
1795             "Total times we had to walk whole list for sack processing");
1796         rack_sack_proc_restart = counter_u64_alloc(M_WAITOK);
1797         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1798             SYSCTL_CHILDREN(rack_counters),
1799             OID_AUTO, "sack_restart", CTLFLAG_RD,
1800             &rack_sack_proc_restart,
1801             "Total times we had to walk whole list due to a restart");
1802         rack_sack_proc_short = counter_u64_alloc(M_WAITOK);
1803         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1804             SYSCTL_CHILDREN(rack_counters),
1805             OID_AUTO, "sack_short", CTLFLAG_RD,
1806             &rack_sack_proc_short,
1807             "Total times we took shortcut for sack processing");
1808         rack_enter_tlp_calc = counter_u64_alloc(M_WAITOK);
1809         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1810             SYSCTL_CHILDREN(rack_counters),
1811             OID_AUTO, "tlp_calc_entered", CTLFLAG_RD,
1812             &rack_enter_tlp_calc,
1813             "Total times we called calc-tlp");
1814         rack_used_tlpmethod = counter_u64_alloc(M_WAITOK);
1815         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1816             SYSCTL_CHILDREN(rack_counters),
1817             OID_AUTO, "hit_tlp_method", CTLFLAG_RD,
1818             &rack_used_tlpmethod,
1819             "Total number of runt sacks");
1820         rack_used_tlpmethod2 = counter_u64_alloc(M_WAITOK);
1821         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1822             SYSCTL_CHILDREN(rack_counters),
1823             OID_AUTO, "hit_tlp_method2", CTLFLAG_RD,
1824             &rack_used_tlpmethod2,
1825             "Total number of times we hit TLP method 2");
1826         rack_sack_skipped_acked = counter_u64_alloc(M_WAITOK);
1827         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1828             SYSCTL_CHILDREN(rack_attack),
1829             OID_AUTO, "skipacked", CTLFLAG_RD,
1830             &rack_sack_skipped_acked,
1831             "Total number of times we skipped previously sacked");
1832         rack_sack_splits = counter_u64_alloc(M_WAITOK);
1833         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1834             SYSCTL_CHILDREN(rack_attack),
1835             OID_AUTO, "ofsplit", CTLFLAG_RD,
1836             &rack_sack_splits,
1837             "Total number of times we did the old fashion tree split");
1838         rack_progress_drops = counter_u64_alloc(M_WAITOK);
1839         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1840             SYSCTL_CHILDREN(rack_counters),
1841             OID_AUTO, "prog_drops", CTLFLAG_RD,
1842             &rack_progress_drops,
1843             "Total number of progress drops");
1844         rack_input_idle_reduces = counter_u64_alloc(M_WAITOK);
1845         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1846             SYSCTL_CHILDREN(rack_counters),
1847             OID_AUTO, "idle_reduce_oninput", CTLFLAG_RD,
1848             &rack_input_idle_reduces,
1849             "Total number of idle reductions on input");
1850         rack_collapsed_win = counter_u64_alloc(M_WAITOK);
1851         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1852             SYSCTL_CHILDREN(rack_counters),
1853             OID_AUTO, "collapsed_win", CTLFLAG_RD,
1854             &rack_collapsed_win,
1855             "Total number of collapsed windows");
1856         rack_tlp_does_nada = counter_u64_alloc(M_WAITOK);
1857         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1858             SYSCTL_CHILDREN(rack_counters),
1859             OID_AUTO, "tlp_nada", CTLFLAG_RD,
1860             &rack_tlp_does_nada,
1861             "Total number of nada tlp calls");
1862         rack_try_scwnd = counter_u64_alloc(M_WAITOK);
1863         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1864             SYSCTL_CHILDREN(rack_counters),
1865             OID_AUTO, "tried_scwnd", CTLFLAG_RD,
1866             &rack_try_scwnd,
1867             "Total number of scwnd attempts");
1868
1869         rack_per_timer_hole = counter_u64_alloc(M_WAITOK);
1870         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1871             SYSCTL_CHILDREN(rack_counters),
1872             OID_AUTO, "timer_hole", CTLFLAG_RD,
1873             &rack_per_timer_hole,
1874             "Total persists start in timer hole");
1875
1876         rack_sbsndptr_wrong = counter_u64_alloc(M_WAITOK);
1877         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1878             SYSCTL_CHILDREN(rack_counters),
1879             OID_AUTO, "sndptr_wrong", CTLFLAG_RD,
1880             &rack_sbsndptr_wrong, "Total number of times the saved sbsndptr was incorret");
1881         rack_sbsndptr_right = counter_u64_alloc(M_WAITOK);
1882         SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1883             SYSCTL_CHILDREN(rack_counters),
1884             OID_AUTO, "sndptr_right", CTLFLAG_RD,
1885             &rack_sbsndptr_right, "Total number of times the saved sbsndptr was corret");
1886
1887         COUNTER_ARRAY_ALLOC(rack_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1888         SYSCTL_ADD_COUNTER_U64_ARRAY(&rack_sysctl_ctx, SYSCTL_CHILDREN(rack_sysctl_root),
1889             OID_AUTO, "outsize", CTLFLAG_RD,
1890             rack_out_size, TCP_MSS_ACCT_SIZE, "MSS send sizes");
1891         COUNTER_ARRAY_ALLOC(rack_opts_arry, RACK_OPTS_SIZE, M_WAITOK);
1892         SYSCTL_ADD_COUNTER_U64_ARRAY(&rack_sysctl_ctx, SYSCTL_CHILDREN(rack_sysctl_root),
1893             OID_AUTO, "opts", CTLFLAG_RD,
1894             rack_opts_arry, RACK_OPTS_SIZE, "RACK Option Stats");
1895         SYSCTL_ADD_PROC(&rack_sysctl_ctx,
1896             SYSCTL_CHILDREN(rack_sysctl_root),
1897             OID_AUTO, "clear", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1898             &rack_clear_counter, 0, sysctl_rack_clear, "IU", "Clear counters");
1899 }
1900
1901 static __inline int
1902 rb_map_cmp(struct rack_sendmap *b, struct rack_sendmap *a)
1903 {
1904         if (SEQ_GEQ(b->r_start, a->r_start) &&
1905             SEQ_LT(b->r_start, a->r_end)) {
1906                 /*
1907                  * The entry b is within the
1908                  * block a. i.e.:
1909                  * a --   |-------------|
1910                  * b --   |----|
1911                  * <or>
1912                  * b --       |------|
1913                  * <or>
1914                  * b --       |-----------|
1915                  */
1916                 return (0);
1917         } else if (SEQ_GEQ(b->r_start, a->r_end)) {
1918                 /*
1919                  * b falls as either the next
1920                  * sequence block after a so a
1921                  * is said to be smaller than b.
1922                  * i.e:
1923                  * a --   |------|
1924                  * b --          |--------|
1925                  * or
1926                  * b --              |-----|
1927                  */
1928                 return (1);
1929         }
1930         /*
1931          * Whats left is where a is
1932          * larger than b. i.e:
1933          * a --         |-------|
1934          * b --  |---|
1935          * or even possibly
1936          * b --   |--------------|
1937          */
1938         return (-1);
1939 }
1940
1941 RB_PROTOTYPE(rack_rb_tree_head, rack_sendmap, r_next, rb_map_cmp);
1942 RB_GENERATE(rack_rb_tree_head, rack_sendmap, r_next, rb_map_cmp);
1943
1944 static uint32_t
1945 rc_init_window(struct tcp_rack *rack)
1946 {
1947         uint32_t win;
1948
1949         if (rack->rc_init_win == 0) {
1950                 /*
1951                  * Nothing set by the user, use the system stack
1952                  * default.
1953                  */
1954                 return (tcp_compute_initwnd(tcp_maxseg(rack->rc_tp)));
1955         }
1956         win = ctf_fixed_maxseg(rack->rc_tp) * rack->rc_init_win;
1957         return (win);
1958 }
1959
1960 static uint64_t
1961 rack_get_fixed_pacing_bw(struct tcp_rack *rack)
1962 {
1963         if (IN_FASTRECOVERY(rack->rc_tp->t_flags))
1964                 return (rack->r_ctl.rc_fixed_pacing_rate_rec);
1965         else if (rack->r_ctl.cwnd_to_use < rack->rc_tp->snd_ssthresh)
1966                 return (rack->r_ctl.rc_fixed_pacing_rate_ss);
1967         else
1968                 return (rack->r_ctl.rc_fixed_pacing_rate_ca);
1969 }
1970
1971 static uint64_t
1972 rack_get_bw(struct tcp_rack *rack)
1973 {
1974         if (rack->use_fixed_rate) {
1975                 /* Return the fixed pacing rate */
1976                 return (rack_get_fixed_pacing_bw(rack));
1977         }
1978         if (rack->r_ctl.gp_bw == 0) {
1979                 /*
1980                  * We have yet no b/w measurement,
1981                  * if we have a user set initial bw
1982                  * return it. If we don't have that and
1983                  * we have an srtt, use the tcp IW (10) to
1984                  * calculate a fictional b/w over the SRTT
1985                  * which is more or less a guess. Note
1986                  * we don't use our IW from rack on purpose
1987                  * so if we have like IW=30, we are not
1988                  * calculating a "huge" b/w.
1989                  */
1990                 uint64_t bw, srtt;
1991                 if (rack->r_ctl.init_rate)
1992                         return (rack->r_ctl.init_rate);
1993
1994                 /* Has the user set a max peak rate? */
1995 #ifdef NETFLIX_PEAKRATE
1996                 if (rack->rc_tp->t_maxpeakrate)
1997                         return (rack->rc_tp->t_maxpeakrate);
1998 #endif
1999                 /* Ok lets come up with the IW guess, if we have a srtt */
2000                 if (rack->rc_tp->t_srtt == 0) {
2001                         /*
2002                          * Go with old pacing method
2003                          * i.e. burst mitigation only.
2004                          */
2005                         return (0);
2006                 }
2007                 /* Ok lets get the initial TCP win (not racks) */
2008                 bw = tcp_compute_initwnd(tcp_maxseg(rack->rc_tp));
2009                 srtt = (uint64_t)rack->rc_tp->t_srtt;
2010                 bw *= (uint64_t)USECS_IN_SECOND;
2011                 bw /= srtt;
2012                 if (rack->r_ctl.bw_rate_cap && (bw > rack->r_ctl.bw_rate_cap))
2013                         bw = rack->r_ctl.bw_rate_cap;
2014                 return (bw);
2015         } else {
2016                 uint64_t bw;
2017
2018                 if (rack->r_ctl.num_measurements >= RACK_REQ_AVG) {
2019                         /* Averaging is done, we can return the value */
2020                         bw = rack->r_ctl.gp_bw;
2021                 } else {
2022                         /* Still doing initial average must calculate */
2023                         bw = rack->r_ctl.gp_bw / rack->r_ctl.num_measurements;
2024                 }
2025 #ifdef NETFLIX_PEAKRATE
2026                 if ((rack->rc_tp->t_maxpeakrate) &&
2027                     (bw > rack->rc_tp->t_maxpeakrate)) {
2028                         /* The user has set a peak rate to pace at
2029                          * don't allow us to pace faster than that.
2030                          */
2031                         return (rack->rc_tp->t_maxpeakrate);
2032                 }
2033 #endif
2034                 if (rack->r_ctl.bw_rate_cap && (bw > rack->r_ctl.bw_rate_cap))
2035                         bw = rack->r_ctl.bw_rate_cap;
2036                 return (bw);
2037         }
2038 }
2039
2040 static uint16_t
2041 rack_get_output_gain(struct tcp_rack *rack, struct rack_sendmap *rsm)
2042 {
2043         if (rack->use_fixed_rate) {
2044                 return (100);
2045         } else if (rack->in_probe_rtt && (rsm == NULL))
2046                 return (rack->r_ctl.rack_per_of_gp_probertt);
2047         else if ((IN_FASTRECOVERY(rack->rc_tp->t_flags) &&
2048                   rack->r_ctl.rack_per_of_gp_rec)) {
2049                 if (rsm) {
2050                         /* a retransmission always use the recovery rate */
2051                         return (rack->r_ctl.rack_per_of_gp_rec);
2052                 } else if (rack->rack_rec_nonrxt_use_cr) {
2053                         /* Directed to use the configured rate */
2054                         goto configured_rate;
2055                 } else if (rack->rack_no_prr &&
2056                            (rack->r_ctl.rack_per_of_gp_rec > 100)) {
2057                         /* No PRR, lets just use the b/w estimate only */
2058                         return (100);
2059                 } else {
2060                         /*
2061                          * Here we may have a non-retransmit but we
2062                          * have no overrides, so just use the recovery
2063                          * rate (prr is in effect).
2064                          */
2065                         return (rack->r_ctl.rack_per_of_gp_rec);
2066                 }
2067         }
2068 configured_rate:
2069         /* For the configured rate we look at our cwnd vs the ssthresh */
2070         if (rack->r_ctl.cwnd_to_use < rack->rc_tp->snd_ssthresh)
2071                 return (rack->r_ctl.rack_per_of_gp_ss);
2072         else
2073                 return (rack->r_ctl.rack_per_of_gp_ca);
2074 }
2075
2076 static void
2077 rack_log_hdwr_pacing(struct tcp_rack *rack,
2078                      uint64_t rate, uint64_t hw_rate, int line,
2079                      int error, uint16_t mod)
2080 {
2081         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2082                 union tcp_log_stackspecific log;
2083                 struct timeval tv;
2084                 const struct ifnet *ifp;
2085
2086                 memset(&log, 0, sizeof(log));
2087                 log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2088                 log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2089                 if (rack->r_ctl.crte) {
2090                         ifp = rack->r_ctl.crte->ptbl->rs_ifp;
2091                 } else if (rack->rc_inp->inp_route.ro_nh &&
2092                            rack->rc_inp->inp_route.ro_nh->nh_ifp) {
2093                         ifp = rack->rc_inp->inp_route.ro_nh->nh_ifp;
2094                 } else
2095                         ifp = NULL;
2096                 if (ifp) {
2097                         log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2098                         log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2099                 }
2100                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2101                 log.u_bbr.bw_inuse = rate;
2102                 log.u_bbr.flex5 = line;
2103                 log.u_bbr.flex6 = error;
2104                 log.u_bbr.flex7 = mod;
2105                 log.u_bbr.applimited = rack->r_ctl.rc_pace_max_segs;
2106                 log.u_bbr.flex8 = rack->use_fixed_rate;
2107                 log.u_bbr.flex8 <<= 1;
2108                 log.u_bbr.flex8 |= rack->rack_hdrw_pacing;
2109                 log.u_bbr.pkts_out = rack->rc_tp->t_maxseg;
2110                 log.u_bbr.delRate = rack->r_ctl.crte_prev_rate;
2111                 if (rack->r_ctl.crte)
2112                         log.u_bbr.cur_del_rate = rack->r_ctl.crte->rate;
2113                 else
2114                         log.u_bbr.cur_del_rate = 0;
2115                 log.u_bbr.rttProp = rack->r_ctl.last_hw_bw_req;
2116                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2117                     &rack->rc_inp->inp_socket->so_rcv,
2118                     &rack->rc_inp->inp_socket->so_snd,
2119                     BBR_LOG_HDWR_PACE, 0,
2120                     0, &log, false, &tv);
2121         }
2122 }
2123
2124 static uint64_t
2125 rack_get_output_bw(struct tcp_rack *rack, uint64_t bw, struct rack_sendmap *rsm, int *capped)
2126 {
2127         /*
2128          * We allow rack_per_of_gp_xx to dictate our bw rate we want.
2129          */
2130         uint64_t bw_est, high_rate;
2131         uint64_t gain;
2132
2133         gain = (uint64_t)rack_get_output_gain(rack, rsm);
2134         bw_est = bw * gain;
2135         bw_est /= (uint64_t)100;
2136         /* Never fall below the minimum (def 64kbps) */
2137         if (bw_est < RACK_MIN_BW)
2138                 bw_est = RACK_MIN_BW;
2139         if (rack->r_rack_hw_rate_caps) {
2140                 /* Rate caps are in place */
2141                 if (rack->r_ctl.crte != NULL) {
2142                         /* We have a hdwr rate already */
2143                         high_rate = tcp_hw_highest_rate(rack->r_ctl.crte);
2144                         if (bw_est >= high_rate) {
2145                                 /* We are capping bw at the highest rate table entry */
2146                                 rack_log_hdwr_pacing(rack,
2147                                                      bw_est, high_rate, __LINE__,
2148                                                      0, 3);
2149                                 bw_est = high_rate;
2150                                 if (capped)
2151                                         *capped = 1;
2152                         }
2153                 } else if ((rack->rack_hdrw_pacing == 0) &&
2154                            (rack->rack_hdw_pace_ena) &&
2155                            (rack->rack_attempt_hdwr_pace == 0) &&
2156                            (rack->rc_inp->inp_route.ro_nh != NULL) &&
2157                            (rack->rc_inp->inp_route.ro_nh->nh_ifp != NULL)) {
2158                         /*
2159                          * Special case, we have not yet attempted hardware
2160                          * pacing, and yet we may, when we do, find out if we are
2161                          * above the highest rate. We need to know the maxbw for the interface
2162                          * in question (if it supports ratelimiting). We get back
2163                          * a 0, if the interface is not found in the RL lists.
2164                          */
2165                         high_rate = tcp_hw_highest_rate_ifp(rack->rc_inp->inp_route.ro_nh->nh_ifp, rack->rc_inp);
2166                         if (high_rate) {
2167                                 /* Yep, we have a rate is it above this rate? */
2168                                 if (bw_est > high_rate) {
2169                                         bw_est = high_rate;
2170                                         if (capped)
2171                                                 *capped = 1;
2172                                 }
2173                         }
2174                 }
2175         }
2176         return (bw_est);
2177 }
2178
2179 static void
2180 rack_log_retran_reason(struct tcp_rack *rack, struct rack_sendmap *rsm, uint32_t tsused, uint32_t thresh, int mod)
2181 {
2182         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2183                 union tcp_log_stackspecific log;
2184                 struct timeval tv;
2185
2186                 if ((mod != 1) && (rack_verbose_logging == 0)) {
2187                         /*
2188                          * We get 3 values currently for mod
2189                          * 1 - We are retransmitting and this tells the reason.
2190                          * 2 - We are clearing a dup-ack count.
2191                          * 3 - We are incrementing a dup-ack count.
2192                          *
2193                          * The clear/increment are only logged
2194                          * if you have BBverbose on.
2195                          */
2196                         return;
2197                 }
2198                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2199                 log.u_bbr.flex1 = tsused;
2200                 log.u_bbr.flex2 = thresh;
2201                 log.u_bbr.flex3 = rsm->r_flags;
2202                 log.u_bbr.flex4 = rsm->r_dupack;
2203                 log.u_bbr.flex5 = rsm->r_start;
2204                 log.u_bbr.flex6 = rsm->r_end;
2205                 log.u_bbr.flex8 = mod;
2206                 log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2207                 log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2208                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2209                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2210                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2211                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2212                 log.u_bbr.pacing_gain = rack->r_must_retran;
2213                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2214                     &rack->rc_inp->inp_socket->so_rcv,
2215                     &rack->rc_inp->inp_socket->so_snd,
2216                     BBR_LOG_SETTINGS_CHG, 0,
2217                     0, &log, false, &tv);
2218         }
2219 }
2220
2221 static void
2222 rack_log_to_start(struct tcp_rack *rack, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2223 {
2224         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2225                 union tcp_log_stackspecific log;
2226                 struct timeval tv;
2227
2228                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2229                 log.u_bbr.flex1 = rack->rc_tp->t_srtt;
2230                 log.u_bbr.flex2 = to;
2231                 log.u_bbr.flex3 = rack->r_ctl.rc_hpts_flags;
2232                 log.u_bbr.flex4 = slot;
2233                 log.u_bbr.flex5 = rack->rc_inp->inp_hptsslot;
2234                 log.u_bbr.flex6 = rack->rc_tp->t_rxtcur;
2235                 log.u_bbr.flex7 = rack->rc_in_persist;
2236                 log.u_bbr.flex8 = which;
2237                 if (rack->rack_no_prr)
2238                         log.u_bbr.pkts_out = 0;
2239                 else
2240                         log.u_bbr.pkts_out = rack->r_ctl.rc_prr_sndcnt;
2241                 log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2242                 log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2243                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2244                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2245                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2246                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2247                 log.u_bbr.pacing_gain = rack->r_must_retran;
2248                 log.u_bbr.lt_epoch = rack->rc_tp->t_rxtshift;
2249                 log.u_bbr.lost = rack_rto_min;
2250                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2251                     &rack->rc_inp->inp_socket->so_rcv,
2252                     &rack->rc_inp->inp_socket->so_snd,
2253                     BBR_LOG_TIMERSTAR, 0,
2254                     0, &log, false, &tv);
2255         }
2256 }
2257
2258 static void
2259 rack_log_to_event(struct tcp_rack *rack, int32_t to_num, struct rack_sendmap *rsm)
2260 {
2261         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2262                 union tcp_log_stackspecific log;
2263                 struct timeval tv;
2264
2265                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2266                 log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2267                 log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2268                 log.u_bbr.flex8 = to_num;
2269                 log.u_bbr.flex1 = rack->r_ctl.rc_rack_min_rtt;
2270                 log.u_bbr.flex2 = rack->rc_rack_rtt;
2271                 if (rsm == NULL)
2272                         log.u_bbr.flex3 = 0;
2273                 else
2274                         log.u_bbr.flex3 = rsm->r_end - rsm->r_start;
2275                 if (rack->rack_no_prr)
2276                         log.u_bbr.flex5 = 0;
2277                 else
2278                         log.u_bbr.flex5 = rack->r_ctl.rc_prr_sndcnt;
2279                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2280                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2281                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2282                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2283                 log.u_bbr.pacing_gain = rack->r_must_retran;
2284                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2285                     &rack->rc_inp->inp_socket->so_rcv,
2286                     &rack->rc_inp->inp_socket->so_snd,
2287                     BBR_LOG_RTO, 0,
2288                     0, &log, false, &tv);
2289         }
2290 }
2291
2292 static void
2293 rack_log_map_chg(struct tcpcb *tp, struct tcp_rack *rack,
2294                  struct rack_sendmap *prev,
2295                  struct rack_sendmap *rsm,
2296                  struct rack_sendmap *next,
2297                  int flag, uint32_t th_ack, int line)
2298 {
2299         if (rack_verbose_logging && (tp->t_logstate != TCP_LOG_STATE_OFF)) {
2300                 union tcp_log_stackspecific log;
2301                 struct timeval tv;
2302
2303                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2304                 log.u_bbr.flex8 = flag;
2305                 log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2306                 log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2307                 log.u_bbr.cur_del_rate = (uint64_t)prev;
2308                 log.u_bbr.delRate = (uint64_t)rsm;
2309                 log.u_bbr.rttProp = (uint64_t)next;
2310                 log.u_bbr.flex7 = 0;
2311                 if (prev) {
2312                         log.u_bbr.flex1 = prev->r_start;
2313                         log.u_bbr.flex2 = prev->r_end;
2314                         log.u_bbr.flex7 |= 0x4;
2315                 }
2316                 if (rsm) {
2317                         log.u_bbr.flex3 = rsm->r_start;
2318                         log.u_bbr.flex4 = rsm->r_end;
2319                         log.u_bbr.flex7 |= 0x2;
2320                 }
2321                 if (next) {
2322                         log.u_bbr.flex5 = next->r_start;
2323                         log.u_bbr.flex6 = next->r_end;
2324                         log.u_bbr.flex7 |= 0x1;
2325                 }
2326                 log.u_bbr.applimited = line;
2327                 log.u_bbr.pkts_out = th_ack;
2328                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2329                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2330                 if (rack->rack_no_prr)
2331                         log.u_bbr.lost = 0;
2332                 else
2333                         log.u_bbr.lost = rack->r_ctl.rc_prr_sndcnt;
2334                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2335                     &rack->rc_inp->inp_socket->so_rcv,
2336                     &rack->rc_inp->inp_socket->so_snd,
2337                     TCP_LOG_MAPCHG, 0,
2338                     0, &log, false, &tv);
2339         }
2340 }
2341
2342 static void
2343 rack_log_rtt_upd(struct tcpcb *tp, struct tcp_rack *rack, uint32_t t, uint32_t len,
2344                  struct rack_sendmap *rsm, int conf)
2345 {
2346         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
2347                 union tcp_log_stackspecific log;
2348                 struct timeval tv;
2349                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2350                 log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2351                 log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2352                 log.u_bbr.flex1 = t;
2353                 log.u_bbr.flex2 = len;
2354                 log.u_bbr.flex3 = rack->r_ctl.rc_rack_min_rtt;
2355                 log.u_bbr.flex4 = rack->r_ctl.rack_rs.rs_rtt_lowest;
2356                 log.u_bbr.flex5 = rack->r_ctl.rack_rs.rs_rtt_highest;
2357                 log.u_bbr.flex6 = rack->r_ctl.rack_rs.rs_us_rtrcnt;
2358                 log.u_bbr.flex7 = conf;
2359                 log.u_bbr.rttProp = (uint64_t)rack->r_ctl.rack_rs.rs_rtt_tot;
2360                 log.u_bbr.flex8 = rack->r_ctl.rc_rate_sample_method;
2361                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2362                 log.u_bbr.delivered = rack->r_ctl.rack_rs.rs_us_rtrcnt;
2363                 log.u_bbr.pkts_out = rack->r_ctl.rack_rs.rs_flags;
2364                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2365                 if (rsm) {
2366                         log.u_bbr.pkt_epoch = rsm->r_start;
2367                         log.u_bbr.lost = rsm->r_end;
2368                         log.u_bbr.cwnd_gain = rsm->r_rtr_cnt;
2369                         log.u_bbr.pacing_gain = rsm->r_flags;
2370                 } else {
2371                         /* Its a SYN */
2372                         log.u_bbr.pkt_epoch = rack->rc_tp->iss;
2373                         log.u_bbr.lost = 0;
2374                         log.u_bbr.cwnd_gain = 0;
2375                         log.u_bbr.pacing_gain = 0;
2376                 }
2377                 /* Write out general bits of interest rrs here */
2378                 log.u_bbr.use_lt_bw = rack->rc_highly_buffered;
2379                 log.u_bbr.use_lt_bw <<= 1;
2380                 log.u_bbr.use_lt_bw |= rack->forced_ack;
2381                 log.u_bbr.use_lt_bw <<= 1;
2382                 log.u_bbr.use_lt_bw |= rack->rc_gp_dyn_mul;
2383                 log.u_bbr.use_lt_bw <<= 1;
2384                 log.u_bbr.use_lt_bw |= rack->in_probe_rtt;
2385                 log.u_bbr.use_lt_bw <<= 1;
2386                 log.u_bbr.use_lt_bw |= rack->measure_saw_probe_rtt;
2387                 log.u_bbr.use_lt_bw <<= 1;
2388                 log.u_bbr.use_lt_bw |= rack->app_limited_needs_set;
2389                 log.u_bbr.use_lt_bw <<= 1;
2390                 log.u_bbr.use_lt_bw |= rack->rc_gp_filled;
2391                 log.u_bbr.use_lt_bw <<= 1;
2392                 log.u_bbr.use_lt_bw |= rack->rc_dragged_bottom;
2393                 log.u_bbr.applimited = rack->r_ctl.rc_target_probertt_flight;
2394                 log.u_bbr.epoch = rack->r_ctl.rc_time_probertt_starts;
2395                 log.u_bbr.lt_epoch = rack->r_ctl.rc_time_probertt_entered;
2396                 log.u_bbr.cur_del_rate = rack->r_ctl.rc_lower_rtt_us_cts;
2397                 log.u_bbr.delRate = rack->r_ctl.rc_gp_srtt;
2398                 log.u_bbr.bw_inuse = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
2399                 log.u_bbr.bw_inuse <<= 32;
2400                 if (rsm)
2401                         log.u_bbr.bw_inuse |= ((uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
2402                 TCP_LOG_EVENTP(tp, NULL,
2403                     &rack->rc_inp->inp_socket->so_rcv,
2404                     &rack->rc_inp->inp_socket->so_snd,
2405                     BBR_LOG_BBRRTT, 0,
2406                     0, &log, false, &tv);
2407
2408
2409         }
2410 }
2411
2412 static void
2413 rack_log_rtt_sample(struct tcp_rack *rack, uint32_t rtt)
2414 {
2415         /*
2416          * Log the rtt sample we are
2417          * applying to the srtt algorithm in
2418          * useconds.
2419          */
2420         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2421                 union tcp_log_stackspecific log;
2422                 struct timeval tv;
2423
2424                 /* Convert our ms to a microsecond */
2425                 memset(&log, 0, sizeof(log));
2426                 log.u_bbr.flex1 = rtt;
2427                 log.u_bbr.flex2 = rack->r_ctl.ack_count;
2428                 log.u_bbr.flex3 = rack->r_ctl.sack_count;
2429                 log.u_bbr.flex4 = rack->r_ctl.sack_noextra_move;
2430                 log.u_bbr.flex5 = rack->r_ctl.sack_moved_extra;
2431                 log.u_bbr.flex6 = rack->rc_tp->t_rxtcur;
2432                 log.u_bbr.flex7 = 1;
2433                 log.u_bbr.flex8 = rack->sack_attack_disable;
2434                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2435                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2436                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2437                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2438                 log.u_bbr.pacing_gain = rack->r_must_retran;
2439                 /*
2440                  * We capture in delRate the upper 32 bits as
2441                  * the confidence level we had declared, and the
2442                  * lower 32 bits as the actual RTT using the arrival
2443                  * timestamp.
2444                  */
2445                 log.u_bbr.delRate = rack->r_ctl.rack_rs.confidence;
2446                 log.u_bbr.delRate <<= 32;
2447                 log.u_bbr.delRate |= rack->r_ctl.rack_rs.rs_us_rtt;
2448                 /* Lets capture all the things that make up t_rtxcur */
2449                 log.u_bbr.applimited = rack_rto_min;
2450                 log.u_bbr.epoch = rack_rto_max;
2451                 log.u_bbr.lt_epoch = rtt;
2452                 log.u_bbr.lost = rack_rto_min;
2453                 log.u_bbr.pkt_epoch = TICKS_2_USEC(tcp_rexmit_slop);
2454                 log.u_bbr.rttProp = RACK_REXMTVAL(rack->rc_tp);
2455                 log.u_bbr.bw_inuse = rack->r_ctl.act_rcv_time.tv_sec;
2456                 log.u_bbr.bw_inuse *= HPTS_USEC_IN_SEC;
2457                 log.u_bbr.bw_inuse += rack->r_ctl.act_rcv_time.tv_usec;
2458                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2459                     &rack->rc_inp->inp_socket->so_rcv,
2460                     &rack->rc_inp->inp_socket->so_snd,
2461                     TCP_LOG_RTT, 0,
2462                     0, &log, false, &tv);
2463         }
2464 }
2465
2466 static void
2467 rack_log_rtt_sample_calc(struct tcp_rack *rack, uint32_t rtt, uint32_t send_time, uint32_t ack_time, int where)
2468 {
2469         if (rack_verbose_logging && (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2470                 union tcp_log_stackspecific log;
2471                 struct timeval tv;
2472
2473                 /* Convert our ms to a microsecond */
2474                 memset(&log, 0, sizeof(log));
2475                 log.u_bbr.flex1 = rtt;
2476                 log.u_bbr.flex2 = send_time;
2477                 log.u_bbr.flex3 = ack_time;
2478                 log.u_bbr.flex4 = where;
2479                 log.u_bbr.flex7 = 2;
2480                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2481                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2482                     &rack->rc_inp->inp_socket->so_rcv,
2483                     &rack->rc_inp->inp_socket->so_snd,
2484                     TCP_LOG_RTT, 0,
2485                     0, &log, false, &tv);
2486         }
2487 }
2488
2489
2490
2491 static inline void
2492 rack_log_progress_event(struct tcp_rack *rack, struct tcpcb *tp, uint32_t tick,  int event, int line)
2493 {
2494         if (rack_verbose_logging && (tp->t_logstate != TCP_LOG_STATE_OFF)) {
2495                 union tcp_log_stackspecific log;
2496                 struct timeval tv;
2497
2498                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2499                 log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2500                 log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2501                 log.u_bbr.flex1 = line;
2502                 log.u_bbr.flex2 = tick;
2503                 log.u_bbr.flex3 = tp->t_maxunacktime;
2504                 log.u_bbr.flex4 = tp->t_acktime;
2505                 log.u_bbr.flex8 = event;
2506                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2507                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2508                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2509                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2510                 log.u_bbr.pacing_gain = rack->r_must_retran;
2511                 TCP_LOG_EVENTP(tp, NULL,
2512                     &rack->rc_inp->inp_socket->so_rcv,
2513                     &rack->rc_inp->inp_socket->so_snd,
2514                     BBR_LOG_PROGRESS, 0,
2515                     0, &log, false, &tv);
2516         }
2517 }
2518
2519 static void
2520 rack_log_type_bbrsnd(struct tcp_rack *rack, uint32_t len, uint32_t slot, uint32_t cts, struct timeval *tv)
2521 {
2522         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2523                 union tcp_log_stackspecific log;
2524
2525                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2526                 log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2527                 log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2528                 log.u_bbr.flex1 = slot;
2529                 if (rack->rack_no_prr)
2530                         log.u_bbr.flex2 = 0;
2531                 else
2532                         log.u_bbr.flex2 = rack->r_ctl.rc_prr_sndcnt;
2533                 log.u_bbr.flex7 = (0x0000ffff & rack->r_ctl.rc_hpts_flags);
2534                 log.u_bbr.flex8 = rack->rc_in_persist;
2535                 log.u_bbr.timeStamp = cts;
2536                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2537                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2538                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2539                 log.u_bbr.pacing_gain = rack->r_must_retran;
2540                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2541                     &rack->rc_inp->inp_socket->so_rcv,
2542                     &rack->rc_inp->inp_socket->so_snd,
2543                     BBR_LOG_BBRSND, 0,
2544                     0, &log, false, tv);
2545         }
2546 }
2547
2548 static void
2549 rack_log_doseg_done(struct tcp_rack *rack, uint32_t cts, int32_t nxt_pkt, int32_t did_out, int way_out, int nsegs)
2550 {
2551         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2552                 union tcp_log_stackspecific log;
2553                 struct timeval tv;
2554
2555                 memset(&log, 0, sizeof(log));
2556                 log.u_bbr.flex1 = did_out;
2557                 log.u_bbr.flex2 = nxt_pkt;
2558                 log.u_bbr.flex3 = way_out;
2559                 log.u_bbr.flex4 = rack->r_ctl.rc_hpts_flags;
2560                 if (rack->rack_no_prr)
2561                         log.u_bbr.flex5 = 0;
2562                 else
2563                         log.u_bbr.flex5 = rack->r_ctl.rc_prr_sndcnt;
2564                 log.u_bbr.flex6 = nsegs;
2565                 log.u_bbr.applimited = rack->r_ctl.rc_pace_min_segs;
2566                 log.u_bbr.flex7 = rack->rc_ack_can_sendout_data;        /* Do we have ack-can-send set */
2567                 log.u_bbr.flex7 <<= 1;
2568                 log.u_bbr.flex7 |= rack->r_fast_output; /* is fast output primed */
2569                 log.u_bbr.flex7 <<= 1;
2570                 log.u_bbr.flex7 |= rack->r_wanted_output;       /* Do we want output */
2571                 log.u_bbr.flex8 = rack->rc_in_persist;
2572                 log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2573                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2574                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2575                 log.u_bbr.use_lt_bw = rack->r_ent_rec_ns;
2576                 log.u_bbr.use_lt_bw <<= 1;
2577                 log.u_bbr.use_lt_bw |= rack->r_might_revert;
2578                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2579                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2580                 log.u_bbr.pacing_gain = rack->r_must_retran;
2581                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2582                     &rack->rc_inp->inp_socket->so_rcv,
2583                     &rack->rc_inp->inp_socket->so_snd,
2584                     BBR_LOG_DOSEG_DONE, 0,
2585                     0, &log, false, &tv);
2586         }
2587 }
2588
2589 static void
2590 rack_log_type_pacing_sizes(struct tcpcb *tp, struct tcp_rack *rack, uint32_t arg1, uint32_t arg2, uint32_t arg3, uint8_t frm)
2591 {
2592         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
2593                 union tcp_log_stackspecific log;
2594                 struct timeval tv;
2595                 uint32_t cts;
2596
2597                 memset(&log, 0, sizeof(log));
2598                 cts = tcp_get_usecs(&tv);
2599                 log.u_bbr.flex1 = rack->r_ctl.rc_pace_min_segs;
2600                 log.u_bbr.flex3 = rack->r_ctl.rc_pace_max_segs;
2601                 log.u_bbr.flex4 = arg1;
2602                 log.u_bbr.flex5 = arg2;
2603                 log.u_bbr.flex6 = arg3;
2604                 log.u_bbr.flex8 = frm;
2605                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2606                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2607                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2608                 log.u_bbr.applimited = rack->r_ctl.rc_sacked;
2609                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2610                 log.u_bbr.pacing_gain = rack->r_must_retran;
2611                 TCP_LOG_EVENTP(tp, NULL,
2612                     &tp->t_inpcb->inp_socket->so_rcv,
2613                     &tp->t_inpcb->inp_socket->so_snd,
2614                     TCP_HDWR_PACE_SIZE, 0,
2615                     0, &log, false, &tv);
2616         }
2617 }
2618
2619 static void
2620 rack_log_type_just_return(struct tcp_rack *rack, uint32_t cts, uint32_t tlen, uint32_t slot,
2621                           uint8_t hpts_calling, int reason, uint32_t cwnd_to_use)
2622 {
2623         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2624                 union tcp_log_stackspecific log;
2625                 struct timeval tv;
2626
2627                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2628                 log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2629                 log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2630                 log.u_bbr.flex1 = slot;
2631                 log.u_bbr.flex2 = rack->r_ctl.rc_hpts_flags;
2632                 log.u_bbr.flex4 = reason;
2633                 if (rack->rack_no_prr)
2634                         log.u_bbr.flex5 = 0;
2635                 else
2636                         log.u_bbr.flex5 = rack->r_ctl.rc_prr_sndcnt;
2637                 log.u_bbr.flex7 = hpts_calling;
2638                 log.u_bbr.flex8 = rack->rc_in_persist;
2639                 log.u_bbr.lt_epoch = cwnd_to_use;
2640                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2641                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2642                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2643                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2644                 log.u_bbr.pacing_gain = rack->r_must_retran;
2645                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2646                     &rack->rc_inp->inp_socket->so_rcv,
2647                     &rack->rc_inp->inp_socket->so_snd,
2648                     BBR_LOG_JUSTRET, 0,
2649                     tlen, &log, false, &tv);
2650         }
2651 }
2652
2653 static void
2654 rack_log_to_cancel(struct tcp_rack *rack, int32_t hpts_removed, int line, uint32_t us_cts,
2655                    struct timeval *tv, uint32_t flags_on_entry)
2656 {
2657         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2658                 union tcp_log_stackspecific log;
2659
2660                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2661                 log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2662                 log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2663                 log.u_bbr.flex1 = line;
2664                 log.u_bbr.flex2 = rack->r_ctl.rc_last_output_to;
2665                 log.u_bbr.flex3 = flags_on_entry;
2666                 log.u_bbr.flex4 = us_cts;
2667                 if (rack->rack_no_prr)
2668                         log.u_bbr.flex5 = 0;
2669                 else
2670                         log.u_bbr.flex5 = rack->r_ctl.rc_prr_sndcnt;
2671                 log.u_bbr.flex6 = rack->rc_tp->t_rxtcur;
2672                 log.u_bbr.flex7 = hpts_removed;
2673                 log.u_bbr.flex8 = 1;
2674                 log.u_bbr.applimited = rack->r_ctl.rc_hpts_flags;
2675                 log.u_bbr.timeStamp = us_cts;
2676                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2677                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2678                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2679                 log.u_bbr.pacing_gain = rack->r_must_retran;
2680                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2681                     &rack->rc_inp->inp_socket->so_rcv,
2682                     &rack->rc_inp->inp_socket->so_snd,
2683                     BBR_LOG_TIMERCANC, 0,
2684                     0, &log, false, tv);
2685         }
2686 }
2687
2688 static void
2689 rack_log_alt_to_to_cancel(struct tcp_rack *rack,
2690                           uint32_t flex1, uint32_t flex2,
2691                           uint32_t flex3, uint32_t flex4,
2692                           uint32_t flex5, uint32_t flex6,
2693                           uint16_t flex7, uint8_t mod)
2694 {
2695         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2696                 union tcp_log_stackspecific log;
2697                 struct timeval tv;
2698
2699                 if (mod == 1) {
2700                         /* No you can't use 1, its for the real to cancel */
2701                         return;
2702                 }
2703                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2704                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2705                 log.u_bbr.flex1 = flex1;
2706                 log.u_bbr.flex2 = flex2;
2707                 log.u_bbr.flex3 = flex3;
2708                 log.u_bbr.flex4 = flex4;
2709                 log.u_bbr.flex5 = flex5;
2710                 log.u_bbr.flex6 = flex6;
2711                 log.u_bbr.flex7 = flex7;
2712                 log.u_bbr.flex8 = mod;
2713                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2714                     &rack->rc_inp->inp_socket->so_rcv,
2715                     &rack->rc_inp->inp_socket->so_snd,
2716                     BBR_LOG_TIMERCANC, 0,
2717                     0, &log, false, &tv);
2718         }
2719 }
2720
2721 static void
2722 rack_log_to_processing(struct tcp_rack *rack, uint32_t cts, int32_t ret, int32_t timers)
2723 {
2724         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2725                 union tcp_log_stackspecific log;
2726                 struct timeval tv;
2727
2728                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2729                 log.u_bbr.flex1 = timers;
2730                 log.u_bbr.flex2 = ret;
2731                 log.u_bbr.flex3 = rack->r_ctl.rc_timer_exp;
2732                 log.u_bbr.flex4 = rack->r_ctl.rc_hpts_flags;
2733                 log.u_bbr.flex5 = cts;
2734                 if (rack->rack_no_prr)
2735                         log.u_bbr.flex6 = 0;
2736                 else
2737                         log.u_bbr.flex6 = rack->r_ctl.rc_prr_sndcnt;
2738                 log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2739                 log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2740                 log.u_bbr.pacing_gain = rack->r_must_retran;
2741                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2742                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2743                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2744                     &rack->rc_inp->inp_socket->so_rcv,
2745                     &rack->rc_inp->inp_socket->so_snd,
2746                     BBR_LOG_TO_PROCESS, 0,
2747                     0, &log, false, &tv);
2748         }
2749 }
2750
2751 static void
2752 rack_log_to_prr(struct tcp_rack *rack, int frm, int orig_cwnd)
2753 {
2754         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2755                 union tcp_log_stackspecific log;
2756                 struct timeval tv;
2757
2758                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2759                 log.u_bbr.flex1 = rack->r_ctl.rc_prr_out;
2760                 log.u_bbr.flex2 = rack->r_ctl.rc_prr_recovery_fs;
2761                 if (rack->rack_no_prr)
2762                         log.u_bbr.flex3 = 0;
2763                 else
2764                         log.u_bbr.flex3 = rack->r_ctl.rc_prr_sndcnt;
2765                 log.u_bbr.flex4 = rack->r_ctl.rc_prr_delivered;
2766                 log.u_bbr.flex5 = rack->r_ctl.rc_sacked;
2767                 log.u_bbr.flex6 = rack->r_ctl.rc_holes_rxt;
2768                 log.u_bbr.flex8 = frm;
2769                 log.u_bbr.pkts_out = orig_cwnd;
2770                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2771                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2772                 log.u_bbr.use_lt_bw = rack->r_ent_rec_ns;
2773                 log.u_bbr.use_lt_bw <<= 1;
2774                 log.u_bbr.use_lt_bw |= rack->r_might_revert;
2775                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2776                     &rack->rc_inp->inp_socket->so_rcv,
2777                     &rack->rc_inp->inp_socket->so_snd,
2778                     BBR_LOG_BBRUPD, 0,
2779                     0, &log, false, &tv);
2780         }
2781 }
2782
2783 #ifdef NETFLIX_EXP_DETECTION
2784 static void
2785 rack_log_sad(struct tcp_rack *rack, int event)
2786 {
2787         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2788                 union tcp_log_stackspecific log;
2789                 struct timeval tv;
2790
2791                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2792                 log.u_bbr.flex1 = rack->r_ctl.sack_count;
2793                 log.u_bbr.flex2 = rack->r_ctl.ack_count;
2794                 log.u_bbr.flex3 = rack->r_ctl.sack_moved_extra;
2795                 log.u_bbr.flex4 = rack->r_ctl.sack_noextra_move;
2796                 log.u_bbr.flex5 = rack->r_ctl.rc_num_maps_alloced;
2797                 log.u_bbr.flex6 = tcp_sack_to_ack_thresh;
2798                 log.u_bbr.pkts_out = tcp_sack_to_move_thresh;
2799                 log.u_bbr.lt_epoch = (tcp_force_detection << 8);
2800                 log.u_bbr.lt_epoch |= rack->do_detection;
2801                 log.u_bbr.applimited = tcp_map_minimum;
2802                 log.u_bbr.flex7 = rack->sack_attack_disable;
2803                 log.u_bbr.flex8 = event;
2804                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2805                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2806                 log.u_bbr.delivered = tcp_sad_decay_val;
2807                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
2808                     &rack->rc_inp->inp_socket->so_rcv,
2809                     &rack->rc_inp->inp_socket->so_snd,
2810                     TCP_SAD_DETECTION, 0,
2811                     0, &log, false, &tv);
2812         }
2813 }
2814 #endif
2815
2816 static void
2817 rack_counter_destroy(void)
2818 {
2819         int i;
2820
2821         counter_u64_free(rack_fto_send);
2822         counter_u64_free(rack_fto_rsm_send);
2823         counter_u64_free(rack_nfto_resend);
2824         counter_u64_free(rack_hw_pace_init_fail);
2825         counter_u64_free(rack_hw_pace_lost);
2826         counter_u64_free(rack_non_fto_send);
2827         counter_u64_free(rack_extended_rfo);
2828         counter_u64_free(rack_ack_total);
2829         counter_u64_free(rack_express_sack);
2830         counter_u64_free(rack_sack_total);
2831         counter_u64_free(rack_move_none);
2832         counter_u64_free(rack_move_some);
2833         counter_u64_free(rack_sack_attacks_detected);
2834         counter_u64_free(rack_sack_attacks_reversed);
2835         counter_u64_free(rack_sack_used_next_merge);
2836         counter_u64_free(rack_sack_used_prev_merge);
2837         counter_u64_free(rack_badfr);
2838         counter_u64_free(rack_badfr_bytes);
2839         counter_u64_free(rack_rtm_prr_retran);
2840         counter_u64_free(rack_rtm_prr_newdata);
2841         counter_u64_free(rack_timestamp_mismatch);
2842         counter_u64_free(rack_find_high);
2843         counter_u64_free(rack_reorder_seen);
2844         counter_u64_free(rack_tlp_tot);
2845         counter_u64_free(rack_tlp_newdata);
2846         counter_u64_free(rack_tlp_retran);
2847         counter_u64_free(rack_tlp_retran_bytes);
2848         counter_u64_free(rack_tlp_retran_fail);
2849         counter_u64_free(rack_to_tot);
2850         counter_u64_free(rack_to_arm_rack);
2851         counter_u64_free(rack_to_arm_tlp);
2852         counter_u64_free(rack_calc_zero);
2853         counter_u64_free(rack_calc_nonzero);
2854         counter_u64_free(rack_paced_segments);
2855         counter_u64_free(rack_unpaced_segments);
2856         counter_u64_free(rack_saw_enobuf);
2857         counter_u64_free(rack_saw_enobuf_hw);
2858         counter_u64_free(rack_saw_enetunreach);
2859         counter_u64_free(rack_hot_alloc);
2860         counter_u64_free(rack_to_alloc);
2861         counter_u64_free(rack_to_alloc_hard);
2862         counter_u64_free(rack_to_alloc_emerg);
2863         counter_u64_free(rack_to_alloc_limited);
2864         counter_u64_free(rack_alloc_limited_conns);
2865         counter_u64_free(rack_split_limited);
2866         for (i = 0; i < MAX_NUM_OF_CNTS; i++) {
2867                 counter_u64_free(rack_proc_comp_ack[i]);
2868         }
2869         counter_u64_free(rack_multi_single_eq);
2870         counter_u64_free(rack_proc_non_comp_ack);
2871         counter_u64_free(rack_sack_proc_all);
2872         counter_u64_free(rack_sack_proc_restart);
2873         counter_u64_free(rack_sack_proc_short);
2874         counter_u64_free(rack_enter_tlp_calc);
2875         counter_u64_free(rack_used_tlpmethod);
2876         counter_u64_free(rack_used_tlpmethod2);
2877         counter_u64_free(rack_sack_skipped_acked);
2878         counter_u64_free(rack_sack_splits);
2879         counter_u64_free(rack_progress_drops);
2880         counter_u64_free(rack_input_idle_reduces);
2881         counter_u64_free(rack_collapsed_win);
2882         counter_u64_free(rack_tlp_does_nada);
2883         counter_u64_free(rack_try_scwnd);
2884         counter_u64_free(rack_per_timer_hole);
2885         counter_u64_free(rack_large_ackcmp);
2886         counter_u64_free(rack_small_ackcmp);
2887 #ifdef INVARIANTS
2888         counter_u64_free(rack_adjust_map_bw);
2889 #endif
2890         COUNTER_ARRAY_FREE(rack_out_size, TCP_MSS_ACCT_SIZE);
2891         COUNTER_ARRAY_FREE(rack_opts_arry, RACK_OPTS_SIZE);
2892 }
2893
2894 static struct rack_sendmap *
2895 rack_alloc(struct tcp_rack *rack)
2896 {
2897         struct rack_sendmap *rsm;
2898
2899         /*
2900          * First get the top of the list it in
2901          * theory is the "hottest" rsm we have,
2902          * possibly just freed by ack processing.
2903          */
2904         if (rack->rc_free_cnt > rack_free_cache) {
2905                 rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
2906                 TAILQ_REMOVE(&rack->r_ctl.rc_free, rsm, r_tnext);
2907                 counter_u64_add(rack_hot_alloc, 1);
2908                 rack->rc_free_cnt--;
2909                 return (rsm);
2910         }
2911         /*
2912          * Once we get under our free cache we probably
2913          * no longer have a "hot" one available. Lets
2914          * get one from UMA.
2915          */
2916         rsm = uma_zalloc(rack_zone, M_NOWAIT);
2917         if (rsm) {
2918                 rack->r_ctl.rc_num_maps_alloced++;
2919                 counter_u64_add(rack_to_alloc, 1);
2920                 return (rsm);
2921         }
2922         /*
2923          * Dig in to our aux rsm's (the last two) since
2924          * UMA failed to get us one.
2925          */
2926         if (rack->rc_free_cnt) {
2927                 counter_u64_add(rack_to_alloc_emerg, 1);
2928                 rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
2929                 TAILQ_REMOVE(&rack->r_ctl.rc_free, rsm, r_tnext);
2930                 rack->rc_free_cnt--;
2931                 return (rsm);
2932         }
2933         return (NULL);
2934 }
2935
2936 static struct rack_sendmap *
2937 rack_alloc_full_limit(struct tcp_rack *rack)
2938 {
2939         if ((V_tcp_map_entries_limit > 0) &&
2940             (rack->do_detection == 0) &&
2941             (rack->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
2942                 counter_u64_add(rack_to_alloc_limited, 1);
2943                 if (!rack->alloc_limit_reported) {
2944                         rack->alloc_limit_reported = 1;
2945                         counter_u64_add(rack_alloc_limited_conns, 1);
2946                 }
2947                 return (NULL);
2948         }
2949         return (rack_alloc(rack));
2950 }
2951
2952 /* wrapper to allocate a sendmap entry, subject to a specific limit */
2953 static struct rack_sendmap *
2954 rack_alloc_limit(struct tcp_rack *rack, uint8_t limit_type)
2955 {
2956         struct rack_sendmap *rsm;
2957
2958         if (limit_type) {
2959                 /* currently there is only one limit type */
2960                 if (V_tcp_map_split_limit > 0 &&
2961                     (rack->do_detection == 0) &&
2962                     rack->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
2963                         counter_u64_add(rack_split_limited, 1);
2964                         if (!rack->alloc_limit_reported) {
2965                                 rack->alloc_limit_reported = 1;
2966                                 counter_u64_add(rack_alloc_limited_conns, 1);
2967                         }
2968                         return (NULL);
2969                 }
2970         }
2971
2972         /* allocate and mark in the limit type, if set */
2973         rsm = rack_alloc(rack);
2974         if (rsm != NULL && limit_type) {
2975                 rsm->r_limit_type = limit_type;
2976                 rack->r_ctl.rc_num_split_allocs++;
2977         }
2978         return (rsm);
2979 }
2980
2981 static void
2982 rack_free(struct tcp_rack *rack, struct rack_sendmap *rsm)
2983 {
2984         if (rsm->r_flags & RACK_APP_LIMITED) {
2985                 if (rack->r_ctl.rc_app_limited_cnt > 0) {
2986                         rack->r_ctl.rc_app_limited_cnt--;
2987                 }
2988         }
2989         if (rsm->r_limit_type) {
2990                 /* currently there is only one limit type */
2991                 rack->r_ctl.rc_num_split_allocs--;
2992         }
2993         if (rsm == rack->r_ctl.rc_first_appl) {
2994                 if (rack->r_ctl.rc_app_limited_cnt == 0)
2995                         rack->r_ctl.rc_first_appl = NULL;
2996                 else {
2997                         /* Follow the next one out */
2998                         struct rack_sendmap fe;
2999
3000                         fe.r_start = rsm->r_nseq_appl;
3001                         rack->r_ctl.rc_first_appl = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
3002                 }
3003         }
3004         if (rsm == rack->r_ctl.rc_resend)
3005                 rack->r_ctl.rc_resend = NULL;
3006         if (rsm == rack->r_ctl.rc_rsm_at_retran)
3007                 rack->r_ctl.rc_rsm_at_retran = NULL;
3008         if (rsm == rack->r_ctl.rc_end_appl)
3009                 rack->r_ctl.rc_end_appl = NULL;
3010         if (rack->r_ctl.rc_tlpsend == rsm)
3011                 rack->r_ctl.rc_tlpsend = NULL;
3012         if (rack->r_ctl.rc_sacklast == rsm)
3013                 rack->r_ctl.rc_sacklast = NULL;
3014         memset(rsm, 0, sizeof(struct rack_sendmap));
3015         TAILQ_INSERT_HEAD(&rack->r_ctl.rc_free, rsm, r_tnext);
3016         rack->rc_free_cnt++;
3017 }
3018
3019 static void
3020 rack_free_trim(struct tcp_rack *rack)
3021 {
3022         struct rack_sendmap *rsm;
3023
3024         /*
3025          * Free up all the tail entries until
3026          * we get our list down to the limit.
3027          */
3028         while (rack->rc_free_cnt > rack_free_cache) {
3029                 rsm = TAILQ_LAST(&rack->r_ctl.rc_free, rack_head);
3030                 TAILQ_REMOVE(&rack->r_ctl.rc_free, rsm, r_tnext);
3031                 rack->rc_free_cnt--;
3032                 uma_zfree(rack_zone, rsm);
3033         }
3034 }
3035
3036
3037 static uint32_t
3038 rack_get_measure_window(struct tcpcb *tp, struct tcp_rack *rack)
3039 {
3040         uint64_t srtt, bw, len, tim;
3041         uint32_t segsiz, def_len, minl;
3042
3043         segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
3044         def_len = rack_def_data_window * segsiz;
3045         if (rack->rc_gp_filled == 0) {
3046                 /*
3047                  * We have no measurement (IW is in flight?) so
3048                  * we can only guess using our data_window sysctl
3049                  * value (usually 100MSS).
3050                  */
3051                 return (def_len);
3052         }
3053         /*
3054          * Now we have a number of factors to consider.
3055          *
3056          * 1) We have a desired BDP which is usually
3057          *    at least 2.
3058          * 2) We have a minimum number of rtt's usually 1 SRTT
3059          *    but we allow it too to be more.
3060          * 3) We want to make sure a measurement last N useconds (if
3061          *    we have set rack_min_measure_usec.
3062          *
3063          * We handle the first concern here by trying to create a data
3064          * window of max(rack_def_data_window, DesiredBDP). The
3065          * second concern we handle in not letting the measurement
3066          * window end normally until at least the required SRTT's
3067          * have gone by which is done further below in
3068          * rack_enough_for_measurement(). Finally the third concern
3069          * we also handle here by calculating how long that time
3070          * would take at the current BW and then return the
3071          * max of our first calculation and that length. Note
3072          * that if rack_min_measure_usec is 0, we don't deal
3073          * with concern 3. Also for both Concern 1 and 3 an
3074          * application limited period could end the measurement
3075          * earlier.
3076          *
3077          * So lets calculate the BDP with the "known" b/w using
3078          * the SRTT has our rtt and then multiply it by the
3079          * goal.
3080          */
3081         bw = rack_get_bw(rack);
3082         srtt = (uint64_t)tp->t_srtt;
3083         len = bw * srtt;
3084         len /= (uint64_t)HPTS_USEC_IN_SEC;
3085         len *= max(1, rack_goal_bdp);
3086         /* Now we need to round up to the nearest MSS */
3087         len = roundup(len, segsiz);
3088         if (rack_min_measure_usec) {
3089                 /* Now calculate our min length for this b/w */
3090                 tim = rack_min_measure_usec;
3091                 minl = (tim * bw) / (uint64_t)HPTS_USEC_IN_SEC;
3092                 if (minl == 0)
3093                         minl = 1;
3094                 minl = roundup(minl, segsiz);
3095                 if (len < minl)
3096                         len = minl;
3097         }
3098         /*
3099          * Now if we have a very small window we want
3100          * to attempt to get the window that is
3101          * as small as possible. This happens on
3102          * low b/w connections and we don't want to
3103          * span huge numbers of rtt's between measurements.
3104          *
3105          * We basically include 2 over our "MIN window" so
3106          * that the measurement can be shortened (possibly) by
3107          * an ack'ed packet.
3108          */
3109         if (len < def_len)
3110                 return (max((uint32_t)len, ((MIN_GP_WIN+2) * segsiz)));
3111         else
3112                 return (max((uint32_t)len, def_len));
3113
3114 }
3115
3116 static int
3117 rack_enough_for_measurement(struct tcpcb *tp, struct tcp_rack *rack, tcp_seq th_ack)
3118 {
3119         uint32_t tim, srtts, segsiz;
3120
3121         /*
3122          * Has enough time passed for the GP measurement to be valid?
3123          */
3124         if ((tp->snd_max == tp->snd_una) ||
3125             (th_ack == tp->snd_max)){
3126                 /* All is acked */
3127                 return (1);
3128         }
3129         if (SEQ_LT(th_ack, tp->gput_seq)) {
3130                 /* Not enough bytes yet */
3131                 return (0);
3132         }
3133         segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
3134         if (SEQ_LT(th_ack, tp->gput_ack) &&
3135             ((th_ack - tp->gput_seq) < max(rc_init_window(rack), (MIN_GP_WIN * segsiz)))) {
3136                 /* Not enough bytes yet */
3137                 return (0);
3138         }
3139         if (rack->r_ctl.rc_first_appl &&
3140             (rack->r_ctl.rc_first_appl->r_start == th_ack)) {
3141                 /*
3142                  * We are up to the app limited point
3143                  * we have to measure irrespective of the time..
3144                  */
3145                 return (1);
3146         }
3147         /* Now what about time? */
3148         srtts = (rack->r_ctl.rc_gp_srtt * rack_min_srtts);
3149         tim = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time) - tp->gput_ts;
3150         if (tim >= srtts) {
3151                 return (1);
3152         }
3153         /* Nope not even a full SRTT has passed */
3154         return (0);
3155 }
3156
3157 static void
3158 rack_log_timely(struct tcp_rack *rack,
3159                 uint32_t logged, uint64_t cur_bw, uint64_t low_bnd,
3160                 uint64_t up_bnd, int line, uint8_t method)
3161 {
3162         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
3163                 union tcp_log_stackspecific log;
3164                 struct timeval tv;
3165
3166                 memset(&log, 0, sizeof(log));
3167                 log.u_bbr.flex1 = logged;
3168                 log.u_bbr.flex2 = rack->rc_gp_timely_inc_cnt;
3169                 log.u_bbr.flex2 <<= 4;
3170                 log.u_bbr.flex2 |= rack->rc_gp_timely_dec_cnt;
3171                 log.u_bbr.flex2 <<= 4;
3172                 log.u_bbr.flex2 |= rack->rc_gp_incr;
3173                 log.u_bbr.flex2 <<= 4;
3174                 log.u_bbr.flex2 |= rack->rc_gp_bwred;
3175                 log.u_bbr.flex3 = rack->rc_gp_incr;
3176                 log.u_bbr.flex4 = rack->r_ctl.rack_per_of_gp_ss;
3177                 log.u_bbr.flex5 = rack->r_ctl.rack_per_of_gp_ca;
3178                 log.u_bbr.flex6 = rack->r_ctl.rack_per_of_gp_rec;
3179                 log.u_bbr.flex7 = rack->rc_gp_bwred;
3180                 log.u_bbr.flex8 = method;
3181                 log.u_bbr.cur_del_rate = cur_bw;
3182                 log.u_bbr.delRate = low_bnd;
3183                 log.u_bbr.bw_inuse = up_bnd;
3184                 log.u_bbr.rttProp = rack_get_bw(rack);
3185                 log.u_bbr.pkt_epoch = line;
3186                 log.u_bbr.pkts_out = rack->r_ctl.rc_rtt_diff;
3187                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
3188                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
3189                 log.u_bbr.epoch = rack->r_ctl.rc_gp_srtt;
3190                 log.u_bbr.lt_epoch = rack->r_ctl.rc_prev_gp_srtt;
3191                 log.u_bbr.cwnd_gain = rack->rc_dragged_bottom;
3192                 log.u_bbr.cwnd_gain <<= 1;
3193                 log.u_bbr.cwnd_gain |= rack->rc_gp_saw_rec;
3194                 log.u_bbr.cwnd_gain <<= 1;
3195                 log.u_bbr.cwnd_gain |= rack->rc_gp_saw_ss;
3196                 log.u_bbr.cwnd_gain <<= 1;
3197                 log.u_bbr.cwnd_gain |= rack->rc_gp_saw_ca;
3198                 log.u_bbr.lost = rack->r_ctl.rc_loss_count;
3199                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
3200                     &rack->rc_inp->inp_socket->so_rcv,
3201                     &rack->rc_inp->inp_socket->so_snd,
3202                     TCP_TIMELY_WORK, 0,
3203                     0, &log, false, &tv);
3204         }
3205 }
3206
3207 static int
3208 rack_bw_can_be_raised(struct tcp_rack *rack, uint64_t cur_bw, uint64_t last_bw_est, uint16_t mult)
3209 {
3210         /*
3211          * Before we increase we need to know if
3212          * the estimate just made was less than
3213          * our pacing goal (i.e. (cur_bw * mult) > last_bw_est)
3214          *
3215          * If we already are pacing at a fast enough
3216          * rate to push us faster there is no sense of
3217          * increasing.
3218          *
3219          * We first caculate our actual pacing rate (ss or ca multipler
3220          * times our cur_bw).
3221          *
3222          * Then we take the last measured rate and multipy by our
3223          * maximum pacing overage to give us a max allowable rate.
3224          *
3225          * If our act_rate is smaller than our max_allowable rate
3226          * then we should increase. Else we should hold steady.
3227          *
3228          */
3229         uint64_t act_rate, max_allow_rate;
3230
3231         if (rack_timely_no_stopping)
3232                 return (1);
3233
3234         if ((cur_bw == 0) || (last_bw_est == 0)) {
3235                 /*
3236                  * Initial startup case or
3237                  * everything is acked case.
3238                  */
3239                 rack_log_timely(rack,  mult, cur_bw, 0, 0,
3240                                 __LINE__, 9);
3241                 return (1);
3242         }
3243         if (mult <= 100) {
3244                 /*
3245                  * We can always pace at or slightly above our rate.
3246                  */
3247                 rack_log_timely(rack,  mult, cur_bw, 0, 0,
3248                                 __LINE__, 9);
3249                 return (1);
3250         }
3251         act_rate = cur_bw * (uint64_t)mult;
3252         act_rate /= 100;
3253         max_allow_rate = last_bw_est * ((uint64_t)rack_max_per_above + (uint64_t)100);
3254         max_allow_rate /= 100;
3255         if (act_rate < max_allow_rate) {
3256                 /*
3257                  * Here the rate we are actually pacing at
3258                  * is smaller than 10% above our last measurement.
3259                  * This means we are pacing below what we would
3260                  * like to try to achieve (plus some wiggle room).
3261                  */
3262                 rack_log_timely(rack,  mult, cur_bw, act_rate, max_allow_rate,
3263                                 __LINE__, 9);
3264                 return (1);
3265         } else {
3266                 /*
3267                  * Here we are already pacing at least rack_max_per_above(10%)
3268                  * what we are getting back. This indicates most likely
3269                  * that we are being limited (cwnd/rwnd/app) and can't
3270                  * get any more b/w. There is no sense of trying to
3271                  * raise up the pacing rate its not speeding us up
3272                  * and we already are pacing faster than we are getting.
3273                  */
3274                 rack_log_timely(rack,  mult, cur_bw, act_rate, max_allow_rate,
3275                                 __LINE__, 8);
3276                 return (0);
3277         }
3278 }
3279
3280 static void
3281 rack_validate_multipliers_at_or_above100(struct tcp_rack *rack)
3282 {
3283         /*
3284          * When we drag bottom, we want to assure
3285          * that no multiplier is below 1.0, if so
3286          * we want to restore it to at least that.
3287          */
3288         if (rack->r_ctl.rack_per_of_gp_rec  < 100) {
3289                 /* This is unlikely we usually do not touch recovery */
3290                 rack->r_ctl.rack_per_of_gp_rec = 100;
3291         }
3292         if (rack->r_ctl.rack_per_of_gp_ca < 100) {
3293                 rack->r_ctl.rack_per_of_gp_ca = 100;
3294         }
3295         if (rack->r_ctl.rack_per_of_gp_ss < 100) {
3296                 rack->r_ctl.rack_per_of_gp_ss = 100;
3297         }
3298 }
3299
3300 static void
3301 rack_validate_multipliers_at_or_below_100(struct tcp_rack *rack)
3302 {
3303         if (rack->r_ctl.rack_per_of_gp_ca > 100) {
3304                 rack->r_ctl.rack_per_of_gp_ca = 100;
3305         }
3306         if (rack->r_ctl.rack_per_of_gp_ss > 100) {
3307                 rack->r_ctl.rack_per_of_gp_ss = 100;
3308         }
3309 }
3310
3311 static void
3312 rack_increase_bw_mul(struct tcp_rack *rack, int timely_says, uint64_t cur_bw, uint64_t last_bw_est, int override)
3313 {
3314         int32_t  calc, logged, plus;
3315
3316         logged = 0;
3317
3318         if (override) {
3319                 /*
3320                  * override is passed when we are
3321                  * loosing b/w and making one last
3322                  * gasp at trying to not loose out
3323                  * to a new-reno flow.
3324                  */
3325                 goto extra_boost;
3326         }
3327         /* In classic timely we boost by 5x if we have 5 increases in a row, lets not */
3328         if (rack->rc_gp_incr &&
3329             ((rack->rc_gp_timely_inc_cnt + 1) >= RACK_TIMELY_CNT_BOOST)) {
3330                 /*
3331                  * Reset and get 5 strokes more before the boost. Note
3332                  * that the count is 0 based so we have to add one.
3333                  */
3334 extra_boost:
3335                 plus = (uint32_t)rack_gp_increase_per * RACK_TIMELY_CNT_BOOST;
3336                 rack->rc_gp_timely_inc_cnt = 0;
3337         } else
3338                 plus = (uint32_t)rack_gp_increase_per;
3339         /* Must be at least 1% increase for true timely increases */
3340         if ((plus < 1) &&
3341             ((rack->r_ctl.rc_rtt_diff <= 0) || (timely_says <= 0)))
3342                 plus = 1;
3343         if (rack->rc_gp_saw_rec &&
3344             (rack->rc_gp_no_rec_chg == 0) &&
3345             rack_bw_can_be_raised(rack, cur_bw, last_bw_est,
3346                                   rack->r_ctl.rack_per_of_gp_rec)) {
3347                 /* We have been in recovery ding it too */
3348                 calc = rack->r_ctl.rack_per_of_gp_rec + plus;
3349                 if (calc > 0xffff)
3350                         calc = 0xffff;
3351                 logged |= 1;
3352                 rack->r_ctl.rack_per_of_gp_rec = (uint16_t)calc;
3353                 if (rack_per_upper_bound_ss &&
3354                     (rack->rc_dragged_bottom == 0) &&
3355                     (rack->r_ctl.rack_per_of_gp_rec > rack_per_upper_bound_ss))
3356                         rack->r_ctl.rack_per_of_gp_rec = rack_per_upper_bound_ss;
3357         }
3358         if (rack->rc_gp_saw_ca &&
3359             (rack->rc_gp_saw_ss == 0) &&
3360             rack_bw_can_be_raised(rack, cur_bw, last_bw_est,
3361                                   rack->r_ctl.rack_per_of_gp_ca)) {
3362                 /* In CA */
3363                 calc = rack->r_ctl.rack_per_of_gp_ca + plus;
3364                 if (calc > 0xffff)
3365                         calc = 0xffff;
3366                 logged |= 2;
3367                 rack->r_ctl.rack_per_of_gp_ca = (uint16_t)calc;
3368                 if (rack_per_upper_bound_ca &&
3369                     (rack->rc_dragged_bottom == 0) &&
3370                     (rack->r_ctl.rack_per_of_gp_ca > rack_per_upper_bound_ca))
3371                         rack->r_ctl.rack_per_of_gp_ca = rack_per_upper_bound_ca;
3372         }
3373         if (rack->rc_gp_saw_ss &&
3374             rack_bw_can_be_raised(rack, cur_bw, last_bw_est,
3375                                   rack->r_ctl.rack_per_of_gp_ss)) {
3376                 /* In SS */
3377                 calc = rack->r_ctl.rack_per_of_gp_ss + plus;
3378                 if (calc > 0xffff)
3379                         calc = 0xffff;
3380                 rack->r_ctl.rack_per_of_gp_ss = (uint16_t)calc;
3381                 if (rack_per_upper_bound_ss &&
3382                     (rack->rc_dragged_bottom == 0) &&
3383                     (rack->r_ctl.rack_per_of_gp_ss > rack_per_upper_bound_ss))
3384                         rack->r_ctl.rack_per_of_gp_ss = rack_per_upper_bound_ss;
3385                 logged |= 4;
3386         }
3387         if (logged &&
3388             (rack->rc_gp_incr == 0)){
3389                 /* Go into increment mode */
3390                 rack->rc_gp_incr = 1;
3391                 rack->rc_gp_timely_inc_cnt = 0;
3392         }
3393         if (rack->rc_gp_incr &&
3394             logged &&
3395             (rack->rc_gp_timely_inc_cnt < RACK_TIMELY_CNT_BOOST)) {
3396                 rack->rc_gp_timely_inc_cnt++;
3397         }
3398         rack_log_timely(rack,  logged, plus, 0, 0,
3399                         __LINE__, 1);
3400 }
3401
3402 static uint32_t
3403 rack_get_decrease(struct tcp_rack *rack, uint32_t curper, int32_t rtt_diff)
3404 {
3405         /*
3406          * norm_grad = rtt_diff / minrtt;
3407          * new_per = curper * (1 - B * norm_grad)
3408          *
3409          * B = rack_gp_decrease_per (default 10%)
3410          * rtt_dif = input var current rtt-diff
3411          * curper = input var current percentage
3412          * minrtt = from rack filter
3413          *
3414          */
3415         uint64_t perf;
3416
3417         perf = (((uint64_t)curper * ((uint64_t)1000000 -
3418                     ((uint64_t)rack_gp_decrease_per * (uint64_t)10000 *
3419                      (((uint64_t)rtt_diff * (uint64_t)1000000)/
3420                       (uint64_t)get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt)))/
3421                      (uint64_t)1000000)) /
3422                 (uint64_t)1000000);
3423         if (perf > curper) {
3424                 /* TSNH */
3425                 perf = curper - 1;
3426         }
3427         return ((uint32_t)perf);
3428 }
3429
3430 static uint32_t
3431 rack_decrease_highrtt(struct tcp_rack *rack, uint32_t curper, uint32_t rtt)
3432 {
3433         /*
3434          *                                   highrttthresh
3435          * result = curper * (1 - (B * ( 1 -  ------          ))
3436          *                                     gp_srtt
3437          *
3438          * B = rack_gp_decrease_per (default 10%)
3439          * highrttthresh = filter_min * rack_gp_rtt_maxmul
3440          */
3441         uint64_t perf;
3442         uint32_t highrttthresh;
3443
3444         highrttthresh = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) * rack_gp_rtt_maxmul;
3445
3446         perf = (((uint64_t)curper * ((uint64_t)1000000 -
3447                                      ((uint64_t)rack_gp_decrease_per * ((uint64_t)1000000 -
3448                                         ((uint64_t)highrttthresh * (uint64_t)1000000) /
3449                                                     (uint64_t)rtt)) / 100)) /(uint64_t)1000000);
3450         return (perf);
3451 }
3452
3453 static void
3454 rack_decrease_bw_mul(struct tcp_rack *rack, int timely_says, uint32_t rtt, int32_t rtt_diff)
3455 {
3456         uint64_t logvar, logvar2, logvar3;
3457         uint32_t logged, new_per, ss_red, ca_red, rec_red, alt, val;
3458
3459         if (rack->rc_gp_incr) {
3460                 /* Turn off increment counting */
3461                 rack->rc_gp_incr = 0;
3462                 rack->rc_gp_timely_inc_cnt = 0;
3463         }
3464         ss_red = ca_red = rec_red = 0;
3465         logged = 0;
3466         /* Calculate the reduction value */
3467         if (rtt_diff < 0) {
3468                 rtt_diff *= -1;
3469         }
3470         /* Must be at least 1% reduction */
3471         if (rack->rc_gp_saw_rec && (rack->rc_gp_no_rec_chg == 0)) {
3472                 /* We have been in recovery ding it too */
3473                 if (timely_says == 2) {
3474                         new_per = rack_decrease_highrtt(rack, rack->r_ctl.rack_per_of_gp_rec, rtt);
3475                         alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_rec, rtt_diff);
3476                         if (alt < new_per)
3477                                 val = alt;
3478                         else
3479                                 val = new_per;
3480                 } else
3481                          val = new_per = alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_rec, rtt_diff);
3482                 if (rack->r_ctl.rack_per_of_gp_rec > val) {
3483                         rec_red = (rack->r_ctl.rack_per_of_gp_rec - val);
3484                         rack->r_ctl.rack_per_of_gp_rec = (uint16_t)val;
3485                 } else {
3486                         rack->r_ctl.rack_per_of_gp_rec = rack_per_lower_bound;
3487                         rec_red = 0;
3488                 }
3489                 if (rack_per_lower_bound > rack->r_ctl.rack_per_of_gp_rec)
3490                         rack->r_ctl.rack_per_of_gp_rec = rack_per_lower_bound;
3491                 logged |= 1;
3492         }
3493         if (rack->rc_gp_saw_ss) {
3494                 /* Sent in SS */
3495                 if (timely_says == 2) {
3496                         new_per = rack_decrease_highrtt(rack, rack->r_ctl.rack_per_of_gp_ss, rtt);
3497                         alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_rec, rtt_diff);
3498                         if (alt < new_per)
3499                                 val = alt;
3500                         else
3501                                 val = new_per;
3502                 } else
3503                         val = new_per = alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_ss, rtt_diff);
3504                 if (rack->r_ctl.rack_per_of_gp_ss > new_per) {
3505                         ss_red = rack->r_ctl.rack_per_of_gp_ss - val;
3506                         rack->r_ctl.rack_per_of_gp_ss = (uint16_t)val;
3507                 } else {
3508                         ss_red = new_per;
3509                         rack->r_ctl.rack_per_of_gp_ss = rack_per_lower_bound;
3510                         logvar = new_per;
3511                         logvar <<= 32;
3512                         logvar |= alt;
3513                         logvar2 = (uint32_t)rtt;
3514                         logvar2 <<= 32;
3515                         logvar2 |= (uint32_t)rtt_diff;
3516                         logvar3 = rack_gp_rtt_maxmul;
3517                         logvar3 <<= 32;
3518                         logvar3 |= get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt);
3519                         rack_log_timely(rack, timely_says,
3520                                         logvar2, logvar3,
3521                                         logvar, __LINE__, 10);
3522                 }
3523                 if (rack_per_lower_bound > rack->r_ctl.rack_per_of_gp_ss)
3524                         rack->r_ctl.rack_per_of_gp_ss = rack_per_lower_bound;
3525                 logged |= 4;
3526         } else if (rack->rc_gp_saw_ca) {
3527                 /* Sent in CA */
3528                 if (timely_says == 2) {
3529                         new_per = rack_decrease_highrtt(rack, rack->r_ctl.rack_per_of_gp_ca, rtt);
3530                         alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_rec, rtt_diff);
3531                         if (alt < new_per)
3532                                 val = alt;
3533                         else
3534                                 val = new_per;
3535                 } else
3536                         val = new_per = alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_ca, rtt_diff);
3537                 if (rack->r_ctl.rack_per_of_gp_ca > val) {
3538                         ca_red = rack->r_ctl.rack_per_of_gp_ca - val;
3539                         rack->r_ctl.rack_per_of_gp_ca = (uint16_t)val;
3540                 } else {
3541                         rack->r_ctl.rack_per_of_gp_ca = rack_per_lower_bound;
3542                         ca_red = 0;
3543                         logvar = new_per;
3544                         logvar <<= 32;
3545                         logvar |= alt;
3546                         logvar2 = (uint32_t)rtt;
3547                         logvar2 <<= 32;
3548                         logvar2 |= (uint32_t)rtt_diff;
3549                         logvar3 = rack_gp_rtt_maxmul;
3550                         logvar3 <<= 32;
3551                         logvar3 |= get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt);
3552                         rack_log_timely(rack, timely_says,
3553                                         logvar2, logvar3,
3554                                         logvar, __LINE__, 10);
3555                 }
3556                 if (rack_per_lower_bound > rack->r_ctl.rack_per_of_gp_ca)
3557                         rack->r_ctl.rack_per_of_gp_ca = rack_per_lower_bound;
3558                 logged |= 2;
3559         }
3560         if (rack->rc_gp_timely_dec_cnt < 0x7) {
3561                 rack->rc_gp_timely_dec_cnt++;
3562                 if (rack_timely_dec_clear &&
3563                     (rack->rc_gp_timely_dec_cnt == rack_timely_dec_clear))
3564                         rack->rc_gp_timely_dec_cnt = 0;
3565         }
3566         logvar = ss_red;
3567         logvar <<= 32;
3568         logvar |= ca_red;
3569         rack_log_timely(rack,  logged, rec_red, rack_per_lower_bound, logvar,
3570                         __LINE__, 2);
3571 }
3572
3573 static void
3574 rack_log_rtt_shrinks(struct tcp_rack *rack, uint32_t us_cts,
3575                      uint32_t rtt, uint32_t line, uint8_t reas)
3576 {
3577         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
3578                 union tcp_log_stackspecific log;
3579                 struct timeval tv;
3580
3581                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
3582                 log.u_bbr.flex1 = line;
3583                 log.u_bbr.flex2 = rack->r_ctl.rc_time_probertt_starts;
3584                 log.u_bbr.flex3 = rack->r_ctl.rc_lower_rtt_us_cts;
3585                 log.u_bbr.flex4 = rack->r_ctl.rack_per_of_gp_ss;
3586                 log.u_bbr.flex5 = rtt;
3587                 log.u_bbr.flex6 = rack->rc_highly_buffered;
3588                 log.u_bbr.flex6 <<= 1;
3589                 log.u_bbr.flex6 |= rack->forced_ack;
3590                 log.u_bbr.flex6 <<= 1;
3591                 log.u_bbr.flex6 |= rack->rc_gp_dyn_mul;
3592                 log.u_bbr.flex6 <<= 1;
3593                 log.u_bbr.flex6 |= rack->in_probe_rtt;
3594                 log.u_bbr.flex6 <<= 1;
3595                 log.u_bbr.flex6 |= rack->measure_saw_probe_rtt;
3596                 log.u_bbr.flex7 = rack->r_ctl.rack_per_of_gp_probertt;
3597                 log.u_bbr.pacing_gain = rack->r_ctl.rack_per_of_gp_ca;
3598                 log.u_bbr.cwnd_gain = rack->r_ctl.rack_per_of_gp_rec;
3599                 log.u_bbr.flex8 = reas;
3600                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
3601                 log.u_bbr.delRate = rack_get_bw(rack);
3602                 log.u_bbr.cur_del_rate = rack->r_ctl.rc_highest_us_rtt;
3603                 log.u_bbr.cur_del_rate <<= 32;
3604                 log.u_bbr.cur_del_rate |= rack->r_ctl.rc_lowest_us_rtt;
3605                 log.u_bbr.applimited = rack->r_ctl.rc_time_probertt_entered;
3606                 log.u_bbr.pkts_out = rack->r_ctl.rc_rtt_diff;
3607                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
3608                 log.u_bbr.epoch = rack->r_ctl.rc_gp_srtt;
3609                 log.u_bbr.lt_epoch = rack->r_ctl.rc_prev_gp_srtt;
3610                 log.u_bbr.pkt_epoch = rack->r_ctl.rc_lower_rtt_us_cts;
3611                 log.u_bbr.delivered = rack->r_ctl.rc_target_probertt_flight;
3612                 log.u_bbr.lost = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt);
3613                 log.u_bbr.rttProp = us_cts;
3614                 log.u_bbr.rttProp <<= 32;
3615                 log.u_bbr.rttProp |= rack->r_ctl.rc_entry_gp_rtt;
3616                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
3617                     &rack->rc_inp->inp_socket->so_rcv,
3618                     &rack->rc_inp->inp_socket->so_snd,
3619                     BBR_LOG_RTT_SHRINKS, 0,
3620                     0, &log, false, &rack->r_ctl.act_rcv_time);
3621         }
3622 }
3623
3624 static void
3625 rack_set_prtt_target(struct tcp_rack *rack, uint32_t segsiz, uint32_t rtt)
3626 {
3627         uint64_t bwdp;
3628
3629         bwdp = rack_get_bw(rack);
3630         bwdp *= (uint64_t)rtt;
3631         bwdp /= (uint64_t)HPTS_USEC_IN_SEC;
3632         rack->r_ctl.rc_target_probertt_flight = roundup((uint32_t)bwdp, segsiz);
3633         if (rack->r_ctl.rc_target_probertt_flight < (segsiz * rack_timely_min_segs)) {
3634                 /*
3635                  * A window protocol must be able to have 4 packets
3636                  * outstanding as the floor in order to function
3637                  * (especially considering delayed ack :D).
3638                  */
3639                 rack->r_ctl.rc_target_probertt_flight = (segsiz * rack_timely_min_segs);
3640         }
3641 }
3642
3643 static void
3644 rack_enter_probertt(struct tcp_rack *rack, uint32_t us_cts)
3645 {
3646         /**
3647          * ProbeRTT is a bit different in rack_pacing than in
3648          * BBR. It is like BBR in that it uses the lowering of
3649          * the RTT as a signal that we saw something new and
3650          * counts from there for how long between. But it is
3651          * different in that its quite simple. It does not
3652          * play with the cwnd and wait until we get down
3653          * to N segments outstanding and hold that for
3654          * 200ms. Instead it just sets the pacing reduction
3655          * rate to a set percentage (70 by default) and hold
3656          * that for a number of recent GP Srtt's.
3657          */
3658         uint32_t segsiz;
3659
3660         if (rack->rc_gp_dyn_mul == 0)
3661                 return;
3662
3663         if (rack->rc_tp->snd_max == rack->rc_tp->snd_una) {
3664                 /* We are idle */
3665                 return;
3666         }
3667         if ((rack->rc_tp->t_flags & TF_GPUTINPROG) &&
3668             SEQ_GT(rack->rc_tp->snd_una, rack->rc_tp->gput_seq)) {
3669                 /*
3670                  * Stop the goodput now, the idea here is
3671                  * that future measurements with in_probe_rtt
3672                  * won't register if they are not greater so
3673                  * we want to get what info (if any) is available
3674                  * now.
3675                  */
3676                 rack_do_goodput_measurement(rack->rc_tp, rack,
3677                                             rack->rc_tp->snd_una, __LINE__);
3678         }
3679         rack->r_ctl.rack_per_of_gp_probertt = rack_per_of_gp_probertt;
3680         rack->r_ctl.rc_time_probertt_entered = us_cts;
3681         segsiz = min(ctf_fixed_maxseg(rack->rc_tp),
3682                      rack->r_ctl.rc_pace_min_segs);
3683         rack->in_probe_rtt = 1;
3684         rack->measure_saw_probe_rtt = 1;
3685         rack->r_ctl.rc_lower_rtt_us_cts = us_cts;
3686         rack->r_ctl.rc_time_probertt_starts = 0;
3687         rack->r_ctl.rc_entry_gp_rtt = rack->r_ctl.rc_gp_srtt;
3688         if (rack_probertt_use_min_rtt_entry)
3689                 rack_set_prtt_target(rack, segsiz, get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt));
3690         else
3691                 rack_set_prtt_target(rack, segsiz, rack->r_ctl.rc_gp_srtt);
3692         rack_log_rtt_shrinks(rack,  us_cts,  get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
3693                              __LINE__, RACK_RTTS_ENTERPROBE);
3694 }
3695
3696 static void
3697 rack_exit_probertt(struct tcp_rack *rack, uint32_t us_cts)
3698 {
3699         struct rack_sendmap *rsm;
3700         uint32_t segsiz;
3701
3702         segsiz = min(ctf_fixed_maxseg(rack->rc_tp),
3703                      rack->r_ctl.rc_pace_min_segs);
3704         rack->in_probe_rtt = 0;
3705         if ((rack->rc_tp->t_flags & TF_GPUTINPROG) &&
3706             SEQ_GT(rack->rc_tp->snd_una, rack->rc_tp->gput_seq)) {
3707                 /*
3708                  * Stop the goodput now, the idea here is
3709                  * that future measurements with in_probe_rtt
3710                  * won't register if they are not greater so
3711                  * we want to get what info (if any) is available
3712                  * now.
3713                  */
3714                 rack_do_goodput_measurement(rack->rc_tp, rack,
3715                                             rack->rc_tp->snd_una, __LINE__);
3716         } else if (rack->rc_tp->t_flags & TF_GPUTINPROG) {
3717                 /*
3718                  * We don't have enough data to make a measurement.
3719                  * So lets just stop and start here after exiting
3720                  * probe-rtt. We probably are not interested in
3721                  * the results anyway.
3722                  */
3723                 rack->rc_tp->t_flags &= ~TF_GPUTINPROG;
3724         }
3725         /*
3726          * Measurements through the current snd_max are going
3727          * to be limited by the slower pacing rate.
3728          *
3729          * We need to mark these as app-limited so we
3730          * don't collapse the b/w.
3731          */
3732         rsm = RB_MAX(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
3733         if (rsm && ((rsm->r_flags & RACK_APP_LIMITED) == 0)) {
3734                 if (rack->r_ctl.rc_app_limited_cnt == 0)
3735                         rack->r_ctl.rc_end_appl = rack->r_ctl.rc_first_appl = rsm;
3736                 else {
3737                         /*
3738                          * Go out to the end app limited and mark
3739                          * this new one as next and move the end_appl up
3740                          * to this guy.
3741                          */
3742                         if (rack->r_ctl.rc_end_appl)
3743                                 rack->r_ctl.rc_end_appl->r_nseq_appl = rsm->r_start;
3744                         rack->r_ctl.rc_end_appl = rsm;
3745                 }
3746                 rsm->r_flags |= RACK_APP_LIMITED;
3747                 rack->r_ctl.rc_app_limited_cnt++;
3748         }
3749         /*
3750          * Now, we need to examine our pacing rate multipliers.
3751          * If its under 100%, we need to kick it back up to
3752          * 100%. We also don't let it be over our "max" above
3753          * the actual rate i.e. 100% + rack_clamp_atexit_prtt.
3754          * Note setting clamp_atexit_prtt to 0 has the effect
3755          * of setting CA/SS to 100% always at exit (which is
3756          * the default behavior).
3757          */
3758         if (rack_probertt_clear_is) {
3759                 rack->rc_gp_incr = 0;
3760                 rack->rc_gp_bwred = 0;
3761                 rack->rc_gp_timely_inc_cnt = 0;
3762                 rack->rc_gp_timely_dec_cnt = 0;
3763         }
3764         /* Do we do any clamping at exit? */
3765         if (rack->rc_highly_buffered && rack_atexit_prtt_hbp) {
3766                 rack->r_ctl.rack_per_of_gp_ca = rack_atexit_prtt_hbp;
3767                 rack->r_ctl.rack_per_of_gp_ss = rack_atexit_prtt_hbp;
3768         }
3769         if ((rack->rc_highly_buffered == 0) && rack_atexit_prtt) {
3770                 rack->r_ctl.rack_per_of_gp_ca = rack_atexit_prtt;
3771                 rack->r_ctl.rack_per_of_gp_ss = rack_atexit_prtt;
3772         }
3773         /*
3774          * Lets set rtt_diff to 0, so that we will get a "boost"
3775          * after exiting.
3776          */
3777         rack->r_ctl.rc_rtt_diff = 0;
3778
3779         /* Clear all flags so we start fresh */
3780         rack->rc_tp->t_bytes_acked = 0;
3781         rack->rc_tp->ccv->flags &= ~CCF_ABC_SENTAWND;
3782         /*
3783          * If configured to, set the cwnd and ssthresh to
3784          * our targets.
3785          */
3786         if (rack_probe_rtt_sets_cwnd) {
3787                 uint64_t ebdp;
3788                 uint32_t setto;
3789
3790                 /* Set ssthresh so we get into CA once we hit our target */
3791                 if (rack_probertt_use_min_rtt_exit == 1) {
3792                         /* Set to min rtt */
3793                         rack_set_prtt_target(rack, segsiz,
3794                                              get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt));
3795                 } else if (rack_probertt_use_min_rtt_exit == 2) {
3796                         /* Set to current gp rtt */
3797                         rack_set_prtt_target(rack, segsiz,
3798                                              rack->r_ctl.rc_gp_srtt);
3799                 } else if (rack_probertt_use_min_rtt_exit == 3) {
3800                         /* Set to entry gp rtt */
3801                         rack_set_prtt_target(rack, segsiz,
3802                                              rack->r_ctl.rc_entry_gp_rtt);
3803                 } else {
3804                         uint64_t sum;
3805                         uint32_t setval;
3806
3807                         sum = rack->r_ctl.rc_entry_gp_rtt;
3808                         sum *= 10;
3809                         sum /= (uint64_t)(max(1, rack->r_ctl.rc_gp_srtt));
3810                         if (sum >= 20) {
3811                                 /*
3812                                  * A highly buffered path needs
3813                                  * cwnd space for timely to work.
3814                                  * Lets set things up as if
3815                                  * we are heading back here again.
3816                                  */
3817                                 setval = rack->r_ctl.rc_entry_gp_rtt;
3818                         } else if (sum >= 15) {
3819                                 /*
3820                                  * Lets take the smaller of the
3821                                  * two since we are just somewhat
3822                                  * buffered.
3823                                  */
3824                                 setval = rack->r_ctl.rc_gp_srtt;
3825                                 if (setval > rack->r_ctl.rc_entry_gp_rtt)
3826                                         setval = rack->r_ctl.rc_entry_gp_rtt;
3827                         } else {
3828                                 /*
3829                                  * Here we are not highly buffered
3830                                  * and should pick the min we can to
3831                                  * keep from causing loss.
3832                                  */
3833                                 setval = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt);
3834                         }
3835                         rack_set_prtt_target(rack, segsiz,
3836                                              setval);
3837                 }
3838                 if (rack_probe_rtt_sets_cwnd > 1) {
3839                         /* There is a percentage here to boost */
3840                         ebdp = rack->r_ctl.rc_target_probertt_flight;
3841                         ebdp *= rack_probe_rtt_sets_cwnd;
3842                         ebdp /= 100;
3843                         setto = rack->r_ctl.rc_target_probertt_flight + ebdp;
3844                 } else
3845                         setto = rack->r_ctl.rc_target_probertt_flight;
3846                 rack->rc_tp->snd_cwnd = roundup(setto, segsiz);
3847                 if (rack->rc_tp->snd_cwnd < (segsiz * rack_timely_min_segs)) {
3848                         /* Enforce a min */
3849                         rack->rc_tp->snd_cwnd = segsiz * rack_timely_min_segs;
3850                 }
3851                 /* If we set in the cwnd also set the ssthresh point so we are in CA */
3852                 rack->rc_tp->snd_ssthresh = (rack->rc_tp->snd_cwnd - 1);
3853         }
3854         rack_log_rtt_shrinks(rack,  us_cts,
3855                              get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
3856                              __LINE__, RACK_RTTS_EXITPROBE);
3857         /* Clear times last so log has all the info */
3858         rack->r_ctl.rc_probertt_sndmax_atexit = rack->rc_tp->snd_max;
3859         rack->r_ctl.rc_time_probertt_entered = us_cts;
3860         rack->r_ctl.rc_time_probertt_starts = rack->r_ctl.rc_lower_rtt_us_cts = us_cts;
3861         rack->r_ctl.rc_time_of_last_probertt = us_cts;
3862 }
3863
3864 static void
3865 rack_check_probe_rtt(struct tcp_rack *rack, uint32_t us_cts)
3866 {
3867         /* Check in on probe-rtt */
3868         if (rack->rc_gp_filled == 0) {
3869                 /* We do not do p-rtt unless we have gp measurements */
3870                 return;
3871         }
3872         if (rack->in_probe_rtt) {
3873                 uint64_t no_overflow;
3874                 uint32_t endtime, must_stay;
3875
3876                 if (rack->r_ctl.rc_went_idle_time &&
3877                     ((us_cts - rack->r_ctl.rc_went_idle_time) > rack_min_probertt_hold)) {
3878                         /*
3879                          * We went idle during prtt, just exit now.
3880                          */
3881                         rack_exit_probertt(rack, us_cts);
3882                 } else if (rack_probe_rtt_safety_val &&
3883                     TSTMP_GT(us_cts, rack->r_ctl.rc_time_probertt_entered) &&
3884                     ((us_cts - rack->r_ctl.rc_time_probertt_entered) > rack_probe_rtt_safety_val)) {
3885                         /*
3886                          * Probe RTT safety value triggered!
3887                          */
3888                         rack_log_rtt_shrinks(rack,  us_cts,
3889                                              get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
3890                                              __LINE__, RACK_RTTS_SAFETY);
3891                         rack_exit_probertt(rack, us_cts);
3892                 }
3893                 /* Calculate the max we will wait */
3894                 endtime = rack->r_ctl.rc_time_probertt_entered + (rack->r_ctl.rc_gp_srtt * rack_max_drain_wait);
3895                 if (rack->rc_highly_buffered)
3896                         endtime += (rack->r_ctl.rc_gp_srtt * rack_max_drain_hbp);
3897                 /* Calculate the min we must wait */
3898                 must_stay = rack->r_ctl.rc_time_probertt_entered + (rack->r_ctl.rc_gp_srtt * rack_must_drain);
3899                 if ((ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked) > rack->r_ctl.rc_target_probertt_flight) &&
3900                     TSTMP_LT(us_cts, endtime)) {
3901                         uint32_t calc;
3902                         /* Do we lower more? */
3903 no_exit:
3904                         if (TSTMP_GT(us_cts, rack->r_ctl.rc_time_probertt_entered))
3905                                 calc = us_cts - rack->r_ctl.rc_time_probertt_entered;
3906                         else
3907                                 calc = 0;
3908                         calc /= max(rack->r_ctl.rc_gp_srtt, 1);
3909                         if (calc) {
3910                                 /* Maybe */
3911                                 calc *= rack_per_of_gp_probertt_reduce;
3912                                 rack->r_ctl.rack_per_of_gp_probertt = rack_per_of_gp_probertt - calc;
3913                                 /* Limit it too */
3914                                 if (rack->r_ctl.rack_per_of_gp_probertt < rack_per_of_gp_lowthresh)
3915                                         rack->r_ctl.rack_per_of_gp_probertt = rack_per_of_gp_lowthresh;
3916                         }
3917                         /* We must reach target or the time set */
3918                         return;
3919                 }
3920                 if (rack->r_ctl.rc_time_probertt_starts == 0) {
3921                         if ((TSTMP_LT(us_cts, must_stay) &&
3922                              rack->rc_highly_buffered) ||
3923                              (ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked) >
3924                               rack->r_ctl.rc_target_probertt_flight)) {
3925                                 /* We are not past the must_stay time */
3926                                 goto no_exit;
3927                         }
3928                         rack_log_rtt_shrinks(rack,  us_cts,
3929                                              get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
3930                                              __LINE__, RACK_RTTS_REACHTARGET);
3931                         rack->r_ctl.rc_time_probertt_starts = us_cts;
3932                         if (rack->r_ctl.rc_time_probertt_starts == 0)
3933                                 rack->r_ctl.rc_time_probertt_starts = 1;
3934                         /* Restore back to our rate we want to pace at in prtt */
3935                         rack->r_ctl.rack_per_of_gp_probertt = rack_per_of_gp_probertt;
3936                 }
3937                 /*
3938                  * Setup our end time, some number of gp_srtts plus 200ms.
3939                  */
3940                 no_overflow = ((uint64_t)rack->r_ctl.rc_gp_srtt *
3941                                (uint64_t)rack_probertt_gpsrtt_cnt_mul);
3942                 if (rack_probertt_gpsrtt_cnt_div)
3943                         endtime = (uint32_t)(no_overflow / (uint64_t)rack_probertt_gpsrtt_cnt_div);
3944                 else
3945                         endtime = 0;
3946                 endtime += rack_min_probertt_hold;
3947                 endtime += rack->r_ctl.rc_time_probertt_starts;
3948                 if (TSTMP_GEQ(us_cts,  endtime)) {
3949                         /* yes, exit probertt */
3950                         rack_exit_probertt(rack, us_cts);
3951                 }
3952
3953         } else if ((us_cts - rack->r_ctl.rc_lower_rtt_us_cts) >= rack_time_between_probertt) {
3954                 /* Go into probertt, its been too long since we went lower */
3955                 rack_enter_probertt(rack, us_cts);
3956         }
3957 }
3958
3959 static void
3960 rack_update_multiplier(struct tcp_rack *rack, int32_t timely_says, uint64_t last_bw_est,
3961                        uint32_t rtt, int32_t rtt_diff)
3962 {
3963         uint64_t cur_bw, up_bnd, low_bnd, subfr;
3964         uint32_t losses;
3965
3966         if ((rack->rc_gp_dyn_mul == 0) ||
3967             (rack->use_fixed_rate) ||
3968             (rack->in_probe_rtt) ||
3969             (rack->rc_always_pace == 0)) {
3970                 /* No dynamic GP multipler in play */
3971                 return;
3972         }
3973         losses = rack->r_ctl.rc_loss_count - rack->r_ctl.rc_loss_at_start;
3974         cur_bw = rack_get_bw(rack);
3975         /* Calculate our up and down range */
3976         up_bnd = rack->r_ctl.last_gp_comp_bw * (uint64_t)rack_gp_per_bw_mul_up;
3977         up_bnd /= 100;
3978         up_bnd += rack->r_ctl.last_gp_comp_bw;
3979
3980         subfr = (uint64_t)rack->r_ctl.last_gp_comp_bw * (uint64_t)rack_gp_per_bw_mul_down;
3981         subfr /= 100;
3982         low_bnd = rack->r_ctl.last_gp_comp_bw - subfr;
3983         if ((timely_says == 2) && (rack->r_ctl.rc_no_push_at_mrtt)) {
3984                 /*
3985                  * This is the case where our RTT is above
3986                  * the max target and we have been configured
3987                  * to just do timely no bonus up stuff in that case.
3988                  *
3989                  * There are two configurations, set to 1, and we
3990                  * just do timely if we are over our max. If its
3991                  * set above 1 then we slam the multipliers down
3992                  * to 100 and then decrement per timely.
3993                  */
3994                 rack_log_timely(rack,  timely_says, cur_bw, low_bnd, up_bnd,
3995                                 __LINE__, 3);
3996                 if (rack->r_ctl.rc_no_push_at_mrtt > 1)
3997                         rack_validate_multipliers_at_or_below_100(rack);
3998                 rack_decrease_bw_mul(rack, timely_says, rtt, rtt_diff);
3999         } else if ((last_bw_est < low_bnd) && !losses) {
4000                 /*
4001                  * We are decreasing this is a bit complicated this
4002                  * means we are loosing ground. This could be
4003                  * because another flow entered and we are competing
4004                  * for b/w with it. This will push the RTT up which
4005                  * makes timely unusable unless we want to get shoved
4006                  * into a corner and just be backed off (the age
4007                  * old problem with delay based CC).
4008                  *
4009                  * On the other hand if it was a route change we
4010                  * would like to stay somewhat contained and not
4011                  * blow out the buffers.
4012                  */
4013                 rack_log_timely(rack,  timely_says, cur_bw, low_bnd, up_bnd,
4014                                 __LINE__, 3);
4015                 rack->r_ctl.last_gp_comp_bw = cur_bw;
4016                 if (rack->rc_gp_bwred == 0) {
4017                         /* Go into reduction counting */
4018                         rack->rc_gp_bwred = 1;
4019                         rack->rc_gp_timely_dec_cnt = 0;
4020                 }
4021                 if ((rack->rc_gp_timely_dec_cnt < rack_timely_max_push_drop) ||
4022                     (timely_says == 0)) {
4023                         /*
4024                          * Push another time with a faster pacing
4025                          * to try to gain back (we include override to
4026                          * get a full raise factor).
4027                          */
4028                         if ((rack->rc_gp_saw_ca && rack->r_ctl.rack_per_of_gp_ca <= rack_down_raise_thresh) ||
4029                             (rack->rc_gp_saw_ss && rack->r_ctl.rack_per_of_gp_ss <= rack_down_raise_thresh) ||
4030                             (timely_says == 0) ||
4031                             (rack_down_raise_thresh == 0)) {
4032                                 /*
4033                                  * Do an override up in b/w if we were
4034                                  * below the threshold or if the threshold
4035                                  * is zero we always do the raise.
4036                                  */
4037                                 rack_increase_bw_mul(rack, timely_says, cur_bw, last_bw_est, 1);
4038                         } else {
4039                                 /* Log it stays the same */
4040                                 rack_log_timely(rack,  0, last_bw_est, low_bnd, 0,
4041                                                 __LINE__, 11);
4042                         }
4043                         rack->rc_gp_timely_dec_cnt++;
4044                         /* We are not incrementing really no-count */
4045                         rack->rc_gp_incr = 0;
4046                         rack->rc_gp_timely_inc_cnt = 0;
4047                 } else {
4048                         /*
4049                          * Lets just use the RTT
4050                          * information and give up
4051                          * pushing.
4052                          */
4053                         goto use_timely;
4054                 }
4055         } else if ((timely_says != 2) &&
4056                     !losses &&
4057                     (last_bw_est > up_bnd)) {
4058                 /*
4059                  * We are increasing b/w lets keep going, updating
4060                  * our b/w and ignoring any timely input, unless
4061                  * of course we are at our max raise (if there is one).
4062                  */
4063
4064                 rack_log_timely(rack,  timely_says, cur_bw, low_bnd, up_bnd,
4065                                 __LINE__, 3);
4066                 rack->r_ctl.last_gp_comp_bw = cur_bw;
4067                 if (rack->rc_gp_saw_ss &&
4068                     rack_per_upper_bound_ss &&
4069                      (rack->r_ctl.rack_per_of_gp_ss == rack_per_upper_bound_ss)) {
4070                             /*
4071                              * In cases where we can't go higher
4072                              * we should just use timely.
4073                              */
4074                             goto use_timely;
4075                 }
4076                 if (rack->rc_gp_saw_ca &&
4077                     rack_per_upper_bound_ca &&
4078                     (rack->r_ctl.rack_per_of_gp_ca == rack_per_upper_bound_ca)) {
4079                             /*
4080                              * In cases where we can't go higher
4081                              * we should just use timely.
4082                              */
4083                             goto use_timely;
4084                 }
4085                 rack->rc_gp_bwred = 0;
4086                 rack->rc_gp_timely_dec_cnt = 0;
4087                 /* You get a set number of pushes if timely is trying to reduce */
4088                 if ((rack->rc_gp_incr < rack_timely_max_push_rise) || (timely_says == 0)) {
4089                         rack_increase_bw_mul(rack, timely_says, cur_bw, last_bw_est, 0);
4090                 } else {
4091                         /* Log it stays the same */
4092                         rack_log_timely(rack,  0, last_bw_est, up_bnd, 0,
4093                             __LINE__, 12);
4094                 }
4095                 return;
4096         } else {
4097                 /*
4098                  * We are staying between the lower and upper range bounds
4099                  * so use timely to decide.
4100                  */
4101                 rack_log_timely(rack,  timely_says, cur_bw, low_bnd, up_bnd,
4102                                 __LINE__, 3);
4103 use_timely:
4104                 if (timely_says) {
4105                         rack->rc_gp_incr = 0;
4106                         rack->rc_gp_timely_inc_cnt = 0;
4107                         if ((rack->rc_gp_timely_dec_cnt < rack_timely_max_push_drop) &&
4108                             !losses &&
4109                             (last_bw_est < low_bnd)) {
4110                                 /* We are loosing ground */
4111                                 rack_increase_bw_mul(rack, timely_says, cur_bw, last_bw_est, 0);
4112                                 rack->rc_gp_timely_dec_cnt++;
4113                                 /* We are not incrementing really no-count */
4114                                 rack->rc_gp_incr = 0;
4115                                 rack->rc_gp_timely_inc_cnt = 0;
4116                         } else
4117                                 rack_decrease_bw_mul(rack, timely_says, rtt, rtt_diff);
4118                 } else {
4119                         rack->rc_gp_bwred = 0;
4120                         rack->rc_gp_timely_dec_cnt = 0;
4121                         rack_increase_bw_mul(rack, timely_says, cur_bw, last_bw_est, 0);
4122                 }
4123         }
4124 }
4125
4126 static int32_t
4127 rack_make_timely_judgement(struct tcp_rack *rack, uint32_t rtt, int32_t rtt_diff, uint32_t prev_rtt)
4128 {
4129         int32_t timely_says;
4130         uint64_t log_mult, log_rtt_a_diff;
4131
4132         log_rtt_a_diff = rtt;
4133         log_rtt_a_diff <<= 32;
4134         log_rtt_a_diff |= (uint32_t)rtt_diff;
4135         if (rtt >= (get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) *
4136                     rack_gp_rtt_maxmul)) {
4137                 /* Reduce the b/w multipler */
4138                 timely_says = 2;
4139                 log_mult = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) * rack_gp_rtt_maxmul;
4140                 log_mult <<= 32;
4141                 log_mult |= prev_rtt;
4142                 rack_log_timely(rack,  timely_says, log_mult,
4143                                 get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
4144                                 log_rtt_a_diff, __LINE__, 4);
4145         } else if (rtt <= (get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) +
4146                            ((get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) * rack_gp_rtt_minmul) /
4147                             max(rack_gp_rtt_mindiv , 1)))) {
4148                 /* Increase the b/w multipler */
4149                 log_mult = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) +
4150                         ((get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) * rack_gp_rtt_minmul) /
4151                          max(rack_gp_rtt_mindiv , 1));
4152                 log_mult <<= 32;
4153                 log_mult |= prev_rtt;
4154                 timely_says = 0;
4155                 rack_log_timely(rack,  timely_says, log_mult ,
4156                                 get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
4157                                 log_rtt_a_diff, __LINE__, 5);
4158         } else {
4159                 /*
4160                  * Use a gradient to find it the timely gradient
4161                  * is:
4162                  * grad = rc_rtt_diff / min_rtt;
4163                  *
4164                  * anything below or equal to 0 will be
4165                  * a increase indication. Anything above
4166                  * zero is a decrease. Note we take care
4167                  * of the actual gradient calculation
4168                  * in the reduction (its not needed for
4169                  * increase).
4170                  */
4171                 log_mult = prev_rtt;
4172                 if (rtt_diff <= 0) {
4173                         /*
4174                          * Rttdiff is less than zero, increase the
4175                          * b/w multipler (its 0 or negative)
4176                          */
4177                         timely_says = 0;
4178                         rack_log_timely(rack,  timely_says, log_mult,
4179                                         get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt), log_rtt_a_diff, __LINE__, 6);
4180                 } else {
4181                         /* Reduce the b/w multipler */
4182                         timely_says = 1;
4183                         rack_log_timely(rack,  timely_says, log_mult,
4184                                         get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt), log_rtt_a_diff, __LINE__, 7);
4185                 }
4186         }
4187         return (timely_says);
4188 }
4189
4190 static void
4191 rack_do_goodput_measurement(struct tcpcb *tp, struct tcp_rack *rack,
4192                             tcp_seq th_ack, int line)
4193 {
4194         uint64_t tim, bytes_ps, ltim, stim, utim;
4195         uint32_t segsiz, bytes, reqbytes, us_cts;
4196         int32_t gput, new_rtt_diff, timely_says;
4197         uint64_t  resid_bw, subpart = 0, addpart = 0, srtt;
4198         int did_add = 0;
4199
4200         us_cts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
4201         segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
4202         if (TSTMP_GEQ(us_cts, tp->gput_ts))
4203                 tim = us_cts - tp->gput_ts;
4204         else
4205                 tim = 0;
4206
4207         if (rack->r_ctl.rc_gp_cumack_ts > rack->r_ctl.rc_gp_output_ts)
4208                 stim = rack->r_ctl.rc_gp_cumack_ts - rack->r_ctl.rc_gp_output_ts;
4209         else
4210                 stim = 0;
4211         /*
4212          * Use the larger of the send time or ack time. This prevents us
4213          * from being influenced by ack artifacts to come up with too
4214          * high of measurement. Note that since we are spanning over many more
4215          * bytes in most of our measurements hopefully that is less likely to
4216          * occur.
4217          */
4218         if (tim > stim)
4219                 utim = max(tim, 1);
4220         else
4221                 utim = max(stim, 1);
4222         /* Lets get a msec time ltim too for the old stuff */
4223         ltim = max(1, (utim / HPTS_USEC_IN_MSEC));
4224         gput = (((uint64_t) (th_ack - tp->gput_seq)) << 3) / ltim;
4225         reqbytes = min(rc_init_window(rack), (MIN_GP_WIN * segsiz));
4226         if ((tim == 0) && (stim == 0)) {
4227                 /*
4228                  * Invalid measurement time, maybe
4229                  * all on one ack/one send?
4230                  */
4231                 bytes = 0;
4232                 bytes_ps = 0;
4233                 rack_log_pacing_delay_calc(rack, bytes_ps, reqbytes,
4234                                            0, 0, 0, 10, __LINE__, NULL);
4235                 goto skip_measurement;
4236         }
4237         if (rack->r_ctl.rc_gp_lowrtt == 0xffffffff) {
4238                 /* We never made a us_rtt measurement? */
4239                 bytes = 0;
4240                 bytes_ps = 0;
4241                 rack_log_pacing_delay_calc(rack, bytes_ps, reqbytes,
4242                                            0, 0, 0, 10, __LINE__, NULL);
4243                 goto skip_measurement;
4244         }
4245         /*
4246          * Calculate the maximum possible b/w this connection
4247          * could have. We base our calculation on the lowest
4248          * rtt we have seen during the measurement and the
4249          * largest rwnd the client has given us in that time. This
4250          * forms a BDP that is the maximum that we could ever
4251          * get to the client. Anything larger is not valid.
4252          *
4253          * I originally had code here that rejected measurements
4254          * where the time was less than 1/2 the latest us_rtt.
4255          * But after thinking on that I realized its wrong since
4256          * say you had a 150Mbps or even 1Gbps link, and you
4257          * were a long way away.. example I am in Europe (100ms rtt)
4258          * talking to my 1Gbps link in S.C. Now measuring say 150,000
4259          * bytes my time would be 1.2ms, and yet my rtt would say
4260          * the measurement was invalid the time was < 50ms. The
4261          * same thing is true for 150Mb (8ms of time).
4262          *
4263          * A better way I realized is to look at what the maximum
4264          * the connection could possibly do. This is gated on
4265          * the lowest RTT we have seen and the highest rwnd.
4266          * We should in theory never exceed that, if we are
4267          * then something on the path is storing up packets
4268          * and then feeding them all at once to our endpoint
4269          * messing up our measurement.
4270          */
4271         rack->r_ctl.last_max_bw = rack->r_ctl.rc_gp_high_rwnd;
4272         rack->r_ctl.last_max_bw *= HPTS_USEC_IN_SEC;
4273         rack->r_ctl.last_max_bw /= rack->r_ctl.rc_gp_lowrtt;
4274         if (SEQ_LT(th_ack, tp->gput_seq)) {
4275                 /* No measurement can be made */
4276                 bytes = 0;
4277                 bytes_ps = 0;
4278                 rack_log_pacing_delay_calc(rack, bytes_ps, reqbytes,
4279                                            0, 0, 0, 10, __LINE__, NULL);
4280                 goto skip_measurement;
4281         } else
4282                 bytes = (th_ack - tp->gput_seq);
4283         bytes_ps = (uint64_t)bytes;
4284         /*
4285          * Don't measure a b/w for pacing unless we have gotten at least
4286          * an initial windows worth of data in this measurement interval.
4287          *
4288          * Small numbers of bytes get badly influenced by delayed ack and
4289          * other artifacts. Note we take the initial window or our
4290          * defined minimum GP (defaulting to 10 which hopefully is the
4291          * IW).
4292          */
4293         if (rack->rc_gp_filled == 0) {
4294                 /*
4295                  * The initial estimate is special. We
4296                  * have blasted out an IW worth of packets
4297                  * without a real valid ack ts results. We
4298                  * then setup the app_limited_needs_set flag,
4299                  * this should get the first ack in (probably 2
4300                  * MSS worth) to be recorded as the timestamp.
4301                  * We thus allow a smaller number of bytes i.e.
4302                  * IW - 2MSS.
4303                  */
4304                 reqbytes -= (2 * segsiz);
4305                 /* Also lets fill previous for our first measurement to be neutral */
4306                 rack->r_ctl.rc_prev_gp_srtt = rack->r_ctl.rc_gp_srtt;
4307         }
4308         if ((bytes_ps < reqbytes) || rack->app_limited_needs_set) {
4309                 rack_log_pacing_delay_calc(rack, bytes_ps, reqbytes,
4310                                            rack->r_ctl.rc_app_limited_cnt,
4311                                            0, 0, 10, __LINE__, NULL);
4312                 goto skip_measurement;
4313         }
4314         /*
4315          * We now need to calculate the Timely like status so
4316          * we can update (possibly) the b/w multipliers.
4317          */
4318         new_rtt_diff = (int32_t)rack->r_ctl.rc_gp_srtt - (int32_t)rack->r_ctl.rc_prev_gp_srtt;
4319         if (rack->rc_gp_filled == 0) {
4320                 /* No previous reading */
4321                 rack->r_ctl.rc_rtt_diff = new_rtt_diff;
4322         } else {
4323                 if (rack->measure_saw_probe_rtt == 0) {
4324                         /*
4325                          * We don't want a probertt to be counted
4326                          * since it will be negative incorrectly. We
4327                          * expect to be reducing the RTT when we
4328                          * pace at a slower rate.
4329                          */
4330                         rack->r_ctl.rc_rtt_diff -= (rack->r_ctl.rc_rtt_diff / 8);
4331                         rack->r_ctl.rc_rtt_diff += (new_rtt_diff / 8);
4332                 }
4333         }
4334         timely_says = rack_make_timely_judgement(rack,
4335                 rack->r_ctl.rc_gp_srtt,
4336                 rack->r_ctl.rc_rtt_diff,
4337                 rack->r_ctl.rc_prev_gp_srtt
4338                 );
4339         bytes_ps *= HPTS_USEC_IN_SEC;
4340         bytes_ps /= utim;
4341         if (bytes_ps > rack->r_ctl.last_max_bw) {
4342                 /*
4343                  * Something is on path playing
4344                  * since this b/w is not possible based
4345                  * on our BDP (highest rwnd and lowest rtt
4346                  * we saw in the measurement window).
4347                  *
4348                  * Another option here would be to
4349                  * instead skip the measurement.
4350                  */
4351                 rack_log_pacing_delay_calc(rack, bytes, reqbytes,
4352                                            bytes_ps, rack->r_ctl.last_max_bw, 0,
4353                                            11, __LINE__, NULL);
4354                 bytes_ps = rack->r_ctl.last_max_bw;
4355         }
4356         /* We store gp for b/w in bytes per second */
4357         if (rack->rc_gp_filled == 0) {
4358                 /* Initial measurment */
4359                 if (bytes_ps) {
4360                         rack->r_ctl.gp_bw = bytes_ps;
4361                         rack->rc_gp_filled = 1;
4362                         rack->r_ctl.num_measurements = 1;
4363                         rack_set_pace_segments(rack->rc_tp, rack, __LINE__, NULL);
4364                 } else {
4365                         rack_log_pacing_delay_calc(rack, bytes_ps, reqbytes,
4366                                                    rack->r_ctl.rc_app_limited_cnt,
4367                                                    0, 0, 10, __LINE__, NULL);
4368                 }
4369                 if (rack->rc_inp->inp_in_hpts &&
4370                     (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
4371                         /*
4372                          * Ok we can't trust the pacer in this case
4373                          * where we transition from un-paced to paced.
4374                          * Or for that matter when the burst mitigation
4375                          * was making a wild guess and got it wrong.
4376                          * Stop the pacer and clear up all the aggregate
4377                          * delays etc.
4378                          */
4379                         tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
4380                         rack->r_ctl.rc_hpts_flags = 0;
4381                         rack->r_ctl.rc_last_output_to = 0;
4382                 }
4383                 did_add = 2;
4384         } else if (rack->r_ctl.num_measurements < RACK_REQ_AVG) {
4385                 /* Still a small number run an average */
4386                 rack->r_ctl.gp_bw += bytes_ps;
4387                 addpart = rack->r_ctl.num_measurements;
4388                 rack->r_ctl.num_measurements++;
4389                 if (rack->r_ctl.num_measurements >= RACK_REQ_AVG) {
4390                         /* We have collected enought to move forward */
4391                         rack->r_ctl.gp_bw /= (uint64_t)rack->r_ctl.num_measurements;
4392                 }
4393                 did_add = 3;
4394         } else {
4395                 /*
4396                  * We want to take 1/wma of the goodput and add in to 7/8th
4397                  * of the old value weighted by the srtt. So if your measurement
4398                  * period is say 2 SRTT's long you would get 1/4 as the
4399                  * value, if it was like 1/2 SRTT then you would get 1/16th.
4400                  *
4401                  * But we must be careful not to take too much i.e. if the
4402                  * srtt is say 20ms and the measurement is taken over
4403                  * 400ms our weight would be 400/20 i.e. 20. On the
4404                  * other hand if we get a measurement over 1ms with a
4405                  * 10ms rtt we only want to take a much smaller portion.
4406                  */
4407                 if (rack->r_ctl.num_measurements < 0xff) {
4408                         rack->r_ctl.num_measurements++;
4409                 }
4410                 srtt = (uint64_t)tp->t_srtt;
4411                 if (srtt == 0) {
4412                         /*
4413                          * Strange why did t_srtt go back to zero?
4414                          */
4415                         if (rack->r_ctl.rc_rack_min_rtt)
4416                                 srtt = rack->r_ctl.rc_rack_min_rtt;
4417                         else
4418                                 srtt = HPTS_USEC_IN_MSEC;
4419                 }
4420                 /*
4421                  * XXXrrs: Note for reviewers, in playing with
4422                  * dynamic pacing I discovered this GP calculation
4423                  * as done originally leads to some undesired results.
4424                  * Basically you can get longer measurements contributing
4425                  * too much to the WMA. Thus I changed it if you are doing
4426                  * dynamic adjustments to only do the aportioned adjustment
4427                  * if we have a very small (time wise) measurement. Longer
4428                  * measurements just get there weight (defaulting to 1/8)
4429                  * add to the WMA. We may want to think about changing
4430                  * this to always do that for both sides i.e. dynamic
4431                  * and non-dynamic... but considering lots of folks
4432                  * were playing with this I did not want to change the
4433                  * calculation per.se. without your thoughts.. Lawerence?
4434                  * Peter??
4435                  */
4436                 if (rack->rc_gp_dyn_mul == 0) {
4437                         subpart = rack->r_ctl.gp_bw * utim;
4438                         subpart /= (srtt * 8);
4439                         if (subpart < (rack->r_ctl.gp_bw / 2)) {
4440                                 /*
4441                                  * The b/w update takes no more
4442                                  * away then 1/2 our running total
4443                                  * so factor it in.
4444                                  */
4445                                 addpart = bytes_ps * utim;
4446                                 addpart /= (srtt * 8);
4447                         } else {
4448                                 /*
4449                                  * Don't allow a single measurement
4450                                  * to account for more than 1/2 of the
4451                                  * WMA. This could happen on a retransmission
4452                                  * where utim becomes huge compared to
4453                                  * srtt (multiple retransmissions when using
4454                                  * the sending rate which factors in all the
4455                                  * transmissions from the first one).
4456                                  */
4457                                 subpart = rack->r_ctl.gp_bw / 2;
4458                                 addpart = bytes_ps / 2;
4459                         }
4460                         resid_bw = rack->r_ctl.gp_bw - subpart;
4461                         rack->r_ctl.gp_bw = resid_bw + addpart;
4462                         did_add = 1;
4463                 } else {
4464                         if ((utim / srtt) <= 1) {
4465                                 /*
4466                                  * The b/w update was over a small period
4467                                  * of time. The idea here is to prevent a small
4468                                  * measurement time period from counting
4469                                  * too much. So we scale it based on the
4470                                  * time so it attributes less than 1/rack_wma_divisor
4471                                  * of its measurement.
4472                                  */
4473                                 subpart = rack->r_ctl.gp_bw * utim;
4474                                 subpart /= (srtt * rack_wma_divisor);
4475                                 addpart = bytes_ps * utim;
4476                                 addpart /= (srtt * rack_wma_divisor);
4477                         } else {
4478                                 /*
4479                                  * The scaled measurement was long
4480                                  * enough so lets just add in the
4481                                  * portion of the measurment i.e. 1/rack_wma_divisor
4482                                  */
4483                                 subpart = rack->r_ctl.gp_bw / rack_wma_divisor;
4484                                 addpart = bytes_ps / rack_wma_divisor;
4485                         }
4486                         if ((rack->measure_saw_probe_rtt == 0) ||
4487                             (bytes_ps > rack->r_ctl.gp_bw)) {
4488                                 /*
4489                                  * For probe-rtt we only add it in
4490                                  * if its larger, all others we just
4491                                  * add in.
4492                                  */
4493                                 did_add = 1;
4494                                 resid_bw = rack->r_ctl.gp_bw - subpart;
4495                                 rack->r_ctl.gp_bw = resid_bw + addpart;
4496                         }
4497                 }
4498         }
4499         if ((rack->gp_ready == 0) &&
4500             (rack->r_ctl.num_measurements >= rack->r_ctl.req_measurements)) {
4501                 /* We have enough measurements now */
4502                 rack->gp_ready = 1;
4503                 rack_set_cc_pacing(rack);
4504                 if (rack->defer_options)
4505                         rack_apply_deferred_options(rack);
4506         }
4507         rack_log_pacing_delay_calc(rack, subpart, addpart, bytes_ps, stim,
4508                                    rack_get_bw(rack), 22, did_add, NULL);
4509         /* We do not update any multipliers if we are in or have seen a probe-rtt */
4510         if ((rack->measure_saw_probe_rtt == 0) && rack->rc_gp_rtt_set)
4511                 rack_update_multiplier(rack, timely_says, bytes_ps,
4512                                        rack->r_ctl.rc_gp_srtt,
4513                                        rack->r_ctl.rc_rtt_diff);
4514         rack_log_pacing_delay_calc(rack, bytes, tim, bytes_ps, stim,
4515                                    rack_get_bw(rack), 3, line, NULL);
4516         /* reset the gp srtt and setup the new prev */
4517         rack->r_ctl.rc_prev_gp_srtt = rack->r_ctl.rc_gp_srtt;
4518         /* Record the lost count for the next measurement */
4519         rack->r_ctl.rc_loss_at_start = rack->r_ctl.rc_loss_count;
4520         /*
4521          * We restart our diffs based on the gpsrtt in the
4522          * measurement window.
4523          */
4524         rack->rc_gp_rtt_set = 0;
4525         rack->rc_gp_saw_rec = 0;
4526         rack->rc_gp_saw_ca = 0;
4527         rack->rc_gp_saw_ss = 0;
4528         rack->rc_dragged_bottom = 0;
4529 skip_measurement:
4530
4531 #ifdef STATS
4532         stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
4533                                  gput);
4534         /*
4535          * XXXLAS: This is a temporary hack, and should be
4536          * chained off VOI_TCP_GPUT when stats(9) grows an
4537          * API to deal with chained VOIs.
4538          */
4539         if (tp->t_stats_gput_prev > 0)
4540                 stats_voi_update_abs_s32(tp->t_stats,
4541                                          VOI_TCP_GPUT_ND,
4542                                          ((gput - tp->t_stats_gput_prev) * 100) /
4543                                          tp->t_stats_gput_prev);
4544 #endif
4545         tp->t_flags &= ~TF_GPUTINPROG;
4546         tp->t_stats_gput_prev = gput;
4547         /*
4548          * Now are we app limited now and there is space from where we
4549          * were to where we want to go?
4550          *
4551          * We don't do the other case i.e. non-applimited here since
4552          * the next send will trigger us picking up the missing data.
4553          */
4554         if (rack->r_ctl.rc_first_appl &&
4555             TCPS_HAVEESTABLISHED(tp->t_state) &&
4556             rack->r_ctl.rc_app_limited_cnt &&
4557             (SEQ_GT(rack->r_ctl.rc_first_appl->r_start, th_ack)) &&
4558             ((rack->r_ctl.rc_first_appl->r_start - th_ack) >
4559              max(rc_init_window(rack), (MIN_GP_WIN * segsiz)))) {
4560                 /*
4561                  * Yep there is enough outstanding to make a measurement here.
4562                  */
4563                 struct rack_sendmap *rsm, fe;
4564
4565                 tp->t_flags |= TF_GPUTINPROG;
4566                 rack->r_ctl.rc_gp_lowrtt = 0xffffffff;
4567                 rack->r_ctl.rc_gp_high_rwnd = rack->rc_tp->snd_wnd;
4568                 tp->gput_ts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
4569                 rack->app_limited_needs_set = 0;
4570                 tp->gput_seq = th_ack;
4571                 if (rack->in_probe_rtt)
4572                         rack->measure_saw_probe_rtt = 1;
4573                 else if ((rack->measure_saw_probe_rtt) &&
4574                          (SEQ_GEQ(tp->gput_seq, rack->r_ctl.rc_probertt_sndmax_atexit)))
4575                         rack->measure_saw_probe_rtt = 0;
4576                 if ((rack->r_ctl.rc_first_appl->r_start - th_ack) >= rack_get_measure_window(tp, rack)) {
4577                         /* There is a full window to gain info from */
4578                         tp->gput_ack = tp->gput_seq + rack_get_measure_window(tp, rack);
4579                 } else {
4580                         /* We can only measure up to the applimited point */
4581                         tp->gput_ack = tp->gput_seq + (rack->r_ctl.rc_first_appl->r_start - th_ack);
4582                 }
4583                 /*
4584                  * Now we need to find the timestamp of the send at tp->gput_seq
4585                  * for the send based measurement.
4586                  */
4587                 fe.r_start = tp->gput_seq;
4588                 rsm = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
4589                 if (rsm) {
4590                         /* Ok send-based limit is set */
4591                         if (SEQ_LT(rsm->r_start, tp->gput_seq)) {
4592                                 /*
4593                                  * Move back to include the earlier part
4594                                  * so our ack time lines up right (this may
4595                                  * make an overlapping measurement but thats
4596                                  * ok).
4597                                  */
4598                                 tp->gput_seq = rsm->r_start;
4599                         }
4600                         if (rsm->r_flags & RACK_ACKED)
4601                                 tp->gput_ts = (uint32_t)rsm->r_ack_arrival;
4602                         else
4603                                 rack->app_limited_needs_set = 1;
4604                         rack->r_ctl.rc_gp_output_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
4605                 } else {
4606                         /*
4607                          * If we don't find the rsm due to some
4608                          * send-limit set the current time, which
4609                          * basically disables the send-limit.
4610                          */
4611                         struct timeval tv;
4612
4613                         microuptime(&tv);
4614                         rack->r_ctl.rc_gp_output_ts = rack_to_usec_ts(&tv);
4615                 }
4616                 rack_log_pacing_delay_calc(rack,
4617                                            tp->gput_seq,
4618                                            tp->gput_ack,
4619                                            (uint64_t)rsm,
4620                                            tp->gput_ts,
4621                                            rack->r_ctl.rc_app_limited_cnt,
4622                                            9,
4623                                            __LINE__, NULL);
4624         }
4625 }
4626
4627 /*
4628  * CC wrapper hook functions
4629  */
4630 static void
4631 rack_ack_received(struct tcpcb *tp, struct tcp_rack *rack, uint32_t th_ack, uint16_t nsegs,
4632     uint16_t type, int32_t recovery)
4633 {
4634         uint32_t prior_cwnd, acked;
4635         struct tcp_log_buffer *lgb = NULL;
4636         uint8_t labc_to_use;
4637
4638         INP_WLOCK_ASSERT(tp->t_inpcb);
4639         tp->ccv->nsegs = nsegs;
4640         acked = tp->ccv->bytes_this_ack = (th_ack - tp->snd_una);
4641         if ((recovery) && (rack->r_ctl.rc_early_recovery_segs)) {
4642                 uint32_t max;
4643
4644                 max = rack->r_ctl.rc_early_recovery_segs * ctf_fixed_maxseg(tp);
4645                 if (tp->ccv->bytes_this_ack > max) {
4646                         tp->ccv->bytes_this_ack = max;
4647                 }
4648         }
4649 #ifdef STATS
4650         stats_voi_update_abs_s32(tp->t_stats, VOI_TCP_CALCFRWINDIFF,
4651             ((int32_t)rack->r_ctl.cwnd_to_use) - tp->snd_wnd);
4652 #endif
4653         if ((tp->t_flags & TF_GPUTINPROG) &&
4654             rack_enough_for_measurement(tp, rack, th_ack)) {
4655                 /* Measure the Goodput */
4656                 rack_do_goodput_measurement(tp, rack, th_ack, __LINE__);
4657 #ifdef NETFLIX_PEAKRATE
4658                 if ((type == CC_ACK) &&
4659                     (tp->t_maxpeakrate)) {
4660                         /*
4661                          * We update t_peakrate_thr. This gives us roughly
4662                          * one update per round trip time. Note
4663                          * it will only be used if pace_always is off i.e
4664                          * we don't do this for paced flows.
4665                          */
4666                         rack_update_peakrate_thr(tp);
4667                 }
4668 #endif
4669         }
4670         /* Which way our we limited, if not cwnd limited no advance in CA */
4671         if (tp->snd_cwnd <= tp->snd_wnd)
4672                 tp->ccv->flags |= CCF_CWND_LIMITED;
4673         else
4674                 tp->ccv->flags &= ~CCF_CWND_LIMITED;
4675         if (tp->snd_cwnd > tp->snd_ssthresh) {
4676                 tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
4677                          nsegs * V_tcp_abc_l_var * ctf_fixed_maxseg(tp));
4678                 /* For the setting of a window past use the actual scwnd we are using */
4679                 if (tp->t_bytes_acked >= rack->r_ctl.cwnd_to_use) {
4680                         tp->t_bytes_acked -= rack->r_ctl.cwnd_to_use;
4681                         tp->ccv->flags |= CCF_ABC_SENTAWND;
4682                 }
4683         } else {
4684                 tp->ccv->flags &= ~CCF_ABC_SENTAWND;
4685                 tp->t_bytes_acked = 0;
4686         }
4687         prior_cwnd = tp->snd_cwnd;
4688         if ((recovery == 0) || (rack_max_abc_post_recovery == 0) || rack->r_use_labc_for_rec ||
4689             (rack_client_low_buf && (rack->client_bufferlvl < rack_client_low_buf)))
4690                 labc_to_use = rack->rc_labc;
4691         else
4692                 labc_to_use = rack_max_abc_post_recovery;
4693         if (rack_verbose_logging && (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
4694                 union tcp_log_stackspecific log;
4695                 struct timeval tv;
4696
4697                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
4698                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
4699                 log.u_bbr.flex1 = th_ack;
4700                 log.u_bbr.flex2 = tp->ccv->flags;
4701                 log.u_bbr.flex3 = tp->ccv->bytes_this_ack;
4702                 log.u_bbr.flex4 = tp->ccv->nsegs;
4703                 log.u_bbr.flex5 = labc_to_use;
4704                 log.u_bbr.flex6 = prior_cwnd;
4705                 log.u_bbr.flex7 = V_tcp_do_newsack;
4706                 log.u_bbr.flex8 = 1;
4707                 lgb = tcp_log_event_(tp, NULL, NULL, NULL, BBR_LOG_CWND, 0,
4708                                      0, &log, false, NULL, NULL, 0, &tv);
4709         }
4710         if (CC_ALGO(tp)->ack_received != NULL) {
4711                 /* XXXLAS: Find a way to live without this */
4712                 tp->ccv->curack = th_ack;
4713                 tp->ccv->labc = labc_to_use;
4714                 tp->ccv->flags |= CCF_USE_LOCAL_ABC;
4715                 CC_ALGO(tp)->ack_received(tp->ccv, type);
4716         }
4717         if (lgb) {
4718                 lgb->tlb_stackinfo.u_bbr.flex6 = tp->snd_cwnd;
4719         }
4720         if (rack->r_must_retran) {
4721                 if (SEQ_GEQ(th_ack, rack->r_ctl.rc_snd_max_at_rto)) {
4722                         /*
4723                          * We now are beyond the rxt point so lets disable
4724                          * the flag.
4725                          */
4726                         rack->r_ctl.rc_out_at_rto = 0;
4727                         rack->r_must_retran = 0;
4728                 } else if ((prior_cwnd + ctf_fixed_maxseg(tp)) <= tp->snd_cwnd) {
4729                         /*
4730                          * Only decrement the rc_out_at_rto if the cwnd advances
4731                          * at least a whole segment. Otherwise next time the peer
4732                          * acks, we won't be able to send this generaly happens
4733                          * when we are in Congestion Avoidance.
4734                          */
4735                         if (acked <= rack->r_ctl.rc_out_at_rto){
4736                                 rack->r_ctl.rc_out_at_rto -= acked;
4737                         } else {
4738                                 rack->r_ctl.rc_out_at_rto = 0;
4739                         }
4740                 }
4741         }
4742 #ifdef STATS
4743         stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_LCWIN, rack->r_ctl.cwnd_to_use);
4744 #endif
4745         if (rack->r_ctl.rc_rack_largest_cwnd < rack->r_ctl.cwnd_to_use) {
4746                 rack->r_ctl.rc_rack_largest_cwnd = rack->r_ctl.cwnd_to_use;
4747         }
4748 #ifdef NETFLIX_PEAKRATE
4749         /* we enforce max peak rate if it is set and we are not pacing */
4750         if ((rack->rc_always_pace == 0) &&
4751             tp->t_peakrate_thr &&
4752             (tp->snd_cwnd > tp->t_peakrate_thr)) {
4753                 tp->snd_cwnd = tp->t_peakrate_thr;
4754         }
4755 #endif
4756 }
4757
4758 static void
4759 tcp_rack_partialack(struct tcpcb *tp)
4760 {
4761         struct tcp_rack *rack;
4762
4763         rack = (struct tcp_rack *)tp->t_fb_ptr;
4764         INP_WLOCK_ASSERT(tp->t_inpcb);
4765         /*
4766          * If we are doing PRR and have enough
4767          * room to send <or> we are pacing and prr
4768          * is disabled we will want to see if we
4769          * can send data (by setting r_wanted_output to
4770          * true).
4771          */
4772         if ((rack->r_ctl.rc_prr_sndcnt > 0) ||
4773             rack->rack_no_prr)
4774                 rack->r_wanted_output = 1;
4775 }
4776
4777 static void
4778 rack_post_recovery(struct tcpcb *tp, uint32_t th_ack)
4779 {
4780         struct tcp_rack *rack;
4781         uint32_t orig_cwnd;
4782
4783         orig_cwnd = tp->snd_cwnd;
4784         INP_WLOCK_ASSERT(tp->t_inpcb);
4785         rack = (struct tcp_rack *)tp->t_fb_ptr;
4786         /* only alert CC if we alerted when we entered */
4787         if (CC_ALGO(tp)->post_recovery != NULL) {
4788                 tp->ccv->curack = th_ack;
4789                 CC_ALGO(tp)->post_recovery(tp->ccv);
4790                 if (tp->snd_cwnd < tp->snd_ssthresh) {
4791                         /*
4792                          * Rack has burst control and pacing
4793                          * so lets not set this any lower than
4794                          * snd_ssthresh per RFC-6582 (option 2).
4795                          */
4796                         tp->snd_cwnd = tp->snd_ssthresh;
4797                 }
4798         }
4799         if (rack_verbose_logging && (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
4800                 union tcp_log_stackspecific log;
4801                 struct timeval tv;
4802
4803                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
4804                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
4805                 log.u_bbr.flex1 = th_ack;
4806                 log.u_bbr.flex2 = tp->ccv->flags;
4807                 log.u_bbr.flex3 = tp->ccv->bytes_this_ack;
4808                 log.u_bbr.flex4 = tp->ccv->nsegs;
4809                 log.u_bbr.flex5 = V_tcp_abc_l_var;
4810                 log.u_bbr.flex6 = orig_cwnd;
4811                 log.u_bbr.flex7 = V_tcp_do_newsack;
4812                 log.u_bbr.pkts_out = rack->r_ctl.rc_prr_sndcnt;
4813                 log.u_bbr.flex8 = 2;
4814                 tcp_log_event_(tp, NULL, NULL, NULL, BBR_LOG_CWND, 0,
4815                                0, &log, false, NULL, NULL, 0, &tv);
4816         }
4817         if ((rack->rack_no_prr == 0) &&
4818             (rack->no_prr_addback == 0) &&
4819             (rack->r_ctl.rc_prr_sndcnt > 0)) {
4820                 /*
4821                  * Suck the next prr cnt back into cwnd, but
4822                  * only do that if we are not application limited.
4823                  */
4824                 if (ctf_outstanding(tp) <= sbavail(&(tp->t_inpcb->inp_socket->so_snd))) {
4825                         /*
4826                          * We are allowed to add back to the cwnd the amount we did
4827                          * not get out if:
4828                          * a) no_prr_addback is off.
4829                          * b) we are not app limited
4830                          * c) we are doing prr
4831                          * <and>
4832                          * d) it is bounded by rack_prr_addbackmax (if addback is 0, then none).
4833                          */
4834                         tp->snd_cwnd += min((ctf_fixed_maxseg(tp) * rack_prr_addbackmax),
4835                                             rack->r_ctl.rc_prr_sndcnt);
4836                 }
4837                 rack->r_ctl.rc_prr_sndcnt = 0;
4838                 rack_log_to_prr(rack, 1, 0);
4839         }
4840         rack_log_to_prr(rack, 14, orig_cwnd);
4841         tp->snd_recover = tp->snd_una;
4842         EXIT_RECOVERY(tp->t_flags);
4843 }
4844
4845 static void
4846 rack_cong_signal(struct tcpcb *tp, uint32_t type, uint32_t ack)
4847 {
4848         struct tcp_rack *rack;
4849         uint32_t ssthresh_enter, cwnd_enter, in_rec_at_entry, orig_cwnd;
4850
4851         INP_WLOCK_ASSERT(tp->t_inpcb);
4852 #ifdef STATS
4853         stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
4854 #endif
4855         if (IN_RECOVERY(tp->t_flags) == 0) {
4856                 in_rec_at_entry = 0;
4857                 ssthresh_enter = tp->snd_ssthresh;
4858                 cwnd_enter = tp->snd_cwnd;
4859         } else
4860                 in_rec_at_entry = 1;
4861         rack = (struct tcp_rack *)tp->t_fb_ptr;
4862         switch (type) {
4863         case CC_NDUPACK:
4864                 tp->t_flags &= ~TF_WASFRECOVERY;
4865                 tp->t_flags &= ~TF_WASCRECOVERY;
4866                 if (!IN_FASTRECOVERY(tp->t_flags)) {
4867                         rack->r_ctl.rc_prr_delivered = 0;
4868                         rack->r_ctl.rc_prr_out = 0;
4869                         if (rack->rack_no_prr == 0) {
4870                                 rack->r_ctl.rc_prr_sndcnt = ctf_fixed_maxseg(tp);
4871                                 rack_log_to_prr(rack, 2, in_rec_at_entry);
4872                         }
4873                         rack->r_ctl.rc_prr_recovery_fs = tp->snd_max - tp->snd_una;
4874                         tp->snd_recover = tp->snd_max;
4875                         if (tp->t_flags2 & TF2_ECN_PERMIT)
4876                                 tp->t_flags2 |= TF2_ECN_SND_CWR;
4877                 }
4878                 break;
4879         case CC_ECN:
4880                 if (!IN_CONGRECOVERY(tp->t_flags) ||
4881                     /*
4882                      * Allow ECN reaction on ACK to CWR, if
4883                      * that data segment was also CE marked.
4884                      */
4885                     SEQ_GEQ(ack, tp->snd_recover)) {
4886                         EXIT_CONGRECOVERY(tp->t_flags);
4887                         KMOD_TCPSTAT_INC(tcps_ecn_rcwnd);
4888                         tp->snd_recover = tp->snd_max + 1;
4889                         if (tp->t_flags2 & TF2_ECN_PERMIT)
4890                                 tp->t_flags2 |= TF2_ECN_SND_CWR;
4891                 }
4892                 break;
4893         case CC_RTO:
4894                 tp->t_dupacks = 0;
4895                 tp->t_bytes_acked = 0;
4896                 EXIT_RECOVERY(tp->t_flags);
4897                 tp->snd_ssthresh = max(2, min(tp->snd_wnd, rack->r_ctl.cwnd_to_use) / 2 /
4898                     ctf_fixed_maxseg(tp)) * ctf_fixed_maxseg(tp);
4899                 orig_cwnd = tp->snd_cwnd;
4900                 tp->snd_cwnd = ctf_fixed_maxseg(tp);
4901                 rack_log_to_prr(rack, 16, orig_cwnd);
4902                 if (tp->t_flags2 & TF2_ECN_PERMIT)
4903                         tp->t_flags2 |= TF2_ECN_SND_CWR;
4904                 break;
4905         case CC_RTO_ERR:
4906                 KMOD_TCPSTAT_INC(tcps_sndrexmitbad);
4907                 /* RTO was unnecessary, so reset everything. */
4908                 tp->snd_cwnd = tp->snd_cwnd_prev;
4909                 tp->snd_ssthresh = tp->snd_ssthresh_prev;
4910                 tp->snd_recover = tp->snd_recover_prev;
4911                 if (tp->t_flags & TF_WASFRECOVERY) {
4912                         ENTER_FASTRECOVERY(tp->t_flags);
4913                         tp->t_flags &= ~TF_WASFRECOVERY;
4914                 }
4915                 if (tp->t_flags & TF_WASCRECOVERY) {
4916                         ENTER_CONGRECOVERY(tp->t_flags);
4917                         tp->t_flags &= ~TF_WASCRECOVERY;
4918                 }
4919                 tp->snd_nxt = tp->snd_max;
4920                 tp->t_badrxtwin = 0;
4921                 break;
4922         }
4923         if ((CC_ALGO(tp)->cong_signal != NULL)  &&
4924             (type != CC_RTO)){
4925                 tp->ccv->curack = ack;
4926                 CC_ALGO(tp)->cong_signal(tp->ccv, type);
4927         }
4928         if ((in_rec_at_entry == 0) && IN_RECOVERY(tp->t_flags)) {
4929                 rack_log_to_prr(rack, 15, cwnd_enter);
4930                 rack->r_ctl.dsack_byte_cnt = 0;
4931                 rack->r_ctl.retran_during_recovery = 0;
4932                 rack->r_ctl.rc_cwnd_at_erec = cwnd_enter;
4933                 rack->r_ctl.rc_ssthresh_at_erec = ssthresh_enter;
4934                 rack->r_ent_rec_ns = 1;
4935         }
4936 }
4937
4938 static inline void
4939 rack_cc_after_idle(struct tcp_rack *rack, struct tcpcb *tp)
4940 {
4941         uint32_t i_cwnd;
4942
4943         INP_WLOCK_ASSERT(tp->t_inpcb);
4944
4945 #ifdef NETFLIX_STATS
4946         KMOD_TCPSTAT_INC(tcps_idle_restarts);
4947         if (tp->t_state == TCPS_ESTABLISHED)
4948                 KMOD_TCPSTAT_INC(tcps_idle_estrestarts);
4949 #endif
4950         if (CC_ALGO(tp)->after_idle != NULL)
4951                 CC_ALGO(tp)->after_idle(tp->ccv);
4952
4953         if (tp->snd_cwnd == 1)
4954                 i_cwnd = tp->t_maxseg;          /* SYN(-ACK) lost */
4955         else
4956                 i_cwnd = rc_init_window(rack);
4957
4958         /*
4959          * Being idle is no differnt than the initial window. If the cc
4960          * clamps it down below the initial window raise it to the initial
4961          * window.
4962          */
4963         if (tp->snd_cwnd < i_cwnd) {
4964                 tp->snd_cwnd = i_cwnd;
4965         }
4966 }
4967
4968 /*
4969  * Indicate whether this ack should be delayed.  We can delay the ack if
4970  * following conditions are met:
4971  *      - There is no delayed ack timer in progress.
4972  *      - Our last ack wasn't a 0-sized window. We never want to delay
4973  *        the ack that opens up a 0-sized window.
4974  *      - LRO wasn't used for this segment. We make sure by checking that the
4975  *        segment size is not larger than the MSS.
4976  *      - Delayed acks are enabled or this is a half-synchronized T/TCP
4977  *        connection.
4978  */
4979 #define DELAY_ACK(tp, tlen)                      \
4980         (((tp->t_flags & TF_RXWIN0SENT) == 0) && \
4981         ((tp->t_flags & TF_DELACK) == 0) &&      \
4982         (tlen <= tp->t_maxseg) &&                \
4983         (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4984
4985 static struct rack_sendmap *
4986 rack_find_lowest_rsm(struct tcp_rack *rack)
4987 {
4988         struct rack_sendmap *rsm;
4989
4990         /*
4991          * Walk the time-order transmitted list looking for an rsm that is
4992          * not acked. This will be the one that was sent the longest time
4993          * ago that is still outstanding.
4994          */
4995         TAILQ_FOREACH(rsm, &rack->r_ctl.rc_tmap, r_tnext) {
4996                 if (rsm->r_flags & RACK_ACKED) {
4997                         continue;
4998                 }
4999                 goto finish;
5000         }
5001 finish:
5002         return (rsm);
5003 }
5004
5005 static struct rack_sendmap *
5006 rack_find_high_nonack(struct tcp_rack *rack, struct rack_sendmap *rsm)
5007 {
5008         struct rack_sendmap *prsm;
5009
5010         /*
5011          * Walk the sequence order list backward until we hit and arrive at
5012          * the highest seq not acked. In theory when this is called it
5013          * should be the last segment (which it was not).
5014          */
5015         counter_u64_add(rack_find_high, 1);
5016         prsm = rsm;
5017         RB_FOREACH_REVERSE_FROM(prsm, rack_rb_tree_head, rsm) {
5018                 if (prsm->r_flags & (RACK_ACKED | RACK_HAS_FIN)) {
5019                         continue;
5020                 }
5021                 return (prsm);
5022         }
5023         return (NULL);
5024 }
5025
5026 static uint32_t
5027 rack_calc_thresh_rack(struct tcp_rack *rack, uint32_t srtt, uint32_t cts)
5028 {
5029         int32_t lro;
5030         uint32_t thresh;
5031
5032         /*
5033          * lro is the flag we use to determine if we have seen reordering.
5034          * If it gets set we have seen reordering. The reorder logic either
5035          * works in one of two ways:
5036          *
5037          * If reorder-fade is configured, then we track the last time we saw
5038          * re-ordering occur. If we reach the point where enough time as
5039          * passed we no longer consider reordering has occuring.
5040          *
5041          * Or if reorder-face is 0, then once we see reordering we consider
5042          * the connection to alway be subject to reordering and just set lro
5043          * to 1.
5044          *
5045          * In the end if lro is non-zero we add the extra time for
5046          * reordering in.
5047          */
5048         if (srtt == 0)
5049                 srtt = 1;
5050         if (rack->r_ctl.rc_reorder_ts) {
5051                 if (rack->r_ctl.rc_reorder_fade) {
5052                         if (SEQ_GEQ(cts, rack->r_ctl.rc_reorder_ts)) {
5053                                 lro = cts - rack->r_ctl.rc_reorder_ts;
5054                                 if (lro == 0) {
5055                                         /*
5056                                          * No time as passed since the last
5057                                          * reorder, mark it as reordering.
5058                                          */
5059                                         lro = 1;
5060                                 }
5061                         } else {
5062                                 /* Negative time? */
5063                                 lro = 0;
5064                         }
5065                         if (lro > rack->r_ctl.rc_reorder_fade) {
5066                                 /* Turn off reordering seen too */
5067                                 rack->r_ctl.rc_reorder_ts = 0;
5068                                 lro = 0;
5069                         }
5070                 } else {
5071                         /* Reodering does not fade */
5072                         lro = 1;
5073                 }
5074         } else {
5075                 lro = 0;
5076         }
5077         thresh = srtt + rack->r_ctl.rc_pkt_delay;
5078         if (lro) {
5079                 /* It must be set, if not you get 1/4 rtt */
5080                 if (rack->r_ctl.rc_reorder_shift)
5081                         thresh += (srtt >> rack->r_ctl.rc_reorder_shift);
5082                 else
5083                         thresh += (srtt >> 2);
5084         } else {
5085                 thresh += 1;
5086         }
5087         /* We don't let the rack timeout be above a RTO */
5088         if (thresh > rack->rc_tp->t_rxtcur) {
5089                 thresh = rack->rc_tp->t_rxtcur;
5090         }
5091         /* And we don't want it above the RTO max either */
5092         if (thresh > rack_rto_max) {
5093                 thresh = rack_rto_max;
5094         }
5095         return (thresh);
5096 }
5097
5098 static uint32_t
5099 rack_calc_thresh_tlp(struct tcpcb *tp, struct tcp_rack *rack,
5100                      struct rack_sendmap *rsm, uint32_t srtt)
5101 {
5102         struct rack_sendmap *prsm;
5103         uint32_t thresh, len;
5104         int segsiz;
5105
5106         if (srtt == 0)
5107                 srtt = 1;
5108         if (rack->r_ctl.rc_tlp_threshold)
5109                 thresh = srtt + (srtt / rack->r_ctl.rc_tlp_threshold);
5110         else
5111                 thresh = (srtt * 2);
5112
5113         /* Get the previous sent packet, if any */
5114         segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
5115         counter_u64_add(rack_enter_tlp_calc, 1);
5116         len = rsm->r_end - rsm->r_start;
5117         if (rack->rack_tlp_threshold_use == TLP_USE_ID) {
5118                 /* Exactly like the ID */
5119                 if (((tp->snd_max - tp->snd_una) - rack->r_ctl.rc_sacked + rack->r_ctl.rc_holes_rxt) <= segsiz) {
5120                         uint32_t alt_thresh;
5121                         /*
5122                          * Compensate for delayed-ack with the d-ack time.
5123                          */
5124                         counter_u64_add(rack_used_tlpmethod, 1);
5125                         alt_thresh = srtt + (srtt / 2) + rack_delayed_ack_time;
5126                         if (alt_thresh > thresh)
5127                                 thresh = alt_thresh;
5128                 }
5129         } else if (rack->rack_tlp_threshold_use == TLP_USE_TWO_ONE) {
5130                 /* 2.1 behavior */
5131                 prsm = TAILQ_PREV(rsm, rack_head, r_tnext);
5132                 if (prsm && (len <= segsiz)) {
5133                         /*
5134                          * Two packets outstanding, thresh should be (2*srtt) +
5135                          * possible inter-packet delay (if any).
5136                          */
5137                         uint32_t inter_gap = 0;
5138                         int idx, nidx;
5139
5140                         counter_u64_add(rack_used_tlpmethod, 1);
5141                         idx = rsm->r_rtr_cnt - 1;
5142                         nidx = prsm->r_rtr_cnt - 1;
5143                         if (rsm->r_tim_lastsent[nidx] >= prsm->r_tim_lastsent[idx]) {
5144                                 /* Yes it was sent later (or at the same time) */
5145                                 inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
5146                         }
5147                         thresh += inter_gap;
5148                 } else if (len <= segsiz) {
5149                         /*
5150                          * Possibly compensate for delayed-ack.
5151                          */
5152                         uint32_t alt_thresh;
5153
5154                         counter_u64_add(rack_used_tlpmethod2, 1);
5155                         alt_thresh = srtt + (srtt / 2) + rack_delayed_ack_time;
5156                         if (alt_thresh > thresh)
5157                                 thresh = alt_thresh;
5158                 }
5159         } else if (rack->rack_tlp_threshold_use == TLP_USE_TWO_TWO) {
5160                 /* 2.2 behavior */
5161                 if (len <= segsiz) {
5162                         uint32_t alt_thresh;
5163                         /*
5164                          * Compensate for delayed-ack with the d-ack time.
5165                          */
5166                         counter_u64_add(rack_used_tlpmethod, 1);
5167                         alt_thresh = srtt + (srtt / 2) + rack_delayed_ack_time;
5168                         if (alt_thresh > thresh)
5169                                 thresh = alt_thresh;
5170                 }
5171         }
5172         /* Not above an RTO */
5173         if (thresh > tp->t_rxtcur) {
5174                 thresh = tp->t_rxtcur;
5175         }
5176         /* Not above a RTO max */
5177         if (thresh > rack_rto_max) {
5178                 thresh = rack_rto_max;
5179         }
5180         /* Apply user supplied min TLP */
5181         if (thresh < rack_tlp_min) {
5182                 thresh = rack_tlp_min;
5183         }
5184         return (thresh);
5185 }
5186
5187 static uint32_t
5188 rack_grab_rtt(struct tcpcb *tp, struct tcp_rack *rack)
5189 {
5190         /*
5191          * We want the rack_rtt which is the
5192          * last rtt we measured. However if that
5193          * does not exist we fallback to the srtt (which
5194          * we probably will never do) and then as a last
5195          * resort we use RACK_INITIAL_RTO if no srtt is
5196          * yet set.
5197          */
5198         if (rack->rc_rack_rtt)
5199                 return (rack->rc_rack_rtt);
5200         else if (tp->t_srtt == 0)
5201                 return (RACK_INITIAL_RTO);
5202         return (tp->t_srtt);
5203 }
5204
5205 static struct rack_sendmap *
5206 rack_check_recovery_mode(struct tcpcb *tp, uint32_t tsused)
5207 {
5208         /*
5209          * Check to see that we don't need to fall into recovery. We will
5210          * need to do so if our oldest transmit is past the time we should
5211          * have had an ack.
5212          */
5213         struct tcp_rack *rack;
5214         struct rack_sendmap *rsm;
5215         int32_t idx;
5216         uint32_t srtt, thresh;
5217
5218         rack = (struct tcp_rack *)tp->t_fb_ptr;
5219         if (RB_EMPTY(&rack->r_ctl.rc_mtree)) {
5220                 return (NULL);
5221         }
5222         rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
5223         if (rsm == NULL)
5224                 return (NULL);
5225
5226         if (rsm->r_flags & RACK_ACKED) {
5227                 rsm = rack_find_lowest_rsm(rack);
5228                 if (rsm == NULL)
5229                         return (NULL);
5230         }
5231         idx = rsm->r_rtr_cnt - 1;
5232         srtt = rack_grab_rtt(tp, rack);
5233         thresh = rack_calc_thresh_rack(rack, srtt, tsused);
5234         if (TSTMP_LT(tsused, ((uint32_t)rsm->r_tim_lastsent[idx]))) {
5235                 return (NULL);
5236         }
5237         if ((tsused - ((uint32_t)rsm->r_tim_lastsent[idx])) < thresh) {
5238                 return (NULL);
5239         }
5240         /* Ok if we reach here we are over-due and this guy can be sent */
5241         if (IN_RECOVERY(tp->t_flags) == 0) {
5242                 /*
5243                  * For the one that enters us into recovery record undo
5244                  * info.
5245                  */
5246                 rack->r_ctl.rc_rsm_start = rsm->r_start;
5247                 rack->r_ctl.rc_cwnd_at = tp->snd_cwnd;
5248                 rack->r_ctl.rc_ssthresh_at = tp->snd_ssthresh;
5249         }
5250         rack_cong_signal(tp, CC_NDUPACK, tp->snd_una);
5251         return (rsm);
5252 }
5253
5254 static uint32_t
5255 rack_get_persists_timer_val(struct tcpcb *tp, struct tcp_rack *rack)
5256 {
5257         int32_t t;
5258         int32_t tt;
5259         uint32_t ret_val;
5260
5261         t = (tp->t_srtt + (tp->t_rttvar << 2));
5262         RACK_TCPT_RANGESET(tt, t * tcp_backoff[tp->t_rxtshift],
5263             rack_persist_min, rack_persist_max);
5264         if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
5265                 tp->t_rxtshift++;
5266         rack->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
5267         ret_val = (uint32_t)tt;
5268         return (ret_val);
5269 }
5270
5271 static uint32_t
5272 rack_timer_start(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, int sup_rack)
5273 {
5274         /*
5275          * Start the FR timer, we do this based on getting the first one in
5276          * the rc_tmap. Note that if its NULL we must stop the timer. in all
5277          * events we need to stop the running timer (if its running) before
5278          * starting the new one.
5279          */
5280         uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
5281         uint32_t srtt_cur;
5282         int32_t idx;
5283         int32_t is_tlp_timer = 0;
5284         struct rack_sendmap *rsm;
5285
5286         if (rack->t_timers_stopped) {
5287                 /* All timers have been stopped none are to run */
5288                 return (0);
5289         }
5290         if (rack->rc_in_persist) {
5291                 /* We can't start any timer in persists */
5292                 return (rack_get_persists_timer_val(tp, rack));
5293         }
5294         rack->rc_on_min_to = 0;
5295         if ((tp->t_state < TCPS_ESTABLISHED) ||
5296             ((tp->t_flags & TF_SACK_PERMIT) == 0)) {
5297                 goto activate_rxt;
5298         }
5299         rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
5300         if ((rsm == NULL) || sup_rack) {
5301                 /* Nothing on the send map or no rack */
5302 activate_rxt:
5303                 time_since_sent = 0;
5304                 rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
5305                 if (rsm) {
5306                         /*
5307                          * Should we discount the RTX timer any?
5308                          *
5309                          * We want to discount it the smallest amount.
5310                          * If a timer (Rack/TLP or RXT) has gone off more
5311                          * recently thats the discount we want to use (now - timer time).
5312                          * If the retransmit of the oldest packet was more recent then
5313                          * we want to use that (now - oldest-packet-last_transmit_time).
5314                          *
5315                          */
5316                         idx = rsm->r_rtr_cnt - 1;
5317                         if (TSTMP_GEQ(rack->r_ctl.rc_tlp_rxt_last_time, ((uint32_t)rsm->r_tim_lastsent[idx])))
5318                                 tstmp_touse = (uint32_t)rack->r_ctl.rc_tlp_rxt_last_time;
5319                         else
5320                                 tstmp_touse = (uint32_t)rsm->r_tim_lastsent[idx];
5321                         if (TSTMP_GT(cts, tstmp_touse))
5322                             time_since_sent = cts - tstmp_touse;
5323                 }
5324                 if (SEQ_LT(tp->snd_una, tp->snd_max) || sbavail(&(tp->t_inpcb->inp_socket->so_snd))) {
5325                         rack->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
5326                         to = tp->t_rxtcur;
5327                         if (to > time_since_sent)
5328                                 to -= time_since_sent;
5329                         else
5330                                 to = rack->r_ctl.rc_min_to;
5331                         if (to == 0)
5332                                 to = 1;
5333                         /* Special case for KEEPINIT */
5334                         if ((TCPS_HAVEESTABLISHED(tp->t_state) == 0) &&
5335                             (TP_KEEPINIT(tp) != 0) &&
5336                             rsm) {
5337                                 /*
5338                                  * We have to put a ceiling on the rxt timer
5339                                  * of the keep-init timeout.
5340                                  */
5341                                 uint32_t max_time, red;
5342
5343                                 max_time = TICKS_2_USEC(TP_KEEPINIT(tp));
5344                                 if (TSTMP_GT(cts, (uint32_t)rsm->r_tim_lastsent[0])) {
5345                                         red = (cts - (uint32_t)rsm->r_tim_lastsent[0]);
5346                                         if (red < max_time)
5347                                                 max_time -= red;
5348                                         else
5349                                                 max_time = 1;
5350                                 }
5351                                 /* Reduce timeout to the keep value if needed */
5352                                 if (max_time < to)
5353                                         to = max_time;
5354                         }
5355                         return (to);
5356                 }
5357                 return (0);
5358         }
5359         if (rsm->r_flags & RACK_ACKED) {
5360                 rsm = rack_find_lowest_rsm(rack);
5361                 if (rsm == NULL) {
5362                         /* No lowest? */
5363                         goto activate_rxt;
5364                 }
5365         }
5366         if (rack->sack_attack_disable) {
5367                 /*
5368                  * We don't want to do
5369                  * any TLP's if you are an attacker.
5370                  * Though if you are doing what
5371                  * is expected you may still have
5372                  * SACK-PASSED marks.
5373                  */
5374                 goto activate_rxt;
5375         }
5376         /* Convert from ms to usecs */
5377         if ((rsm->r_flags & RACK_SACK_PASSED) || (rsm->r_dupack >= DUP_ACK_THRESHOLD)) {
5378                 if ((tp->t_flags & TF_SENTFIN) &&
5379                     ((tp->snd_max - tp->snd_una) == 1) &&
5380                     (rsm->r_flags & RACK_HAS_FIN)) {
5381                         /*
5382                          * We don't start a rack timer if all we have is a
5383                          * FIN outstanding.
5384                          */
5385                         goto activate_rxt;
5386                 }
5387                 if ((rack->use_rack_rr == 0) &&
5388                     (IN_FASTRECOVERY(tp->t_flags)) &&
5389                     (rack->rack_no_prr == 0) &&
5390                      (rack->r_ctl.rc_prr_sndcnt  < ctf_fixed_maxseg(tp))) {
5391                         /*
5392                          * We are not cheating, in recovery  and
5393                          * not enough ack's to yet get our next
5394                          * retransmission out.
5395                          *
5396                          * Note that classified attackers do not
5397                          * get to use the rack-cheat.
5398                          */
5399                         goto activate_tlp;
5400                 }
5401                 srtt = rack_grab_rtt(tp, rack);
5402                 thresh = rack_calc_thresh_rack(rack, srtt, cts);
5403                 idx = rsm->r_rtr_cnt - 1;
5404                 exp = ((uint32_t)rsm->r_tim_lastsent[idx]) + thresh;
5405                 if (SEQ_GEQ(exp, cts)) {
5406                         to = exp - cts;
5407                         if (to < rack->r_ctl.rc_min_to) {
5408                                 to = rack->r_ctl.rc_min_to;
5409                                 if (rack->r_rr_config == 3)
5410                                         rack->rc_on_min_to = 1;
5411                         }
5412                 } else {
5413                         to = rack->r_ctl.rc_min_to;
5414                         if (rack->r_rr_config == 3)
5415                                 rack->rc_on_min_to = 1;
5416                 }
5417         } else {
5418                 /* Ok we need to do a TLP not RACK */
5419 activate_tlp:
5420                 if ((rack->rc_tlp_in_progress != 0) &&
5421                     (rack->r_ctl.rc_tlp_cnt_out >= rack_tlp_limit)) {
5422                         /*
5423                          * The previous send was a TLP and we have sent
5424                          * N TLP's without sending new data.
5425                          */
5426                         goto activate_rxt;
5427                 }
5428                 rsm = TAILQ_LAST_FAST(&rack->r_ctl.rc_tmap, rack_sendmap, r_tnext);
5429                 if (rsm == NULL) {
5430                         /* We found no rsm to TLP with. */
5431                         goto activate_rxt;
5432                 }
5433                 if (rsm->r_flags & RACK_HAS_FIN) {
5434                         /* If its a FIN we dont do TLP */
5435                         rsm = NULL;
5436                         goto activate_rxt;
5437                 }
5438                 idx = rsm->r_rtr_cnt - 1;
5439                 time_since_sent = 0;
5440                 if (TSTMP_GEQ(((uint32_t)rsm->r_tim_lastsent[idx]), rack->r_ctl.rc_tlp_rxt_last_time))
5441                         tstmp_touse = (uint32_t)rsm->r_tim_lastsent[idx];
5442                 else
5443                         tstmp_touse = (uint32_t)rack->r_ctl.rc_tlp_rxt_last_time;
5444                 if (TSTMP_GT(cts, tstmp_touse))
5445                     time_since_sent = cts - tstmp_touse;
5446                 is_tlp_timer = 1;
5447                 if (tp->t_srtt) {
5448                         if ((rack->rc_srtt_measure_made == 0) &&
5449                             (tp->t_srtt == 1)) {
5450                                 /*
5451                                  * If another stack as run and set srtt to 1,
5452                                  * then the srtt was 0, so lets use the initial.
5453                                  */
5454                                 srtt = RACK_INITIAL_RTO;
5455                         } else {
5456                                 srtt_cur = tp->t_srtt;
5457                                 srtt = srtt_cur;
5458                         }
5459                 } else
5460                         srtt = RACK_INITIAL_RTO;
5461                 /*
5462                  * If the SRTT is not keeping up and the
5463                  * rack RTT has spiked we want to use
5464                  * the last RTT not the smoothed one.
5465                  */
5466                 if (rack_tlp_use_greater &&
5467                     tp->t_srtt &&
5468                     (srtt < rack_grab_rtt(tp, rack))) {
5469                         srtt = rack_grab_rtt(tp, rack);
5470                 }
5471                 thresh = rack_calc_thresh_tlp(tp, rack, rsm, srtt);
5472                 if (thresh > time_since_sent) {
5473                         to = thresh - time_since_sent;
5474                 } else {
5475                         to = rack->r_ctl.rc_min_to;
5476                         rack_log_alt_to_to_cancel(rack,
5477                                                   thresh,               /* flex1 */
5478                                                   time_since_sent,      /* flex2 */
5479                                                   tstmp_touse,          /* flex3 */
5480                                                   rack->r_ctl.rc_tlp_rxt_last_time, /* flex4 */
5481                                                   (uint32_t)rsm->r_tim_lastsent[idx],
5482                                                   srtt,
5483                                                   idx, 99);
5484                 }
5485                 if (to < rack_tlp_min) {
5486                         to = rack_tlp_min;
5487                 }
5488                 if (to > TICKS_2_USEC(TCPTV_REXMTMAX)) {
5489                         /*
5490                          * If the TLP time works out to larger than the max
5491                          * RTO lets not do TLP.. just RTO.
5492                          */
5493                         goto activate_rxt;
5494                 }
5495         }
5496         if (is_tlp_timer == 0) {
5497                 rack->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
5498         } else {
5499                 rack->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
5500         }
5501         if (to == 0)
5502                 to = 1;
5503         return (to);
5504 }
5505
5506 static void
5507 rack_enter_persist(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
5508 {
5509         if (rack->rc_in_persist == 0) {
5510                 if (tp->t_flags & TF_GPUTINPROG) {
5511                         /*
5512                          * Stop the goodput now, the calling of the
5513                          * measurement function clears the flag.
5514                          */
5515                         rack_do_goodput_measurement(tp, rack, tp->snd_una, __LINE__);
5516                 }
5517 #ifdef NETFLIX_SHARED_CWND
5518                 if (rack->r_ctl.rc_scw) {
5519                         tcp_shared_cwnd_idle(rack->r_ctl.rc_scw, rack->r_ctl.rc_scw_index);
5520                         rack->rack_scwnd_is_idle = 1;
5521                 }
5522 #endif
5523                 rack->r_ctl.rc_went_idle_time = tcp_get_usecs(NULL);
5524                 if (rack->r_ctl.rc_went_idle_time == 0)
5525                         rack->r_ctl.rc_went_idle_time = 1;
5526                 rack_timer_cancel(tp, rack, cts, __LINE__);
5527                 tp->t_rxtshift = 0;
5528                 RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
5529                               rack_rto_min, rack_rto_max);
5530                 rack->rc_in_persist = 1;
5531         }
5532 }
5533
5534 static void
5535 rack_exit_persist(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
5536 {
5537         if (rack->rc_inp->inp_in_hpts) {
5538                 tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
5539                 rack->r_ctl.rc_hpts_flags = 0;
5540         }
5541 #ifdef NETFLIX_SHARED_CWND
5542         if (rack->r_ctl.rc_scw) {
5543                 tcp_shared_cwnd_active(rack->r_ctl.rc_scw, rack->r_ctl.rc_scw_index);
5544                 rack->rack_scwnd_is_idle = 0;
5545         }
5546 #endif
5547         if (rack->rc_gp_dyn_mul &&
5548             (rack->use_fixed_rate == 0) &&
5549             (rack->rc_always_pace)) {
5550                 /*
5551                  * Do we count this as if a probe-rtt just
5552                  * finished?
5553                  */
5554                 uint32_t time_idle, idle_min;
5555
5556                 time_idle = tcp_get_usecs(NULL) - rack->r_ctl.rc_went_idle_time;
5557                 idle_min = rack_min_probertt_hold;
5558                 if (rack_probertt_gpsrtt_cnt_div) {
5559                         uint64_t extra;
5560                         extra = (uint64_t)rack->r_ctl.rc_gp_srtt *
5561                                 (uint64_t)rack_probertt_gpsrtt_cnt_mul;
5562                         extra /= (uint64_t)rack_probertt_gpsrtt_cnt_div;
5563                         idle_min += (uint32_t)extra;
5564                 }
5565                 if (time_idle >= idle_min) {
5566                         /* Yes, we count it as a probe-rtt. */
5567                         uint32_t us_cts;
5568
5569                         us_cts = tcp_get_usecs(NULL);
5570                         if (rack->in_probe_rtt == 0) {
5571                                 rack->r_ctl.rc_lower_rtt_us_cts = us_cts;
5572                                 rack->r_ctl.rc_time_probertt_entered = rack->r_ctl.rc_lower_rtt_us_cts;
5573                                 rack->r_ctl.rc_time_probertt_starts = rack->r_ctl.rc_lower_rtt_us_cts;
5574                                 rack->r_ctl.rc_time_of_last_probertt = rack->r_ctl.rc_lower_rtt_us_cts;
5575                         } else {
5576                                 rack_exit_probertt(rack, us_cts);
5577                         }
5578                 }
5579         }
5580         rack->rc_in_persist = 0;
5581         rack->r_ctl.rc_went_idle_time = 0;
5582         tp->t_rxtshift = 0;
5583         RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
5584            rack_rto_min, rack_rto_max);
5585         rack->r_ctl.rc_agg_delayed = 0;
5586         rack->r_early = 0;
5587         rack->r_late = 0;
5588         rack->r_ctl.rc_agg_early = 0;
5589 }
5590
5591 static void
5592 rack_log_hpts_diag(struct tcp_rack *rack, uint32_t cts,
5593                    struct hpts_diag *diag, struct timeval *tv)
5594 {
5595         if (rack_verbose_logging && rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
5596                 union tcp_log_stackspecific log;
5597
5598                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
5599                 log.u_bbr.flex1 = diag->p_nxt_slot;
5600                 log.u_bbr.flex2 = diag->p_cur_slot;
5601                 log.u_bbr.flex3 = diag->slot_req;
5602                 log.u_bbr.flex4 = diag->inp_hptsslot;
5603                 log.u_bbr.flex5 = diag->slot_remaining;
5604                 log.u_bbr.flex6 = diag->need_new_to;
5605                 log.u_bbr.flex7 = diag->p_hpts_active;
5606                 log.u_bbr.flex8 = diag->p_on_min_sleep;
5607                 /* Hijack other fields as needed */
5608                 log.u_bbr.epoch = diag->have_slept;
5609                 log.u_bbr.lt_epoch = diag->yet_to_sleep;
5610                 log.u_bbr.pkts_out = diag->co_ret;
5611                 log.u_bbr.applimited = diag->hpts_sleep_time;
5612                 log.u_bbr.delivered = diag->p_prev_slot;
5613                 log.u_bbr.inflight = diag->p_runningtick;
5614                 log.u_bbr.bw_inuse = diag->wheel_tick;
5615                 log.u_bbr.rttProp = diag->wheel_cts;
5616                 log.u_bbr.timeStamp = cts;
5617                 log.u_bbr.delRate = diag->maxticks;
5618                 log.u_bbr.cur_del_rate = diag->p_curtick;
5619                 log.u_bbr.cur_del_rate <<= 32;
5620                 log.u_bbr.cur_del_rate |= diag->p_lasttick;
5621                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
5622                     &rack->rc_inp->inp_socket->so_rcv,
5623                     &rack->rc_inp->inp_socket->so_snd,
5624                     BBR_LOG_HPTSDIAG, 0,
5625                     0, &log, false, tv);
5626         }
5627
5628 }
5629
5630 static void
5631 rack_log_wakeup(struct tcpcb *tp, struct tcp_rack *rack, struct sockbuf *sb, uint32_t len, int type)
5632 {
5633         if (rack_verbose_logging && rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
5634                 union tcp_log_stackspecific log;
5635                 struct timeval tv;
5636
5637                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
5638                 log.u_bbr.flex1 = sb->sb_flags;
5639                 log.u_bbr.flex2 = len;
5640                 log.u_bbr.flex3 = sb->sb_state;
5641                 log.u_bbr.flex8 = type;
5642                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
5643                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
5644                     &rack->rc_inp->inp_socket->so_rcv,
5645                     &rack->rc_inp->inp_socket->so_snd,
5646                     TCP_LOG_SB_WAKE, 0,
5647                     len, &log, false, &tv);
5648         }
5649 }
5650
5651 static void
5652 rack_start_hpts_timer(struct tcp_rack *rack, struct tcpcb *tp, uint32_t cts,
5653       int32_t slot, uint32_t tot_len_this_send, int sup_rack)
5654 {
5655         struct hpts_diag diag;
5656         struct inpcb *inp;
5657         struct timeval tv;
5658         uint32_t delayed_ack = 0;
5659         uint32_t hpts_timeout;
5660         uint32_t entry_slot = slot;
5661         uint8_t stopped;
5662         uint32_t left = 0;
5663         uint32_t us_cts;
5664
5665         inp = tp->t_inpcb;
5666         if ((tp->t_state == TCPS_CLOSED) ||
5667             (tp->t_state == TCPS_LISTEN)) {
5668                 return;
5669         }
5670         if (inp->inp_in_hpts) {
5671                 /* Already on the pacer */
5672                 return;
5673         }
5674         stopped = rack->rc_tmr_stopped;
5675         if (stopped && TSTMP_GT(rack->r_ctl.rc_timer_exp, cts)) {
5676                 left = rack->r_ctl.rc_timer_exp - cts;
5677         }
5678         rack->r_ctl.rc_timer_exp = 0;
5679         rack->r_ctl.rc_hpts_flags = 0;
5680         us_cts = tcp_get_usecs(&tv);
5681         /* Now early/late accounting */
5682         rack_log_pacing_delay_calc(rack, entry_slot, slot, 0, 0, 0, 26, __LINE__, NULL);
5683         if (rack->r_early && (rack->rc_ack_can_sendout_data == 0)) {
5684                 /*
5685                  * We have a early carry over set,
5686                  * we can always add more time so we
5687                  * can always make this compensation.
5688                  *
5689                  * Note if ack's are allowed to wake us do not
5690                  * penalize the next timer for being awoke
5691                  * by an ack aka the rc_agg_early (non-paced mode).
5692                  */
5693                 slot += rack->r_ctl.rc_agg_early;
5694                 rack->r_early = 0;
5695                 rack->r_ctl.rc_agg_early = 0;
5696         }
5697         if (rack->r_late) {
5698                 /*
5699                  * This is harder, we can
5700                  * compensate some but it
5701                  * really depends on what
5702                  * the current pacing time is.
5703                  */
5704                 if (rack->r_ctl.rc_agg_delayed >= slot) {
5705                         /*
5706                          * We can't compensate for it all.
5707                          * And we have to have some time
5708                          * on the clock. We always have a min
5709                          * 10 slots (10 x 10 i.e. 100 usecs).
5710                          */
5711                         if (slot <= HPTS_TICKS_PER_USEC) {
5712                                 /* We gain delay */
5713                                 rack->r_ctl.rc_agg_delayed += (HPTS_TICKS_PER_USEC - slot);
5714                                 slot = HPTS_TICKS_PER_USEC;
5715                         } else {
5716                                 /* We take off some */
5717                                 rack->r_ctl.rc_agg_delayed -= (slot - HPTS_TICKS_PER_USEC);
5718                                 slot = HPTS_TICKS_PER_USEC;
5719                         }
5720                 } else {
5721                         slot -= rack->r_ctl.rc_agg_delayed;
5722                         rack->r_ctl.rc_agg_delayed = 0;
5723                         /* Make sure we have 100 useconds at minimum */
5724                         if (slot < HPTS_TICKS_PER_USEC) {
5725                                 rack->r_ctl.rc_agg_delayed = HPTS_TICKS_PER_USEC - slot;
5726                                 slot = HPTS_TICKS_PER_USEC;
5727                         }
5728                         if (rack->r_ctl.rc_agg_delayed == 0)
5729                                 rack->r_late = 0;
5730                 }
5731         }
5732         if (slot) {
5733                 /* We are pacing too */
5734                 rack->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
5735         }
5736         hpts_timeout = rack_timer_start(tp, rack, cts, sup_rack);
5737 #ifdef NETFLIX_EXP_DETECTION
5738         if (rack->sack_attack_disable &&
5739             (slot < tcp_sad_pacing_interval)) {
5740                 /*
5741                  * We have a potential attacker on
5742                  * the line. We have possibly some
5743                  * (or now) pacing time set. We want to
5744                  * slow down the processing of sacks by some
5745                  * amount (if it is an attacker). Set the default
5746                  * slot for attackers in place (unless the orginal
5747                  * interval is longer). Its stored in
5748                  * micro-seconds, so lets convert to msecs.
5749                  */
5750                 slot = tcp_sad_pacing_interval;
5751         }
5752 #endif
5753         if (tp->t_flags & TF_DELACK) {
5754                 delayed_ack = TICKS_2_USEC(tcp_delacktime);
5755                 rack->r_ctl.rc_hpts_flags |= PACE_TMR_DELACK;
5756         }
5757         if (delayed_ack && ((hpts_timeout == 0) ||
5758                             (delayed_ack < hpts_timeout)))
5759                 hpts_timeout = delayed_ack;
5760         else
5761                 rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
5762         /*
5763          * If no timers are going to run and we will fall off the hptsi
5764          * wheel, we resort to a keep-alive timer if its configured.
5765          */
5766         if ((hpts_timeout == 0) &&
5767             (slot == 0)) {
5768                 if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
5769                     (tp->t_state <= TCPS_CLOSING)) {
5770                         /*
5771                          * Ok we have no timer (persists, rack, tlp, rxt  or
5772                          * del-ack), we don't have segments being paced. So
5773                          * all that is left is the keepalive timer.
5774                          */
5775                         if (TCPS_HAVEESTABLISHED(tp->t_state)) {
5776                                 /* Get the established keep-alive time */
5777                                 hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
5778                         } else {
5779                                 /*
5780                                  * Get the initial setup keep-alive time,
5781                                  * note that this is probably not going to
5782                                  * happen, since rack will be running a rxt timer
5783                                  * if a SYN of some sort is outstanding. It is
5784                                  * actually handled in rack_timeout_rxt().
5785                                  */
5786                                 hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
5787                         }
5788                         rack->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
5789                         if (rack->in_probe_rtt) {
5790                                 /*
5791                                  * We want to instead not wake up a long time from
5792                                  * now but to wake up about the time we would
5793                                  * exit probe-rtt and initiate a keep-alive ack.
5794                                  * This will get us out of probe-rtt and update
5795                                  * our min-rtt.
5796                                  */
5797                                 hpts_timeout = rack_min_probertt_hold;
5798                         }
5799                 }
5800         }
5801         if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
5802             (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
5803                 /*
5804                  * RACK, TLP, persists and RXT timers all are restartable
5805                  * based on actions input .. i.e we received a packet (ack
5806                  * or sack) and that changes things (rw, or snd_una etc).
5807                  * Thus we can restart them with a new value. For
5808                  * keep-alive, delayed_ack we keep track of what was left
5809                  * and restart the timer with a smaller value.
5810                  */
5811                 if (left < hpts_timeout)
5812                         hpts_timeout = left;
5813         }
5814         if (hpts_timeout) {
5815                 /*
5816                  * Hack alert for now we can't time-out over 2,147,483
5817                  * seconds (a bit more than 596 hours), which is probably ok
5818                  * :).
5819                  */
5820                 if (hpts_timeout > 0x7ffffffe)
5821                         hpts_timeout = 0x7ffffffe;
5822                 rack->r_ctl.rc_timer_exp = cts + hpts_timeout;
5823         }
5824         rack_log_pacing_delay_calc(rack, entry_slot, slot, hpts_timeout, 0, 0, 27, __LINE__, NULL);
5825         if ((rack->gp_ready == 0) &&
5826             (rack->use_fixed_rate == 0) &&
5827             (hpts_timeout < slot) &&
5828             (rack->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
5829                 /*
5830                  * We have no good estimate yet for the
5831                  * old clunky burst mitigation or the
5832                  * real pacing. And the tlp or rxt is smaller
5833                  * than the pacing calculation. Lets not
5834                  * pace that long since we know the calculation
5835                  * so far is not accurate.
5836                  */
5837                 slot = hpts_timeout;
5838         }
5839         rack->r_ctl.last_pacing_time = slot;
5840         /**
5841          * Turn off all the flags for queuing by default. The
5842          * flags have important meanings to what happens when
5843          * LRO interacts with the transport. Most likely (by default now)
5844          * mbuf_queueing and ack compression are on. So the transport
5845          * has a couple of flags that control what happens (if those
5846          * are not on then these flags won't have any effect since it
5847          * won't go through the queuing LRO path).
5848          *
5849          * INP_MBUF_QUEUE_READY - This flags says that I am busy
5850          *                        pacing output, so don't disturb. But
5851          *                        it also means LRO can wake me if there
5852          *                        is a SACK arrival.
5853          *
5854          * INP_DONT_SACK_QUEUE - This flag is used in conjunction
5855          *                       with the above flag (QUEUE_READY) and
5856          *                       when present it says don't even wake me
5857          *                       if a SACK arrives.
5858          *
5859          * The idea behind these flags is that if we are pacing we
5860          * set the MBUF_QUEUE_READY and only get woken up if
5861          * a SACK arrives (which could change things) or if
5862          * our pacing timer expires. If, however, we have a rack
5863          * timer running, then we don't even want a sack to wake
5864          * us since the rack timer has to expire before we can send.
5865          *
5866          * Other cases should usually have none of the flags set
5867          * so LRO can call into us.
5868          */
5869         inp->inp_flags2 &= ~(INP_DONT_SACK_QUEUE|INP_MBUF_QUEUE_READY);
5870         if (slot) {
5871                 rack->r_ctl.rc_last_output_to = us_cts + slot;
5872                 /*
5873                  * A pacing timer (slot) is being set, in
5874                  * such a case we cannot send (we are blocked by
5875                  * the timer). So lets tell LRO that it should not
5876                  * wake us unless there is a SACK. Note this only
5877                  * will be effective if mbuf queueing is on or
5878                  * compressed acks are being processed.
5879                  */
5880                 inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
5881                 /*
5882                  * But wait if we have a Rack timer running
5883                  * even a SACK should not disturb us (with
5884                  * the exception of r_rr_config 3).
5885                  */
5886                 if ((rack->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
5887                     (rack->r_rr_config != 3))
5888                         inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
5889                 if (rack->rc_ack_can_sendout_data) {
5890                         /*
5891                          * Ahh but wait, this is that special case
5892                          * where the pacing timer can be disturbed
5893                          * backout the changes (used for non-paced
5894                          * burst limiting).
5895                          */
5896                         inp->inp_flags2 &= ~(INP_DONT_SACK_QUEUE|INP_MBUF_QUEUE_READY);
5897                 }
5898                 if ((rack->use_rack_rr) &&
5899                     (rack->r_rr_config < 2) &&
5900                     ((hpts_timeout) && (hpts_timeout < slot))) {
5901                         /*
5902                          * Arrange for the hpts to kick back in after the
5903                          * t-o if the t-o does not cause a send.
5904                          */
5905                         (void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(hpts_timeout),
5906                                                    __LINE__, &diag);
5907                         rack_log_hpts_diag(rack, us_cts, &diag, &tv);
5908                         rack_log_to_start(rack, cts, hpts_timeout, slot, 0);
5909                 } else {
5910                         (void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(slot),
5911                                                    __LINE__, &diag);
5912                         rack_log_hpts_diag(rack, us_cts, &diag, &tv);
5913                         rack_log_to_start(rack, cts, hpts_timeout, slot, 1);
5914                 }
5915         } else if (hpts_timeout) {
5916                 /*
5917                  * With respect to inp_flags2 here, lets let any new acks wake
5918                  * us up here. Since we are not pacing (no pacing timer), output
5919                  * can happen so we should let it. If its a Rack timer, then any inbound
5920                  * packet probably won't change the sending (we will be blocked)
5921                  * but it may change the prr stats so letting it in (the set defaults
5922                  * at the start of this block) are good enough.
5923                  */
5924                 (void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(hpts_timeout),
5925                                            __LINE__, &diag);
5926                 rack_log_hpts_diag(rack, us_cts, &diag, &tv);
5927                 rack_log_to_start(rack, cts, hpts_timeout, slot, 0);
5928         } else {
5929                 /* No timer starting */
5930 #ifdef INVARIANTS
5931                 if (SEQ_GT(tp->snd_max, tp->snd_una)) {
5932                         panic("tp:%p rack:%p tlts:%d cts:%u slot:%u pto:%u -- no timer started?",
5933                             tp, rack, tot_len_this_send, cts, slot, hpts_timeout);
5934                 }
5935 #endif
5936         }
5937         rack->rc_tmr_stopped = 0;
5938         if (slot)
5939                 rack_log_type_bbrsnd(rack, tot_len_this_send, slot, us_cts, &tv);
5940 }
5941
5942 /*
5943  * RACK Timer, here we simply do logging and house keeping.
5944  * the normal rack_output() function will call the
5945  * appropriate thing to check if we need to do a RACK retransmit.
5946  * We return 1, saying don't proceed with rack_output only
5947  * when all timers have been stopped (destroyed PCB?).
5948  */
5949 static int
5950 rack_timeout_rack(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
5951 {
5952         /*
5953          * This timer simply provides an internal trigger to send out data.
5954          * The check_recovery_mode call will see if there are needed
5955          * retransmissions, if so we will enter fast-recovery. The output
5956          * call may or may not do the same thing depending on sysctl
5957          * settings.
5958          */
5959         struct rack_sendmap *rsm;
5960
5961         if (tp->t_timers->tt_flags & TT_STOPPED) {
5962                 return (1);
5963         }
5964         counter_u64_add(rack_to_tot, 1);
5965         if (rack->r_state && (rack->r_state != tp->t_state))
5966                 rack_set_state(tp, rack);
5967         rack->rc_on_min_to = 0;
5968         rsm = rack_check_recovery_mode(tp, cts);
5969         rack_log_to_event(rack, RACK_TO_FRM_RACK, rsm);
5970         if (rsm) {
5971                 rack->r_ctl.rc_resend = rsm;
5972                 rack->r_timer_override = 1;
5973                 if (rack->use_rack_rr) {
5974                         /*
5975                          * Don't accumulate extra pacing delay
5976                          * we are allowing the rack timer to
5977                          * over-ride pacing i.e. rrr takes precedence
5978                          * if the pacing interval is longer than the rrr
5979                          * time (in other words we get the min pacing
5980                          * time versus rrr pacing time).
5981                          */
5982                         rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
5983                 }
5984         }
5985         rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
5986         if (rsm == NULL) {
5987                 /* restart a timer and return 1 */
5988                 rack_start_hpts_timer(rack, tp, cts,
5989                                       0, 0, 0);
5990                 return (1);
5991         }
5992         return (0);
5993 }
5994
5995 static void
5996 rack_adjust_orig_mlen(struct rack_sendmap *rsm)
5997 {
5998         if (rsm->m->m_len > rsm->orig_m_len) {
5999                 /*
6000                  * Mbuf grew, caused by sbcompress, our offset does
6001                  * not change.
6002                  */
6003                 rsm->orig_m_len = rsm->m->m_len;
6004         } else if (rsm->m->m_len < rsm->orig_m_len) {
6005                 /*
6006                  * Mbuf shrank, trimmed off the top by an ack, our
6007                  * offset changes.
6008                  */
6009                 rsm->soff -= (rsm->orig_m_len - rsm->m->m_len);
6010                 rsm->orig_m_len = rsm->m->m_len;
6011         }
6012 }
6013
6014 static void
6015 rack_setup_offset_for_rsm(struct rack_sendmap *src_rsm, struct rack_sendmap *rsm)
6016 {
6017         struct mbuf *m;
6018         uint32_t soff;
6019
6020         if (src_rsm->orig_m_len != src_rsm->m->m_len) {
6021                 /* Fix up the orig_m_len and possibly the mbuf offset */
6022                 rack_adjust_orig_mlen(src_rsm);
6023         }
6024         m = src_rsm->m;
6025         soff = src_rsm->soff + (src_rsm->r_end - src_rsm->r_start);
6026         while (soff >= m->m_len) {
6027                 /* Move out past this mbuf */
6028                 soff -= m->m_len;
6029                 m = m->m_next;
6030                 KASSERT((m != NULL),
6031                         ("rsm:%p nrsm:%p hit at soff:%u null m",
6032                          src_rsm, rsm, soff));
6033         }
6034         rsm->m = m;
6035         rsm->soff = soff;
6036         rsm->orig_m_len = m->m_len;
6037 }
6038
6039 static __inline void
6040 rack_clone_rsm(struct tcp_rack *rack, struct rack_sendmap *nrsm,
6041                struct rack_sendmap *rsm, uint32_t start)
6042 {
6043         int idx;
6044
6045         nrsm->r_start = start;
6046         nrsm->r_end = rsm->r_end;
6047         nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
6048         nrsm->r_flags = rsm->r_flags;
6049         nrsm->r_dupack = rsm->r_dupack;
6050         nrsm->r_no_rtt_allowed = rsm->r_no_rtt_allowed;
6051         nrsm->r_rtr_bytes = 0;
6052         rsm->r_end = nrsm->r_start;
6053         nrsm->r_just_ret = rsm->r_just_ret;
6054         for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
6055                 nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
6056         }
6057         /* Now if we have SYN flag we keep it on the left edge */
6058         if (nrsm->r_flags & RACK_HAS_SYN)
6059                 nrsm->r_flags &= ~RACK_HAS_SYN;
6060         /* Now if we have a FIN flag we keep it on the right edge */
6061         if (nrsm->r_flags & RACK_HAS_FIN)
6062                 nrsm->r_flags &= ~RACK_HAS_FIN;
6063         /*
6064          * Now we need to find nrsm's new location in the mbuf chain
6065          * we basically calculate a new offset, which is soff +
6066          * how much is left in original rsm. Then we walk out the mbuf
6067          * chain to find the righ postion, it may be the same mbuf
6068          * or maybe not.
6069          */
6070         KASSERT(((rsm->m != NULL) ||
6071                  (rsm->r_flags & (RACK_HAS_SYN|RACK_HAS_FIN))),
6072                 ("rsm:%p nrsm:%p rack:%p -- rsm->m is NULL?", rsm, nrsm, rack));
6073         if (rsm->m)
6074                 rack_setup_offset_for_rsm(rsm, nrsm);
6075 }
6076
6077 static struct rack_sendmap *
6078 rack_merge_rsm(struct tcp_rack *rack,
6079                struct rack_sendmap *l_rsm,
6080                struct rack_sendmap *r_rsm)
6081 {
6082         /*
6083          * We are merging two ack'd RSM's,
6084          * the l_rsm is on the left (lower seq
6085          * values) and the r_rsm is on the right
6086          * (higher seq value). The simplest way
6087          * to merge these is to move the right
6088          * one into the left. I don't think there
6089          * is any reason we need to try to find
6090          * the oldest (or last oldest retransmitted).
6091          */
6092         struct rack_sendmap *rm;
6093
6094         rack_log_map_chg(rack->rc_tp, rack, NULL,
6095                          l_rsm, r_rsm, MAP_MERGE, r_rsm->r_end, __LINE__);
6096         l_rsm->r_end = r_rsm->r_end;
6097         if (l_rsm->r_dupack < r_rsm->r_dupack)
6098                 l_rsm->r_dupack = r_rsm->r_dupack;
6099         if (r_rsm->r_rtr_bytes)
6100                 l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
6101         if (r_rsm->r_in_tmap) {
6102                 /* This really should not happen */
6103                 TAILQ_REMOVE(&rack->r_ctl.rc_tmap, r_rsm, r_tnext);
6104                 r_rsm->r_in_tmap = 0;
6105         }
6106
6107         /* Now the flags */
6108         if (r_rsm->r_flags & RACK_HAS_FIN)
6109                 l_rsm->r_flags |= RACK_HAS_FIN;
6110         if (r_rsm->r_flags & RACK_TLP)
6111                 l_rsm->r_flags |= RACK_TLP;
6112         if (r_rsm->r_flags & RACK_RWND_COLLAPSED)
6113                 l_rsm->r_flags |= RACK_RWND_COLLAPSED;
6114         if ((r_rsm->r_flags & RACK_APP_LIMITED)  &&
6115             ((l_rsm->r_flags & RACK_APP_LIMITED) == 0)) {
6116                 /*
6117                  * If both are app-limited then let the
6118                  * free lower the count. If right is app
6119                  * limited and left is not, transfer.
6120                  */
6121                 l_rsm->r_flags |= RACK_APP_LIMITED;
6122                 r_rsm->r_flags &= ~RACK_APP_LIMITED;
6123                 if (r_rsm == rack->r_ctl.rc_first_appl)
6124                         rack->r_ctl.rc_first_appl = l_rsm;
6125         }
6126         rm = RB_REMOVE(rack_rb_tree_head, &rack->r_ctl.rc_mtree, r_rsm);
6127 #ifdef INVARIANTS
6128         if (rm != r_rsm) {
6129                 panic("removing head in rack:%p rsm:%p rm:%p",
6130                       rack, r_rsm, rm);
6131         }
6132 #endif
6133         if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
6134                 /* Transfer the split limit to the map we free */
6135                 r_rsm->r_limit_type = l_rsm->r_limit_type;
6136                 l_rsm->r_limit_type = 0;
6137         }
6138         rack_free(rack, r_rsm);
6139         return (l_rsm);
6140 }
6141
6142 /*
6143  * TLP Timer, here we simply setup what segment we want to
6144  * have the TLP expire on, the normal rack_output() will then
6145  * send it out.
6146  *
6147  * We return 1, saying don't proceed with rack_output only
6148  * when all timers have been stopped (destroyed PCB?).
6149  */
6150 static int
6151 rack_timeout_tlp(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
6152 {
6153         /*
6154          * Tail Loss Probe.
6155          */
6156         struct rack_sendmap *rsm = NULL;
6157         struct rack_sendmap *insret;
6158         struct socket *so;
6159         uint32_t amm;
6160         uint32_t out, avail;
6161         int collapsed_win = 0;
6162
6163         if (tp->t_timers->tt_flags & TT_STOPPED) {
6164                 return (1);
6165         }
6166         if (TSTMP_LT(cts, rack->r_ctl.rc_timer_exp)) {
6167                 /* Its not time yet */
6168                 return (0);
6169         }
6170         if (ctf_progress_timeout_check(tp, true)) {
6171                 rack_log_progress_event(rack, tp, tick, PROGRESS_DROP, __LINE__);
6172                 tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
6173                 return (1);
6174         }
6175         /*
6176          * A TLP timer has expired. We have been idle for 2 rtts. So we now
6177          * need to figure out how to force a full MSS segment out.
6178          */
6179         rack_log_to_event(rack, RACK_TO_FRM_TLP, NULL);
6180         rack->r_ctl.retran_during_recovery = 0;
6181         rack->r_ctl.dsack_byte_cnt = 0;
6182         counter_u64_add(rack_tlp_tot, 1);
6183         if (rack->r_state && (rack->r_state != tp->t_state))
6184                 rack_set_state(tp, rack);
6185         so = tp->t_inpcb->inp_socket;
6186         avail = sbavail(&so->so_snd);
6187         out = tp->snd_max - tp->snd_una;
6188         if (out > tp->snd_wnd) {
6189                 /* special case, we need a retransmission */
6190                 collapsed_win = 1;
6191                 goto need_retran;
6192         }
6193         /*
6194          * Check our send oldest always settings, and if
6195          * there is an oldest to send jump to the need_retran.
6196          */
6197         if (rack_always_send_oldest && (TAILQ_EMPTY(&rack->r_ctl.rc_tmap) == 0))
6198                 goto need_retran;
6199
6200         if (avail > out) {
6201                 /* New data is available */
6202                 amm = avail - out;
6203                 if (amm > ctf_fixed_maxseg(tp)) {
6204                         amm = ctf_fixed_maxseg(tp);
6205                         if ((amm + out) > tp->snd_wnd) {
6206                                 /* We are rwnd limited */
6207                                 goto need_retran;
6208                         }
6209                 } else if (amm < ctf_fixed_maxseg(tp)) {
6210                         /* not enough to fill a MTU */
6211                         goto need_retran;
6212                 }
6213                 if (IN_FASTRECOVERY(tp->t_flags)) {
6214                         /* Unlikely */
6215                         if (rack->rack_no_prr == 0) {
6216                                 if (out + amm <= tp->snd_wnd) {
6217                                         rack->r_ctl.rc_prr_sndcnt = amm;
6218                                         rack_log_to_prr(rack, 4, 0);
6219                                 }
6220                         } else
6221                                 goto need_retran;
6222                 } else {
6223                         /* Set the send-new override */
6224                         if (out + amm <= tp->snd_wnd)
6225                                 rack->r_ctl.rc_tlp_new_data = amm;
6226                         else
6227                                 goto need_retran;
6228                 }
6229                 rack->r_ctl.rc_tlpsend = NULL;
6230                 counter_u64_add(rack_tlp_newdata, 1);
6231                 goto send;
6232         }
6233 need_retran:
6234         /*
6235          * Ok we need to arrange the last un-acked segment to be re-sent, or
6236          * optionally the first un-acked segment.
6237          */
6238         if (collapsed_win == 0) {
6239                 if (rack_always_send_oldest)
6240                         rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
6241                 else {
6242                         rsm = RB_MAX(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
6243                         if (rsm && (rsm->r_flags & (RACK_ACKED | RACK_HAS_FIN))) {
6244                                 rsm = rack_find_high_nonack(rack, rsm);
6245                         }
6246                 }
6247                 if (rsm == NULL) {
6248                         counter_u64_add(rack_tlp_does_nada, 1);
6249 #ifdef TCP_BLACKBOX
6250                         tcp_log_dump_tp_logbuf(tp, "nada counter trips", M_NOWAIT, true);
6251 #endif
6252                         goto out;
6253                 }
6254         } else {
6255                 /*
6256                  * We must find the last segment
6257                  * that was acceptable by the client.
6258                  */
6259                 RB_FOREACH_REVERSE(rsm, rack_rb_tree_head, &rack->r_ctl.rc_mtree) {
6260                         if ((rsm->r_flags & RACK_RWND_COLLAPSED) == 0) {
6261                                 /* Found one */
6262                                 break;
6263                         }
6264                 }
6265                 if (rsm == NULL) {
6266                         /* None? if so send the first */
6267                         rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
6268                         if (rsm == NULL) {
6269                                 counter_u64_add(rack_tlp_does_nada, 1);
6270 #ifdef TCP_BLACKBOX
6271                                 tcp_log_dump_tp_logbuf(tp, "nada counter trips", M_NOWAIT, true);
6272 #endif
6273                                 goto out;
6274                         }
6275                 }
6276         }
6277         if ((rsm->r_end - rsm->r_start) > ctf_fixed_maxseg(tp)) {
6278                 /*
6279                  * We need to split this the last segment in two.
6280                  */
6281                 struct rack_sendmap *nrsm;
6282
6283                 nrsm = rack_alloc_full_limit(rack);
6284                 if (nrsm == NULL) {
6285                         /*
6286                          * No memory to split, we will just exit and punt
6287                          * off to the RXT timer.
6288                          */
6289                         counter_u64_add(rack_tlp_does_nada, 1);
6290                         goto out;
6291                 }
6292                 rack_clone_rsm(rack, nrsm, rsm,
6293                                (rsm->r_end - ctf_fixed_maxseg(tp)));
6294                 rack_log_map_chg(tp, rack, NULL, rsm, nrsm, MAP_SPLIT, 0, __LINE__);
6295                 insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
6296 #ifdef INVARIANTS
6297                 if (insret != NULL) {
6298                         panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
6299                               nrsm, insret, rack, rsm);
6300                 }
6301 #endif
6302                 if (rsm->r_in_tmap) {
6303                         TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6304                         nrsm->r_in_tmap = 1;
6305                 }
6306                 rsm->r_flags &= (~RACK_HAS_FIN);
6307                 rsm = nrsm;
6308         }
6309         rack->r_ctl.rc_tlpsend = rsm;
6310 send:
6311         rack->r_timer_override = 1;
6312         rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
6313         return (0);
6314 out:
6315         rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
6316         return (0);
6317 }
6318
6319 /*
6320  * Delayed ack Timer, here we simply need to setup the
6321  * ACK_NOW flag and remove the DELACK flag. From there
6322  * the output routine will send the ack out.
6323  *
6324  * We only return 1, saying don't proceed, if all timers
6325  * are stopped (destroyed PCB?).
6326  */
6327 static int
6328 rack_timeout_delack(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
6329 {
6330         if (tp->t_timers->tt_flags & TT_STOPPED) {
6331                 return (1);
6332         }
6333         rack_log_to_event(rack, RACK_TO_FRM_DELACK, NULL);
6334         tp->t_flags &= ~TF_DELACK;
6335         tp->t_flags |= TF_ACKNOW;
6336         KMOD_TCPSTAT_INC(tcps_delack);
6337         rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
6338         return (0);
6339 }
6340
6341 /*
6342  * Persists timer, here we simply send the
6343  * same thing as a keepalive will.
6344  * the one byte send.
6345  *
6346  * We only return 1, saying don't proceed, if all timers
6347  * are stopped (destroyed PCB?).
6348  */
6349 static int
6350 rack_timeout_persist(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
6351 {
6352         struct tcptemp *t_template;
6353         struct inpcb *inp;
6354         int32_t retval = 1;
6355
6356         inp = tp->t_inpcb;
6357
6358         if (tp->t_timers->tt_flags & TT_STOPPED) {
6359                 return (1);
6360         }
6361         if (rack->rc_in_persist == 0)
6362                 return (0);
6363         if (ctf_progress_timeout_check(tp, false)) {
6364                 tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
6365                 rack_log_progress_event(rack, tp, tick, PROGRESS_DROP, __LINE__);
6366                 tcp_set_inp_to_drop(inp, ETIMEDOUT);
6367                 return (1);
6368         }
6369         KASSERT(inp != NULL, ("%s: tp %p tp->t_inpcb == NULL", __func__, tp));
6370         /*
6371          * Persistence timer into zero window. Force a byte to be output, if
6372          * possible.
6373          */
6374         KMOD_TCPSTAT_INC(tcps_persisttimeo);
6375         /*
6376          * Hack: if the peer is dead/unreachable, we do not time out if the
6377          * window is closed.  After a full backoff, drop the connection if
6378          * the idle time (no responses to probes) reaches the maximum
6379          * backoff that we would use if retransmitting.
6380          */
6381         if (tp->t_rxtshift == TCP_MAXRXTSHIFT &&
6382             (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
6383              TICKS_2_USEC(ticks - tp->t_rcvtime) >= RACK_REXMTVAL(tp) * tcp_totbackoff)) {
6384                 KMOD_TCPSTAT_INC(tcps_persistdrop);
6385                 retval = 1;
6386                 tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
6387                 tcp_set_inp_to_drop(rack->rc_inp, ETIMEDOUT);
6388                 goto out;
6389         }
6390         if ((sbavail(&rack->rc_inp->inp_socket->so_snd) == 0) &&
6391             tp->snd_una == tp->snd_max)
6392                 rack_exit_persist(tp, rack, cts);
6393         rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
6394         /*
6395          * If the user has closed the socket then drop a persisting
6396          * connection after a much reduced timeout.
6397          */
6398         if (tp->t_state > TCPS_CLOSE_WAIT &&
6399             (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
6400                 retval = 1;
6401                 KMOD_TCPSTAT_INC(tcps_persistdrop);
6402                 tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
6403                 tcp_set_inp_to_drop(rack->rc_inp, ETIMEDOUT);
6404                 goto out;
6405         }
6406         t_template = tcpip_maketemplate(rack->rc_inp);
6407         if (t_template) {
6408                 /* only set it if we were answered */
6409                 if (rack->forced_ack == 0) {
6410                         rack->forced_ack = 1;
6411                         rack->r_ctl.forced_ack_ts = tcp_get_usecs(NULL);
6412                 }
6413                 tcp_respond(tp, t_template->tt_ipgen,
6414                             &t_template->tt_t, (struct mbuf *)NULL,
6415                             tp->rcv_nxt, tp->snd_una - 1, 0);
6416                 /* This sends an ack */
6417                 if (tp->t_flags & TF_DELACK)
6418                         tp->t_flags &= ~TF_DELACK;
6419                 free(t_template, M_TEMP);
6420         }
6421         if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
6422                 tp->t_rxtshift++;
6423 out:
6424         rack_log_to_event(rack, RACK_TO_FRM_PERSIST, NULL);
6425         rack_start_hpts_timer(rack, tp, cts,
6426                               0, 0, 0);
6427         return (retval);
6428 }
6429
6430 /*
6431  * If a keepalive goes off, we had no other timers
6432  * happening. We always return 1 here since this
6433  * routine either drops the connection or sends
6434  * out a segment with respond.
6435  */
6436 static int
6437 rack_timeout_keepalive(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
6438 {
6439         struct tcptemp *t_template;
6440         struct inpcb *inp;
6441
6442         if (tp->t_timers->tt_flags & TT_STOPPED) {
6443                 return (1);
6444         }
6445         rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
6446         inp = tp->t_inpcb;
6447         rack_log_to_event(rack, RACK_TO_FRM_KEEP, NULL);
6448         /*
6449          * Keep-alive timer went off; send something or drop connection if
6450          * idle for too long.
6451          */
6452         KMOD_TCPSTAT_INC(tcps_keeptimeo);
6453         if (tp->t_state < TCPS_ESTABLISHED)
6454                 goto dropit;
6455         if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
6456             tp->t_state <= TCPS_CLOSING) {
6457                 if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
6458                         goto dropit;
6459                 /*
6460                  * Send a packet designed to force a response if the peer is
6461                  * up and reachable: either an ACK if the connection is
6462                  * still alive, or an RST if the peer has closed the
6463                  * connection due to timeout or reboot. Using sequence
6464                  * number tp->snd_una-1 causes the transmitted zero-length
6465                  * segment to lie outside the receive window; by the
6466                  * protocol spec, this requires the correspondent TCP to
6467                  * respond.
6468                  */
6469                 KMOD_TCPSTAT_INC(tcps_keepprobe);
6470                 t_template = tcpip_maketemplate(inp);
6471                 if (t_template) {
6472                         if (rack->forced_ack == 0) {
6473                                 rack->forced_ack = 1;
6474                                 rack->r_ctl.forced_ack_ts = tcp_get_usecs(NULL);
6475                         }
6476                         tcp_respond(tp, t_template->tt_ipgen,
6477                             &t_template->tt_t, (struct mbuf *)NULL,
6478                             tp->rcv_nxt, tp->snd_una - 1, 0);
6479                         free(t_template, M_TEMP);
6480                 }
6481         }
6482         rack_start_hpts_timer(rack, tp, cts, 0, 0, 0);
6483         return (1);
6484 dropit:
6485         KMOD_TCPSTAT_INC(tcps_keepdrops);
6486         tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
6487         tcp_set_inp_to_drop(rack->rc_inp, ETIMEDOUT);
6488         return (1);
6489 }
6490
6491 /*
6492  * Retransmit helper function, clear up all the ack
6493  * flags and take care of important book keeping.
6494  */
6495 static void
6496 rack_remxt_tmr(struct tcpcb *tp)
6497 {
6498         /*
6499          * The retransmit timer went off, all sack'd blocks must be
6500          * un-acked.
6501          */
6502         struct rack_sendmap *rsm, *trsm = NULL;
6503         struct tcp_rack *rack;
6504
6505         rack = (struct tcp_rack *)tp->t_fb_ptr;
6506         rack_timer_cancel(tp, rack, tcp_get_usecs(NULL), __LINE__);
6507         rack_log_to_event(rack, RACK_TO_FRM_TMR, NULL);
6508         if (rack->r_state && (rack->r_state != tp->t_state))
6509                 rack_set_state(tp, rack);
6510         /*
6511          * Ideally we would like to be able to
6512          * mark SACK-PASS on anything not acked here.
6513          *
6514          * However, if we do that we would burst out
6515          * all that data 1ms apart. This would be unwise,
6516          * so for now we will just let the normal rxt timer
6517          * and tlp timer take care of it.
6518          *
6519          * Also we really need to stick them back in sequence
6520          * order. This way we send in the proper order and any
6521          * sacks that come floating in will "re-ack" the data.
6522          * To do this we zap the tmap with an INIT and then
6523          * walk through and place every rsm in the RB tree
6524          * back in its seq ordered place.
6525          */
6526         TAILQ_INIT(&rack->r_ctl.rc_tmap);
6527         RB_FOREACH(rsm, rack_rb_tree_head, &rack->r_ctl.rc_mtree) {
6528                 rsm->r_dupack = 0;
6529                 rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
6530                 /* We must re-add it back to the tlist */
6531                 if (trsm == NULL) {
6532                         TAILQ_INSERT_HEAD(&rack->r_ctl.rc_tmap, rsm, r_tnext);
6533                 } else {
6534                         TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, trsm, rsm, r_tnext);
6535                 }
6536                 rsm->r_in_tmap = 1;
6537                 trsm = rsm;
6538                 if (rsm->r_flags & RACK_ACKED)
6539                         rsm->r_flags |= RACK_WAS_ACKED;
6540                 rsm->r_flags &= ~(RACK_ACKED | RACK_SACK_PASSED | RACK_WAS_SACKPASS);
6541         }
6542         /* Clear the count (we just un-acked them) */
6543         rack->r_ctl.rc_last_timeout_snduna = tp->snd_una;
6544         rack->r_ctl.rc_sacked = 0;
6545         rack->r_ctl.rc_sacklast = NULL;
6546         rack->r_ctl.rc_agg_delayed = 0;
6547         rack->r_early = 0;
6548         rack->r_ctl.rc_agg_early = 0;
6549         rack->r_late = 0;
6550         /* Clear the tlp rtx mark */
6551         rack->r_ctl.rc_resend = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
6552         if (rack->r_ctl.rc_resend != NULL)
6553                 rack->r_ctl.rc_resend->r_flags |= RACK_TO_REXT;
6554         rack->r_ctl.rc_prr_sndcnt = 0;
6555         rack_log_to_prr(rack, 6, 0);
6556         rack->r_timer_override = 1;
6557         if ((((tp->t_flags & TF_SACK_PERMIT) == 0)
6558 #ifdef NETFLIX_EXP_DETECTION
6559             || (rack->sack_attack_disable != 0)
6560 #endif
6561                     ) && ((tp->t_flags & TF_SENTFIN) == 0)) {
6562                 /*
6563                  * For non-sack customers new data
6564                  * needs to go out as retransmits until
6565                  * we retransmit up to snd_max.
6566                  */
6567                 rack->r_must_retran = 1;
6568                 rack->r_ctl.rc_out_at_rto = ctf_flight_size(rack->rc_tp,
6569                                                 rack->r_ctl.rc_sacked);
6570         }
6571         rack->r_ctl.rc_snd_max_at_rto = tp->snd_max;
6572 }
6573
6574 static void
6575 rack_convert_rtts(struct tcpcb *tp)
6576 {
6577         if (tp->t_srtt > 1) {
6578                 uint32_t val, frac;
6579
6580                 val = tp->t_srtt >> TCP_RTT_SHIFT;
6581                 frac = tp->t_srtt & 0x1f;
6582                 tp->t_srtt = TICKS_2_USEC(val);
6583                 /*
6584                  * frac is the fractional part of the srtt (if any)
6585                  * but its in ticks and every bit represents
6586                  * 1/32nd of a hz.
6587                  */
6588                 if (frac) {
6589                         if (hz == 1000) {
6590                                 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE);
6591                         } else {
6592                                 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE));
6593                         }
6594                         tp->t_srtt += frac;
6595                 }
6596         }
6597         if (tp->t_rttvar) {
6598                 uint32_t val, frac;
6599
6600                 val = tp->t_rttvar >> TCP_RTTVAR_SHIFT;
6601                 frac = tp->t_rttvar & 0x1f;
6602                 tp->t_rttvar = TICKS_2_USEC(val);
6603                 /*
6604                  * frac is the fractional part of the srtt (if any)
6605                  * but its in ticks and every bit represents
6606                  * 1/32nd of a hz.
6607                  */
6608                 if (frac) {
6609                         if (hz == 1000) {
6610                                 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE);
6611                         } else {
6612                                 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE));
6613                         }
6614                         tp->t_rttvar += frac;
6615                 }
6616         }
6617         tp->t_rxtcur = RACK_REXMTVAL(tp);
6618         if (TCPS_HAVEESTABLISHED(tp->t_state)) {
6619                 tp->t_rxtcur += TICKS_2_USEC(tcp_rexmit_slop);
6620         }
6621         if (tp->t_rxtcur > rack_rto_max) {
6622                 tp->t_rxtcur = rack_rto_max;
6623         }
6624 }
6625
6626 static void
6627 rack_cc_conn_init(struct tcpcb *tp)
6628 {
6629         struct tcp_rack *rack;
6630         uint32_t srtt;
6631
6632         rack = (struct tcp_rack *)tp->t_fb_ptr;
6633         srtt = tp->t_srtt;
6634         cc_conn_init(tp);
6635         /*
6636          * Now convert to rack's internal format,
6637          * if required.
6638          */
6639         if ((srtt == 0) && (tp->t_srtt != 0))
6640                 rack_convert_rtts(tp);
6641         /*
6642          * We want a chance to stay in slowstart as
6643          * we create a connection. TCP spec says that
6644          * initially ssthresh is infinite. For our
6645          * purposes that is the snd_wnd.
6646          */
6647         if (tp->snd_ssthresh < tp->snd_wnd) {
6648                 tp->snd_ssthresh = tp->snd_wnd;
6649         }
6650         /*
6651          * We also want to assure a IW worth of
6652          * data can get inflight.
6653          */
6654         if (rc_init_window(rack) < tp->snd_cwnd)
6655                 tp->snd_cwnd = rc_init_window(rack);
6656 }
6657
6658 /*
6659  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
6660  * we will setup to retransmit the lowest seq number outstanding.
6661  */
6662 static int
6663 rack_timeout_rxt(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
6664 {
6665         int32_t rexmt;
6666         struct inpcb *inp;
6667         int32_t retval = 0;
6668         bool isipv6;
6669
6670         inp = tp->t_inpcb;
6671         if (tp->t_timers->tt_flags & TT_STOPPED) {
6672                 return (1);
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                 tcp_set_inp_to_drop(inp, ETIMEDOUT);
6678                 return (1);
6679         }
6680         rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
6681         rack->r_ctl.retran_during_recovery = 0;
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         /*
6697          * Rack can only run one timer  at a time, so we cannot
6698          * run a KEEPINIT (gating SYN sending) and a retransmit
6699          * timer for the SYN. So if we are in a front state and
6700          * have a KEEPINIT timer we need to check the first transmit
6701          * against now to see if we have exceeded the KEEPINIT time
6702          * (if one is set).
6703          */
6704         if ((TCPS_HAVEESTABLISHED(tp->t_state) == 0) &&
6705             (TP_KEEPINIT(tp) != 0)) {
6706                 struct rack_sendmap *rsm;
6707
6708                 rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
6709                 if (rsm) {
6710                         /* Ok we have something outstanding to test keepinit with */
6711                         if ((TSTMP_GT(cts, (uint32_t)rsm->r_tim_lastsent[0])) &&
6712                             ((cts - (uint32_t)rsm->r_tim_lastsent[0]) >= TICKS_2_USEC(TP_KEEPINIT(tp)))) {
6713                                 /* We have exceeded the KEEPINIT time */
6714                                 tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
6715                                 goto drop_it;
6716                         }
6717                 }
6718         }
6719         /*
6720          * Retransmission timer went off.  Message has not been acked within
6721          * retransmit interval.  Back off to a longer retransmit interval
6722          * and retransmit one segment.
6723          */
6724         rack_remxt_tmr(tp);
6725         if ((rack->r_ctl.rc_resend == NULL) ||
6726             ((rack->r_ctl.rc_resend->r_flags & RACK_RWND_COLLAPSED) == 0)) {
6727                 /*
6728                  * If the rwnd collapsed on
6729                  * the one we are retransmitting
6730                  * it does not count against the
6731                  * rxt count.
6732                  */
6733                 tp->t_rxtshift++;
6734         }
6735         if (tp->t_rxtshift > TCP_MAXRXTSHIFT) {
6736                 tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
6737 drop_it:
6738                 tp->t_rxtshift = TCP_MAXRXTSHIFT;
6739                 KMOD_TCPSTAT_INC(tcps_timeoutdrop);
6740                 retval = 1;
6741                 tcp_set_inp_to_drop(rack->rc_inp,
6742                     (tp->t_softerror ? (uint16_t) tp->t_softerror : ETIMEDOUT));
6743                 goto out;
6744         }
6745         if (tp->t_state == TCPS_SYN_SENT) {
6746                 /*
6747                  * If the SYN was retransmitted, indicate CWND to be limited
6748                  * to 1 segment in cc_conn_init().
6749                  */
6750                 tp->snd_cwnd = 1;
6751         } else if (tp->t_rxtshift == 1) {
6752                 /*
6753                  * first retransmit; record ssthresh and cwnd so they can be
6754                  * recovered if this turns out to be a "bad" retransmit. A
6755                  * retransmit is considered "bad" if an ACK for this segment
6756                  * is received within RTT/2 interval; the assumption here is
6757                  * that the ACK was already in flight.  See "On Estimating
6758                  * End-to-End Network Path Properties" by Allman and Paxson
6759                  * for more details.
6760                  */
6761                 tp->snd_cwnd_prev = tp->snd_cwnd;
6762                 tp->snd_ssthresh_prev = tp->snd_ssthresh;
6763                 tp->snd_recover_prev = tp->snd_recover;
6764                 tp->t_badrxtwin = ticks + (USEC_2_TICKS(tp->t_srtt)/2);
6765                 tp->t_flags |= TF_PREVVALID;
6766         } else if ((tp->t_flags & TF_RCVD_TSTMP) == 0)
6767                 tp->t_flags &= ~TF_PREVVALID;
6768         KMOD_TCPSTAT_INC(tcps_rexmttimeo);
6769         if ((tp->t_state == TCPS_SYN_SENT) ||
6770             (tp->t_state == TCPS_SYN_RECEIVED))
6771                 rexmt = RACK_INITIAL_RTO * tcp_backoff[tp->t_rxtshift];
6772         else
6773                 rexmt = max(rack_rto_min, (tp->t_srtt + (tp->t_rttvar << 2))) * tcp_backoff[tp->t_rxtshift];
6774
6775         RACK_TCPT_RANGESET(tp->t_rxtcur, rexmt,
6776            max(rack_rto_min, rexmt), rack_rto_max);
6777         /*
6778          * We enter the path for PLMTUD if connection is established or, if
6779          * connection is FIN_WAIT_1 status, reason for the last is that if
6780          * amount of data we send is very small, we could send it in couple
6781          * of packets and process straight to FIN. In that case we won't
6782          * catch ESTABLISHED state.
6783          */
6784 #ifdef INET6
6785         isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) ? true : false;
6786 #else
6787         isipv6 = false;
6788 #endif
6789         if (((V_tcp_pmtud_blackhole_detect == 1) ||
6790             (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
6791             (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
6792             ((tp->t_state == TCPS_ESTABLISHED) ||
6793             (tp->t_state == TCPS_FIN_WAIT_1))) {
6794                 /*
6795                  * Idea here is that at each stage of mtu probe (usually,
6796                  * 1448 -> 1188 -> 524) should be given 2 chances to recover
6797                  * before further clamping down. 'tp->t_rxtshift % 2 == 0'
6798                  * should take care of that.
6799                  */
6800                 if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
6801                     (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
6802                     (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
6803                     tp->t_rxtshift % 2 == 0)) {
6804                         /*
6805                          * Enter Path MTU Black-hole Detection mechanism: -
6806                          * Disable Path MTU Discovery (IP "DF" bit). -
6807                          * Reduce MTU to lower value than what we negotiated
6808                          * with peer.
6809                          */
6810                         if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
6811                                 /* Record that we may have found a black hole. */
6812                                 tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
6813                                 /* Keep track of previous MSS. */
6814                                 tp->t_pmtud_saved_maxseg = tp->t_maxseg;
6815                         }
6816
6817                         /*
6818                          * Reduce the MSS to blackhole value or to the
6819                          * default in an attempt to retransmit.
6820                          */
6821 #ifdef INET6
6822                         if (isipv6 &&
6823                             tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
6824                                 /* Use the sysctl tuneable blackhole MSS. */
6825                                 tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
6826                                 KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
6827                         } else if (isipv6) {
6828                                 /* Use the default MSS. */
6829                                 tp->t_maxseg = V_tcp_v6mssdflt;
6830                                 /*
6831                                  * Disable Path MTU Discovery when we switch
6832                                  * to minmss.
6833                                  */
6834                                 tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
6835                                 KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
6836                         }
6837 #endif
6838 #if defined(INET6) && defined(INET)
6839                         else
6840 #endif
6841 #ifdef INET
6842                         if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
6843                                 /* Use the sysctl tuneable blackhole MSS. */
6844                                 tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
6845                                 KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
6846                         } else {
6847                                 /* Use the default MSS. */
6848                                 tp->t_maxseg = V_tcp_mssdflt;
6849                                 /*
6850                                  * Disable Path MTU Discovery when we switch
6851                                  * to minmss.
6852                                  */
6853                                 tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
6854                                 KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
6855                         }
6856 #endif
6857                 } else {
6858                         /*
6859                          * If further retransmissions are still unsuccessful
6860                          * with a lowered MTU, maybe this isn't a blackhole
6861                          * and we restore the previous MSS and blackhole
6862                          * detection flags. The limit '6' is determined by
6863                          * giving each probe stage (1448, 1188, 524) 2
6864                          * chances to recover.
6865                          */
6866                         if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
6867                             (tp->t_rxtshift >= 6)) {
6868                                 tp->t_flags2 |= TF2_PLPMTU_PMTUD;
6869                                 tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
6870                                 tp->t_maxseg = tp->t_pmtud_saved_maxseg;
6871                                 KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
6872                         }
6873                 }
6874         }
6875         /*
6876          * Disable RFC1323 and SACK if we haven't got any response to
6877          * our third SYN to work-around some broken terminal servers
6878          * (most of which have hopefully been retired) that have bad VJ
6879          * header compression code which trashes TCP segments containing
6880          * unknown-to-them TCP options.
6881          */
6882         if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
6883             (tp->t_rxtshift == 3))
6884                 tp->t_flags &= ~(TF_REQ_SCALE|TF_REQ_TSTMP|TF_SACK_PERMIT);
6885         /*
6886          * If we backed off this far, our srtt estimate is probably bogus.
6887          * Clobber it so we'll take the next rtt measurement as our srtt;
6888          * move the current srtt into rttvar to keep the current retransmit
6889          * times until then.
6890          */
6891         if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
6892 #ifdef INET6
6893                 if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
6894                         in6_losing(tp->t_inpcb);
6895                 else
6896 #endif
6897                         in_losing(tp->t_inpcb);
6898                 tp->t_rttvar += tp->t_srtt;
6899                 tp->t_srtt = 0;
6900         }
6901         sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
6902         tp->snd_recover = tp->snd_max;
6903         tp->t_flags |= TF_ACKNOW;
6904         tp->t_rtttime = 0;
6905         rack_cong_signal(tp, CC_RTO, tp->snd_una);
6906 out:
6907         return (retval);
6908 }
6909
6910 static int
6911 rack_process_timers(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, uint8_t hpts_calling)
6912 {
6913         int32_t ret = 0;
6914         int32_t timers = (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
6915
6916         if (timers == 0) {
6917                 return (0);
6918         }
6919         if (tp->t_state == TCPS_LISTEN) {
6920                 /* no timers on listen sockets */
6921                 if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
6922                         return (0);
6923                 return (1);
6924         }
6925         if ((timers & PACE_TMR_RACK) &&
6926             rack->rc_on_min_to) {
6927                 /*
6928                  * For the rack timer when we
6929                  * are on a min-timeout (which means rrr_conf = 3)
6930                  * we don't want to check the timer. It may
6931                  * be going off for a pace and thats ok we
6932                  * want to send the retransmit (if its ready).
6933                  *
6934                  * If its on a normal rack timer (non-min) then
6935                  * we will check if its expired.
6936                  */
6937                 goto skip_time_check;
6938         }
6939         if (TSTMP_LT(cts, rack->r_ctl.rc_timer_exp)) {
6940                 uint32_t left;
6941
6942                 if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
6943                         ret = -1;
6944                         rack_log_to_processing(rack, cts, ret, 0);
6945                         return (0);
6946                 }
6947                 if (hpts_calling == 0) {
6948                         /*
6949                          * A user send or queued mbuf (sack) has called us? We
6950                          * return 0 and let the pacing guards
6951                          * deal with it if they should or
6952                          * should not cause a send.
6953                          */
6954                         ret = -2;
6955                         rack_log_to_processing(rack, cts, ret, 0);
6956                         return (0);
6957                 }
6958                 /*
6959                  * Ok our timer went off early and we are not paced false
6960                  * alarm, go back to sleep.
6961                  */
6962                 ret = -3;
6963                 left = rack->r_ctl.rc_timer_exp - cts;
6964                 tcp_hpts_insert(tp->t_inpcb, HPTS_MS_TO_SLOTS(left));
6965                 rack_log_to_processing(rack, cts, ret, left);
6966                 return (1);
6967         }
6968 skip_time_check:
6969         rack->rc_tmr_stopped = 0;
6970         rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
6971         if (timers & PACE_TMR_DELACK) {
6972                 ret = rack_timeout_delack(tp, rack, cts);
6973         } else if (timers & PACE_TMR_RACK) {
6974                 rack->r_ctl.rc_tlp_rxt_last_time = cts;
6975                 rack->r_fast_output = 0;
6976                 ret = rack_timeout_rack(tp, rack, cts);
6977         } else if (timers & PACE_TMR_TLP) {
6978                 rack->r_ctl.rc_tlp_rxt_last_time = cts;
6979                 ret = rack_timeout_tlp(tp, rack, cts);
6980         } else if (timers & PACE_TMR_RXT) {
6981                 rack->r_ctl.rc_tlp_rxt_last_time = cts;
6982                 rack->r_fast_output = 0;
6983                 ret = rack_timeout_rxt(tp, rack, cts);
6984         } else if (timers & PACE_TMR_PERSIT) {
6985                 ret = rack_timeout_persist(tp, rack, cts);
6986         } else if (timers & PACE_TMR_KEEP) {
6987                 ret = rack_timeout_keepalive(tp, rack, cts);
6988         }
6989         rack_log_to_processing(rack, cts, ret, timers);
6990         return (ret);
6991 }
6992
6993 static void
6994 rack_timer_cancel(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, int line)
6995 {
6996         struct timeval tv;
6997         uint32_t us_cts, flags_on_entry;
6998         uint8_t hpts_removed = 0;
6999
7000         flags_on_entry = rack->r_ctl.rc_hpts_flags;
7001         us_cts = tcp_get_usecs(&tv);
7002         if ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
7003             ((TSTMP_GEQ(us_cts, rack->r_ctl.rc_last_output_to)) ||
7004              ((tp->snd_max - tp->snd_una) == 0))) {
7005                 tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
7006                 hpts_removed = 1;
7007                 /* If we were not delayed cancel out the flag. */
7008                 if ((tp->snd_max - tp->snd_una) == 0)
7009                         rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
7010                 rack_log_to_cancel(rack, hpts_removed, line, us_cts, &tv, flags_on_entry);
7011         }
7012         if (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
7013                 rack->rc_tmr_stopped = rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
7014                 if (rack->rc_inp->inp_in_hpts &&
7015                     ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0)) {
7016                         /*
7017                          * Canceling timer's when we have no output being
7018                          * paced. We also must remove ourselves from the
7019                          * hpts.
7020                          */
7021                         tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
7022                         hpts_removed = 1;
7023                 }
7024                 rack->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
7025         }
7026         if (hpts_removed == 0)
7027                 rack_log_to_cancel(rack, hpts_removed, line, us_cts, &tv, flags_on_entry);
7028 }
7029
7030 static void
7031 rack_timer_stop(struct tcpcb *tp, uint32_t timer_type)
7032 {
7033         return;
7034 }
7035
7036 static int
7037 rack_stopall(struct tcpcb *tp)
7038 {
7039         struct tcp_rack *rack;
7040         rack = (struct tcp_rack *)tp->t_fb_ptr;
7041         rack->t_timers_stopped = 1;
7042         return (0);
7043 }
7044
7045 static void
7046 rack_timer_activate(struct tcpcb *tp, uint32_t timer_type, uint32_t delta)
7047 {
7048         return;
7049 }
7050
7051 static int
7052 rack_timer_active(struct tcpcb *tp, uint32_t timer_type)
7053 {
7054         return (0);
7055 }
7056
7057 static void
7058 rack_stop_all_timers(struct tcpcb *tp)
7059 {
7060         struct tcp_rack *rack;
7061
7062         /*
7063          * Assure no timers are running.
7064          */
7065         if (tcp_timer_active(tp, TT_PERSIST)) {
7066                 /* We enter in persists, set the flag appropriately */
7067                 rack = (struct tcp_rack *)tp->t_fb_ptr;
7068                 rack->rc_in_persist = 1;
7069         }
7070         tcp_timer_suspend(tp, TT_PERSIST);
7071         tcp_timer_suspend(tp, TT_REXMT);
7072         tcp_timer_suspend(tp, TT_KEEP);
7073         tcp_timer_suspend(tp, TT_DELACK);
7074 }
7075
7076 static void
7077 rack_update_rsm(struct tcpcb *tp, struct tcp_rack *rack,
7078     struct rack_sendmap *rsm, uint64_t ts, uint16_t add_flag)
7079 {
7080         int32_t idx;
7081         uint16_t stripped_flags;
7082
7083         rsm->r_rtr_cnt++;
7084         rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
7085         rsm->r_dupack = 0;
7086         if (rsm->r_rtr_cnt > RACK_NUM_OF_RETRANS) {
7087                 rsm->r_rtr_cnt = RACK_NUM_OF_RETRANS;
7088                 rsm->r_flags |= RACK_OVERMAX;
7089         }
7090         if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & RACK_TLP) == 0)) {
7091                 rack->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
7092                 rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
7093         }
7094         idx = rsm->r_rtr_cnt - 1;
7095         rsm->r_tim_lastsent[idx] = ts;
7096         stripped_flags = rsm->r_flags & ~(RACK_SENT_SP|RACK_SENT_FP);
7097         if (rsm->r_flags & RACK_ACKED) {
7098                 /* Problably MTU discovery messing with us */
7099                 rsm->r_flags &= ~RACK_ACKED;
7100                 rack->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7101         }
7102         if (rsm->r_in_tmap) {
7103                 TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
7104                 rsm->r_in_tmap = 0;
7105         }
7106         TAILQ_INSERT_TAIL(&rack->r_ctl.rc_tmap, rsm, r_tnext);
7107         rsm->r_in_tmap = 1;
7108         if (rsm->r_flags & RACK_SACK_PASSED) {
7109                 /* We have retransmitted due to the SACK pass */
7110                 rsm->r_flags &= ~RACK_SACK_PASSED;
7111                 rsm->r_flags |= RACK_WAS_SACKPASS;
7112         }
7113 }
7114
7115 static uint32_t
7116 rack_update_entry(struct tcpcb *tp, struct tcp_rack *rack,
7117     struct rack_sendmap *rsm, uint64_t ts, int32_t *lenp, uint16_t add_flag)
7118 {
7119         /*
7120          * We (re-)transmitted starting at rsm->r_start for some length
7121          * (possibly less than r_end.
7122          */
7123         struct rack_sendmap *nrsm, *insret;
7124         uint32_t c_end;
7125         int32_t len;
7126
7127         len = *lenp;
7128         c_end = rsm->r_start + len;
7129         if (SEQ_GEQ(c_end, rsm->r_end)) {
7130                 /*
7131                  * We retransmitted the whole piece or more than the whole
7132                  * slopping into the next rsm.
7133                  */
7134                 rack_update_rsm(tp, rack, rsm, ts, add_flag);
7135                 if (c_end == rsm->r_end) {
7136                         *lenp = 0;
7137                         return (0);
7138                 } else {
7139                         int32_t act_len;
7140
7141                         /* Hangs over the end return whats left */
7142                         act_len = rsm->r_end - rsm->r_start;
7143                         *lenp = (len - act_len);
7144                         return (rsm->r_end);
7145                 }
7146                 /* We don't get out of this block. */
7147         }
7148         /*
7149          * Here we retransmitted less than the whole thing which means we
7150          * have to split this into what was transmitted and what was not.
7151          */
7152         nrsm = rack_alloc_full_limit(rack);
7153         if (nrsm == NULL) {
7154                 /*
7155                  * We can't get memory, so lets not proceed.
7156                  */
7157                 *lenp = 0;
7158                 return (0);
7159         }
7160         /*
7161          * So here we are going to take the original rsm and make it what we
7162          * retransmitted. nrsm will be the tail portion we did not
7163          * retransmit. For example say the chunk was 1, 11 (10 bytes). And
7164          * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
7165          * 1, 6 and the new piece will be 6, 11.
7166          */
7167         rack_clone_rsm(rack, nrsm, rsm, c_end);
7168         nrsm->r_dupack = 0;
7169         rack_log_retran_reason(rack, nrsm, __LINE__, 0, 2);
7170         insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
7171 #ifdef INVARIANTS
7172         if (insret != NULL) {
7173                 panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
7174                       nrsm, insret, rack, rsm);
7175         }
7176 #endif
7177         if (rsm->r_in_tmap) {
7178                 TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7179                 nrsm->r_in_tmap = 1;
7180         }
7181         rsm->r_flags &= (~RACK_HAS_FIN);
7182         rack_update_rsm(tp, rack, rsm, ts, add_flag);
7183         /* Log a split of rsm into rsm and nrsm */
7184         rack_log_map_chg(tp, rack, NULL, rsm, nrsm, MAP_SPLIT, 0, __LINE__);
7185         *lenp = 0;
7186         return (0);
7187 }
7188
7189 static void
7190 rack_log_output(struct tcpcb *tp, struct tcpopt *to, int32_t len,
7191                 uint32_t seq_out, uint8_t th_flags, int32_t err, uint64_t cts,
7192                 struct rack_sendmap *hintrsm, uint16_t add_flag, struct mbuf *s_mb, uint32_t s_moff)
7193 {
7194         struct tcp_rack *rack;
7195         struct rack_sendmap *rsm, *nrsm, *insret, fe;
7196         register uint32_t snd_max, snd_una;
7197
7198         /*
7199          * Add to the RACK log of packets in flight or retransmitted. If
7200          * there is a TS option we will use the TS echoed, if not we will
7201          * grab a TS.
7202          *
7203          * Retransmissions will increment the count and move the ts to its
7204          * proper place. Note that if options do not include TS's then we
7205          * won't be able to effectively use the ACK for an RTT on a retran.
7206          *
7207          * Notes about r_start and r_end. Lets consider a send starting at
7208          * sequence 1 for 10 bytes. In such an example the r_start would be
7209          * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
7210          * This means that r_end is actually the first sequence for the next
7211          * slot (11).
7212          *
7213          */
7214         /*
7215          * If err is set what do we do XXXrrs? should we not add the thing?
7216          * -- i.e. return if err != 0 or should we pretend we sent it? --
7217          * i.e. proceed with add ** do this for now.
7218          */
7219         INP_WLOCK_ASSERT(tp->t_inpcb);
7220         if (err)
7221                 /*
7222                  * We don't log errors -- we could but snd_max does not
7223                  * advance in this case either.
7224                  */
7225                 return;
7226
7227         if (th_flags & TH_RST) {
7228                 /*
7229                  * We don't log resets and we return immediately from
7230                  * sending
7231                  */
7232                 return;
7233         }
7234         rack = (struct tcp_rack *)tp->t_fb_ptr;
7235         snd_una = tp->snd_una;
7236         snd_max = tp->snd_max;
7237         if (th_flags & (TH_SYN | TH_FIN)) {
7238                 /*
7239                  * The call to rack_log_output is made before bumping
7240                  * snd_max. This means we can record one extra byte on a SYN
7241                  * or FIN if seq_out is adding more on and a FIN is present
7242                  * (and we are not resending).
7243                  */
7244                 if ((th_flags & TH_SYN) && (seq_out == tp->iss))
7245                         len++;
7246                 if (th_flags & TH_FIN)
7247                         len++;
7248                 if (SEQ_LT(snd_max, tp->snd_nxt)) {
7249                         /*
7250                          * The add/update as not been done for the FIN/SYN
7251                          * yet.
7252                          */
7253                         snd_max = tp->snd_nxt;
7254                 }
7255         }
7256         if (SEQ_LEQ((seq_out + len), snd_una)) {
7257                 /* Are sending an old segment to induce an ack (keep-alive)? */
7258                 return;
7259         }
7260         if (SEQ_LT(seq_out, snd_una)) {
7261                 /* huh? should we panic? */
7262                 uint32_t end;
7263
7264                 end = seq_out + len;
7265                 seq_out = snd_una;
7266                 if (SEQ_GEQ(end, seq_out))
7267                         len = end - seq_out;
7268                 else
7269                         len = 0;
7270         }
7271         if (len == 0) {
7272                 /* We don't log zero window probes */
7273                 return;
7274         }
7275         rack->r_ctl.rc_time_last_sent = cts;
7276         if (IN_FASTRECOVERY(tp->t_flags)) {
7277                 rack->r_ctl.rc_prr_out += len;
7278         }
7279         /* First question is it a retransmission or new? */
7280         if (seq_out == snd_max) {
7281                 /* Its new */
7282 again:
7283                 rsm = rack_alloc(rack);
7284                 if (rsm == NULL) {
7285                         /*
7286                          * Hmm out of memory and the tcb got destroyed while
7287                          * we tried to wait.
7288                          */
7289                         return;
7290                 }
7291                 if (th_flags & TH_FIN) {
7292                         rsm->r_flags = RACK_HAS_FIN|add_flag;
7293                 } else {
7294                         rsm->r_flags = add_flag;
7295                 }
7296                 rsm->r_tim_lastsent[0] = cts;
7297                 rsm->r_rtr_cnt = 1;
7298                 rsm->r_rtr_bytes = 0;
7299                 if (th_flags & TH_SYN) {
7300                         /* The data space is one beyond snd_una */
7301                         rsm->r_flags |= RACK_HAS_SYN;
7302                 }
7303                 rsm->r_start = seq_out;
7304                 rsm->r_end = rsm->r_start + len;
7305                 rsm->r_dupack = 0;
7306                 /*
7307                  * save off the mbuf location that
7308                  * sndmbuf_noadv returned (which is
7309                  * where we started copying from)..
7310                  */
7311                 rsm->m = s_mb;
7312                 rsm->soff = s_moff;
7313                 /* rsm->m will be NULL if RACK_HAS_SYN or RACK_HAS_FIN is set */
7314                 if (rsm->m) {
7315                         if (rsm->m->m_len <= rsm->soff) {
7316                                 /*
7317                                  * XXXrrs Question, will this happen?
7318                                  *
7319                                  * If sbsndptr is set at the correct place
7320                                  * then s_moff should always be somewhere
7321                                  * within rsm->m. But if the sbsndptr was
7322                                  * off then that won't be true. If it occurs
7323                                  * we need to walkout to the correct location.
7324                                  */
7325                                 struct mbuf *lm;
7326
7327                                 lm = rsm->m;
7328                                 while (lm->m_len <= rsm->soff) {
7329                                         rsm->soff -= lm->m_len;
7330                                         lm = lm->m_next;
7331                                         KASSERT(lm != NULL, ("%s rack:%p lm goes null orig_off:%u origmb:%p rsm->soff:%u",
7332                                                              __func__, rack, s_moff, s_mb, rsm->soff));
7333                                 }
7334                                 rsm->m = lm;
7335                                 counter_u64_add(rack_sbsndptr_wrong, 1);
7336                         } else
7337                                 counter_u64_add(rack_sbsndptr_right, 1);
7338                         rsm->orig_m_len = rsm->m->m_len;
7339                 } else
7340                         rsm->orig_m_len = 0;
7341                 rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
7342                 /* Log a new rsm */
7343                 rack_log_map_chg(tp, rack, NULL, rsm, NULL, MAP_NEW, 0, __LINE__);
7344                 insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
7345 #ifdef INVARIANTS
7346                 if (insret != NULL) {
7347                         panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
7348                               nrsm, insret, rack, rsm);
7349                 }
7350 #endif
7351                 TAILQ_INSERT_TAIL(&rack->r_ctl.rc_tmap, rsm, r_tnext);
7352                 rsm->r_in_tmap = 1;
7353                 /*
7354                  * Special case detection, is there just a single
7355                  * packet outstanding when we are not in recovery?
7356                  *
7357                  * If this is true mark it so.
7358                  */
7359                 if ((IN_FASTRECOVERY(tp->t_flags) == 0) &&
7360                     (ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked) == ctf_fixed_maxseg(tp))) {
7361                         struct rack_sendmap *prsm;
7362
7363                         prsm = RB_PREV(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
7364                         if (prsm)
7365                                 prsm->r_one_out_nr = 1;
7366                 }
7367                 return;
7368         }
7369         /*
7370          * If we reach here its a retransmission and we need to find it.
7371          */
7372         memset(&fe, 0, sizeof(fe));
7373 more:
7374         if (hintrsm && (hintrsm->r_start == seq_out)) {
7375                 rsm = hintrsm;
7376                 hintrsm = NULL;
7377         } else {
7378                 /* No hints sorry */
7379                 rsm = NULL;
7380         }
7381         if ((rsm) && (rsm->r_start == seq_out)) {
7382                 seq_out = rack_update_entry(tp, rack, rsm, cts, &len, add_flag);
7383                 if (len == 0) {
7384                         return;
7385                 } else {
7386                         goto more;
7387                 }
7388         }
7389         /* Ok it was not the last pointer go through it the hard way. */
7390 refind:
7391         fe.r_start = seq_out;
7392         rsm = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
7393         if (rsm) {
7394                 if (rsm->r_start == seq_out) {
7395                         seq_out = rack_update_entry(tp, rack, rsm, cts, &len, add_flag);
7396                         if (len == 0) {
7397                                 return;
7398                         } else {
7399                                 goto refind;
7400                         }
7401                 }
7402                 if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
7403                         /* Transmitted within this piece */
7404                         /*
7405                          * Ok we must split off the front and then let the
7406                          * update do the rest
7407                          */
7408                         nrsm = rack_alloc_full_limit(rack);
7409                         if (nrsm == NULL) {
7410                                 rack_update_rsm(tp, rack, rsm, cts, add_flag);
7411                                 return;
7412                         }
7413                         /*
7414                          * copy rsm to nrsm and then trim the front of rsm
7415                          * to not include this part.
7416                          */
7417                         rack_clone_rsm(rack, nrsm, rsm, seq_out);
7418                         insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
7419                         rack_log_map_chg(tp, rack, NULL, rsm, nrsm, MAP_SPLIT, 0, __LINE__);
7420 #ifdef INVARIANTS
7421                         if (insret != NULL) {
7422                                 panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
7423                                       nrsm, insret, rack, rsm);
7424                         }
7425 #endif
7426                         if (rsm->r_in_tmap) {
7427                                 TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7428                                 nrsm->r_in_tmap = 1;
7429                         }
7430                         rsm->r_flags &= (~RACK_HAS_FIN);
7431                         seq_out = rack_update_entry(tp, rack, nrsm, cts, &len, add_flag);
7432                         if (len == 0) {
7433                                 return;
7434                         } else if (len > 0)
7435                                 goto refind;
7436                 }
7437         }
7438         /*
7439          * Hmm not found in map did they retransmit both old and on into the
7440          * new?
7441          */
7442         if (seq_out == tp->snd_max) {
7443                 goto again;
7444         } else if (SEQ_LT(seq_out, tp->snd_max)) {
7445 #ifdef INVARIANTS
7446                 printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
7447                        seq_out, len, tp->snd_una, tp->snd_max);
7448                 printf("Starting Dump of all rack entries\n");
7449                 RB_FOREACH(rsm, rack_rb_tree_head, &rack->r_ctl.rc_mtree) {
7450                         printf("rsm:%p start:%u end:%u\n",
7451                                rsm, rsm->r_start, rsm->r_end);
7452                 }
7453                 printf("Dump complete\n");
7454                 panic("seq_out not found rack:%p tp:%p",
7455                       rack, tp);
7456 #endif
7457         } else {
7458 #ifdef INVARIANTS
7459                 /*
7460                  * Hmm beyond sndmax? (only if we are using the new rtt-pack
7461                  * flag)
7462                  */
7463                 panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
7464                       seq_out, len, tp->snd_max, tp);
7465 #endif
7466         }
7467 }
7468
7469 /*
7470  * Record one of the RTT updates from an ack into
7471  * our sample structure.
7472  */
7473
7474 static void
7475 tcp_rack_xmit_timer(struct tcp_rack *rack, int32_t rtt, uint32_t len, uint32_t us_rtt,
7476                     int confidence, struct rack_sendmap *rsm, uint16_t rtrcnt)
7477 {
7478         if ((rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY) ||
7479             (rack->r_ctl.rack_rs.rs_rtt_lowest > rtt)) {
7480                 rack->r_ctl.rack_rs.rs_rtt_lowest = rtt;
7481         }
7482         if ((rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY) ||
7483             (rack->r_ctl.rack_rs.rs_rtt_highest < rtt)) {
7484                 rack->r_ctl.rack_rs.rs_rtt_highest = rtt;
7485         }
7486         if (rack->rc_tp->t_flags & TF_GPUTINPROG) {
7487             if (us_rtt < rack->r_ctl.rc_gp_lowrtt)
7488                 rack->r_ctl.rc_gp_lowrtt = us_rtt;
7489             if (rack->rc_tp->snd_wnd > rack->r_ctl.rc_gp_high_rwnd)
7490                     rack->r_ctl.rc_gp_high_rwnd = rack->rc_tp->snd_wnd;
7491         }
7492         if ((confidence == 1) &&
7493             ((rsm == NULL) ||
7494              (rsm->r_just_ret) ||
7495              (rsm->r_one_out_nr &&
7496               len < (ctf_fixed_maxseg(rack->rc_tp) * 2)))) {
7497                 /*
7498                  * If the rsm had a just return
7499                  * hit it then we can't trust the
7500                  * rtt measurement for buffer deterimination
7501                  * Note that a confidence of 2, indicates
7502                  * SACK'd which overrides the r_just_ret or
7503                  * the r_one_out_nr. If it was a CUM-ACK and
7504                  * we had only two outstanding, but get an
7505                  * ack for only 1. Then that also lowers our
7506                  * confidence.
7507                  */
7508                 confidence = 0;
7509         }
7510         if ((rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY) ||
7511             (rack->r_ctl.rack_rs.rs_us_rtt > us_rtt)) {
7512                 if (rack->r_ctl.rack_rs.confidence == 0) {
7513                         /*
7514                          * We take anything with no current confidence
7515                          * saved.
7516                          */
7517                         rack->r_ctl.rack_rs.rs_us_rtt = us_rtt;
7518                         rack->r_ctl.rack_rs.confidence = confidence;
7519                         rack->r_ctl.rack_rs.rs_us_rtrcnt = rtrcnt;
7520                 } else if (confidence || rack->r_ctl.rack_rs.confidence) {
7521                         /*
7522                          * Once we have a confident number,
7523                          * we can update it with a smaller
7524                          * value since this confident number
7525                          * may include the DSACK time until
7526                          * the next segment (the second one) arrived.
7527                          */
7528                         rack->r_ctl.rack_rs.rs_us_rtt = us_rtt;
7529                         rack->r_ctl.rack_rs.confidence = confidence;
7530                         rack->r_ctl.rack_rs.rs_us_rtrcnt = rtrcnt;
7531                 }
7532         }
7533         rack_log_rtt_upd(rack->rc_tp, rack, us_rtt, len, rsm, confidence);
7534         rack->r_ctl.rack_rs.rs_flags = RACK_RTT_VALID;
7535         rack->r_ctl.rack_rs.rs_rtt_tot += rtt;
7536         rack->r_ctl.rack_rs.rs_rtt_cnt++;
7537 }
7538
7539 /*
7540  * Collect new round-trip time estimate
7541  * and update averages and current timeout.
7542  */
7543 static void
7544 tcp_rack_xmit_timer_commit(struct tcp_rack *rack, struct tcpcb *tp)
7545 {
7546         int32_t delta;
7547         uint32_t o_srtt, o_var;
7548         int32_t hrtt_up = 0;
7549         int32_t rtt;
7550
7551         if (rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY)
7552                 /* No valid sample */
7553                 return;
7554         if (rack->r_ctl.rc_rate_sample_method == USE_RTT_LOW) {
7555                 /* We are to use the lowest RTT seen in a single ack */
7556                 rtt = rack->r_ctl.rack_rs.rs_rtt_lowest;
7557         } else if (rack->r_ctl.rc_rate_sample_method == USE_RTT_HIGH) {
7558                 /* We are to use the highest RTT seen in a single ack */
7559                 rtt = rack->r_ctl.rack_rs.rs_rtt_highest;
7560         } else if (rack->r_ctl.rc_rate_sample_method == USE_RTT_AVG) {
7561                 /* We are to use the average RTT seen in a single ack */
7562                 rtt = (int32_t)(rack->r_ctl.rack_rs.rs_rtt_tot /
7563                                 (uint64_t)rack->r_ctl.rack_rs.rs_rtt_cnt);
7564         } else {
7565 #ifdef INVARIANTS
7566                 panic("Unknown rtt variant %d", rack->r_ctl.rc_rate_sample_method);
7567 #endif
7568                 return;
7569         }
7570         if (rtt == 0)
7571                 rtt = 1;
7572         if (rack->rc_gp_rtt_set == 0) {
7573                 /*
7574                  * With no RTT we have to accept
7575                  * even one we are not confident of.
7576                  */
7577                 rack->r_ctl.rc_gp_srtt = rack->r_ctl.rack_rs.rs_us_rtt;
7578                 rack->rc_gp_rtt_set = 1;
7579         } else if (rack->r_ctl.rack_rs.confidence) {
7580                 /* update the running gp srtt */
7581                 rack->r_ctl.rc_gp_srtt -= (rack->r_ctl.rc_gp_srtt/8);
7582                 rack->r_ctl.rc_gp_srtt += rack->r_ctl.rack_rs.rs_us_rtt / 8;
7583         }
7584         if (rack->r_ctl.rack_rs.confidence) {
7585                 /*
7586                  * record the low and high for highly buffered path computation,
7587                  * we only do this if we are confident (not a retransmission).
7588                  */
7589                 if (rack->r_ctl.rc_highest_us_rtt < rack->r_ctl.rack_rs.rs_us_rtt) {
7590                         rack->r_ctl.rc_highest_us_rtt = rack->r_ctl.rack_rs.rs_us_rtt;
7591                         hrtt_up = 1;
7592                 }
7593                 if (rack->rc_highly_buffered == 0) {
7594                         /*
7595                          * Currently once we declare a path has
7596                          * highly buffered there is no going
7597                          * back, which may be a problem...
7598                          */
7599                         if ((rack->r_ctl.rc_highest_us_rtt / rack->r_ctl.rc_lowest_us_rtt) > rack_hbp_thresh) {
7600                                 rack_log_rtt_shrinks(rack, rack->r_ctl.rack_rs.rs_us_rtt,
7601                                                      rack->r_ctl.rc_highest_us_rtt,
7602                                                      rack->r_ctl.rc_lowest_us_rtt,
7603                                                      RACK_RTTS_SEEHBP);
7604                                 rack->rc_highly_buffered = 1;
7605                         }
7606                 }
7607         }
7608         if ((rack->r_ctl.rack_rs.confidence) ||
7609             (rack->r_ctl.rack_rs.rs_us_rtrcnt == 1)) {
7610                 /*
7611                  * If we are highly confident of it <or> it was
7612                  * never retransmitted we accept it as the last us_rtt.
7613                  */
7614                 rack->r_ctl.rc_last_us_rtt = rack->r_ctl.rack_rs.rs_us_rtt;
7615                 /* The lowest rtt can be set if its was not retransmited */
7616                 if (rack->r_ctl.rc_lowest_us_rtt > rack->r_ctl.rack_rs.rs_us_rtt) {
7617                         rack->r_ctl.rc_lowest_us_rtt = rack->r_ctl.rack_rs.rs_us_rtt;
7618                         if (rack->r_ctl.rc_lowest_us_rtt == 0)
7619                                 rack->r_ctl.rc_lowest_us_rtt = 1;
7620                 }
7621         }
7622         o_srtt = tp->t_srtt;
7623         o_var = tp->t_rttvar;
7624         rack = (struct tcp_rack *)tp->t_fb_ptr;
7625         if (tp->t_srtt != 0) {
7626                 /*
7627                  * We keep a simple srtt in microseconds, like our rtt
7628                  * measurement. We don't need to do any tricks with shifting
7629                  * etc. Instead we just add in 1/8th of the new measurement
7630                  * and subtract out 1/8 of the old srtt. We do the same with
7631                  * the variance after finding the absolute value of the
7632                  * difference between this sample and the current srtt.
7633                  */
7634                 delta = tp->t_srtt - rtt;
7635                 /* Take off 1/8th of the current sRTT */
7636                 tp->t_srtt -= (tp->t_srtt >> 3);
7637                 /* Add in 1/8th of the new RTT just measured */
7638                 tp->t_srtt += (rtt >> 3);
7639                 if (tp->t_srtt <= 0)
7640                         tp->t_srtt = 1;
7641                 /* Now lets make the absolute value of the variance */
7642                 if (delta < 0)
7643                         delta = -delta;
7644                 /* Subtract out 1/8th */
7645                 tp->t_rttvar -= (tp->t_rttvar >> 3);
7646                 /* Add in 1/8th of the new variance we just saw */
7647                 tp->t_rttvar += (delta >> 3);
7648                 if (tp->t_rttvar <= 0)
7649                         tp->t_rttvar = 1;
7650                 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
7651                         tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
7652         } else {
7653                 /*
7654                  * No rtt measurement yet - use the unsmoothed rtt. Set the
7655                  * variance to half the rtt (so our first retransmit happens
7656                  * at 3*rtt).
7657                  */
7658                 tp->t_srtt = rtt;
7659                 tp->t_rttvar = rtt >> 1;
7660                 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
7661         }
7662         rack->rc_srtt_measure_made = 1;
7663         KMOD_TCPSTAT_INC(tcps_rttupdated);
7664         tp->t_rttupdated++;
7665 #ifdef STATS
7666         if (rack_stats_gets_ms_rtt == 0) {
7667                 /* Send in the microsecond rtt used for rxt timeout purposes */
7668                 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt));
7669         } else if (rack_stats_gets_ms_rtt == 1) {
7670                 /* Send in the millisecond rtt used for rxt timeout purposes */
7671                 int32_t ms_rtt;
7672
7673                 /* Round up */
7674                 ms_rtt = (rtt + HPTS_USEC_IN_MSEC - 1) / HPTS_USEC_IN_MSEC;
7675                 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, ms_rtt));
7676         } else if (rack_stats_gets_ms_rtt == 2) {
7677                 /* Send in the millisecond rtt has close to the path RTT as we can get  */
7678                 int32_t ms_rtt;
7679
7680                 /* Round up */
7681                 ms_rtt = (rack->r_ctl.rack_rs.rs_us_rtt + HPTS_USEC_IN_MSEC - 1) / HPTS_USEC_IN_MSEC;
7682                 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, ms_rtt));
7683         }  else {
7684                 /* Send in the microsecond rtt has close to the path RTT as we can get  */
7685                 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rack->r_ctl.rack_rs.rs_us_rtt));
7686         }
7687
7688 #endif
7689         /*
7690          * the retransmit should happen at rtt + 4 * rttvar. Because of the
7691          * way we do the smoothing, srtt and rttvar will each average +1/2
7692          * tick of bias.  When we compute the retransmit timer, we want 1/2
7693          * tick of rounding and 1 extra tick because of +-1/2 tick
7694          * uncertainty in the firing of the timer.  The bias will give us
7695          * exactly the 1.5 tick we need.  But, because the bias is
7696          * statistical, we have to test that we don't drop below the minimum
7697          * feasible timer (which is 2 ticks).
7698          */
7699         tp->t_rxtshift = 0;
7700         RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
7701                       max(rack_rto_min, rtt + 2), rack_rto_max);
7702         rack_log_rtt_sample(rack, rtt);
7703         tp->t_softerror = 0;
7704 }
7705
7706
7707 static void
7708 rack_apply_updated_usrtt(struct tcp_rack *rack, uint32_t us_rtt, uint32_t us_cts)
7709 {
7710         /*
7711          * Apply to filter the inbound us-rtt at us_cts.
7712          */
7713         uint32_t old_rtt;
7714
7715         old_rtt = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt);
7716         apply_filter_min_small(&rack->r_ctl.rc_gp_min_rtt,
7717                                us_rtt, us_cts);
7718         if (rack->r_ctl.last_pacing_time &&
7719             rack->rc_gp_dyn_mul &&
7720             (rack->r_ctl.last_pacing_time > us_rtt))
7721                 rack->pacing_longer_than_rtt = 1;
7722         else
7723                 rack->pacing_longer_than_rtt = 0;
7724         if (old_rtt > us_rtt) {
7725                 /* We just hit a new lower rtt time */
7726                 rack_log_rtt_shrinks(rack,  us_cts,  old_rtt,
7727                                      __LINE__, RACK_RTTS_NEWRTT);
7728                 /*
7729                  * Only count it if its lower than what we saw within our
7730                  * calculated range.
7731                  */
7732                 if ((old_rtt - us_rtt) > rack_min_rtt_movement) {
7733                         if (rack_probertt_lower_within &&
7734                             rack->rc_gp_dyn_mul &&
7735                             (rack->use_fixed_rate == 0) &&
7736                             (rack->rc_always_pace)) {
7737                                 /*
7738                                  * We are seeing a new lower rtt very close
7739                                  * to the time that we would have entered probe-rtt.
7740                                  * This is probably due to the fact that a peer flow
7741                                  * has entered probe-rtt. Lets go in now too.
7742                                  */
7743                                 uint32_t val;
7744
7745                                 val = rack_probertt_lower_within * rack_time_between_probertt;
7746                                 val /= 100;
7747                                 if ((rack->in_probe_rtt == 0)  &&
7748                                     ((us_cts - rack->r_ctl.rc_lower_rtt_us_cts) >= (rack_time_between_probertt - val))) {
7749                                         rack_enter_probertt(rack, us_cts);
7750                                 }
7751                         }
7752                         rack->r_ctl.rc_lower_rtt_us_cts = us_cts;
7753                 }
7754         }
7755 }
7756
7757 static int
7758 rack_update_rtt(struct tcpcb *tp, struct tcp_rack *rack,
7759     struct rack_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, tcp_seq th_ack)
7760 {
7761         int32_t i, all;
7762         uint32_t t, len_acked;
7763
7764         if ((rsm->r_flags & RACK_ACKED) ||
7765             (rsm->r_flags & RACK_WAS_ACKED))
7766                 /* Already done */
7767                 return (0);
7768         if (rsm->r_no_rtt_allowed) {
7769                 /* Not allowed */
7770                 return (0);
7771         }
7772         if (ack_type == CUM_ACKED) {
7773                 if (SEQ_GT(th_ack, rsm->r_end)) {
7774                         len_acked = rsm->r_end - rsm->r_start;
7775                         all = 1;
7776                 } else {
7777                         len_acked = th_ack - rsm->r_start;
7778                         all = 0;
7779                 }
7780         } else {
7781                 len_acked = rsm->r_end - rsm->r_start;
7782                 all = 0;
7783         }
7784         if (rsm->r_rtr_cnt == 1) {
7785                 uint32_t us_rtt;
7786
7787                 t = cts - (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
7788                 if ((int)t <= 0)
7789                         t = 1;
7790                 if (!tp->t_rttlow || tp->t_rttlow > t)
7791                         tp->t_rttlow = t;
7792                 if (!rack->r_ctl.rc_rack_min_rtt ||
7793                     SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
7794                         rack->r_ctl.rc_rack_min_rtt = t;
7795                         if (rack->r_ctl.rc_rack_min_rtt == 0) {
7796                                 rack->r_ctl.rc_rack_min_rtt = 1;
7797                         }
7798                 }
7799                 if (TSTMP_GT(tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time), rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]))
7800                         us_rtt = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time) - (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
7801                 else
7802                         us_rtt = tcp_get_usecs(NULL) - (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
7803                 if (us_rtt == 0)
7804                         us_rtt = 1;
7805                 rack_apply_updated_usrtt(rack, us_rtt, tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time));
7806                 if (ack_type == SACKED) {
7807                         rack_log_rtt_sample_calc(rack, t, (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)], cts, 1);
7808                         tcp_rack_xmit_timer(rack, t + 1, len_acked, us_rtt, 2 , rsm, rsm->r_rtr_cnt);
7809                 } else {
7810                         /*
7811                          * We need to setup what our confidence
7812                          * is in this ack.
7813                          *
7814                          * If the rsm was app limited and it is
7815                          * less than a mss in length (the end
7816                          * of the send) then we have a gap. If we
7817                          * were app limited but say we were sending
7818                          * multiple MSS's then we are more confident
7819                          * int it.
7820                          *
7821                          * When we are not app-limited then we see if
7822                          * the rsm is being included in the current
7823                          * measurement, we tell this by the app_limited_needs_set
7824                          * flag.
7825                          *
7826                          * Note that being cwnd blocked is not applimited
7827                          * as well as the pacing delay between packets which
7828                          * are sending only 1 or 2 MSS's also will show up
7829                          * in the RTT. We probably need to examine this algorithm
7830                          * a bit more and enhance it to account for the delay
7831                          * between rsm's. We could do that by saving off the
7832                          * pacing delay of each rsm (in an rsm) and then
7833                          * factoring that in somehow though for now I am
7834                          * not sure how :)
7835                          */
7836                         int calc_conf = 0;
7837
7838                         if (rsm->r_flags & RACK_APP_LIMITED) {
7839                                 if (all && (len_acked <= ctf_fixed_maxseg(tp)))
7840                                         calc_conf = 0;
7841                                 else
7842                                         calc_conf = 1;
7843                         } else if (rack->app_limited_needs_set == 0) {
7844                                 calc_conf = 1;
7845                         } else {
7846                                 calc_conf = 0;
7847                         }
7848                         rack_log_rtt_sample_calc(rack, t, (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)], cts, 2);
7849                         tcp_rack_xmit_timer(rack, t + 1, len_acked, us_rtt,
7850                                             calc_conf, rsm, rsm->r_rtr_cnt);
7851                 }
7852                 if ((rsm->r_flags & RACK_TLP) &&
7853                     (!IN_FASTRECOVERY(tp->t_flags))) {
7854                         /* Segment was a TLP and our retrans matched */
7855                         if (rack->r_ctl.rc_tlp_cwnd_reduce) {
7856                                 rack->r_ctl.rc_rsm_start = tp->snd_max;
7857                                 rack->r_ctl.rc_cwnd_at = tp->snd_cwnd;
7858                                 rack->r_ctl.rc_ssthresh_at = tp->snd_ssthresh;
7859                                 rack_cong_signal(tp, CC_NDUPACK, tp->snd_una);
7860                         }
7861                 }
7862                 if (SEQ_LT(rack->r_ctl.rc_rack_tmit_time, (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)])) {
7863                         /* New more recent rack_tmit_time */
7864                         rack->r_ctl.rc_rack_tmit_time = (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
7865                         rack->rc_rack_rtt = t;
7866                 }
7867                 return (1);
7868         }
7869         /*
7870          * We clear the soft/rxtshift since we got an ack.
7871          * There is no assurance we will call the commit() function
7872          * so we need to clear these to avoid incorrect handling.
7873          */
7874         tp->t_rxtshift = 0;
7875         RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
7876                       rack_rto_min, rack_rto_max);
7877         tp->t_softerror = 0;
7878         if (to && (to->to_flags & TOF_TS) &&
7879             (ack_type == CUM_ACKED) &&
7880             (to->to_tsecr) &&
7881             ((rsm->r_flags & RACK_OVERMAX) == 0)) {
7882                 /*
7883                  * Now which timestamp does it match? In this block the ACK
7884                  * must be coming from a previous transmission.
7885                  */
7886                 for (i = 0; i < rsm->r_rtr_cnt; i++) {
7887                         if (rack_ts_to_msec(rsm->r_tim_lastsent[i]) == to->to_tsecr) {
7888                                 t = cts - (uint32_t)rsm->r_tim_lastsent[i];
7889                                 if ((int)t <= 0)
7890                                         t = 1;
7891                                 if ((i + 1) < rsm->r_rtr_cnt) {
7892                                         /*
7893                                          * The peer ack'd from our previous
7894                                          * transmission. We have a spurious
7895                                          * retransmission and thus we dont
7896                                          * want to update our rack_rtt.
7897                                          */
7898                                         return (0);
7899                                 }
7900                                 if (!tp->t_rttlow || tp->t_rttlow > t)
7901                                         tp->t_rttlow = t;
7902                                 if (!rack->r_ctl.rc_rack_min_rtt || SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
7903                                         rack->r_ctl.rc_rack_min_rtt = t;
7904                                         if (rack->r_ctl.rc_rack_min_rtt == 0) {
7905                                                 rack->r_ctl.rc_rack_min_rtt = 1;
7906                                         }
7907                                 }
7908                                 if (SEQ_LT(rack->r_ctl.rc_rack_tmit_time,
7909                                            (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)])) {
7910                                         /* New more recent rack_tmit_time */
7911                                         rack->r_ctl.rc_rack_tmit_time = (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
7912                                         rack->rc_rack_rtt = t;
7913                                 }
7914                                 rack_log_rtt_sample_calc(rack, t, (uint32_t)rsm->r_tim_lastsent[i], cts, 3);
7915                                 tcp_rack_xmit_timer(rack, t + 1, len_acked, t, 0, rsm,
7916                                                     rsm->r_rtr_cnt);
7917                                 return (1);
7918                         }
7919                 }
7920                 goto ts_not_found;
7921         } else {
7922                 /*
7923                  * Ok its a SACK block that we retransmitted. or a windows
7924                  * machine without timestamps. We can tell nothing from the
7925                  * time-stamp since its not there or the time the peer last
7926                  * recieved a segment that moved forward its cum-ack point.
7927                  */
7928 ts_not_found:
7929                 i = rsm->r_rtr_cnt - 1;
7930                 t = cts - (uint32_t)rsm->r_tim_lastsent[i];
7931                 if ((int)t <= 0)
7932                         t = 1;
7933                 if (rack->r_ctl.rc_rack_min_rtt && SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
7934                         /*
7935                          * We retransmitted and the ack came back in less
7936                          * than the smallest rtt we have observed. We most
7937                          * likely did an improper retransmit as outlined in
7938                          * 6.2 Step 2 point 2 in the rack-draft so we
7939                          * don't want to update our rack_rtt. We in
7940                          * theory (in future) might want to think about reverting our
7941                          * cwnd state but we won't for now.
7942                          */
7943                         return (0);
7944                 } else if (rack->r_ctl.rc_rack_min_rtt) {
7945                         /*
7946                          * We retransmitted it and the retransmit did the
7947                          * job.
7948                          */
7949                         if (!rack->r_ctl.rc_rack_min_rtt ||
7950                             SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
7951                                 rack->r_ctl.rc_rack_min_rtt = t;
7952                                 if (rack->r_ctl.rc_rack_min_rtt == 0) {
7953                                         rack->r_ctl.rc_rack_min_rtt = 1;
7954                                 }
7955                         }
7956                         if (SEQ_LT(rack->r_ctl.rc_rack_tmit_time, (uint32_t)rsm->r_tim_lastsent[i])) {
7957                                 /* New more recent rack_tmit_time */
7958                                 rack->r_ctl.rc_rack_tmit_time = (uint32_t)rsm->r_tim_lastsent[i];
7959                                 rack->rc_rack_rtt = t;
7960                         }
7961                         return (1);
7962                 }
7963         }
7964         return (0);
7965 }
7966
7967 /*
7968  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
7969  */
7970 static void
7971 rack_log_sack_passed(struct tcpcb *tp,
7972     struct tcp_rack *rack, struct rack_sendmap *rsm)
7973 {
7974         struct rack_sendmap *nrsm;
7975
7976         nrsm = rsm;
7977         TAILQ_FOREACH_REVERSE_FROM(nrsm, &rack->r_ctl.rc_tmap,
7978             rack_head, r_tnext) {
7979                 if (nrsm == rsm) {
7980                         /* Skip orginal segment he is acked */
7981                         continue;
7982                 }
7983                 if (nrsm->r_flags & RACK_ACKED) {
7984                         /*
7985                          * Skip ack'd segments, though we
7986                          * should not see these, since tmap
7987                          * should not have ack'd segments.
7988                          */
7989                         continue;
7990                 }
7991                 if (nrsm->r_flags & RACK_SACK_PASSED) {
7992                         /*
7993                          * We found one that is already marked
7994                          * passed, we have been here before and
7995                          * so all others below this are marked.
7996                          */
7997                         break;
7998                 }
7999                 nrsm->r_flags |= RACK_SACK_PASSED;
8000                 nrsm->r_flags &= ~RACK_WAS_SACKPASS;
8001         }
8002 }
8003
8004 static void
8005 rack_need_set_test(struct tcpcb *tp,
8006                    struct tcp_rack *rack,
8007                    struct rack_sendmap *rsm,
8008                    tcp_seq th_ack,
8009                    int line,
8010                    int use_which)
8011 {
8012
8013         if ((tp->t_flags & TF_GPUTINPROG) &&
8014             SEQ_GEQ(rsm->r_end, tp->gput_seq)) {
8015                 /*
8016                  * We were app limited, and this ack
8017                  * butts up or goes beyond the point where we want
8018                  * to start our next measurement. We need
8019                  * to record the new gput_ts as here and
8020                  * possibly update the start sequence.
8021                  */
8022                 uint32_t seq, ts;
8023
8024                 if (rsm->r_rtr_cnt > 1) {
8025                         /*
8026                          * This is a retransmit, can we
8027                          * really make any assessment at this
8028                          * point?  We are not really sure of
8029                          * the timestamp, is it this or the
8030                          * previous transmission?
8031                          *
8032                          * Lets wait for something better that
8033                          * is not retransmitted.
8034                          */
8035                         return;
8036                 }
8037                 seq = tp->gput_seq;
8038                 ts = tp->gput_ts;
8039                 rack->app_limited_needs_set = 0;
8040                 tp->gput_ts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
8041                 /* Do we start at a new end? */
8042                 if ((use_which == RACK_USE_BEG) &&
8043                     SEQ_GEQ(rsm->r_start, tp->gput_seq)) {
8044                         /*
8045                          * When we get an ACK that just eats
8046                          * up some of the rsm, we set RACK_USE_BEG
8047                          * since whats at r_start (i.e. th_ack)
8048                          * is left unacked and thats where the
8049                          * measurement not starts.
8050                          */
8051                         tp->gput_seq = rsm->r_start;
8052                         rack->r_ctl.rc_gp_output_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
8053                 }
8054                 if ((use_which == RACK_USE_END) &&
8055                     SEQ_GEQ(rsm->r_end, tp->gput_seq)) {
8056                             /*
8057                              * We use the end when the cumack
8058                              * is moving forward and completely
8059                              * deleting the rsm passed so basically
8060                              * r_end holds th_ack.
8061                              *
8062                              * For SACK's we also want to use the end
8063                              * since this piece just got sacked and
8064                              * we want to target anything after that
8065                              * in our measurement.
8066                              */
8067                             tp->gput_seq = rsm->r_end;
8068                             rack->r_ctl.rc_gp_output_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
8069                 }
8070                 if (use_which == RACK_USE_END_OR_THACK) {
8071                         /*
8072                          * special case for ack moving forward,
8073                          * not a sack, we need to move all the
8074                          * way up to where this ack cum-ack moves
8075                          * to.
8076                          */
8077                         if (SEQ_GT(th_ack, rsm->r_end))
8078                                 tp->gput_seq = th_ack;
8079                         else
8080                                 tp->gput_seq = rsm->r_end;
8081                         rack->r_ctl.rc_gp_output_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
8082                 }
8083                 if (SEQ_GT(tp->gput_seq, tp->gput_ack)) {
8084                         /*
8085                          * We moved beyond this guy's range, re-calculate
8086                          * the new end point.
8087                          */
8088                         if (rack->rc_gp_filled == 0) {
8089                                 tp->gput_ack = tp->gput_seq + max(rc_init_window(rack), (MIN_GP_WIN * ctf_fixed_maxseg(tp)));
8090                         } else {
8091                                 tp->gput_ack = tp->gput_seq + rack_get_measure_window(tp, rack);
8092                         }
8093                 }
8094                 /*
8095                  * We are moving the goal post, we may be able to clear the
8096                  * measure_saw_probe_rtt flag.
8097                  */
8098                 if ((rack->in_probe_rtt == 0) &&
8099                     (rack->measure_saw_probe_rtt) &&
8100                     (SEQ_GEQ(tp->gput_seq, rack->r_ctl.rc_probertt_sndmax_atexit)))
8101                         rack->measure_saw_probe_rtt = 0;
8102                 rack_log_pacing_delay_calc(rack, ts, tp->gput_ts,
8103                                            seq, tp->gput_seq, 0, 5, line, NULL);
8104                 if (rack->rc_gp_filled &&
8105                     ((tp->gput_ack - tp->gput_seq) <
8106                      max(rc_init_window(rack), (MIN_GP_WIN *
8107                                                 ctf_fixed_maxseg(tp))))) {
8108                         uint32_t ideal_amount;
8109
8110                         ideal_amount = rack_get_measure_window(tp, rack);
8111                         if (ideal_amount > sbavail(&tp->t_inpcb->inp_socket->so_snd)) {
8112                                 /*
8113                                  * There is no sense of continuing this measurement
8114                                  * because its too small to gain us anything we
8115                                  * trust. Skip it and that way we can start a new
8116                                  * measurement quicker.
8117                                  */
8118                                 tp->t_flags &= ~TF_GPUTINPROG;
8119                                 rack_log_pacing_delay_calc(rack, tp->gput_ack, tp->gput_seq,
8120                                                            0, 0, 0, 6, __LINE__, NULL);
8121                         } else {
8122                                 /*
8123                                  * Reset the window further out.
8124                                  */
8125                                 tp->gput_ack = tp->gput_seq + ideal_amount;
8126                         }
8127                 }
8128         }
8129 }
8130
8131 static uint32_t
8132 rack_proc_sack_blk(struct tcpcb *tp, struct tcp_rack *rack, struct sackblk *sack,
8133                    struct tcpopt *to, struct rack_sendmap **prsm, uint32_t cts, int *moved_two)
8134 {
8135         uint32_t start, end, changed = 0;
8136         struct rack_sendmap stack_map;
8137         struct rack_sendmap *rsm, *nrsm, fe, *insret, *prev, *next;
8138         int32_t used_ref = 1;
8139         int moved = 0;
8140
8141         start = sack->start;
8142         end = sack->end;
8143         rsm = *prsm;
8144         memset(&fe, 0, sizeof(fe));
8145 do_rest_ofb:
8146         if ((rsm == NULL) ||
8147             (SEQ_LT(end, rsm->r_start)) ||
8148             (SEQ_GEQ(start, rsm->r_end)) ||
8149             (SEQ_LT(start, rsm->r_start))) {
8150                 /*
8151                  * We are not in the right spot,
8152                  * find the correct spot in the tree.
8153                  */
8154                 used_ref = 0;
8155                 fe.r_start = start;
8156                 rsm = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
8157                 moved++;
8158         }
8159         if (rsm == NULL) {
8160                 /* TSNH */
8161                 goto out;
8162         }
8163         /* Ok we have an ACK for some piece of this rsm */
8164         if (rsm->r_start != start) {
8165                 if ((rsm->r_flags & RACK_ACKED) == 0) {
8166                         /**
8167                          * Need to split this in two pieces the before and after,
8168                          * the before remains in the map, the after must be
8169                          * added. In other words we have:
8170                          * rsm        |--------------|
8171                          * sackblk        |------->
8172                          * rsm will become
8173                          *     rsm    |---|
8174                          * and nrsm will be  the sacked piece
8175                          *     nrsm       |----------|
8176                          *
8177                          * But before we start down that path lets
8178                          * see if the sack spans over on top of
8179                          * the next guy and it is already sacked.
8180                          */
8181                         next = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8182                         if (next && (next->r_flags & RACK_ACKED) &&
8183                             SEQ_GEQ(end, next->r_start)) {
8184                                 /**
8185                                  * So the next one is already acked, and
8186                                  * we can thus by hookery use our stack_map
8187                                  * to reflect the piece being sacked and
8188                                  * then adjust the two tree entries moving
8189                                  * the start and ends around. So we start like:
8190                                  *  rsm     |------------|             (not-acked)
8191                                  *  next                 |-----------| (acked)
8192                                  *  sackblk        |-------->
8193                                  *  We want to end like so:
8194                                  *  rsm     |------|                   (not-acked)
8195                                  *  next           |-----------------| (acked)
8196                                  *  nrsm           |-----|
8197                                  * Where nrsm is a temporary stack piece we
8198                                  * use to update all the gizmos.
8199                                  */
8200                                 /* Copy up our fudge block */
8201                                 nrsm = &stack_map;
8202                                 memcpy(nrsm, rsm, sizeof(struct rack_sendmap));
8203                                 /* Now adjust our tree blocks */
8204                                 rsm->r_end = start;
8205                                 next->r_start = start;
8206                                 /* Now we must adjust back where next->m is */
8207                                 rack_setup_offset_for_rsm(rsm, next);
8208
8209                                 /* We don't need to adjust rsm, it did not change */
8210                                 /* Clear out the dup ack count of the remainder */
8211                                 rsm->r_dupack = 0;
8212                                 rsm->r_just_ret = 0;
8213                                 rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
8214                                 /* Now lets make sure our fudge block is right */
8215                                 nrsm->r_start = start;
8216                                 /* Now lets update all the stats and such */
8217                                 rack_update_rtt(tp, rack, nrsm, to, cts, SACKED, 0);
8218                                 if (rack->app_limited_needs_set)
8219                                         rack_need_set_test(tp, rack, nrsm, tp->snd_una, __LINE__, RACK_USE_END);
8220                                 changed += (nrsm->r_end - nrsm->r_start);
8221                                 rack->r_ctl.rc_sacked += (nrsm->r_end - nrsm->r_start);
8222                                 if (nrsm->r_flags & RACK_SACK_PASSED) {
8223                                         counter_u64_add(rack_reorder_seen, 1);
8224                                         rack->r_ctl.rc_reorder_ts = cts;
8225                                 }
8226                                 /*
8227                                  * Now we want to go up from rsm (the
8228                                  * one left un-acked) to the next one
8229                                  * in the tmap. We do this so when
8230                                  * we walk backwards we include marking
8231                                  * sack-passed on rsm (The one passed in
8232                                  * is skipped since it is generally called
8233                                  * on something sacked before removing it
8234                                  * from the tmap).
8235                                  */
8236                                 if (rsm->r_in_tmap) {
8237                                         nrsm = TAILQ_NEXT(rsm, r_tnext);
8238                                         /*
8239                                          * Now that we have the next
8240                                          * one walk backwards from there.
8241                                          */
8242                                         if (nrsm && nrsm->r_in_tmap)
8243                                                 rack_log_sack_passed(tp, rack, nrsm);
8244                                 }
8245                                 /* Now are we done? */
8246                                 if (SEQ_LT(end, next->r_end) ||
8247                                     (end == next->r_end)) {
8248                                         /* Done with block */
8249                                         goto out;
8250                                 }
8251                                 rack_log_map_chg(tp, rack, &stack_map, rsm, next, MAP_SACK_M1, end, __LINE__);
8252                                 counter_u64_add(rack_sack_used_next_merge, 1);
8253                                 /* Postion for the next block */
8254                                 start = next->r_end;
8255                                 rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, next);
8256                                 if (rsm == NULL)
8257                                         goto out;
8258                         } else {
8259                                 /**
8260                                  * We can't use any hookery here, so we
8261                                  * need to split the map. We enter like
8262                                  * so:
8263                                  *  rsm      |--------|
8264                                  *  sackblk       |----->
8265                                  * We will add the new block nrsm and
8266                                  * that will be the new portion, and then
8267                                  * fall through after reseting rsm. So we
8268                                  * split and look like this:
8269                                  *  rsm      |----|
8270                                  *  sackblk       |----->
8271                                  *  nrsm          |---|
8272                                  * We then fall through reseting
8273                                  * rsm to nrsm, so the next block
8274                                  * picks it up.
8275                                  */
8276                                 nrsm = rack_alloc_limit(rack, RACK_LIMIT_TYPE_SPLIT);
8277                                 if (nrsm == NULL) {
8278                                         /*
8279                                          * failed XXXrrs what can we do but loose the sack
8280                                          * info?
8281                                          */
8282                                         goto out;
8283                                 }
8284                                 counter_u64_add(rack_sack_splits, 1);
8285                                 rack_clone_rsm(rack, nrsm, rsm, start);
8286                                 rsm->r_just_ret = 0;
8287                                 insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
8288 #ifdef INVARIANTS
8289                                 if (insret != NULL) {
8290                                         panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
8291                                               nrsm, insret, rack, rsm);
8292                                 }
8293 #endif
8294                                 if (rsm->r_in_tmap) {
8295                                         TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8296                                         nrsm->r_in_tmap = 1;
8297                                 }
8298                                 rack_log_map_chg(tp, rack, NULL, rsm, nrsm, MAP_SACK_M2, end, __LINE__);
8299                                 rsm->r_flags &= (~RACK_HAS_FIN);
8300                                 /* Position us to point to the new nrsm that starts the sack blk */
8301                                 rsm = nrsm;
8302                         }
8303                 } else {
8304                         /* Already sacked this piece */
8305                         counter_u64_add(rack_sack_skipped_acked, 1);
8306                         moved++;
8307                         if (end == rsm->r_end) {
8308                                 /* Done with block */
8309                                 rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8310                                 goto out;
8311                         } else if (SEQ_LT(end, rsm->r_end)) {
8312                                 /* A partial sack to a already sacked block */
8313                                 moved++;
8314                                 rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8315                                 goto out;
8316                         } else {
8317                                 /*
8318                                  * The end goes beyond this guy
8319                                  * repostion the start to the
8320                                  * next block.
8321                                  */
8322                                 start = rsm->r_end;
8323                                 rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8324                                 if (rsm == NULL)
8325                                         goto out;
8326                         }
8327                 }
8328         }
8329         if (SEQ_GEQ(end, rsm->r_end)) {
8330                 /**
8331                  * The end of this block is either beyond this guy or right
8332                  * at this guy. I.e.:
8333                  *  rsm ---                 |-----|
8334                  *  end                     |-----|
8335                  *  <or>
8336                  *  end                     |---------|
8337                  */
8338                 if ((rsm->r_flags & RACK_ACKED) == 0) {
8339                         rack_update_rtt(tp, rack, rsm, to, cts, SACKED, 0);
8340                         changed += (rsm->r_end - rsm->r_start);
8341                         rack->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
8342                         if (rsm->r_in_tmap) /* should be true */
8343                                 rack_log_sack_passed(tp, rack, rsm);
8344                         /* Is Reordering occuring? */
8345                         if (rsm->r_flags & RACK_SACK_PASSED) {
8346                                 rsm->r_flags &= ~RACK_SACK_PASSED;
8347                                 counter_u64_add(rack_reorder_seen, 1);
8348                                 rack->r_ctl.rc_reorder_ts = cts;
8349                         }
8350                         if (rack->app_limited_needs_set)
8351                                 rack_need_set_test(tp, rack, rsm, tp->snd_una, __LINE__, RACK_USE_END);
8352                         rsm->r_ack_arrival = rack_to_usec_ts(&rack->r_ctl.act_rcv_time);
8353                         rsm->r_flags |= RACK_ACKED;
8354                         rsm->r_flags &= ~RACK_TLP;
8355                         if (rsm->r_in_tmap) {
8356                                 TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
8357                                 rsm->r_in_tmap = 0;
8358                         }
8359                         rack_log_map_chg(tp, rack, NULL, rsm, NULL, MAP_SACK_M3, end, __LINE__);
8360                 } else {
8361                         counter_u64_add(rack_sack_skipped_acked, 1);
8362                         moved++;
8363                 }
8364                 if (end == rsm->r_end) {
8365                         /* This block only - done, setup for next */
8366                         goto out;
8367                 }
8368                 /*
8369                  * There is more not coverend by this rsm move on
8370                  * to the next block in the RB tree.
8371                  */
8372                 nrsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8373                 start = rsm->r_end;
8374                 rsm = nrsm;
8375                 if (rsm == NULL)
8376                         goto out;
8377                 goto do_rest_ofb;
8378         }
8379         /**
8380          * The end of this sack block is smaller than
8381          * our rsm i.e.:
8382          *  rsm ---                 |-----|
8383          *  end                     |--|
8384          */
8385         if ((rsm->r_flags & RACK_ACKED) == 0) {
8386                 prev = RB_PREV(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8387                 if (prev && (prev->r_flags & RACK_ACKED)) {
8388                         /**
8389                          * Goal, we want the right remainder of rsm to shrink
8390                          * in place and span from (rsm->r_start = end) to rsm->r_end.
8391                          * We want to expand prev to go all the way
8392                          * to prev->r_end <- end.
8393                          * so in the tree we have before:
8394                          *   prev     |--------|         (acked)
8395                          *   rsm               |-------| (non-acked)
8396                          *   sackblk           |-|
8397                          * We churn it so we end up with
8398                          *   prev     |----------|       (acked)
8399                          *   rsm                 |-----| (non-acked)
8400                          *   nrsm              |-| (temporary)
8401                          */
8402                         nrsm = &stack_map;
8403                         memcpy(nrsm, rsm, sizeof(struct rack_sendmap));
8404                         prev->r_end = end;
8405                         rsm->r_start = end;
8406                         /* Now adjust nrsm (stack copy) to be
8407                          * the one that is the small
8408                          * piece that was "sacked".
8409                          */
8410                         nrsm->r_end = end;
8411                         rsm->r_dupack = 0;
8412                         rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
8413                         /*
8414                          * Now that the rsm has had its start moved forward
8415                          * lets go ahead and get its new place in the world.
8416                          */
8417                         rack_setup_offset_for_rsm(prev, rsm);
8418                         /*
8419                          * Now nrsm is our new little piece
8420                          * that is acked (which was merged
8421                          * to prev). Update the rtt and changed
8422                          * based on that. Also check for reordering.
8423                          */
8424                         rack_update_rtt(tp, rack, nrsm, to, cts, SACKED, 0);
8425                         if (rack->app_limited_needs_set)
8426                                 rack_need_set_test(tp, rack, nrsm, tp->snd_una, __LINE__, RACK_USE_END);
8427                         changed += (nrsm->r_end - nrsm->r_start);
8428                         rack->r_ctl.rc_sacked += (nrsm->r_end - nrsm->r_start);
8429                         if (nrsm->r_flags & RACK_SACK_PASSED) {
8430                                 counter_u64_add(rack_reorder_seen, 1);
8431                                 rack->r_ctl.rc_reorder_ts = cts;
8432                         }
8433                         rack_log_map_chg(tp, rack, prev, &stack_map, rsm, MAP_SACK_M4, end, __LINE__);
8434                         rsm = prev;
8435                         counter_u64_add(rack_sack_used_prev_merge, 1);
8436                 } else {
8437                         /**
8438                          * This is the case where our previous
8439                          * block is not acked either, so we must
8440                          * split the block in two.
8441                          */
8442                         nrsm = rack_alloc_limit(rack, RACK_LIMIT_TYPE_SPLIT);
8443                         if (nrsm == NULL) {
8444                                 /* failed rrs what can we do but loose the sack info? */
8445                                 goto out;
8446                         }
8447                         /**
8448                          * In this case nrsm becomes
8449                          * nrsm->r_start = end;
8450                          * nrsm->r_end = rsm->r_end;
8451                          * which is un-acked.
8452                          * <and>
8453                          * rsm->r_end = nrsm->r_start;
8454                          * i.e. the remaining un-acked
8455                          * piece is left on the left
8456                          * hand side.
8457                          *
8458                          * So we start like this
8459                          * rsm      |----------| (not acked)
8460                          * sackblk  |---|
8461                          * build it so we have
8462                          * rsm      |---|         (acked)
8463                          * nrsm         |------|  (not acked)
8464                          */
8465                         counter_u64_add(rack_sack_splits, 1);
8466                         rack_clone_rsm(rack, nrsm, rsm, end);
8467                         rsm->r_flags &= (~RACK_HAS_FIN);
8468                         rsm->r_just_ret = 0;
8469                         insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
8470 #ifdef INVARIANTS
8471                         if (insret != NULL) {
8472                                 panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
8473                                       nrsm, insret, rack, rsm);
8474                         }
8475 #endif
8476                         if (rsm->r_in_tmap) {
8477                                 TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8478                                 nrsm->r_in_tmap = 1;
8479                         }
8480                         nrsm->r_dupack = 0;
8481                         rack_log_retran_reason(rack, nrsm, __LINE__, 0, 2);
8482                         rack_update_rtt(tp, rack, rsm, to, cts, SACKED, 0);
8483                         changed += (rsm->r_end - rsm->r_start);
8484                         rack->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
8485                         if (rsm->r_in_tmap) /* should be true */
8486                                 rack_log_sack_passed(tp, rack, rsm);
8487                         /* Is Reordering occuring? */
8488                         if (rsm->r_flags & RACK_SACK_PASSED) {
8489                                 rsm->r_flags &= ~RACK_SACK_PASSED;
8490                                 counter_u64_add(rack_reorder_seen, 1);
8491                                 rack->r_ctl.rc_reorder_ts = cts;
8492                         }
8493                         if (rack->app_limited_needs_set)
8494                                 rack_need_set_test(tp, rack, rsm, tp->snd_una, __LINE__, RACK_USE_END);
8495                         rsm->r_ack_arrival = rack_to_usec_ts(&rack->r_ctl.act_rcv_time);
8496                         rsm->r_flags |= RACK_ACKED;
8497                         rsm->r_flags &= ~RACK_TLP;
8498                         rack_log_map_chg(tp, rack, NULL, rsm, nrsm, MAP_SACK_M5, end, __LINE__);
8499                         if (rsm->r_in_tmap) {
8500                                 TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
8501                                 rsm->r_in_tmap = 0;
8502                         }
8503                 }
8504         } else if (start != end){
8505                 /*
8506                  * The block was already acked.
8507                  */
8508                 counter_u64_add(rack_sack_skipped_acked, 1);
8509                 moved++;
8510         }
8511 out:
8512         if (rsm && (rsm->r_flags & RACK_ACKED)) {
8513                 /*
8514                  * Now can we merge where we worked
8515                  * with either the previous or
8516                  * next block?
8517                  */
8518                 next = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8519                 while (next) {
8520                     if (next->r_flags & RACK_ACKED) {
8521                         /* yep this and next can be merged */
8522                         rsm = rack_merge_rsm(rack, rsm, next);
8523                         next = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8524                     } else
8525                             break;
8526                 }
8527                 /* Now what about the previous? */
8528                 prev = RB_PREV(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8529                 while (prev) {
8530                     if (prev->r_flags & RACK_ACKED) {
8531                         /* yep the previous and this can be merged */
8532                         rsm = rack_merge_rsm(rack, prev, rsm);
8533                         prev = RB_PREV(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8534                     } else
8535                             break;
8536                 }
8537         }
8538         if (used_ref == 0) {
8539                 counter_u64_add(rack_sack_proc_all, 1);
8540         } else {
8541                 counter_u64_add(rack_sack_proc_short, 1);
8542         }
8543         /* Save off the next one for quick reference. */
8544         if (rsm)
8545                 nrsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8546         else
8547                 nrsm = NULL;
8548         *prsm = rack->r_ctl.rc_sacklast = nrsm;
8549         /* Pass back the moved. */
8550         *moved_two = moved;
8551         return (changed);
8552 }
8553
8554 static void inline
8555 rack_peer_reneges(struct tcp_rack *rack, struct rack_sendmap *rsm, tcp_seq th_ack)
8556 {
8557         struct rack_sendmap *tmap;
8558
8559         tmap = NULL;
8560         while (rsm && (rsm->r_flags & RACK_ACKED)) {
8561                 /* Its no longer sacked, mark it so */
8562                 rack->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
8563 #ifdef INVARIANTS
8564                 if (rsm->r_in_tmap) {
8565                         panic("rack:%p rsm:%p flags:0x%x in tmap?",
8566                               rack, rsm, rsm->r_flags);
8567                 }
8568 #endif
8569                 rsm->r_flags &= ~(RACK_ACKED|RACK_SACK_PASSED|RACK_WAS_SACKPASS);
8570                 /* Rebuild it into our tmap */
8571                 if (tmap == NULL) {
8572                         TAILQ_INSERT_HEAD(&rack->r_ctl.rc_tmap, rsm, r_tnext);
8573                         tmap = rsm;
8574                 } else {
8575                         TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, tmap, rsm, r_tnext);
8576                         tmap = rsm;
8577                 }
8578                 tmap->r_in_tmap = 1;
8579                 rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8580         }
8581         /*
8582          * Now lets possibly clear the sack filter so we start
8583          * recognizing sacks that cover this area.
8584          */
8585         sack_filter_clear(&rack->r_ctl.rack_sf, th_ack);
8586
8587 }
8588
8589 static void
8590 rack_do_decay(struct tcp_rack *rack)
8591 {
8592         struct timeval res;
8593
8594 #define timersub(tvp, uvp, vvp)                                         \
8595         do {                                                            \
8596                 (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;          \
8597                 (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;       \
8598                 if ((vvp)->tv_usec < 0) {                               \
8599                         (vvp)->tv_sec--;                                \
8600                         (vvp)->tv_usec += 1000000;                      \
8601                 }                                                       \
8602         } while (0)
8603
8604         timersub(&rack->r_ctl.act_rcv_time, &rack->r_ctl.rc_last_time_decay, &res);
8605 #undef timersub
8606
8607         rack->r_ctl.input_pkt++;
8608         if ((rack->rc_in_persist) ||
8609             (res.tv_sec >= 1) ||
8610             (rack->rc_tp->snd_max == rack->rc_tp->snd_una)) {
8611                 /*
8612                  * Check for decay of non-SAD,
8613                  * we want all SAD detection metrics to
8614                  * decay 1/4 per second (or more) passed.
8615                  */
8616                 uint32_t pkt_delta;
8617
8618                 pkt_delta = rack->r_ctl.input_pkt - rack->r_ctl.saved_input_pkt;
8619                 /* Update our saved tracking values */
8620                 rack->r_ctl.saved_input_pkt = rack->r_ctl.input_pkt;
8621                 rack->r_ctl.rc_last_time_decay = rack->r_ctl.act_rcv_time;
8622                 /* Now do we escape without decay? */
8623 #ifdef NETFLIX_EXP_DETECTION
8624                 if (rack->rc_in_persist ||
8625                     (rack->rc_tp->snd_max == rack->rc_tp->snd_una) ||
8626                     (pkt_delta < tcp_sad_low_pps)){
8627                         /*
8628                          * We don't decay idle connections
8629                          * or ones that have a low input pps.
8630                          */
8631                         return;
8632                 }
8633                 /* Decay the counters */
8634                 rack->r_ctl.ack_count = ctf_decay_count(rack->r_ctl.ack_count,
8635                                                         tcp_sad_decay_val);
8636                 rack->r_ctl.sack_count = ctf_decay_count(rack->r_ctl.sack_count,
8637                                                          tcp_sad_decay_val);
8638                 rack->r_ctl.sack_moved_extra = ctf_decay_count(rack->r_ctl.sack_moved_extra,
8639                                                                tcp_sad_decay_val);
8640                 rack->r_ctl.sack_noextra_move = ctf_decay_count(rack->r_ctl.sack_noextra_move,
8641                                                                 tcp_sad_decay_val);
8642 #endif
8643         }
8644 }
8645
8646 static void
8647 rack_process_to_cumack(struct tcpcb *tp, struct tcp_rack *rack, register uint32_t th_ack, uint32_t cts, struct tcpopt *to)
8648 {
8649         struct rack_sendmap *rsm, *rm;
8650
8651         /*
8652          * The ACK point is advancing to th_ack, we must drop off
8653          * the packets in the rack log and calculate any eligble
8654          * RTT's.
8655          */
8656         rack->r_wanted_output = 1;
8657 more:
8658         rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
8659         if (rsm == NULL) {
8660                 if ((th_ack - 1) == tp->iss) {
8661                         /*
8662                          * For the SYN incoming case we will not
8663                          * have called tcp_output for the sending of
8664                          * the SYN, so there will be no map. All
8665                          * other cases should probably be a panic.
8666                          */
8667                         return;
8668                 }
8669                 if (tp->t_flags & TF_SENTFIN) {
8670                         /* if we sent a FIN we often will not have map */
8671                         return;
8672                 }
8673 #ifdef INVARIANTS
8674                 panic("No rack map tp:%p for state:%d ack:%u rack:%p snd_una:%u snd_max:%u snd_nxt:%u\n",
8675                       tp,
8676                       tp->t_state, th_ack, rack,
8677                       tp->snd_una, tp->snd_max, tp->snd_nxt);
8678 #endif
8679                 return;
8680         }
8681         if (SEQ_LT(th_ack, rsm->r_start)) {
8682                 /* Huh map is missing this */
8683 #ifdef INVARIANTS
8684                 printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d\n",
8685                        rsm->r_start,
8686                        th_ack, tp->t_state, rack->r_state);
8687 #endif
8688                 return;
8689         }
8690         rack_update_rtt(tp, rack, rsm, to, cts, CUM_ACKED, th_ack);
8691         /* Now do we consume the whole thing? */
8692         if (SEQ_GEQ(th_ack, rsm->r_end)) {
8693                 /* Its all consumed. */
8694                 uint32_t left;
8695                 uint8_t newly_acked;
8696
8697                 rack_log_map_chg(tp, rack, NULL, rsm, NULL, MAP_FREE, rsm->r_end, __LINE__);
8698                 rack->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
8699                 rsm->r_rtr_bytes = 0;
8700                 /* Record the time of highest cumack sent */
8701                 rack->r_ctl.rc_gp_cumack_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
8702                 rm = RB_REMOVE(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8703 #ifdef INVARIANTS
8704                 if (rm != rsm) {
8705                         panic("removing head in rack:%p rsm:%p rm:%p",
8706                               rack, rsm, rm);
8707                 }
8708 #endif
8709                 if (rsm->r_in_tmap) {
8710                         TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
8711                         rsm->r_in_tmap = 0;
8712                 }
8713                 newly_acked = 1;
8714                 if (rsm->r_flags & RACK_ACKED) {
8715                         /*
8716                          * It was acked on the scoreboard -- remove
8717                          * it from total
8718                          */
8719                         rack->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
8720                         newly_acked = 0;
8721                 } else if (rsm->r_flags & RACK_SACK_PASSED) {
8722                         /*
8723                          * There are segments ACKED on the
8724                          * scoreboard further up. We are seeing
8725                          * reordering.
8726                          */
8727                         rsm->r_flags &= ~RACK_SACK_PASSED;
8728                         counter_u64_add(rack_reorder_seen, 1);
8729                         rsm->r_ack_arrival = rack_to_usec_ts(&rack->r_ctl.act_rcv_time);
8730                         rsm->r_flags |= RACK_ACKED;
8731                         rack->r_ctl.rc_reorder_ts = cts;
8732                         if (rack->r_ent_rec_ns) {
8733                                 /*
8734                                  * We have sent no more, and we saw an sack
8735                                  * then ack arrive.
8736                                  */
8737                                 rack->r_might_revert = 1;
8738                         }
8739                 }
8740                 if ((rsm->r_flags & RACK_TO_REXT) &&
8741                     (tp->t_flags & TF_RCVD_TSTMP) &&
8742                     (to->to_flags & TOF_TS) &&
8743                     (tp->t_flags & TF_PREVVALID)) {
8744                         /*
8745                          * We can use the timestamp to see
8746                          * if this retransmission was from the
8747                          * first transmit. If so we made a mistake.
8748                          */
8749                         tp->t_flags &= ~TF_PREVVALID;
8750                         if (to->to_tsecr == rack_ts_to_msec(rsm->r_tim_lastsent[0])) {
8751                                 /* The first transmit is what this ack is for */
8752                                 rack_cong_signal(tp, CC_RTO_ERR, th_ack);
8753                         }
8754                 }
8755                 left = th_ack - rsm->r_end;
8756                 if (rack->app_limited_needs_set && newly_acked)
8757                         rack_need_set_test(tp, rack, rsm, th_ack, __LINE__, RACK_USE_END_OR_THACK);
8758                 /* Free back to zone */
8759                 rack_free(rack, rsm);
8760                 if (left) {
8761                         goto more;
8762                 }
8763                 /* Check for reneging */
8764                 rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
8765                 if (rsm && (rsm->r_flags & RACK_ACKED) && (th_ack == rsm->r_start)) {
8766                         /*
8767                          * The peer has moved snd_una up to
8768                          * the edge of this send, i.e. one
8769                          * that it had previously acked. The only
8770                          * way that can be true if the peer threw
8771                          * away data (space issues) that it had
8772                          * previously sacked (else it would have
8773                          * given us snd_una up to (rsm->r_end).
8774                          * We need to undo the acked markings here.
8775                          *
8776                          * Note we have to look to make sure th_ack is
8777                          * our rsm->r_start in case we get an old ack
8778                          * where th_ack is behind snd_una.
8779                          */
8780                         rack_peer_reneges(rack, rsm, th_ack);
8781                 }
8782                 return;
8783         }
8784         if (rsm->r_flags & RACK_ACKED) {
8785                 /*
8786                  * It was acked on the scoreboard -- remove it from
8787                  * total for the part being cum-acked.
8788                  */
8789                 rack->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
8790         }
8791         /*
8792          * Clear the dup ack count for
8793          * the piece that remains.
8794          */
8795         rsm->r_dupack = 0;
8796         rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
8797         if (rsm->r_rtr_bytes) {
8798                 /*
8799                  * It was retransmitted adjust the
8800                  * sack holes for what was acked.
8801                  */
8802                 int ack_am;
8803
8804                 ack_am = (th_ack - rsm->r_start);
8805                 if (ack_am >= rsm->r_rtr_bytes) {
8806                         rack->r_ctl.rc_holes_rxt -= ack_am;
8807                         rsm->r_rtr_bytes -= ack_am;
8808                 }
8809         }
8810         /*
8811          * Update where the piece starts and record
8812          * the time of send of highest cumack sent.
8813          */
8814         rack->r_ctl.rc_gp_cumack_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
8815         rack_log_map_chg(tp, rack, NULL, rsm, NULL, MAP_TRIM_HEAD, th_ack, __LINE__);
8816         /* Now we need to move our offset forward too */
8817         if (rsm->orig_m_len != rsm->m->m_len) {
8818                 /* Fix up the orig_m_len and possibly the mbuf offset */
8819                 rack_adjust_orig_mlen(rsm);
8820         }
8821         rsm->soff += (th_ack - rsm->r_start);
8822         rsm->r_start = th_ack;
8823         /* Now do we need to move the mbuf fwd too? */
8824         while (rsm->soff >= rsm->m->m_len) {
8825                 rsm->soff -= rsm->m->m_len;
8826                 rsm->m = rsm->m->m_next;
8827                 KASSERT((rsm->m != NULL),
8828                         (" nrsm:%p hit at soff:%u null m",
8829                          rsm, rsm->soff));
8830         }
8831         rsm->orig_m_len = rsm->m->m_len;
8832         if (rack->app_limited_needs_set)
8833                 rack_need_set_test(tp, rack, rsm, tp->snd_una, __LINE__, RACK_USE_BEG);
8834 }
8835
8836 static void
8837 rack_handle_might_revert(struct tcpcb *tp, struct tcp_rack *rack)
8838 {
8839         struct rack_sendmap *rsm;
8840         int sack_pass_fnd = 0;
8841
8842         if (rack->r_might_revert) {
8843                 /*
8844                  * Ok we have reordering, have not sent anything, we
8845                  * might want to revert the congestion state if nothing
8846                  * further has SACK_PASSED on it. Lets check.
8847                  *
8848                  * We also get here when we have DSACKs come in for
8849                  * all the data that we FR'd. Note that a rxt or tlp
8850                  * timer clears this from happening.
8851                  */
8852
8853                 TAILQ_FOREACH(rsm, &rack->r_ctl.rc_tmap, r_tnext) {
8854                         if (rsm->r_flags & RACK_SACK_PASSED) {
8855                                 sack_pass_fnd = 1;
8856                                 break;
8857                         }
8858                 }
8859                 if (sack_pass_fnd == 0) {
8860                         /*
8861                          * We went into recovery
8862                          * incorrectly due to reordering!
8863                          */
8864                         int orig_cwnd;
8865
8866                         rack->r_ent_rec_ns = 0;
8867                         orig_cwnd = tp->snd_cwnd;
8868                         tp->snd_cwnd = rack->r_ctl.rc_cwnd_at_erec;
8869                         tp->snd_ssthresh = rack->r_ctl.rc_ssthresh_at_erec;
8870                         tp->snd_recover = tp->snd_una;
8871                         rack_log_to_prr(rack, 14, orig_cwnd);
8872                         EXIT_RECOVERY(tp->t_flags);
8873                 }
8874                 rack->r_might_revert = 0;
8875         }
8876 }
8877
8878 #ifdef NETFLIX_EXP_DETECTION
8879 static void
8880 rack_do_detection(struct tcpcb *tp, struct tcp_rack *rack,  uint32_t bytes_this_ack, uint32_t segsiz)
8881 {
8882         if ((rack->do_detection || tcp_force_detection) &&
8883             tcp_sack_to_ack_thresh &&
8884             tcp_sack_to_move_thresh &&
8885             ((rack->r_ctl.rc_num_maps_alloced > tcp_map_minimum) || rack->sack_attack_disable)) {
8886                 /*
8887                  * We have thresholds set to find
8888                  * possible attackers and disable sack.
8889                  * Check them.
8890                  */
8891                 uint64_t ackratio, moveratio, movetotal;
8892
8893                 /* Log detecting */
8894                 rack_log_sad(rack, 1);
8895                 ackratio = (uint64_t)(rack->r_ctl.sack_count);
8896                 ackratio *= (uint64_t)(1000);
8897                 if (rack->r_ctl.ack_count)
8898                         ackratio /= (uint64_t)(rack->r_ctl.ack_count);
8899                 else {
8900                         /* We really should not hit here */
8901                         ackratio = 1000;
8902                 }
8903                 if ((rack->sack_attack_disable == 0) &&
8904                     (ackratio > rack_highest_sack_thresh_seen))
8905                         rack_highest_sack_thresh_seen = (uint32_t)ackratio;
8906                 movetotal = rack->r_ctl.sack_moved_extra;
8907                 movetotal += rack->r_ctl.sack_noextra_move;
8908                 moveratio = rack->r_ctl.sack_moved_extra;
8909                 moveratio *= (uint64_t)1000;
8910                 if (movetotal)
8911                         moveratio /= movetotal;
8912                 else {
8913                         /* No moves, thats pretty good */
8914                         moveratio = 0;
8915                 }
8916                 if ((rack->sack_attack_disable == 0) &&
8917                     (moveratio > rack_highest_move_thresh_seen))
8918                         rack_highest_move_thresh_seen = (uint32_t)moveratio;
8919                 if (rack->sack_attack_disable == 0) {
8920                         if ((ackratio > tcp_sack_to_ack_thresh) &&
8921                             (moveratio > tcp_sack_to_move_thresh)) {
8922                                 /* Disable sack processing */
8923                                 rack->sack_attack_disable = 1;
8924                                 if (rack->r_rep_attack == 0) {
8925                                         rack->r_rep_attack = 1;
8926                                         counter_u64_add(rack_sack_attacks_detected, 1);
8927                                 }
8928                                 if (tcp_attack_on_turns_on_logging) {
8929                                         /*
8930                                          * Turn on logging, used for debugging
8931                                          * false positives.
8932                                          */
8933                                         rack->rc_tp->t_logstate = tcp_attack_on_turns_on_logging;
8934                                 }
8935                                 /* Clamp the cwnd at flight size */
8936                                 rack->r_ctl.rc_saved_cwnd = rack->rc_tp->snd_cwnd;
8937                                 rack->rc_tp->snd_cwnd = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
8938                                 rack_log_sad(rack, 2);
8939                         }
8940                 } else {
8941                         /* We are sack-disabled check for false positives */
8942                         if ((ackratio <= tcp_restoral_thresh) ||
8943                             (rack->r_ctl.rc_num_maps_alloced  < tcp_map_minimum)) {
8944                                 rack->sack_attack_disable = 0;
8945                                 rack_log_sad(rack, 3);
8946                                 /* Restart counting */
8947                                 rack->r_ctl.sack_count = 0;
8948                                 rack->r_ctl.sack_moved_extra = 0;
8949                                 rack->r_ctl.sack_noextra_move = 1;
8950                                 rack->r_ctl.ack_count = max(1,
8951                                       (bytes_this_ack / segsiz));
8952
8953                                 if (rack->r_rep_reverse == 0) {
8954                                         rack->r_rep_reverse = 1;
8955                                         counter_u64_add(rack_sack_attacks_reversed, 1);
8956                                 }
8957                                 /* Restore the cwnd */
8958                                 if (rack->r_ctl.rc_saved_cwnd > rack->rc_tp->snd_cwnd)
8959                                         rack->rc_tp->snd_cwnd = rack->r_ctl.rc_saved_cwnd;
8960                         }
8961                 }
8962         }
8963 }
8964 #endif
8965
8966 static void
8967 rack_note_dsack(struct tcp_rack *rack, tcp_seq start, tcp_seq end)
8968 {
8969
8970         uint32_t am;
8971
8972         if (SEQ_GT(end, start))
8973                 am = end - start;
8974         else
8975                 am = 0;
8976         /*
8977          * We keep track of how many DSACK blocks we get
8978          * after a recovery incident.
8979          */
8980         rack->r_ctl.dsack_byte_cnt += am;
8981         if (!IN_FASTRECOVERY(rack->rc_tp->t_flags) &&
8982             rack->r_ctl.retran_during_recovery &&
8983             (rack->r_ctl.dsack_byte_cnt >= rack->r_ctl.retran_during_recovery)) {
8984                 /*
8985                  * False recovery most likely culprit is reordering. If
8986                  * nothing else is missing we need to revert.
8987                  */
8988                 rack->r_might_revert = 1;
8989                 rack_handle_might_revert(rack->rc_tp, rack);
8990                 rack->r_might_revert = 0;
8991                 rack->r_ctl.retran_during_recovery = 0;
8992                 rack->r_ctl.dsack_byte_cnt = 0;
8993         }
8994 }
8995
8996 static void
8997 rack_update_prr(struct tcpcb *tp, struct tcp_rack *rack, uint32_t changed, tcp_seq th_ack)
8998 {
8999         /* Deal with changed and PRR here (in recovery only) */
9000         uint32_t pipe, snd_una;
9001
9002         rack->r_ctl.rc_prr_delivered += changed;
9003
9004         if (sbavail(&rack->rc_inp->inp_socket->so_snd) <= (tp->snd_max - tp->snd_una)) {
9005                 /*
9006                  * It is all outstanding, we are application limited
9007                  * and thus we don't need more room to send anything.
9008                  * Note we use tp->snd_una here and not th_ack because
9009                  * the data as yet not been cut from the sb.
9010                  */
9011                 rack->r_ctl.rc_prr_sndcnt = 0;
9012                 return;
9013         }
9014         /* Compute prr_sndcnt */
9015         if (SEQ_GT(tp->snd_una, th_ack)) {
9016                 snd_una = tp->snd_una;
9017         } else {
9018                 snd_una = th_ack;
9019         }
9020         pipe = ((tp->snd_max - snd_una) - rack->r_ctl.rc_sacked) + rack->r_ctl.rc_holes_rxt;
9021         if (pipe > tp->snd_ssthresh) {
9022                 long sndcnt;
9023
9024                 sndcnt = rack->r_ctl.rc_prr_delivered * tp->snd_ssthresh;
9025                 if (rack->r_ctl.rc_prr_recovery_fs > 0)
9026                         sndcnt /= (long)rack->r_ctl.rc_prr_recovery_fs;
9027                 else {
9028                         rack->r_ctl.rc_prr_sndcnt = 0;
9029                         rack_log_to_prr(rack, 9, 0);
9030                         sndcnt = 0;
9031                 }
9032                 sndcnt++;
9033                 if (sndcnt > (long)rack->r_ctl.rc_prr_out)
9034                         sndcnt -= rack->r_ctl.rc_prr_out;
9035                 else
9036                         sndcnt = 0;
9037                 rack->r_ctl.rc_prr_sndcnt = sndcnt;
9038                 rack_log_to_prr(rack, 10, 0);
9039         } else {
9040                 uint32_t limit;
9041
9042                 if (rack->r_ctl.rc_prr_delivered > rack->r_ctl.rc_prr_out)
9043                         limit = (rack->r_ctl.rc_prr_delivered - rack->r_ctl.rc_prr_out);
9044                 else
9045                         limit = 0;
9046                 if (changed > limit)
9047                         limit = changed;
9048                 limit += ctf_fixed_maxseg(tp);
9049                 if (tp->snd_ssthresh > pipe) {
9050                         rack->r_ctl.rc_prr_sndcnt = min((tp->snd_ssthresh - pipe), limit);
9051                         rack_log_to_prr(rack, 11, 0);
9052                 } else {
9053                         rack->r_ctl.rc_prr_sndcnt = min(0, limit);
9054                         rack_log_to_prr(rack, 12, 0);
9055                 }
9056         }
9057 }
9058
9059 static void
9060 rack_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th, int entered_recovery, int dup_ack_struck)
9061 {
9062         uint32_t changed;
9063         struct tcp_rack *rack;
9064         struct rack_sendmap *rsm;
9065         struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
9066         register uint32_t th_ack;
9067         int32_t i, j, k, num_sack_blks = 0;
9068         uint32_t cts, acked, ack_point, sack_changed = 0;
9069         int loop_start = 0, moved_two = 0;
9070         uint32_t tsused;
9071
9072
9073         INP_WLOCK_ASSERT(tp->t_inpcb);
9074         if (th->th_flags & TH_RST) {
9075                 /* We don't log resets */
9076                 return;
9077         }
9078         rack = (struct tcp_rack *)tp->t_fb_ptr;
9079         cts = tcp_get_usecs(NULL);
9080         rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
9081         changed = 0;
9082         th_ack = th->th_ack;
9083         if (rack->sack_attack_disable == 0)
9084                 rack_do_decay(rack);
9085         if (BYTES_THIS_ACK(tp, th) >= ctf_fixed_maxseg(rack->rc_tp)) {
9086                 /*
9087                  * You only get credit for
9088                  * MSS and greater (and you get extra
9089                  * credit for larger cum-ack moves).
9090                  */
9091                 int ac;
9092
9093                 ac = BYTES_THIS_ACK(tp, th) / ctf_fixed_maxseg(rack->rc_tp);
9094                 rack->r_ctl.ack_count += ac;
9095                 counter_u64_add(rack_ack_total, ac);
9096         }
9097         if (rack->r_ctl.ack_count > 0xfff00000) {
9098                 /*
9099                  * reduce the number to keep us under
9100                  * a uint32_t.
9101                  */
9102                 rack->r_ctl.ack_count /= 2;
9103                 rack->r_ctl.sack_count /= 2;
9104         }
9105         if (SEQ_GT(th_ack, tp->snd_una)) {
9106                 rack_log_progress_event(rack, tp, ticks, PROGRESS_UPDATE, __LINE__);
9107                 tp->t_acktime = ticks;
9108         }
9109         if (rsm && SEQ_GT(th_ack, rsm->r_start))
9110                 changed = th_ack - rsm->r_start;
9111         if (changed) {
9112                 rack_process_to_cumack(tp, rack, th_ack, cts, to);
9113         }
9114         if ((to->to_flags & TOF_SACK) == 0) {
9115                 /* We are done nothing left and no sack. */
9116                 rack_handle_might_revert(tp, rack);
9117                 /*
9118                  * For cases where we struck a dup-ack
9119                  * with no SACK, add to the changes so
9120                  * PRR will work right.
9121                  */
9122                 if (dup_ack_struck && (changed == 0)) {
9123                         changed += ctf_fixed_maxseg(rack->rc_tp);
9124                 }
9125                 goto out;
9126         }
9127         /* Sack block processing */
9128         if (SEQ_GT(th_ack, tp->snd_una))
9129                 ack_point = th_ack;
9130         else
9131                 ack_point = tp->snd_una;
9132         for (i = 0; i < to->to_nsacks; i++) {
9133                 bcopy((to->to_sacks + i * TCPOLEN_SACK),
9134                       &sack, sizeof(sack));
9135                 sack.start = ntohl(sack.start);
9136                 sack.end = ntohl(sack.end);
9137                 if (SEQ_GT(sack.end, sack.start) &&
9138                     SEQ_GT(sack.start, ack_point) &&
9139                     SEQ_LT(sack.start, tp->snd_max) &&
9140                     SEQ_GT(sack.end, ack_point) &&
9141                     SEQ_LEQ(sack.end, tp->snd_max)) {
9142                         sack_blocks[num_sack_blks] = sack;
9143                         num_sack_blks++;
9144 #ifdef NETFLIX_STATS
9145                 } else if (SEQ_LEQ(sack.start, th_ack) &&
9146                            SEQ_LEQ(sack.end, th_ack)) {
9147                         /*
9148                          * Its a D-SACK block.
9149                          */
9150                         tcp_record_dsack(sack.start, sack.end);
9151 #endif
9152                         rack_note_dsack(rack, sack.start, sack.end);
9153                 }
9154         }
9155         /*
9156          * Sort the SACK blocks so we can update the rack scoreboard with
9157          * just one pass.
9158          */
9159         num_sack_blks = sack_filter_blks(&rack->r_ctl.rack_sf, sack_blocks,
9160                                          num_sack_blks, th->th_ack);
9161         ctf_log_sack_filter(rack->rc_tp, num_sack_blks, sack_blocks);
9162         if (num_sack_blks == 0) {
9163                 /* Nothing to sack (DSACKs?) */
9164                 goto out_with_totals;
9165         }
9166         if (num_sack_blks < 2) {
9167                 /* Only one, we don't need to sort */
9168                 goto do_sack_work;
9169         }
9170         /* Sort the sacks */
9171         for (i = 0; i < num_sack_blks; i++) {
9172                 for (j = i + 1; j < num_sack_blks; j++) {
9173                         if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
9174                                 sack = sack_blocks[i];
9175                                 sack_blocks[i] = sack_blocks[j];
9176                                 sack_blocks[j] = sack;
9177                         }
9178                 }
9179         }
9180         /*
9181          * Now are any of the sack block ends the same (yes some
9182          * implementations send these)?
9183          */
9184 again:
9185         if (num_sack_blks == 0)
9186                 goto out_with_totals;
9187         if (num_sack_blks > 1) {
9188                 for (i = 0; i < num_sack_blks; i++) {
9189                         for (j = i + 1; j < num_sack_blks; j++) {
9190                                 if (sack_blocks[i].end == sack_blocks[j].end) {
9191                                         /*
9192                                          * Ok these two have the same end we
9193                                          * want the smallest end and then
9194                                          * throw away the larger and start
9195                                          * again.
9196                                          */
9197                                         if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
9198                                                 /*
9199                                                  * The second block covers
9200                                                  * more area use that
9201                                                  */
9202                                                 sack_blocks[i].start = sack_blocks[j].start;
9203                                         }
9204                                         /*
9205                                          * Now collapse out the dup-sack and
9206                                          * lower the count
9207                                          */
9208                                         for (k = (j + 1); k < num_sack_blks; k++) {
9209                                                 sack_blocks[j].start = sack_blocks[k].start;
9210                                                 sack_blocks[j].end = sack_blocks[k].end;
9211                                                 j++;
9212                                         }
9213                                         num_sack_blks--;
9214                                         goto again;
9215                                 }
9216                         }
9217                 }
9218         }
9219 do_sack_work:
9220         /*
9221          * First lets look to see if
9222          * we have retransmitted and
9223          * can use the transmit next?
9224          */
9225         rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
9226         if (rsm &&
9227             SEQ_GT(sack_blocks[0].end, rsm->r_start) &&
9228             SEQ_LT(sack_blocks[0].start, rsm->r_end)) {
9229                 /*
9230                  * We probably did the FR and the next
9231                  * SACK in continues as we would expect.
9232                  */
9233                 acked = rack_proc_sack_blk(tp, rack, &sack_blocks[0], to, &rsm, cts, &moved_two);
9234                 if (acked) {
9235                         rack->r_wanted_output = 1;
9236                         changed += acked;
9237                         sack_changed += acked;
9238                 }
9239                 if (num_sack_blks == 1) {
9240                         /*
9241                          * This is what we would expect from
9242                          * a normal implementation to happen
9243                          * after we have retransmitted the FR,
9244                          * i.e the sack-filter pushes down
9245                          * to 1 block and the next to be retransmitted
9246                          * is the sequence in the sack block (has more
9247                          * are acked). Count this as ACK'd data to boost
9248                          * up the chances of recovering any false positives.
9249                          */
9250                         rack->r_ctl.ack_count += (acked / ctf_fixed_maxseg(rack->rc_tp));
9251                         counter_u64_add(rack_ack_total, (acked / ctf_fixed_maxseg(rack->rc_tp)));
9252                         counter_u64_add(rack_express_sack, 1);
9253                         if (rack->r_ctl.ack_count > 0xfff00000) {
9254                                 /*
9255                                  * reduce the number to keep us under
9256                                  * a uint32_t.
9257                                  */
9258                                 rack->r_ctl.ack_count /= 2;
9259                                 rack->r_ctl.sack_count /= 2;
9260                         }
9261                         goto out_with_totals;
9262                 } else {
9263                         /*
9264                          * Start the loop through the
9265                          * rest of blocks, past the first block.
9266                          */
9267                         moved_two = 0;
9268                         loop_start = 1;
9269                 }
9270         }
9271         /* Its a sack of some sort */
9272         rack->r_ctl.sack_count++;
9273         if (rack->r_ctl.sack_count > 0xfff00000) {
9274                 /*
9275                  * reduce the number to keep us under
9276                  * a uint32_t.
9277                  */
9278                 rack->r_ctl.ack_count /= 2;
9279                 rack->r_ctl.sack_count /= 2;
9280         }
9281         counter_u64_add(rack_sack_total, 1);
9282         if (rack->sack_attack_disable) {
9283                 /* An attacker disablement is in place */
9284                 if (num_sack_blks > 1) {
9285                         rack->r_ctl.sack_count += (num_sack_blks - 1);
9286                         rack->r_ctl.sack_moved_extra++;
9287                         counter_u64_add(rack_move_some, 1);
9288                         if (rack->r_ctl.sack_moved_extra > 0xfff00000) {
9289                                 rack->r_ctl.sack_moved_extra /= 2;
9290                                 rack->r_ctl.sack_noextra_move /= 2;
9291                         }
9292                 }
9293                 goto out;
9294         }
9295         rsm = rack->r_ctl.rc_sacklast;
9296         for (i = loop_start; i < num_sack_blks; i++) {
9297                 acked = rack_proc_sack_blk(tp, rack, &sack_blocks[i], to, &rsm, cts, &moved_two);
9298                 if (acked) {
9299                         rack->r_wanted_output = 1;
9300                         changed += acked;
9301                         sack_changed += acked;
9302                 }
9303                 if (moved_two) {
9304                         /*
9305                          * If we did not get a SACK for at least a MSS and
9306                          * had to move at all, or if we moved more than our
9307                          * threshold, it counts against the "extra" move.
9308                          */
9309                         rack->r_ctl.sack_moved_extra += moved_two;
9310                         counter_u64_add(rack_move_some, 1);
9311                 } else {
9312                         /*
9313                          * else we did not have to move
9314                          * any more than we would expect.
9315                          */
9316                         rack->r_ctl.sack_noextra_move++;
9317                         counter_u64_add(rack_move_none, 1);
9318                 }
9319                 if (moved_two && (acked < ctf_fixed_maxseg(rack->rc_tp))) {
9320                         /*
9321                          * If the SACK was not a full MSS then
9322                          * we add to sack_count the number of
9323                          * MSS's (or possibly more than
9324                          * a MSS if its a TSO send) we had to skip by.
9325                          */
9326                         rack->r_ctl.sack_count += moved_two;
9327                         counter_u64_add(rack_sack_total, moved_two);
9328                 }
9329                 /*
9330                  * Now we need to setup for the next
9331                  * round. First we make sure we won't
9332                  * exceed the size of our uint32_t on
9333                  * the various counts, and then clear out
9334                  * moved_two.
9335                  */
9336                 if ((rack->r_ctl.sack_moved_extra > 0xfff00000) ||
9337                     (rack->r_ctl.sack_noextra_move > 0xfff00000)) {
9338                         rack->r_ctl.sack_moved_extra /= 2;
9339                         rack->r_ctl.sack_noextra_move /= 2;
9340                 }
9341                 if (rack->r_ctl.sack_count > 0xfff00000) {
9342                         rack->r_ctl.ack_count /= 2;
9343                         rack->r_ctl.sack_count /= 2;
9344                 }
9345                 moved_two = 0;
9346         }
9347 out_with_totals:
9348         if (num_sack_blks > 1) {
9349                 /*
9350                  * You get an extra stroke if
9351                  * you have more than one sack-blk, this
9352                  * could be where we are skipping forward
9353                  * and the sack-filter is still working, or
9354                  * it could be an attacker constantly
9355                  * moving us.
9356                  */
9357                 rack->r_ctl.sack_moved_extra++;
9358                 counter_u64_add(rack_move_some, 1);
9359         }
9360 out:
9361 #ifdef NETFLIX_EXP_DETECTION
9362         rack_do_detection(tp, rack, BYTES_THIS_ACK(tp, th), ctf_fixed_maxseg(rack->rc_tp));
9363 #endif
9364         if (changed) {
9365                 /* Something changed cancel the rack timer */
9366                 rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
9367         }
9368         tsused = tcp_get_usecs(NULL);
9369         rsm = tcp_rack_output(tp, rack, tsused);
9370         if ((!IN_FASTRECOVERY(tp->t_flags)) &&
9371             rsm) {
9372                 /* Enter recovery */
9373                 rack->r_ctl.rc_rsm_start = rsm->r_start;
9374                 rack->r_ctl.rc_cwnd_at = tp->snd_cwnd;
9375                 rack->r_ctl.rc_ssthresh_at = tp->snd_ssthresh;
9376                 entered_recovery = 1;
9377                 rack_cong_signal(tp, CC_NDUPACK, tp->snd_una);
9378                 /*
9379                  * When we enter recovery we need to assure we send
9380                  * one packet.
9381                  */
9382                 if (rack->rack_no_prr == 0) {
9383                         rack->r_ctl.rc_prr_sndcnt = ctf_fixed_maxseg(tp);
9384                         rack_log_to_prr(rack, 8, 0);
9385                 }
9386                 rack->r_timer_override = 1;
9387                 rack->r_early = 0;
9388                 rack->r_ctl.rc_agg_early = 0;
9389         } else if (IN_FASTRECOVERY(tp->t_flags) &&
9390                    rsm &&
9391                    (rack->r_rr_config == 3)) {
9392                 /*
9393                  * Assure we can output and we get no
9394                  * remembered pace time except the retransmit.
9395                  */
9396                 rack->r_timer_override = 1;
9397                 rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
9398                 rack->r_ctl.rc_resend = rsm;
9399         }
9400         if (IN_FASTRECOVERY(tp->t_flags) &&
9401             (rack->rack_no_prr == 0) &&
9402             (entered_recovery == 0)) {
9403                 rack_update_prr(tp, rack, changed, th_ack);
9404                 if ((rsm && (rack->r_ctl.rc_prr_sndcnt >= ctf_fixed_maxseg(tp)) &&
9405                      ((rack->rc_inp->inp_in_hpts == 0) &&
9406                       ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0)))) {
9407                         /*
9408                          * If you are pacing output you don't want
9409                          * to override.
9410                          */
9411                         rack->r_early = 0;
9412                         rack->r_ctl.rc_agg_early = 0;
9413                         rack->r_timer_override = 1;
9414                 }
9415         }
9416 }
9417
9418 static void
9419 rack_strike_dupack(struct tcp_rack *rack)
9420 {
9421         struct rack_sendmap *rsm;
9422
9423         rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
9424         while (rsm && (rsm->r_dupack >= DUP_ACK_THRESHOLD)) {
9425                 rsm = TAILQ_NEXT(rsm, r_tnext);
9426         }
9427         if (rsm && (rsm->r_dupack < 0xff)) {
9428                 rsm->r_dupack++;
9429                 if (rsm->r_dupack >= DUP_ACK_THRESHOLD) {
9430                         struct timeval tv;
9431                         uint32_t cts;
9432                         /*
9433                          * Here we see if we need to retransmit. For
9434                          * a SACK type connection if enough time has passed
9435                          * we will get a return of the rsm. For a non-sack
9436                          * connection we will get the rsm returned if the
9437                          * dupack value is 3 or more.
9438                          */
9439                         cts = tcp_get_usecs(&tv);
9440                         rack->r_ctl.rc_resend = tcp_rack_output(rack->rc_tp, rack, cts);
9441                         if (rack->r_ctl.rc_resend != NULL) {
9442                                 if (!IN_FASTRECOVERY(rack->rc_tp->t_flags)) {
9443                                         rack_cong_signal(rack->rc_tp, CC_NDUPACK,
9444                                                          rack->rc_tp->snd_una);
9445                                 }
9446                                 rack->r_wanted_output = 1;
9447                                 rack->r_timer_override = 1;
9448                                 rack_log_retran_reason(rack, rsm, __LINE__, 1, 3);
9449                         }
9450                 } else {
9451                         rack_log_retran_reason(rack, rsm, __LINE__, 0, 3);
9452                 }
9453         }
9454 }
9455
9456 static void
9457 rack_check_bottom_drag(struct tcpcb *tp,
9458                        struct tcp_rack *rack,
9459                        struct socket *so, int32_t acked)
9460 {
9461         uint32_t segsiz, minseg;
9462
9463         segsiz = ctf_fixed_maxseg(tp);
9464         minseg = segsiz;
9465
9466         if (tp->snd_max == tp->snd_una) {
9467                 /*
9468                  * We are doing dynamic pacing and we are way
9469                  * under. Basically everything got acked while
9470                  * we were still waiting on the pacer to expire.
9471                  *
9472                  * This means we need to boost the b/w in
9473                  * addition to any earlier boosting of
9474                  * the multipler.
9475                  */
9476                 rack->rc_dragged_bottom = 1;
9477                 rack_validate_multipliers_at_or_above100(rack);
9478                 /*
9479                  * Lets use the segment bytes acked plus
9480                  * the lowest RTT seen as the basis to
9481                  * form a b/w estimate. This will be off
9482                  * due to the fact that the true estimate
9483                  * should be around 1/2 the time of the RTT
9484                  * but we can settle for that.
9485                  */
9486                 if ((rack->r_ctl.rack_rs.rs_flags & RACK_RTT_VALID) &&
9487                     acked) {
9488                         uint64_t bw, calc_bw, rtt;
9489
9490                         rtt = rack->r_ctl.rack_rs.rs_us_rtt;
9491                         if (rtt == 0) {
9492                                 /* no us sample is there a ms one? */
9493                                 if (rack->r_ctl.rack_rs.rs_rtt_lowest) {
9494                                         rtt = rack->r_ctl.rack_rs.rs_rtt_lowest;
9495                                 } else {
9496                                         goto no_measurement;
9497                                 }
9498                         }
9499                         bw = acked;
9500                         calc_bw = bw * 1000000;
9501                         calc_bw /= rtt;
9502                         if (rack->r_ctl.last_max_bw &&
9503                             (rack->r_ctl.last_max_bw < calc_bw)) {
9504                                 /*
9505                                  * If we have a last calculated max bw
9506                                  * enforce it.
9507                                  */
9508                                 calc_bw = rack->r_ctl.last_max_bw;
9509                         }
9510                         /* now plop it in */
9511                         if (rack->rc_gp_filled == 0) {
9512                                 if (calc_bw > ONE_POINT_TWO_MEG) {
9513                                         /*
9514                                          * If we have no measurement
9515                                          * don't let us set in more than
9516                                          * 1.2Mbps. If we are still too
9517                                          * low after pacing with this we
9518                                          * will hopefully have a max b/w
9519                                          * available to sanity check things.
9520                                          */
9521                                         calc_bw = ONE_POINT_TWO_MEG;
9522                                 }
9523                                 rack->r_ctl.rc_rtt_diff = 0;
9524                                 rack->r_ctl.gp_bw = calc_bw;
9525                                 rack->rc_gp_filled = 1;
9526                                 if (rack->r_ctl.num_measurements < RACK_REQ_AVG)
9527                                         rack->r_ctl.num_measurements = RACK_REQ_AVG;
9528                                 rack_set_pace_segments(rack->rc_tp, rack, __LINE__, NULL);
9529                         } else if (calc_bw > rack->r_ctl.gp_bw) {
9530                                 rack->r_ctl.rc_rtt_diff = 0;
9531                                 if (rack->r_ctl.num_measurements < RACK_REQ_AVG)
9532                                         rack->r_ctl.num_measurements = RACK_REQ_AVG;
9533                                 rack->r_ctl.gp_bw = calc_bw;
9534                                 rack_set_pace_segments(rack->rc_tp, rack, __LINE__, NULL);
9535                         } else
9536                                 rack_increase_bw_mul(rack, -1, 0, 0, 1);
9537                         if ((rack->gp_ready == 0) &&
9538                             (rack->r_ctl.num_measurements >= rack->r_ctl.req_measurements)) {
9539                                 /* We have enough measurements now */
9540                                 rack->gp_ready = 1;
9541                                 rack_set_cc_pacing(rack);
9542                                 if (rack->defer_options)
9543                                         rack_apply_deferred_options(rack);
9544                         }
9545                         /*
9546                          * For acks over 1mss we do a extra boost to simulate
9547                          * where we would get 2 acks (we want 110 for the mul).
9548                          */
9549                         if (acked > segsiz)
9550                                 rack_increase_bw_mul(rack, -1, 0, 0, 1);
9551                 } else {
9552                         /*
9553                          * zero rtt possibly?, settle for just an old increase.
9554                          */
9555 no_measurement:
9556                         rack_increase_bw_mul(rack, -1, 0, 0, 1);
9557                 }
9558         } else if ((IN_FASTRECOVERY(tp->t_flags) == 0) &&
9559                    (sbavail(&so->so_snd) > max((segsiz * (4 + rack_req_segs)),
9560                                                minseg)) &&
9561                    (rack->r_ctl.cwnd_to_use > max((segsiz * (rack_req_segs + 2)), minseg)) &&
9562                    (tp->snd_wnd > max((segsiz * (rack_req_segs + 2)), minseg)) &&
9563                    (ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked) <=
9564                     (segsiz * rack_req_segs))) {
9565                 /*
9566                  * We are doing dynamic GP pacing and
9567                  * we have everything except 1MSS or less
9568                  * bytes left out. We are still pacing away.
9569                  * And there is data that could be sent, This
9570                  * means we are inserting delayed ack time in
9571                  * our measurements because we are pacing too slow.
9572                  */
9573                 rack_validate_multipliers_at_or_above100(rack);
9574                 rack->rc_dragged_bottom = 1;
9575                 rack_increase_bw_mul(rack, -1, 0, 0, 1);
9576         }
9577 }
9578
9579
9580
9581 static void
9582 rack_gain_for_fastoutput(struct tcp_rack *rack, struct tcpcb *tp, struct socket *so, uint32_t acked_amount)
9583 {
9584         /*
9585          * The fast output path is enabled and we
9586          * have moved the cumack forward. Lets see if
9587          * we can expand forward the fast path length by
9588          * that amount. What we would ideally like to
9589          * do is increase the number of bytes in the
9590          * fast path block (left_to_send) by the
9591          * acked amount. However we have to gate that
9592          * by two factors:
9593          * 1) The amount outstanding and the rwnd of the peer
9594          *    (i.e. we don't want to exceed the rwnd of the peer).
9595          *    <and>
9596          * 2) The amount of data left in the socket buffer (i.e.
9597          *    we can't send beyond what is in the buffer).
9598          *
9599          * Note that this does not take into account any increase
9600          * in the cwnd. We will only extend the fast path by
9601          * what was acked.
9602          */
9603         uint32_t new_total, gating_val;
9604
9605         new_total = acked_amount + rack->r_ctl.fsb.left_to_send;
9606         gating_val = min((sbavail(&so->so_snd) - (tp->snd_max - tp->snd_una)),
9607                          (tp->snd_wnd - (tp->snd_max - tp->snd_una)));
9608         if (new_total <= gating_val) {
9609                 /* We can increase left_to_send by the acked amount */
9610                 counter_u64_add(rack_extended_rfo, 1);
9611                 rack->r_ctl.fsb.left_to_send = new_total;
9612                 KASSERT((rack->r_ctl.fsb.left_to_send <= (sbavail(&rack->rc_inp->inp_socket->so_snd) - (tp->snd_max - tp->snd_una))),
9613                         ("rack:%p left_to_send:%u sbavail:%u out:%u",
9614                          rack, rack->r_ctl.fsb.left_to_send,
9615                          sbavail(&rack->rc_inp->inp_socket->so_snd),
9616                          (tp->snd_max - tp->snd_una)));
9617
9618         }
9619 }
9620
9621 static void
9622 rack_adjust_sendmap(struct tcp_rack *rack, struct sockbuf *sb, tcp_seq snd_una)
9623 {
9624         /*
9625          * Here any sendmap entry that points to the
9626          * beginning mbuf must be adjusted to the correct
9627          * offset. This must be called with:
9628          * 1) The socket buffer locked
9629          * 2) snd_una adjusted to its new postion.
9630          *
9631          * Note that (2) implies rack_ack_received has also
9632          * been called.
9633          *
9634          * We grab the first mbuf in the socket buffer and
9635          * then go through the front of the sendmap, recalculating
9636          * the stored offset for any sendmap entry that has
9637          * that mbuf. We must use the sb functions to do this
9638          * since its possible an add was done has well as
9639          * the subtraction we may have just completed. This should
9640          * not be a penalty though, since we just referenced the sb
9641          * to go in and trim off the mbufs that we freed (of course
9642          * there will be a penalty for the sendmap references though).
9643          */
9644         struct mbuf *m;
9645         struct rack_sendmap *rsm;
9646
9647         SOCKBUF_LOCK_ASSERT(sb);
9648         m = sb->sb_mb;
9649         rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
9650         if ((rsm == NULL) || (m == NULL)) {
9651                 /* Nothing outstanding */
9652                 return;
9653         }
9654         while (rsm->m == m) {
9655                 /* one to adjust */
9656 #ifdef INVARIANTS
9657                 struct mbuf *tm;
9658                 uint32_t soff;
9659
9660                 tm = sbsndmbuf(sb, (rsm->r_start - snd_una), &soff);
9661                 if (rsm->orig_m_len != m->m_len) {
9662                         rack_adjust_orig_mlen(rsm);
9663                 }
9664                 if (rsm->soff != soff) {
9665                         /*
9666                          * This is not a fatal error, we anticipate it
9667                          * might happen (the else code), so we count it here
9668                          * so that under invariant we can see that it really
9669                          * does happen.
9670                          */
9671                         counter_u64_add(rack_adjust_map_bw, 1);
9672                 }
9673                 rsm->m = tm;
9674                 rsm->soff = soff;
9675                 rsm->orig_m_len = rsm->m->m_len;
9676 #else
9677                 rsm->m = sbsndmbuf(sb, (rsm->r_start - snd_una), &rsm->soff);
9678                 rsm->orig_m_len = rsm->m->m_len;
9679 #endif
9680                 rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree,
9681                               rsm);
9682                 if (rsm == NULL)
9683                         break;
9684         }
9685 }
9686
9687 /*
9688  * Return value of 1, we do not need to call rack_process_data().
9689  * return value of 0, rack_process_data can be called.
9690  * For ret_val if its 0 the TCP is locked, if its non-zero
9691  * its unlocked and probably unsafe to touch the TCB.
9692  */
9693 static int
9694 rack_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9695     struct tcpcb *tp, struct tcpopt *to,
9696     uint32_t tiwin, int32_t tlen,
9697     int32_t * ofia, int32_t thflags, int32_t *ret_val)
9698 {
9699         int32_t ourfinisacked = 0;
9700         int32_t nsegs, acked_amount;
9701         int32_t acked;
9702         struct mbuf *mfree;
9703         struct tcp_rack *rack;
9704         int32_t under_pacing = 0;
9705         int32_t recovery = 0;
9706
9707         rack = (struct tcp_rack *)tp->t_fb_ptr;
9708         if (SEQ_GT(th->th_ack, tp->snd_max)) {
9709                 __ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val,
9710                                       &rack->r_ctl.challenge_ack_ts,
9711                                       &rack->r_ctl.challenge_ack_cnt);
9712                 rack->r_wanted_output = 1;
9713                 return (1);
9714         }
9715         if (rack->gp_ready &&
9716             (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
9717                 under_pacing = 1;
9718         }
9719         if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
9720                 int in_rec, dup_ack_struck = 0;
9721
9722                 in_rec = IN_FASTRECOVERY(tp->t_flags);
9723                 if (rack->rc_in_persist) {
9724                         tp->t_rxtshift = 0;
9725                         RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
9726                                       rack_rto_min, rack_rto_max);
9727                 }
9728                 if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd)) {
9729                         rack_strike_dupack(rack);
9730                         dup_ack_struck = 1;
9731                 }
9732                 rack_log_ack(tp, to, th, ((in_rec == 0) && IN_FASTRECOVERY(tp->t_flags)), dup_ack_struck);
9733         }
9734         if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
9735                 /*
9736                  * Old ack, behind (or duplicate to) the last one rcv'd
9737                  * Note: We mark reordering is occuring if its
9738                  * less than and we have not closed our window.
9739                  */
9740                 if (SEQ_LT(th->th_ack, tp->snd_una) && (sbspace(&so->so_rcv) > ctf_fixed_maxseg(tp))) {
9741                         counter_u64_add(rack_reorder_seen, 1);
9742                         rack->r_ctl.rc_reorder_ts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
9743                 }
9744                 return (0);
9745         }
9746         /*
9747          * If we reach this point, ACK is not a duplicate, i.e., it ACKs
9748          * something we sent.
9749          */
9750         if (tp->t_flags & TF_NEEDSYN) {
9751                 /*
9752                  * T/TCP: Connection was half-synchronized, and our SYN has
9753                  * been ACK'd (so connection is now fully synchronized).  Go
9754                  * to non-starred state, increment snd_una for ACK of SYN,
9755                  * and check if we can do window scaling.
9756                  */
9757                 tp->t_flags &= ~TF_NEEDSYN;
9758                 tp->snd_una++;
9759                 /* Do window scaling? */
9760                 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9761                     (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9762                         tp->rcv_scale = tp->request_r_scale;
9763                         /* Send window already scaled. */
9764                 }
9765         }
9766         nsegs = max(1, m->m_pkthdr.lro_nsegs);
9767         INP_WLOCK_ASSERT(tp->t_inpcb);
9768
9769         acked = BYTES_THIS_ACK(tp, th);
9770         KMOD_TCPSTAT_ADD(tcps_rcvackpack, nsegs);
9771         KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
9772         /*
9773          * If we just performed our first retransmit, and the ACK arrives
9774          * within our recovery window, then it was a mistake to do the
9775          * retransmit in the first place.  Recover our original cwnd and
9776          * ssthresh, and proceed to transmit where we left off.
9777          */
9778         if ((tp->t_flags & TF_PREVVALID) &&
9779             ((tp->t_flags & TF_RCVD_TSTMP) == 0)) {
9780                 tp->t_flags &= ~TF_PREVVALID;
9781                 if (tp->t_rxtshift == 1 &&
9782                     (int)(ticks - tp->t_badrxtwin) < 0)
9783                         rack_cong_signal(tp, CC_RTO_ERR, th->th_ack);
9784         }
9785         if (acked) {
9786                 /* assure we are not backed off */
9787                 tp->t_rxtshift = 0;
9788                 RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
9789                               rack_rto_min, rack_rto_max);
9790                 rack->rc_tlp_in_progress = 0;
9791                 rack->r_ctl.rc_tlp_cnt_out = 0;
9792                 /*
9793                  * If it is the RXT timer we want to
9794                  * stop it, so we can restart a TLP.
9795                  */
9796                 if (rack->r_ctl.rc_hpts_flags & PACE_TMR_RXT)
9797                         rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
9798 #ifdef NETFLIX_HTTP_LOGGING
9799                 tcp_http_check_for_comp(rack->rc_tp, th->th_ack);
9800 #endif
9801         }
9802         /*
9803          * If we have a timestamp reply, update smoothed round trip time. If
9804          * no timestamp is present but transmit timer is running and timed
9805          * sequence number was acked, update smoothed round trip time. Since
9806          * we now have an rtt measurement, cancel the timer backoff (cf.,
9807          * Phil Karn's retransmit alg.). Recompute the initial retransmit
9808          * timer.
9809          *
9810          * Some boxes send broken timestamp replies during the SYN+ACK
9811          * phase, ignore timestamps of 0 or we could calculate a huge RTT
9812          * and blow up the retransmit timer.
9813          */
9814         /*
9815          * If all outstanding data is acked, stop retransmit timer and
9816          * remember to restart (more output or persist). If there is more
9817          * data to be acked, restart retransmit timer, using current
9818          * (possibly backed-off) value.
9819          */
9820         if (acked == 0) {
9821                 if (ofia)
9822                         *ofia = ourfinisacked;
9823                 return (0);
9824         }
9825         if (IN_RECOVERY(tp->t_flags)) {
9826                 if (SEQ_LT(th->th_ack, tp->snd_recover) &&
9827                     (SEQ_LT(th->th_ack, tp->snd_max))) {
9828                         tcp_rack_partialack(tp);
9829                 } else {
9830                         rack_post_recovery(tp, th->th_ack);
9831                         recovery = 1;
9832                 }
9833         }
9834         /*
9835          * Let the congestion control algorithm update congestion control
9836          * related information. This typically means increasing the
9837          * congestion window.
9838          */
9839         rack_ack_received(tp, rack, th->th_ack, nsegs, CC_ACK, recovery);
9840         SOCKBUF_LOCK(&so->so_snd);
9841         acked_amount = min(acked, (int)sbavail(&so->so_snd));
9842         tp->snd_wnd -= acked_amount;
9843         mfree = sbcut_locked(&so->so_snd, acked_amount);
9844         if ((sbused(&so->so_snd) == 0) &&
9845             (acked > acked_amount) &&
9846             (tp->t_state >= TCPS_FIN_WAIT_1) &&
9847             (tp->t_flags & TF_SENTFIN)) {
9848                 /*
9849                  * We must be sure our fin
9850                  * was sent and acked (we can be
9851                  * in FIN_WAIT_1 without having
9852                  * sent the fin).
9853                  */
9854                 ourfinisacked = 1;
9855         }
9856         tp->snd_una = th->th_ack;
9857         if (acked_amount && sbavail(&so->so_snd))
9858                 rack_adjust_sendmap(rack, &so->so_snd, tp->snd_una);
9859         rack_log_wakeup(tp,rack, &so->so_snd, acked, 2);
9860         SOCKBUF_UNLOCK(&so->so_snd);
9861         tp->t_flags |= TF_WAKESOW;
9862         m_freem(mfree);
9863         if (SEQ_GT(tp->snd_una, tp->snd_recover))
9864                 tp->snd_recover = tp->snd_una;
9865
9866         if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
9867                 tp->snd_nxt = tp->snd_una;
9868         }
9869         if (under_pacing &&
9870             (rack->use_fixed_rate == 0) &&
9871             (rack->in_probe_rtt == 0) &&
9872             rack->rc_gp_dyn_mul &&
9873             rack->rc_always_pace) {
9874                 /* Check if we are dragging bottom */
9875                 rack_check_bottom_drag(tp, rack, so, acked);
9876         }
9877         if (tp->snd_una == tp->snd_max) {
9878                 /* Nothing left outstanding */
9879                 tp->t_flags &= ~TF_PREVVALID;
9880                 rack->r_ctl.rc_went_idle_time = tcp_get_usecs(NULL);
9881                 rack->r_ctl.retran_during_recovery = 0;
9882                 rack->r_ctl.dsack_byte_cnt = 0;
9883                 if (rack->r_ctl.rc_went_idle_time == 0)
9884                         rack->r_ctl.rc_went_idle_time = 1;
9885                 rack_log_progress_event(rack, tp, 0, PROGRESS_CLEAR, __LINE__);
9886                 if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
9887                         tp->t_acktime = 0;
9888                 rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
9889                 /* Set need output so persist might get set */
9890                 rack->r_wanted_output = 1;
9891                 sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
9892                 if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
9893                     (sbavail(&so->so_snd) == 0) &&
9894                     (tp->t_flags2 & TF2_DROP_AF_DATA)) {
9895                         /*
9896                          * The socket was gone and the
9897                          * peer sent data (now or in the past), time to
9898                          * reset him.
9899                          */
9900                         *ret_val = 1;
9901                         /* tcp_close will kill the inp pre-log the Reset */
9902                         tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
9903                         tp = tcp_close(tp);
9904                         ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
9905                         return (1);
9906                 }
9907         }
9908         if (ofia)
9909                 *ofia = ourfinisacked;
9910         return (0);
9911 }
9912
9913 static void
9914 rack_collapsed_window(struct tcp_rack *rack)
9915 {
9916         /*
9917          * Now we must walk the
9918          * send map and divide the
9919          * ones left stranded. These
9920          * guys can't cause us to abort
9921          * the connection and are really
9922          * "unsent". However if a buggy
9923          * client actually did keep some
9924          * of the data i.e. collapsed the win
9925          * and refused to ack and then opened
9926          * the win and acked that data. We would
9927          * get into an ack war, the simplier
9928          * method then of just pretending we
9929          * did not send those segments something
9930          * won't work.
9931          */
9932         struct rack_sendmap *rsm, *nrsm, fe, *insret;
9933         tcp_seq max_seq;
9934
9935         max_seq = rack->rc_tp->snd_una + rack->rc_tp->snd_wnd;
9936         memset(&fe, 0, sizeof(fe));
9937         fe.r_start = max_seq;
9938         /* Find the first seq past or at maxseq */
9939         rsm = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
9940         if (rsm == NULL) {
9941                 /* Nothing to do strange */
9942                 rack->rc_has_collapsed = 0;
9943                 return;
9944         }
9945         /*
9946          * Now do we need to split at
9947          * the collapse point?
9948          */
9949         if (SEQ_GT(max_seq, rsm->r_start)) {
9950                 nrsm = rack_alloc_limit(rack, RACK_LIMIT_TYPE_SPLIT);
9951                 if (nrsm == NULL) {
9952                         /* We can't get a rsm, mark all? */
9953                         nrsm = rsm;
9954                         goto no_split;
9955                 }
9956                 /* Clone it */
9957                 rack_clone_rsm(rack, nrsm, rsm, max_seq);
9958                 insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
9959 #ifdef INVARIANTS
9960                 if (insret != NULL) {
9961                         panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
9962                               nrsm, insret, rack, rsm);
9963                 }
9964 #endif
9965                 rack_log_map_chg(rack->rc_tp, rack, NULL, rsm, nrsm, MAP_SPLIT, max_seq, __LINE__);
9966                 if (rsm->r_in_tmap) {
9967                         TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
9968                         nrsm->r_in_tmap = 1;
9969                 }
9970                 /*
9971                  * Set in the new RSM as the
9972                  * collapsed starting point
9973                  */
9974                 rsm = nrsm;
9975         }
9976 no_split:
9977         counter_u64_add(rack_collapsed_win, 1);
9978         RB_FOREACH_FROM(nrsm, rack_rb_tree_head, rsm) {
9979                 nrsm->r_flags |= RACK_RWND_COLLAPSED;
9980         }
9981         rack->rc_has_collapsed = 1;
9982 }
9983
9984 static void
9985 rack_un_collapse_window(struct tcp_rack *rack)
9986 {
9987         struct rack_sendmap *rsm;
9988
9989         RB_FOREACH_REVERSE(rsm, rack_rb_tree_head, &rack->r_ctl.rc_mtree) {
9990                 if (rsm->r_flags & RACK_RWND_COLLAPSED)
9991                         rsm->r_flags &= ~RACK_RWND_COLLAPSED;
9992                 else
9993                         break;
9994         }
9995         rack->rc_has_collapsed = 0;
9996 }
9997
9998 static void
9999 rack_handle_delayed_ack(struct tcpcb *tp, struct tcp_rack *rack,
10000                         int32_t tlen, int32_t tfo_syn)
10001 {
10002         if (DELAY_ACK(tp, tlen) || tfo_syn) {
10003                 if (rack->rc_dack_mode &&
10004                     (tlen > 500) &&
10005                     (rack->rc_dack_toggle == 1)) {
10006                         goto no_delayed_ack;
10007                 }
10008                 rack_timer_cancel(tp, rack,
10009                                   rack->r_ctl.rc_rcvtime, __LINE__);
10010                 tp->t_flags |= TF_DELACK;
10011         } else {
10012 no_delayed_ack:
10013                 rack->r_wanted_output = 1;
10014                 tp->t_flags |= TF_ACKNOW;
10015                 if (rack->rc_dack_mode) {
10016                         if (tp->t_flags & TF_DELACK)
10017                                 rack->rc_dack_toggle = 1;
10018                         else
10019                                 rack->rc_dack_toggle = 0;
10020                 }
10021         }
10022 }
10023
10024 static void
10025 rack_validate_fo_sendwin_up(struct tcpcb *tp, struct tcp_rack *rack)
10026 {
10027         /*
10028          * If fast output is in progress, lets validate that
10029          * the new window did not shrink on us and make it
10030          * so fast output should end.
10031          */
10032         if (rack->r_fast_output) {
10033                 uint32_t out;
10034
10035                 /*
10036                  * Calculate what we will send if left as is
10037                  * and compare that to our send window.
10038                  */
10039                 out = ctf_outstanding(tp);
10040                 if ((out + rack->r_ctl.fsb.left_to_send) > tp->snd_wnd) {
10041                         /* ok we have an issue */
10042                         if (out >= tp->snd_wnd) {
10043                                 /* Turn off fast output the window is met or collapsed */
10044                                 rack->r_fast_output = 0;
10045                         } else {
10046                                 /* we have some room left */
10047                                 rack->r_ctl.fsb.left_to_send = tp->snd_wnd - out;
10048                                 if (rack->r_ctl.fsb.left_to_send < ctf_fixed_maxseg(tp)) {
10049                                         /* If not at least 1 full segment never mind */
10050                                         rack->r_fast_output = 0;
10051                                 }
10052                         }
10053                 }
10054         }
10055 }
10056
10057 /*
10058  * Return value of 1, the TCB is unlocked and most
10059  * likely gone, return value of 0, the TCP is still
10060  * locked.
10061  */
10062 static int
10063 rack_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
10064     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
10065     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
10066 {
10067         /*
10068          * Update window information. Don't look at window if no ACK: TAC's
10069          * send garbage on first SYN.
10070          */
10071         int32_t nsegs;
10072         int32_t tfo_syn;
10073         struct tcp_rack *rack;
10074
10075         rack = (struct tcp_rack *)tp->t_fb_ptr;
10076         INP_WLOCK_ASSERT(tp->t_inpcb);
10077         nsegs = max(1, m->m_pkthdr.lro_nsegs);
10078         if ((thflags & TH_ACK) &&
10079             (SEQ_LT(tp->snd_wl1, th->th_seq) ||
10080             (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
10081             (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
10082                 /* keep track of pure window updates */
10083                 if (tlen == 0 &&
10084                     tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
10085                         KMOD_TCPSTAT_INC(tcps_rcvwinupd);
10086                 tp->snd_wnd = tiwin;
10087                 rack_validate_fo_sendwin_up(tp, rack);
10088                 tp->snd_wl1 = th->th_seq;
10089                 tp->snd_wl2 = th->th_ack;
10090                 if (tp->snd_wnd > tp->max_sndwnd)
10091                         tp->max_sndwnd = tp->snd_wnd;
10092                 rack->r_wanted_output = 1;
10093         } else if (thflags & TH_ACK) {
10094                 if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
10095                         tp->snd_wnd = tiwin;
10096                         rack_validate_fo_sendwin_up(tp, rack);
10097                         tp->snd_wl1 = th->th_seq;
10098                         tp->snd_wl2 = th->th_ack;
10099                 }
10100         }
10101         if (tp->snd_wnd < ctf_outstanding(tp))
10102                 /* The peer collapsed the window */
10103                 rack_collapsed_window(rack);
10104         else if (rack->rc_has_collapsed)
10105                 rack_un_collapse_window(rack);
10106         /* Was persist timer active and now we have window space? */
10107         if ((rack->rc_in_persist != 0) &&
10108             (tp->snd_wnd >= min((rack->r_ctl.rc_high_rwnd/2),
10109                                 rack->r_ctl.rc_pace_min_segs))) {
10110                 rack_exit_persist(tp, rack, rack->r_ctl.rc_rcvtime);
10111                 tp->snd_nxt = tp->snd_max;
10112                 /* Make sure we output to start the timer */
10113                 rack->r_wanted_output = 1;
10114         }
10115         /* Do we enter persists? */
10116         if ((rack->rc_in_persist == 0) &&
10117             (tp->snd_wnd < min((rack->r_ctl.rc_high_rwnd/2), rack->r_ctl.rc_pace_min_segs)) &&
10118             TCPS_HAVEESTABLISHED(tp->t_state) &&
10119             (tp->snd_max == tp->snd_una) &&
10120             sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
10121             (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
10122                 /*
10123                  * Here the rwnd is less than
10124                  * the pacing size, we are established,
10125                  * nothing is outstanding, and there is
10126                  * data to send. Enter persists.
10127                  */
10128                 rack_enter_persist(tp, rack, rack->r_ctl.rc_rcvtime);
10129         }
10130         if (tp->t_flags2 & TF2_DROP_AF_DATA) {
10131                 m_freem(m);
10132                 return (0);
10133         }
10134         /*
10135          * don't process the URG bit, ignore them drag
10136          * along the up.
10137          */
10138         tp->rcv_up = tp->rcv_nxt;
10139         INP_WLOCK_ASSERT(tp->t_inpcb);
10140
10141         /*
10142          * Process the segment text, merging it into the TCP sequencing
10143          * queue, and arranging for acknowledgment of receipt if necessary.
10144          * This process logically involves adjusting tp->rcv_wnd as data is
10145          * presented to the user (this happens in tcp_usrreq.c, case
10146          * PRU_RCVD).  If a FIN has already been received on this connection
10147          * then we just ignore the text.
10148          */
10149         tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
10150                    IS_FASTOPEN(tp->t_flags));
10151         if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
10152             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
10153                 tcp_seq save_start = th->th_seq;
10154                 tcp_seq save_rnxt  = tp->rcv_nxt;
10155                 int     save_tlen  = tlen;
10156
10157                 m_adj(m, drop_hdrlen);  /* delayed header drop */
10158                 /*
10159                  * Insert segment which includes th into TCP reassembly
10160                  * queue with control block tp.  Set thflags to whether
10161                  * reassembly now includes a segment with FIN.  This handles
10162                  * the common case inline (segment is the next to be
10163                  * received on an established connection, and the queue is
10164                  * empty), avoiding linkage into and removal from the queue
10165                  * and repetition of various conversions. Set DELACK for
10166                  * segments received in order, but ack immediately when
10167                  * segments are out of order (so fast retransmit can work).
10168                  */
10169                 if (th->th_seq == tp->rcv_nxt &&
10170                     SEGQ_EMPTY(tp) &&
10171                     (TCPS_HAVEESTABLISHED(tp->t_state) ||
10172                     tfo_syn)) {
10173 #ifdef NETFLIX_SB_LIMITS
10174                         u_int mcnt, appended;
10175
10176                         if (so->so_rcv.sb_shlim) {
10177                                 mcnt = m_memcnt(m);
10178                                 appended = 0;
10179                                 if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
10180                                     CFO_NOSLEEP, NULL) == false) {
10181                                         counter_u64_add(tcp_sb_shlim_fails, 1);
10182                                         m_freem(m);
10183                                         return (0);
10184                                 }
10185                         }
10186 #endif
10187                         rack_handle_delayed_ack(tp, rack, tlen, tfo_syn);
10188                         tp->rcv_nxt += tlen;
10189                         if (tlen &&
10190                             ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
10191                             (tp->t_fbyte_in == 0)) {
10192                                 tp->t_fbyte_in = ticks;
10193                                 if (tp->t_fbyte_in == 0)
10194                                         tp->t_fbyte_in = 1;
10195                                 if (tp->t_fbyte_out && tp->t_fbyte_in)
10196                                         tp->t_flags2 |= TF2_FBYTES_COMPLETE;
10197                         }
10198                         thflags = th->th_flags & TH_FIN;
10199                         KMOD_TCPSTAT_ADD(tcps_rcvpack, nsegs);
10200                         KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
10201                         SOCKBUF_LOCK(&so->so_rcv);
10202                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
10203                                 m_freem(m);
10204                         } else
10205 #ifdef NETFLIX_SB_LIMITS
10206                                 appended =
10207 #endif
10208                                         sbappendstream_locked(&so->so_rcv, m, 0);
10209
10210                         rack_log_wakeup(tp,rack, &so->so_rcv, tlen, 1);
10211                         SOCKBUF_UNLOCK(&so->so_rcv);
10212                         tp->t_flags |= TF_WAKESOR;
10213 #ifdef NETFLIX_SB_LIMITS
10214                         if (so->so_rcv.sb_shlim && appended != mcnt)
10215                                 counter_fo_release(so->so_rcv.sb_shlim,
10216                                     mcnt - appended);
10217 #endif
10218                 } else {
10219                         /*
10220                          * XXX: Due to the header drop above "th" is
10221                          * theoretically invalid by now.  Fortunately
10222                          * m_adj() doesn't actually frees any mbufs when
10223                          * trimming from the head.
10224                          */
10225                         tcp_seq temp = save_start;
10226
10227                         thflags = tcp_reass(tp, th, &temp, &tlen, m);
10228                         tp->t_flags |= TF_ACKNOW;
10229                 }
10230                 if ((tp->t_flags & TF_SACK_PERMIT) &&
10231                     (save_tlen > 0) &&
10232                     TCPS_HAVEESTABLISHED(tp->t_state)) {
10233                         if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
10234                                 /*
10235                                  * DSACK actually handled in the fastpath
10236                                  * above.
10237                                  */
10238                                 RACK_OPTS_INC(tcp_sack_path_1);
10239                                 tcp_update_sack_list(tp, save_start,
10240                                     save_start + save_tlen);
10241                         } else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
10242                                 if ((tp->rcv_numsacks >= 1) &&
10243                                     (tp->sackblks[0].end == save_start)) {
10244                                         /*
10245                                          * Partial overlap, recorded at todrop
10246                                          * above.
10247                                          */
10248                                         RACK_OPTS_INC(tcp_sack_path_2a);
10249                                         tcp_update_sack_list(tp,
10250                                             tp->sackblks[0].start,
10251                                             tp->sackblks[0].end);
10252                                 } else {
10253                                         RACK_OPTS_INC(tcp_sack_path_2b);
10254                                         tcp_update_dsack_list(tp, save_start,
10255                                             save_start + save_tlen);
10256                                 }
10257                         } else if (tlen >= save_tlen) {
10258                                 /* Update of sackblks. */
10259                                 RACK_OPTS_INC(tcp_sack_path_3);
10260                                 tcp_update_dsack_list(tp, save_start,
10261                                     save_start + save_tlen);
10262                         } else if (tlen > 0) {
10263                                 RACK_OPTS_INC(tcp_sack_path_4);
10264                                 tcp_update_dsack_list(tp, save_start,
10265                                     save_start + tlen);
10266                         }
10267                 }
10268         } else {
10269                 m_freem(m);
10270                 thflags &= ~TH_FIN;
10271         }
10272
10273         /*
10274          * If FIN is received ACK the FIN and let the user know that the
10275          * connection is closing.
10276          */
10277         if (thflags & TH_FIN) {
10278                 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
10279                         socantrcvmore(so);
10280                         /* The socket upcall is handled by socantrcvmore. */
10281                         tp->t_flags &= ~TF_WAKESOR;
10282                         /*
10283                          * If connection is half-synchronized (ie NEEDSYN
10284                          * flag on) then delay ACK, so it may be piggybacked
10285                          * when SYN is sent. Otherwise, since we received a
10286                          * FIN then no more input can be expected, send ACK
10287                          * now.
10288                          */
10289                         if (tp->t_flags & TF_NEEDSYN) {
10290                                 rack_timer_cancel(tp, rack,
10291                                     rack->r_ctl.rc_rcvtime, __LINE__);
10292                                 tp->t_flags |= TF_DELACK;
10293                         } else {
10294                                 tp->t_flags |= TF_ACKNOW;
10295                         }
10296                         tp->rcv_nxt++;
10297                 }
10298                 switch (tp->t_state) {
10299                         /*
10300                          * In SYN_RECEIVED and ESTABLISHED STATES enter the
10301                          * CLOSE_WAIT state.
10302                          */
10303                 case TCPS_SYN_RECEIVED:
10304                         tp->t_starttime = ticks;
10305                         /* FALLTHROUGH */
10306                 case TCPS_ESTABLISHED:
10307                         rack_timer_cancel(tp, rack,
10308                             rack->r_ctl.rc_rcvtime, __LINE__);
10309                         tcp_state_change(tp, TCPS_CLOSE_WAIT);
10310                         break;
10311
10312                         /*
10313                          * If still in FIN_WAIT_1 STATE FIN has not been
10314                          * acked so enter the CLOSING state.
10315                          */
10316                 case TCPS_FIN_WAIT_1:
10317                         rack_timer_cancel(tp, rack,
10318                             rack->r_ctl.rc_rcvtime, __LINE__);
10319                         tcp_state_change(tp, TCPS_CLOSING);
10320                         break;
10321
10322                         /*
10323                          * In FIN_WAIT_2 state enter the TIME_WAIT state,
10324                          * starting the time-wait timer, turning off the
10325                          * other standard timers.
10326                          */
10327                 case TCPS_FIN_WAIT_2:
10328                         rack_timer_cancel(tp, rack,
10329                             rack->r_ctl.rc_rcvtime, __LINE__);
10330                         tcp_twstart(tp);
10331                         return (1);
10332                 }
10333         }
10334         /*
10335          * Return any desired output.
10336          */
10337         if ((tp->t_flags & TF_ACKNOW) ||
10338             (sbavail(&so->so_snd) > (tp->snd_max - tp->snd_una))) {
10339                 rack->r_wanted_output = 1;
10340         }
10341         INP_WLOCK_ASSERT(tp->t_inpcb);
10342         return (0);
10343 }
10344
10345 /*
10346  * Here nothing is really faster, its just that we
10347  * have broken out the fast-data path also just like
10348  * the fast-ack.
10349  */
10350 static int
10351 rack_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
10352     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
10353     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
10354 {
10355         int32_t nsegs;
10356         int32_t newsize = 0;    /* automatic sockbuf scaling */
10357         struct tcp_rack *rack;
10358 #ifdef NETFLIX_SB_LIMITS
10359         u_int mcnt, appended;
10360 #endif
10361 #ifdef TCPDEBUG
10362         /*
10363          * The size of tcp_saveipgen must be the size of the max ip header,
10364          * now IPv6.
10365          */
10366         u_char tcp_saveipgen[IP6_HDR_LEN];
10367         struct tcphdr tcp_savetcp;
10368         short ostate = 0;
10369
10370 #endif
10371         /*
10372          * If last ACK falls within this segment's sequence numbers, record
10373          * the timestamp. NOTE that the test is modified according to the
10374          * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
10375          */
10376         if (__predict_false(th->th_seq != tp->rcv_nxt)) {
10377                 return (0);
10378         }
10379         if (__predict_false(tp->snd_nxt != tp->snd_max)) {
10380                 return (0);
10381         }
10382         if (tiwin && tiwin != tp->snd_wnd) {
10383                 return (0);
10384         }
10385         if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
10386                 return (0);
10387         }
10388         if (__predict_false((to->to_flags & TOF_TS) &&
10389             (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
10390                 return (0);
10391         }
10392         if (__predict_false((th->th_ack != tp->snd_una))) {
10393                 return (0);
10394         }
10395         if (__predict_false(tlen > sbspace(&so->so_rcv))) {
10396                 return (0);
10397         }
10398         if ((to->to_flags & TOF_TS) != 0 &&
10399             SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
10400                 tp->ts_recent_age = tcp_ts_getticks();
10401                 tp->ts_recent = to->to_tsval;
10402         }
10403         rack = (struct tcp_rack *)tp->t_fb_ptr;
10404         /*
10405          * This is a pure, in-sequence data packet with nothing on the
10406          * reassembly queue and we have enough buffer space to take it.
10407          */
10408         nsegs = max(1, m->m_pkthdr.lro_nsegs);
10409
10410 #ifdef NETFLIX_SB_LIMITS
10411         if (so->so_rcv.sb_shlim) {
10412                 mcnt = m_memcnt(m);
10413                 appended = 0;
10414                 if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
10415                     CFO_NOSLEEP, NULL) == false) {
10416                         counter_u64_add(tcp_sb_shlim_fails, 1);
10417                         m_freem(m);
10418                         return (1);
10419                 }
10420         }
10421 #endif
10422         /* Clean receiver SACK report if present */
10423         if (tp->rcv_numsacks)
10424                 tcp_clean_sackreport(tp);
10425         KMOD_TCPSTAT_INC(tcps_preddat);
10426         tp->rcv_nxt += tlen;
10427         if (tlen &&
10428             ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
10429             (tp->t_fbyte_in == 0)) {
10430                 tp->t_fbyte_in = ticks;
10431                 if (tp->t_fbyte_in == 0)
10432                         tp->t_fbyte_in = 1;
10433                 if (tp->t_fbyte_out && tp->t_fbyte_in)
10434                         tp->t_flags2 |= TF2_FBYTES_COMPLETE;
10435         }
10436         /*
10437          * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
10438          */
10439         tp->snd_wl1 = th->th_seq;
10440         /*
10441          * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
10442          */
10443         tp->rcv_up = tp->rcv_nxt;
10444         KMOD_TCPSTAT_ADD(tcps_rcvpack, nsegs);
10445         KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
10446 #ifdef TCPDEBUG
10447         if (so->so_options & SO_DEBUG)
10448                 tcp_trace(TA_INPUT, ostate, tp,
10449                     (void *)tcp_saveipgen, &tcp_savetcp, 0);
10450 #endif
10451         newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
10452
10453         /* Add data to socket buffer. */
10454         SOCKBUF_LOCK(&so->so_rcv);
10455         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
10456                 m_freem(m);
10457         } else {
10458                 /*
10459                  * Set new socket buffer size. Give up when limit is
10460                  * reached.
10461                  */
10462                 if (newsize)
10463                         if (!sbreserve_locked(&so->so_rcv,
10464                             newsize, so, NULL))
10465                                 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
10466                 m_adj(m, drop_hdrlen);  /* delayed header drop */
10467 #ifdef NETFLIX_SB_LIMITS
10468                 appended =
10469 #endif
10470                         sbappendstream_locked(&so->so_rcv, m, 0);
10471                 ctf_calc_rwin(so, tp);
10472         }
10473         rack_log_wakeup(tp,rack, &so->so_rcv, tlen, 1);
10474         SOCKBUF_UNLOCK(&so->so_rcv);
10475         tp->t_flags |= TF_WAKESOR;
10476 #ifdef NETFLIX_SB_LIMITS
10477         if (so->so_rcv.sb_shlim && mcnt != appended)
10478                 counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
10479 #endif
10480         rack_handle_delayed_ack(tp, rack, tlen, 0);
10481         if (tp->snd_una == tp->snd_max)
10482                 sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
10483         return (1);
10484 }
10485
10486 /*
10487  * This subfunction is used to try to highly optimize the
10488  * fast path. We again allow window updates that are
10489  * in sequence to remain in the fast-path. We also add
10490  * in the __predict's to attempt to help the compiler.
10491  * Note that if we return a 0, then we can *not* process
10492  * it and the caller should push the packet into the
10493  * slow-path.
10494  */
10495 static int
10496 rack_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
10497     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
10498     uint32_t tiwin, int32_t nxt_pkt, uint32_t cts)
10499 {
10500         int32_t acked;
10501         int32_t nsegs;
10502 #ifdef TCPDEBUG
10503         /*
10504          * The size of tcp_saveipgen must be the size of the max ip header,
10505          * now IPv6.
10506          */
10507         u_char tcp_saveipgen[IP6_HDR_LEN];
10508         struct tcphdr tcp_savetcp;
10509         short ostate = 0;
10510 #endif
10511         int32_t under_pacing = 0;
10512         struct tcp_rack *rack;
10513
10514         if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
10515                 /* Old ack, behind (or duplicate to) the last one rcv'd */
10516                 return (0);
10517         }
10518         if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
10519                 /* Above what we have sent? */
10520                 return (0);
10521         }
10522         if (__predict_false(tp->snd_nxt != tp->snd_max)) {
10523                 /* We are retransmitting */
10524                 return (0);
10525         }
10526         if (__predict_false(tiwin == 0)) {
10527                 /* zero window */
10528                 return (0);
10529         }
10530         if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
10531                 /* We need a SYN or a FIN, unlikely.. */
10532                 return (0);
10533         }
10534         if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
10535                 /* Timestamp is behind .. old ack with seq wrap? */
10536                 return (0);
10537         }
10538         if (__predict_false(IN_RECOVERY(tp->t_flags))) {
10539                 /* Still recovering */
10540                 return (0);
10541         }
10542         rack = (struct tcp_rack *)tp->t_fb_ptr;
10543         if (rack->r_ctl.rc_sacked) {
10544                 /* We have sack holes on our scoreboard */
10545                 return (0);
10546         }
10547         /* Ok if we reach here, we can process a fast-ack */
10548         if (rack->gp_ready &&
10549             (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
10550                 under_pacing = 1;
10551         }
10552         nsegs = max(1, m->m_pkthdr.lro_nsegs);
10553         rack_log_ack(tp, to, th, 0, 0);
10554         /* Did the window get updated? */
10555         if (tiwin != tp->snd_wnd) {
10556                 tp->snd_wnd = tiwin;
10557                 rack_validate_fo_sendwin_up(tp, rack);
10558                 tp->snd_wl1 = th->th_seq;
10559                 if (tp->snd_wnd > tp->max_sndwnd)
10560                         tp->max_sndwnd = tp->snd_wnd;
10561         }
10562         /* Do we exit persists? */
10563         if ((rack->rc_in_persist != 0) &&
10564             (tp->snd_wnd >= min((rack->r_ctl.rc_high_rwnd/2),
10565                                rack->r_ctl.rc_pace_min_segs))) {
10566                 rack_exit_persist(tp, rack, cts);
10567         }
10568         /* Do we enter persists? */
10569         if ((rack->rc_in_persist == 0) &&
10570             (tp->snd_wnd < min((rack->r_ctl.rc_high_rwnd/2), rack->r_ctl.rc_pace_min_segs)) &&
10571             TCPS_HAVEESTABLISHED(tp->t_state) &&
10572             (tp->snd_max == tp->snd_una) &&
10573             sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
10574             (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
10575                 /*
10576                  * Here the rwnd is less than
10577                  * the pacing size, we are established,
10578                  * nothing is outstanding, and there is
10579                  * data to send. Enter persists.
10580                  */
10581                 rack_enter_persist(tp, rack, rack->r_ctl.rc_rcvtime);
10582         }
10583         /*
10584          * If last ACK falls within this segment's sequence numbers, record
10585          * the timestamp. NOTE that the test is modified according to the
10586          * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
10587          */
10588         if ((to->to_flags & TOF_TS) != 0 &&
10589             SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
10590                 tp->ts_recent_age = tcp_ts_getticks();
10591                 tp->ts_recent = to->to_tsval;
10592         }
10593         /*
10594          * This is a pure ack for outstanding data.
10595          */
10596         KMOD_TCPSTAT_INC(tcps_predack);
10597
10598         /*
10599          * "bad retransmit" recovery.
10600          */
10601         if ((tp->t_flags & TF_PREVVALID) &&
10602             ((tp->t_flags & TF_RCVD_TSTMP) == 0)) {
10603                 tp->t_flags &= ~TF_PREVVALID;
10604                 if (tp->t_rxtshift == 1 &&
10605                     (int)(ticks - tp->t_badrxtwin) < 0)
10606                         rack_cong_signal(tp, CC_RTO_ERR, th->th_ack);
10607         }
10608         /*
10609          * Recalculate the transmit timer / rtt.
10610          *
10611          * Some boxes send broken timestamp replies during the SYN+ACK
10612          * phase, ignore timestamps of 0 or we could calculate a huge RTT
10613          * and blow up the retransmit timer.
10614          */
10615         acked = BYTES_THIS_ACK(tp, th);
10616
10617 #ifdef TCP_HHOOK
10618         /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
10619         hhook_run_tcp_est_in(tp, th, to);
10620 #endif
10621         KMOD_TCPSTAT_ADD(tcps_rcvackpack, nsegs);
10622         KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
10623         if (acked) {
10624                 struct mbuf *mfree;
10625
10626                 rack_ack_received(tp, rack, th->th_ack, nsegs, CC_ACK, 0);
10627                 SOCKBUF_LOCK(&so->so_snd);
10628                 mfree = sbcut_locked(&so->so_snd, acked);
10629                 tp->snd_una = th->th_ack;
10630                 /* Note we want to hold the sb lock through the sendmap adjust */
10631                 rack_adjust_sendmap(rack, &so->so_snd, tp->snd_una);
10632                 /* Wake up the socket if we have room to write more */
10633                 rack_log_wakeup(tp,rack, &so->so_snd, acked, 2);
10634                 SOCKBUF_UNLOCK(&so->so_snd);
10635                 tp->t_flags |= TF_WAKESOW;
10636                 m_freem(mfree);
10637                 tp->t_rxtshift = 0;
10638                 RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
10639                               rack_rto_min, rack_rto_max);
10640                 rack->rc_tlp_in_progress = 0;
10641                 rack->r_ctl.rc_tlp_cnt_out = 0;
10642                 /*
10643                  * If it is the RXT timer we want to
10644                  * stop it, so we can restart a TLP.
10645                  */
10646                 if (rack->r_ctl.rc_hpts_flags & PACE_TMR_RXT)
10647                         rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
10648 #ifdef NETFLIX_HTTP_LOGGING
10649                 tcp_http_check_for_comp(rack->rc_tp, th->th_ack);
10650 #endif
10651         }
10652         /*
10653          * Let the congestion control algorithm update congestion control
10654          * related information. This typically means increasing the
10655          * congestion window.
10656          */
10657         if (tp->snd_wnd < ctf_outstanding(tp)) {
10658                 /* The peer collapsed the window */
10659                 rack_collapsed_window(rack);
10660         } else if (rack->rc_has_collapsed)
10661                 rack_un_collapse_window(rack);
10662
10663         /*
10664          * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
10665          */
10666         tp->snd_wl2 = th->th_ack;
10667         tp->t_dupacks = 0;
10668         m_freem(m);
10669         /* ND6_HINT(tp);         *//* Some progress has been made. */
10670
10671         /*
10672          * If all outstanding data are acked, stop retransmit timer,
10673          * otherwise restart timer using current (possibly backed-off)
10674          * value. If process is waiting for space, wakeup/selwakeup/signal.
10675          * If data are ready to send, let tcp_output decide between more
10676          * output or persist.
10677          */
10678 #ifdef TCPDEBUG
10679         if (so->so_options & SO_DEBUG)
10680                 tcp_trace(TA_INPUT, ostate, tp,
10681                     (void *)tcp_saveipgen,
10682                     &tcp_savetcp, 0);
10683 #endif
10684         if (under_pacing &&
10685             (rack->use_fixed_rate == 0) &&
10686             (rack->in_probe_rtt == 0) &&
10687             rack->rc_gp_dyn_mul &&
10688             rack->rc_always_pace) {
10689                 /* Check if we are dragging bottom */
10690                 rack_check_bottom_drag(tp, rack, so, acked);
10691         }
10692         if (tp->snd_una == tp->snd_max) {
10693                 tp->t_flags &= ~TF_PREVVALID;
10694                 rack->r_ctl.retran_during_recovery = 0;
10695                 rack->r_ctl.dsack_byte_cnt = 0;
10696                 rack->r_ctl.rc_went_idle_time = tcp_get_usecs(NULL);
10697                 if (rack->r_ctl.rc_went_idle_time == 0)
10698                         rack->r_ctl.rc_went_idle_time = 1;
10699                 rack_log_progress_event(rack, tp, 0, PROGRESS_CLEAR, __LINE__);
10700                 if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
10701                         tp->t_acktime = 0;
10702                 rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
10703         }
10704         if (acked && rack->r_fast_output)
10705                 rack_gain_for_fastoutput(rack, tp, so, (uint32_t)acked);
10706         if (sbavail(&so->so_snd)) {
10707                 rack->r_wanted_output = 1;
10708         }
10709         return (1);
10710 }
10711
10712 /*
10713  * Return value of 1, the TCB is unlocked and most
10714  * likely gone, return value of 0, the TCP is still
10715  * locked.
10716  */
10717 static int
10718 rack_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
10719     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
10720     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
10721 {
10722         int32_t ret_val = 0;
10723         int32_t todrop;
10724         int32_t ourfinisacked = 0;
10725         struct tcp_rack *rack;
10726
10727         ctf_calc_rwin(so, tp);
10728         /*
10729          * If the state is SYN_SENT: if seg contains an ACK, but not for our
10730          * SYN, drop the input. if seg contains a RST, then drop the
10731          * connection. if seg does not contain SYN, then drop it. Otherwise
10732          * this is an acceptable SYN segment initialize tp->rcv_nxt and
10733          * tp->irs if seg contains ack then advance tp->snd_una if seg
10734          * contains an ECE and ECN support is enabled, the stream is ECN
10735          * capable. if SYN has been acked change to ESTABLISHED else
10736          * SYN_RCVD state arrange for segment to be acked (eventually)
10737          * continue processing rest of data/controls.
10738          */
10739         if ((thflags & TH_ACK) &&
10740             (SEQ_LEQ(th->th_ack, tp->iss) ||
10741             SEQ_GT(th->th_ack, tp->snd_max))) {
10742                 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
10743                 ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
10744                 return (1);
10745         }
10746         if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
10747                 TCP_PROBE5(connect__refused, NULL, tp,
10748                     mtod(m, const char *), tp, th);
10749                 tp = tcp_drop(tp, ECONNREFUSED);
10750                 ctf_do_drop(m, tp);
10751                 return (1);
10752         }
10753         if (thflags & TH_RST) {
10754                 ctf_do_drop(m, tp);
10755                 return (1);
10756         }
10757         if (!(thflags & TH_SYN)) {
10758                 ctf_do_drop(m, tp);
10759                 return (1);
10760         }
10761         tp->irs = th->th_seq;
10762         tcp_rcvseqinit(tp);
10763         rack = (struct tcp_rack *)tp->t_fb_ptr;
10764         if (thflags & TH_ACK) {
10765                 int tfo_partial = 0;
10766
10767                 KMOD_TCPSTAT_INC(tcps_connects);
10768                 soisconnected(so);
10769 #ifdef MAC
10770                 mac_socketpeer_set_from_mbuf(m, so);
10771 #endif
10772                 /* Do window scaling on this connection? */
10773                 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
10774                     (TF_RCVD_SCALE | TF_REQ_SCALE)) {
10775                         tp->rcv_scale = tp->request_r_scale;
10776                 }
10777                 tp->rcv_adv += min(tp->rcv_wnd,
10778                     TCP_MAXWIN << tp->rcv_scale);
10779                 /*
10780                  * If not all the data that was sent in the TFO SYN
10781                  * has been acked, resend the remainder right away.
10782                  */
10783                 if (IS_FASTOPEN(tp->t_flags) &&
10784                     (tp->snd_una != tp->snd_max)) {
10785                         tp->snd_nxt = th->th_ack;
10786                         tfo_partial = 1;
10787                 }
10788                 /*
10789                  * If there's data, delay ACK; if there's also a FIN ACKNOW
10790                  * will be turned on later.
10791                  */
10792                 if (DELAY_ACK(tp, tlen) && tlen != 0 && !tfo_partial) {
10793                         rack_timer_cancel(tp, rack,
10794                                           rack->r_ctl.rc_rcvtime, __LINE__);
10795                         tp->t_flags |= TF_DELACK;
10796                 } else {
10797                         rack->r_wanted_output = 1;
10798                         tp->t_flags |= TF_ACKNOW;
10799                         rack->rc_dack_toggle = 0;
10800                 }
10801                 if (((thflags & (TH_CWR | TH_ECE)) == TH_ECE) &&
10802                     (V_tcp_do_ecn == 1)) {
10803                         tp->t_flags2 |= TF2_ECN_PERMIT;
10804                         KMOD_TCPSTAT_INC(tcps_ecn_shs);
10805                 }
10806                 if (SEQ_GT(th->th_ack, tp->snd_una)) {
10807                         /*
10808                          * We advance snd_una for the
10809                          * fast open case. If th_ack is
10810                          * acknowledging data beyond
10811                          * snd_una we can't just call
10812                          * ack-processing since the
10813                          * data stream in our send-map
10814                          * will start at snd_una + 1 (one
10815                          * beyond the SYN). If its just
10816                          * equal we don't need to do that
10817                          * and there is no send_map.
10818                          */
10819                         tp->snd_una++;
10820                 }
10821                 /*
10822                  * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
10823                  * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
10824                  */
10825                 tp->t_starttime = ticks;
10826                 if (tp->t_flags & TF_NEEDFIN) {
10827                         tcp_state_change(tp, TCPS_FIN_WAIT_1);
10828                         tp->t_flags &= ~TF_NEEDFIN;
10829                         thflags &= ~TH_SYN;
10830                 } else {
10831                         tcp_state_change(tp, TCPS_ESTABLISHED);
10832                         TCP_PROBE5(connect__established, NULL, tp,
10833                             mtod(m, const char *), tp, th);
10834                         rack_cc_conn_init(tp);
10835                 }
10836         } else {
10837                 /*
10838                  * Received initial SYN in SYN-SENT[*] state => simultaneous
10839                  * open.  If segment contains CC option and there is a
10840                  * cached CC, apply TAO test. If it succeeds, connection is *
10841                  * half-synchronized. Otherwise, do 3-way handshake:
10842                  * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
10843                  * there was no CC option, clear cached CC value.
10844                  */
10845                 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
10846                 tcp_state_change(tp, TCPS_SYN_RECEIVED);
10847         }
10848         INP_WLOCK_ASSERT(tp->t_inpcb);
10849         /*
10850          * Advance th->th_seq to correspond to first data byte. If data,
10851          * trim to stay within window, dropping FIN if necessary.
10852          */
10853         th->th_seq++;
10854         if (tlen > tp->rcv_wnd) {
10855                 todrop = tlen - tp->rcv_wnd;
10856                 m_adj(m, -todrop);
10857                 tlen = tp->rcv_wnd;
10858                 thflags &= ~TH_FIN;
10859                 KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
10860                 KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
10861         }
10862         tp->snd_wl1 = th->th_seq - 1;
10863         tp->rcv_up = th->th_seq;
10864         /*
10865          * Client side of transaction: already sent SYN and data. If the
10866          * remote host used T/TCP to validate the SYN, our data will be
10867          * ACK'd; if so, enter normal data segment processing in the middle
10868          * of step 5, ack processing. Otherwise, goto step 6.
10869          */
10870         if (thflags & TH_ACK) {
10871                 /* For syn-sent we need to possibly update the rtt */
10872                 if ((to->to_flags & TOF_TS) != 0 && to->to_tsecr) {
10873                         uint32_t t, mcts;
10874
10875                         mcts = tcp_ts_getticks();
10876                         t = (mcts - to->to_tsecr) * HPTS_USEC_IN_MSEC;
10877                         if (!tp->t_rttlow || tp->t_rttlow > t)
10878                                 tp->t_rttlow = t;
10879                         rack_log_rtt_sample_calc(rack, t, (to->to_tsecr * 1000), (mcts * 1000), 4);
10880                         tcp_rack_xmit_timer(rack, t + 1, 1, t, 0, NULL, 2);
10881                         tcp_rack_xmit_timer_commit(rack, tp);
10882                 }
10883                 if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
10884                         return (ret_val);
10885                 /* We may have changed to FIN_WAIT_1 above */
10886                 if (tp->t_state == TCPS_FIN_WAIT_1) {
10887                         /*
10888                          * In FIN_WAIT_1 STATE in addition to the processing
10889                          * for the ESTABLISHED state if our FIN is now
10890                          * acknowledged then enter FIN_WAIT_2.
10891                          */
10892                         if (ourfinisacked) {
10893                                 /*
10894                                  * If we can't receive any more data, then
10895                                  * closing user can proceed. Starting the
10896                                  * timer is contrary to the specification,
10897                                  * but if we don't get a FIN we'll hang
10898                                  * forever.
10899                                  *
10900                                  * XXXjl: we should release the tp also, and
10901                                  * use a compressed state.
10902                                  */
10903                                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
10904                                         soisdisconnected(so);
10905                                         tcp_timer_activate(tp, TT_2MSL,
10906                                             (tcp_fast_finwait2_recycle ?
10907                                             tcp_finwait2_timeout :
10908                                             TP_MAXIDLE(tp)));
10909                                 }
10910                                 tcp_state_change(tp, TCPS_FIN_WAIT_2);
10911                         }
10912                 }
10913         }
10914         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
10915            tiwin, thflags, nxt_pkt));
10916 }
10917
10918 /*
10919  * Return value of 1, the TCB is unlocked and most
10920  * likely gone, return value of 0, the TCP is still
10921  * locked.
10922  */
10923 static int
10924 rack_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
10925     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
10926     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
10927 {
10928         struct tcp_rack *rack;
10929         int32_t ret_val = 0;
10930         int32_t ourfinisacked = 0;
10931
10932         ctf_calc_rwin(so, tp);
10933         if ((thflags & TH_ACK) &&
10934             (SEQ_LEQ(th->th_ack, tp->snd_una) ||
10935             SEQ_GT(th->th_ack, tp->snd_max))) {
10936                 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
10937                 ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
10938                 return (1);
10939         }
10940         rack = (struct tcp_rack *)tp->t_fb_ptr;
10941         if (IS_FASTOPEN(tp->t_flags)) {
10942                 /*
10943                  * When a TFO connection is in SYN_RECEIVED, the
10944                  * only valid packets are the initial SYN, a
10945                  * retransmit/copy of the initial SYN (possibly with
10946                  * a subset of the original data), a valid ACK, a
10947                  * FIN, or a RST.
10948                  */
10949                 if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
10950                         tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
10951                         ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
10952                         return (1);
10953                 } else if (thflags & TH_SYN) {
10954                         /* non-initial SYN is ignored */
10955                         if ((rack->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
10956                             (rack->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
10957                             (rack->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
10958                                 ctf_do_drop(m, NULL);
10959                                 return (0);
10960                         }
10961                 } else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
10962                         ctf_do_drop(m, NULL);
10963                         return (0);
10964                 }
10965         }
10966         if ((thflags & TH_RST) ||
10967             (tp->t_fin_is_rst && (thflags & TH_FIN)))
10968                 return (ctf_process_rst(m, th, so, tp));
10969         /*
10970          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
10971          * it's less than ts_recent, drop it.
10972          */
10973         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
10974             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
10975                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
10976                         return (ret_val);
10977         }
10978         /*
10979          * In the SYN-RECEIVED state, validate that the packet belongs to
10980          * this connection before trimming the data to fit the receive
10981          * window.  Check the sequence number versus IRS since we know the
10982          * sequence numbers haven't wrapped.  This is a partial fix for the
10983          * "LAND" DoS attack.
10984          */
10985         if (SEQ_LT(th->th_seq, tp->irs)) {
10986                 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
10987                 ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
10988                 return (1);
10989         }
10990         if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
10991                               &rack->r_ctl.challenge_ack_ts,
10992                               &rack->r_ctl.challenge_ack_cnt)) {
10993                 return (ret_val);
10994         }
10995         /*
10996          * If last ACK falls within this segment's sequence numbers, record
10997          * its timestamp. NOTE: 1) That the test incorporates suggestions
10998          * from the latest proposal of the tcplw@cray.com list (Braden
10999          * 1993/04/26). 2) That updating only on newer timestamps interferes
11000          * with our earlier PAWS tests, so this check should be solely
11001          * predicated on the sequence space of this segment. 3) That we
11002          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
11003          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
11004          * SEG.Len, This modified check allows us to overcome RFC1323's
11005          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
11006          * p.869. In such cases, we can still calculate the RTT correctly
11007          * when RCV.NXT == Last.ACK.Sent.
11008          */
11009         if ((to->to_flags & TOF_TS) != 0 &&
11010             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
11011             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
11012             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
11013                 tp->ts_recent_age = tcp_ts_getticks();
11014                 tp->ts_recent = to->to_tsval;
11015         }
11016         tp->snd_wnd = tiwin;
11017         rack_validate_fo_sendwin_up(tp, rack);
11018         /*
11019          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
11020          * is on (half-synchronized state), then queue data for later
11021          * processing; else drop segment and return.
11022          */
11023         if ((thflags & TH_ACK) == 0) {
11024                 if (IS_FASTOPEN(tp->t_flags)) {
11025                         rack_cc_conn_init(tp);
11026                 }
11027                 return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11028                     tiwin, thflags, nxt_pkt));
11029         }
11030         KMOD_TCPSTAT_INC(tcps_connects);
11031         soisconnected(so);
11032         /* Do window scaling? */
11033         if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
11034             (TF_RCVD_SCALE | TF_REQ_SCALE)) {
11035                 tp->rcv_scale = tp->request_r_scale;
11036         }
11037         /*
11038          * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
11039          * FIN-WAIT-1
11040          */
11041         tp->t_starttime = ticks;
11042         if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
11043                 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
11044                 tp->t_tfo_pending = NULL;
11045         }
11046         if (tp->t_flags & TF_NEEDFIN) {
11047                 tcp_state_change(tp, TCPS_FIN_WAIT_1);
11048                 tp->t_flags &= ~TF_NEEDFIN;
11049         } else {
11050                 tcp_state_change(tp, TCPS_ESTABLISHED);
11051                 TCP_PROBE5(accept__established, NULL, tp,
11052                     mtod(m, const char *), tp, th);
11053                 /*
11054                  * TFO connections call cc_conn_init() during SYN
11055                  * processing.  Calling it again here for such connections
11056                  * is not harmless as it would undo the snd_cwnd reduction
11057                  * that occurs when a TFO SYN|ACK is retransmitted.
11058                  */
11059                 if (!IS_FASTOPEN(tp->t_flags))
11060                         rack_cc_conn_init(tp);
11061         }
11062         /*
11063          * Account for the ACK of our SYN prior to
11064          * regular ACK processing below, except for
11065          * simultaneous SYN, which is handled later.
11066          */
11067         if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
11068                 tp->snd_una++;
11069         /*
11070          * If segment contains data or ACK, will call tcp_reass() later; if
11071          * not, do so now to pass queued data to user.
11072          */
11073         if (tlen == 0 && (thflags & TH_FIN) == 0)
11074                 (void) tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
11075                     (struct mbuf *)0);
11076         tp->snd_wl1 = th->th_seq - 1;
11077         /* For syn-recv we need to possibly update the rtt */
11078         if ((to->to_flags & TOF_TS) != 0 && to->to_tsecr) {
11079                 uint32_t t, mcts;
11080
11081                 mcts = tcp_ts_getticks();
11082                 t = (mcts - to->to_tsecr) * HPTS_USEC_IN_MSEC;
11083                 if (!tp->t_rttlow || tp->t_rttlow > t)
11084                         tp->t_rttlow = t;
11085                 rack_log_rtt_sample_calc(rack, t, (to->to_tsecr * 1000), (mcts * 1000), 5);
11086                 tcp_rack_xmit_timer(rack, t + 1, 1, t, 0, NULL, 2);
11087                 tcp_rack_xmit_timer_commit(rack, tp);
11088         }
11089         if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
11090                 return (ret_val);
11091         }
11092         if (tp->t_state == TCPS_FIN_WAIT_1) {
11093                 /* We could have went to FIN_WAIT_1 (or EST) above */
11094                 /*
11095                  * In FIN_WAIT_1 STATE in addition to the processing for the
11096                  * ESTABLISHED state if our FIN is now acknowledged then
11097                  * enter FIN_WAIT_2.
11098                  */
11099                 if (ourfinisacked) {
11100                         /*
11101                          * If we can't receive any more data, then closing
11102                          * user can proceed. Starting the timer is contrary
11103                          * to the specification, but if we don't get a FIN
11104                          * we'll hang forever.
11105                          *
11106                          * XXXjl: we should release the tp also, and use a
11107                          * compressed state.
11108                          */
11109                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
11110                                 soisdisconnected(so);
11111                                 tcp_timer_activate(tp, TT_2MSL,
11112                                     (tcp_fast_finwait2_recycle ?
11113                                     tcp_finwait2_timeout :
11114                                     TP_MAXIDLE(tp)));
11115                         }
11116                         tcp_state_change(tp, TCPS_FIN_WAIT_2);
11117                 }
11118         }
11119         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11120             tiwin, thflags, nxt_pkt));
11121 }
11122
11123 /*
11124  * Return value of 1, the TCB is unlocked and most
11125  * likely gone, return value of 0, the TCP is still
11126  * locked.
11127  */
11128 static int
11129 rack_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
11130     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
11131     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
11132 {
11133         int32_t ret_val = 0;
11134         struct tcp_rack *rack;
11135
11136         /*
11137          * Header prediction: check for the two common cases of a
11138          * uni-directional data xfer.  If the packet has no control flags,
11139          * is in-sequence, the window didn't change and we're not
11140          * retransmitting, it's a candidate.  If the length is zero and the
11141          * ack moved forward, we're the sender side of the xfer.  Just free
11142          * the data acked & wake any higher level process that was blocked
11143          * waiting for space.  If the length is non-zero and the ack didn't
11144          * move, we're the receiver side.  If we're getting packets in-order
11145          * (the reassembly queue is empty), add the data toc The socket
11146          * buffer and note that we need a delayed ack. Make sure that the
11147          * hidden state-flags are also off. Since we check for
11148          * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
11149          */
11150         rack = (struct tcp_rack *)tp->t_fb_ptr;
11151         if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
11152             __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_ACK)) == TH_ACK) &&
11153             __predict_true(SEGQ_EMPTY(tp)) &&
11154             __predict_true(th->th_seq == tp->rcv_nxt)) {
11155                 if (tlen == 0) {
11156                         if (rack_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
11157                             tiwin, nxt_pkt, rack->r_ctl.rc_rcvtime)) {
11158                                 return (0);
11159                         }
11160                 } else {
11161                         if (rack_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
11162                             tiwin, nxt_pkt, iptos)) {
11163                                 return (0);
11164                         }
11165                 }
11166         }
11167         ctf_calc_rwin(so, tp);
11168
11169         if ((thflags & TH_RST) ||
11170             (tp->t_fin_is_rst && (thflags & TH_FIN)))
11171                 return (ctf_process_rst(m, th, so, tp));
11172
11173         /*
11174          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
11175          * synchronized state.
11176          */
11177         if (thflags & TH_SYN) {
11178                 ctf_challenge_ack(m, th, tp, &ret_val);
11179                 return (ret_val);
11180         }
11181         /*
11182          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
11183          * it's less than ts_recent, drop it.
11184          */
11185         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
11186             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
11187                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
11188                         return (ret_val);
11189         }
11190         if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
11191                               &rack->r_ctl.challenge_ack_ts,
11192                               &rack->r_ctl.challenge_ack_cnt)) {
11193                 return (ret_val);
11194         }
11195         /*
11196          * If last ACK falls within this segment's sequence numbers, record
11197          * its timestamp. NOTE: 1) That the test incorporates suggestions
11198          * from the latest proposal of the tcplw@cray.com list (Braden
11199          * 1993/04/26). 2) That updating only on newer timestamps interferes
11200          * with our earlier PAWS tests, so this check should be solely
11201          * predicated on the sequence space of this segment. 3) That we
11202          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
11203          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
11204          * SEG.Len, This modified check allows us to overcome RFC1323's
11205          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
11206          * p.869. In such cases, we can still calculate the RTT correctly
11207          * when RCV.NXT == Last.ACK.Sent.
11208          */
11209         if ((to->to_flags & TOF_TS) != 0 &&
11210             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
11211             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
11212             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
11213                 tp->ts_recent_age = tcp_ts_getticks();
11214                 tp->ts_recent = to->to_tsval;
11215         }
11216         /*
11217          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
11218          * is on (half-synchronized state), then queue data for later
11219          * processing; else drop segment and return.
11220          */
11221         if ((thflags & TH_ACK) == 0) {
11222                 if (tp->t_flags & TF_NEEDSYN) {
11223                         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11224                             tiwin, thflags, nxt_pkt));
11225
11226                 } else if (tp->t_flags & TF_ACKNOW) {
11227                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
11228                         ((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
11229                         return (ret_val);
11230                 } else {
11231                         ctf_do_drop(m, NULL);
11232                         return (0);
11233                 }
11234         }
11235         /*
11236          * Ack processing.
11237          */
11238         if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
11239                 return (ret_val);
11240         }
11241         if (sbavail(&so->so_snd)) {
11242                 if (ctf_progress_timeout_check(tp, true)) {
11243                         rack_log_progress_event(rack, tp, tick, PROGRESS_DROP, __LINE__);
11244                         tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
11245                         ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11246                         return (1);
11247                 }
11248         }
11249         /* State changes only happen in rack_process_data() */
11250         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11251             tiwin, thflags, nxt_pkt));
11252 }
11253
11254 /*
11255  * Return value of 1, the TCB is unlocked and most
11256  * likely gone, return value of 0, the TCP is still
11257  * locked.
11258  */
11259 static int
11260 rack_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
11261     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
11262     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
11263 {
11264         int32_t ret_val = 0;
11265         struct tcp_rack *rack;
11266
11267         rack = (struct tcp_rack *)tp->t_fb_ptr;
11268         ctf_calc_rwin(so, tp);
11269         if ((thflags & TH_RST) ||
11270             (tp->t_fin_is_rst && (thflags & TH_FIN)))
11271                 return (ctf_process_rst(m, th, so, tp));
11272         /*
11273          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
11274          * synchronized state.
11275          */
11276         if (thflags & TH_SYN) {
11277                 ctf_challenge_ack(m, th, tp, &ret_val);
11278                 return (ret_val);
11279         }
11280         /*
11281          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
11282          * it's less than ts_recent, drop it.
11283          */
11284         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
11285             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
11286                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
11287                         return (ret_val);
11288         }
11289         if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
11290                               &rack->r_ctl.challenge_ack_ts,
11291                               &rack->r_ctl.challenge_ack_cnt)) {
11292                 return (ret_val);
11293         }
11294         /*
11295          * If last ACK falls within this segment's sequence numbers, record
11296          * its timestamp. NOTE: 1) That the test incorporates suggestions
11297          * from the latest proposal of the tcplw@cray.com list (Braden
11298          * 1993/04/26). 2) That updating only on newer timestamps interferes
11299          * with our earlier PAWS tests, so this check should be solely
11300          * predicated on the sequence space of this segment. 3) That we
11301          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
11302          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
11303          * SEG.Len, This modified check allows us to overcome RFC1323's
11304          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
11305          * p.869. In such cases, we can still calculate the RTT correctly
11306          * when RCV.NXT == Last.ACK.Sent.
11307          */
11308         if ((to->to_flags & TOF_TS) != 0 &&
11309             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
11310             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
11311             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
11312                 tp->ts_recent_age = tcp_ts_getticks();
11313                 tp->ts_recent = to->to_tsval;
11314         }
11315         /*
11316          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
11317          * is on (half-synchronized state), then queue data for later
11318          * processing; else drop segment and return.
11319          */
11320         if ((thflags & TH_ACK) == 0) {
11321                 if (tp->t_flags & TF_NEEDSYN) {
11322                         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11323                             tiwin, thflags, nxt_pkt));
11324
11325                 } else if (tp->t_flags & TF_ACKNOW) {
11326                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
11327                         ((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
11328                         return (ret_val);
11329                 } else {
11330                         ctf_do_drop(m, NULL);
11331                         return (0);
11332                 }
11333         }
11334         /*
11335          * Ack processing.
11336          */
11337         if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
11338                 return (ret_val);
11339         }
11340         if (sbavail(&so->so_snd)) {
11341                 if (ctf_progress_timeout_check(tp, true)) {
11342                         rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
11343                                                 tp, tick, PROGRESS_DROP, __LINE__);
11344                         tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
11345                         ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11346                         return (1);
11347                 }
11348         }
11349         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11350             tiwin, thflags, nxt_pkt));
11351 }
11352
11353 static int
11354 rack_check_data_after_close(struct mbuf *m,
11355     struct tcpcb *tp, int32_t *tlen, struct tcphdr *th, struct socket *so)
11356 {
11357         struct tcp_rack *rack;
11358
11359         rack = (struct tcp_rack *)tp->t_fb_ptr;
11360         if (rack->rc_allow_data_af_clo == 0) {
11361         close_now:
11362                 tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
11363                 /* tcp_close will kill the inp pre-log the Reset */
11364                 tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
11365                 tp = tcp_close(tp);
11366                 KMOD_TCPSTAT_INC(tcps_rcvafterclose);
11367                 ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
11368                 return (1);
11369         }
11370         if (sbavail(&so->so_snd) == 0)
11371                 goto close_now;
11372         /* Ok we allow data that is ignored and a followup reset */
11373         tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
11374         tp->rcv_nxt = th->th_seq + *tlen;
11375         tp->t_flags2 |= TF2_DROP_AF_DATA;
11376         rack->r_wanted_output = 1;
11377         *tlen = 0;
11378         return (0);
11379 }
11380
11381 /*
11382  * Return value of 1, the TCB is unlocked and most
11383  * likely gone, return value of 0, the TCP is still
11384  * locked.
11385  */
11386 static int
11387 rack_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
11388     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
11389     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
11390 {
11391         int32_t ret_val = 0;
11392         int32_t ourfinisacked = 0;
11393         struct tcp_rack *rack;
11394
11395         rack = (struct tcp_rack *)tp->t_fb_ptr;
11396         ctf_calc_rwin(so, tp);
11397
11398         if ((thflags & TH_RST) ||
11399             (tp->t_fin_is_rst && (thflags & TH_FIN)))
11400                 return (ctf_process_rst(m, th, so, tp));
11401         /*
11402          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
11403          * synchronized state.
11404          */
11405         if (thflags & TH_SYN) {
11406                 ctf_challenge_ack(m, th, tp, &ret_val);
11407                 return (ret_val);
11408         }
11409         /*
11410          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
11411          * it's less than ts_recent, drop it.
11412          */
11413         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
11414             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
11415                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
11416                         return (ret_val);
11417         }
11418         if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
11419                               &rack->r_ctl.challenge_ack_ts,
11420                               &rack->r_ctl.challenge_ack_cnt)) {
11421                 return (ret_val);
11422         }
11423         /*
11424          * If new data are received on a connection after the user processes
11425          * are gone, then RST the other end.
11426          */
11427         if ((so->so_state & SS_NOFDREF) && tlen) {
11428                 if (rack_check_data_after_close(m, tp, &tlen, th, so))
11429                         return (1);
11430         }
11431         /*
11432          * If last ACK falls within this segment's sequence numbers, record
11433          * its timestamp. NOTE: 1) That the test incorporates suggestions
11434          * from the latest proposal of the tcplw@cray.com list (Braden
11435          * 1993/04/26). 2) That updating only on newer timestamps interferes
11436          * with our earlier PAWS tests, so this check should be solely
11437          * predicated on the sequence space of this segment. 3) That we
11438          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
11439          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
11440          * SEG.Len, This modified check allows us to overcome RFC1323's
11441          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
11442          * p.869. In such cases, we can still calculate the RTT correctly
11443          * when RCV.NXT == Last.ACK.Sent.
11444          */
11445         if ((to->to_flags & TOF_TS) != 0 &&
11446             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
11447             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
11448             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
11449                 tp->ts_recent_age = tcp_ts_getticks();
11450                 tp->ts_recent = to->to_tsval;
11451         }
11452         /*
11453          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
11454          * is on (half-synchronized state), then queue data for later
11455          * processing; else drop segment and return.
11456          */
11457         if ((thflags & TH_ACK) == 0) {
11458                 if (tp->t_flags & TF_NEEDSYN) {
11459                         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11460                             tiwin, thflags, nxt_pkt));
11461                 } else if (tp->t_flags & TF_ACKNOW) {
11462                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
11463                         ((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
11464                         return (ret_val);
11465                 } else {
11466                         ctf_do_drop(m, NULL);
11467                         return (0);
11468                 }
11469         }
11470         /*
11471          * Ack processing.
11472          */
11473         if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
11474                 return (ret_val);
11475         }
11476         if (ourfinisacked) {
11477                 /*
11478                  * If we can't receive any more data, then closing user can
11479                  * proceed. Starting the timer is contrary to the
11480                  * specification, but if we don't get a FIN we'll hang
11481                  * forever.
11482                  *
11483                  * XXXjl: we should release the tp also, and use a
11484                  * compressed state.
11485                  */
11486                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
11487                         soisdisconnected(so);
11488                         tcp_timer_activate(tp, TT_2MSL,
11489                             (tcp_fast_finwait2_recycle ?
11490                             tcp_finwait2_timeout :
11491                             TP_MAXIDLE(tp)));
11492                 }
11493                 tcp_state_change(tp, TCPS_FIN_WAIT_2);
11494         }
11495         if (sbavail(&so->so_snd)) {
11496                 if (ctf_progress_timeout_check(tp, true)) {
11497                         rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
11498                                                 tp, tick, PROGRESS_DROP, __LINE__);
11499                         tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
11500                         ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11501                         return (1);
11502                 }
11503         }
11504         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11505             tiwin, thflags, nxt_pkt));
11506 }
11507
11508 /*
11509  * Return value of 1, the TCB is unlocked and most
11510  * likely gone, return value of 0, the TCP is still
11511  * locked.
11512  */
11513 static int
11514 rack_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
11515     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
11516     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
11517 {
11518         int32_t ret_val = 0;
11519         int32_t ourfinisacked = 0;
11520         struct tcp_rack *rack;
11521
11522         rack = (struct tcp_rack *)tp->t_fb_ptr;
11523         ctf_calc_rwin(so, tp);
11524
11525         if ((thflags & TH_RST) ||
11526             (tp->t_fin_is_rst && (thflags & TH_FIN)))
11527                 return (ctf_process_rst(m, th, so, tp));
11528         /*
11529          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
11530          * synchronized state.
11531          */
11532         if (thflags & TH_SYN) {
11533                 ctf_challenge_ack(m, th, tp, &ret_val);
11534                 return (ret_val);
11535         }
11536         /*
11537          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
11538          * it's less than ts_recent, drop it.
11539          */
11540         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
11541             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
11542                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
11543                         return (ret_val);
11544         }
11545         if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
11546                               &rack->r_ctl.challenge_ack_ts,
11547                               &rack->r_ctl.challenge_ack_cnt)) {
11548                 return (ret_val);
11549         }
11550         /*
11551          * If new data are received on a connection after the user processes
11552          * are gone, then RST the other end.
11553          */
11554         if ((so->so_state & SS_NOFDREF) && tlen) {
11555                 if (rack_check_data_after_close(m, tp, &tlen, th, so))
11556                         return (1);
11557         }
11558         /*
11559          * If last ACK falls within this segment's sequence numbers, record
11560          * its timestamp. NOTE: 1) That the test incorporates suggestions
11561          * from the latest proposal of the tcplw@cray.com list (Braden
11562          * 1993/04/26). 2) That updating only on newer timestamps interferes
11563          * with our earlier PAWS tests, so this check should be solely
11564          * predicated on the sequence space of this segment. 3) That we
11565          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
11566          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
11567          * SEG.Len, This modified check allows us to overcome RFC1323's
11568          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
11569          * p.869. In such cases, we can still calculate the RTT correctly
11570          * when RCV.NXT == Last.ACK.Sent.
11571          */
11572         if ((to->to_flags & TOF_TS) != 0 &&
11573             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
11574             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
11575             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
11576                 tp->ts_recent_age = tcp_ts_getticks();
11577                 tp->ts_recent = to->to_tsval;
11578         }
11579         /*
11580          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
11581          * is on (half-synchronized state), then queue data for later
11582          * processing; else drop segment and return.
11583          */
11584         if ((thflags & TH_ACK) == 0) {
11585                 if (tp->t_flags & TF_NEEDSYN) {
11586                         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11587                             tiwin, thflags, nxt_pkt));
11588                 } else if (tp->t_flags & TF_ACKNOW) {
11589                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
11590                         ((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
11591                         return (ret_val);
11592                 } else {
11593                         ctf_do_drop(m, NULL);
11594                         return (0);
11595                 }
11596         }
11597         /*
11598          * Ack processing.
11599          */
11600         if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
11601                 return (ret_val);
11602         }
11603         if (ourfinisacked) {
11604                 tcp_twstart(tp);
11605                 m_freem(m);
11606                 return (1);
11607         }
11608         if (sbavail(&so->so_snd)) {
11609                 if (ctf_progress_timeout_check(tp, true)) {
11610                         rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
11611                                                 tp, tick, PROGRESS_DROP, __LINE__);
11612                         tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
11613                         ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11614                         return (1);
11615                 }
11616         }
11617         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11618             tiwin, thflags, nxt_pkt));
11619 }
11620
11621 /*
11622  * Return value of 1, the TCB is unlocked and most
11623  * likely gone, return value of 0, the TCP is still
11624  * locked.
11625  */
11626 static int
11627 rack_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
11628     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
11629     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
11630 {
11631         int32_t ret_val = 0;
11632         int32_t ourfinisacked = 0;
11633         struct tcp_rack *rack;
11634
11635         rack = (struct tcp_rack *)tp->t_fb_ptr;
11636         ctf_calc_rwin(so, tp);
11637
11638         if ((thflags & TH_RST) ||
11639             (tp->t_fin_is_rst && (thflags & TH_FIN)))
11640                 return (ctf_process_rst(m, th, so, tp));
11641         /*
11642          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
11643          * synchronized state.
11644          */
11645         if (thflags & TH_SYN) {
11646                 ctf_challenge_ack(m, th, tp, &ret_val);
11647                 return (ret_val);
11648         }
11649         /*
11650          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
11651          * it's less than ts_recent, drop it.
11652          */
11653         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
11654             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
11655                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
11656                         return (ret_val);
11657         }
11658         if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
11659                               &rack->r_ctl.challenge_ack_ts,
11660                               &rack->r_ctl.challenge_ack_cnt)) {
11661                 return (ret_val);
11662         }
11663         /*
11664          * If new data are received on a connection after the user processes
11665          * are gone, then RST the other end.
11666          */
11667         if ((so->so_state & SS_NOFDREF) && tlen) {
11668                 if (rack_check_data_after_close(m, tp, &tlen, th, so))
11669                         return (1);
11670         }
11671         /*
11672          * If last ACK falls within this segment's sequence numbers, record
11673          * its timestamp. NOTE: 1) That the test incorporates suggestions
11674          * from the latest proposal of the tcplw@cray.com list (Braden
11675          * 1993/04/26). 2) That updating only on newer timestamps interferes
11676          * with our earlier PAWS tests, so this check should be solely
11677          * predicated on the sequence space of this segment. 3) That we
11678          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
11679          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
11680          * SEG.Len, This modified check allows us to overcome RFC1323's
11681          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
11682          * p.869. In such cases, we can still calculate the RTT correctly
11683          * when RCV.NXT == Last.ACK.Sent.
11684          */
11685         if ((to->to_flags & TOF_TS) != 0 &&
11686             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
11687             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
11688             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
11689                 tp->ts_recent_age = tcp_ts_getticks();
11690                 tp->ts_recent = to->to_tsval;
11691         }
11692         /*
11693          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
11694          * is on (half-synchronized state), then queue data for later
11695          * processing; else drop segment and return.
11696          */
11697         if ((thflags & TH_ACK) == 0) {
11698                 if (tp->t_flags & TF_NEEDSYN) {
11699                         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11700                             tiwin, thflags, nxt_pkt));
11701                 } else if (tp->t_flags & TF_ACKNOW) {
11702                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
11703                         ((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
11704                         return (ret_val);
11705                 } else {
11706                         ctf_do_drop(m, NULL);
11707                         return (0);
11708                 }
11709         }
11710         /*
11711          * case TCPS_LAST_ACK: Ack processing.
11712          */
11713         if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
11714                 return (ret_val);
11715         }
11716         if (ourfinisacked) {
11717                 tp = tcp_close(tp);
11718                 ctf_do_drop(m, tp);
11719                 return (1);
11720         }
11721         if (sbavail(&so->so_snd)) {
11722                 if (ctf_progress_timeout_check(tp, true)) {
11723                         rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
11724                                                 tp, tick, PROGRESS_DROP, __LINE__);
11725                         tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
11726                         ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11727                         return (1);
11728                 }
11729         }
11730         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11731             tiwin, thflags, nxt_pkt));
11732 }
11733
11734 /*
11735  * Return value of 1, the TCB is unlocked and most
11736  * likely gone, return value of 0, the TCP is still
11737  * locked.
11738  */
11739 static int
11740 rack_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
11741     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
11742     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
11743 {
11744         int32_t ret_val = 0;
11745         int32_t ourfinisacked = 0;
11746         struct tcp_rack *rack;
11747
11748         rack = (struct tcp_rack *)tp->t_fb_ptr;
11749         ctf_calc_rwin(so, tp);
11750
11751         /* Reset receive buffer auto scaling when not in bulk receive mode. */
11752         if ((thflags & TH_RST) ||
11753             (tp->t_fin_is_rst && (thflags & TH_FIN)))
11754                 return (ctf_process_rst(m, th, so, tp));
11755         /*
11756          * RFC5961 Section 4.2 Send challenge ACK for any SYN in
11757          * synchronized state.
11758          */
11759         if (thflags & TH_SYN) {
11760                 ctf_challenge_ack(m, th, tp, &ret_val);
11761                 return (ret_val);
11762         }
11763         /*
11764          * RFC 1323 PAWS: If we have a timestamp reply on this segment and
11765          * it's less than ts_recent, drop it.
11766          */
11767         if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
11768             TSTMP_LT(to->to_tsval, tp->ts_recent)) {
11769                 if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
11770                         return (ret_val);
11771         }
11772         if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
11773                               &rack->r_ctl.challenge_ack_ts,
11774                               &rack->r_ctl.challenge_ack_cnt)) {
11775                 return (ret_val);
11776         }
11777         /*
11778          * If new data are received on a connection after the user processes
11779          * are gone, then RST the other end.
11780          */
11781         if ((so->so_state & SS_NOFDREF) &&
11782             tlen) {
11783                 if (rack_check_data_after_close(m, tp, &tlen, th, so))
11784                         return (1);
11785         }
11786         /*
11787          * If last ACK falls within this segment's sequence numbers, record
11788          * its timestamp. NOTE: 1) That the test incorporates suggestions
11789          * from the latest proposal of the tcplw@cray.com list (Braden
11790          * 1993/04/26). 2) That updating only on newer timestamps interferes
11791          * with our earlier PAWS tests, so this check should be solely
11792          * predicated on the sequence space of this segment. 3) That we
11793          * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
11794          * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
11795          * SEG.Len, This modified check allows us to overcome RFC1323's
11796          * limitations as described in Stevens TCP/IP Illustrated Vol. 2
11797          * p.869. In such cases, we can still calculate the RTT correctly
11798          * when RCV.NXT == Last.ACK.Sent.
11799          */
11800         if ((to->to_flags & TOF_TS) != 0 &&
11801             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
11802             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
11803             ((thflags & (TH_SYN | TH_FIN)) != 0))) {
11804                 tp->ts_recent_age = tcp_ts_getticks();
11805                 tp->ts_recent = to->to_tsval;
11806         }
11807         /*
11808          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
11809          * is on (half-synchronized state), then queue data for later
11810          * processing; else drop segment and return.
11811          */
11812         if ((thflags & TH_ACK) == 0) {
11813                 if (tp->t_flags & TF_NEEDSYN) {
11814                         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11815                             tiwin, thflags, nxt_pkt));
11816                 } else if (tp->t_flags & TF_ACKNOW) {
11817                         ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
11818                         ((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
11819                         return (ret_val);
11820                 } else {
11821                         ctf_do_drop(m, NULL);
11822                         return (0);
11823                 }
11824         }
11825         /*
11826          * Ack processing.
11827          */
11828         if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
11829                 return (ret_val);
11830         }
11831         if (sbavail(&so->so_snd)) {
11832                 if (ctf_progress_timeout_check(tp, true)) {
11833                         rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
11834                                                 tp, tick, PROGRESS_DROP, __LINE__);
11835                         tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
11836                         ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11837                         return (1);
11838                 }
11839         }
11840         return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11841             tiwin, thflags, nxt_pkt));
11842 }
11843
11844 static void inline
11845 rack_clear_rate_sample(struct tcp_rack *rack)
11846 {
11847         rack->r_ctl.rack_rs.rs_flags = RACK_RTT_EMPTY;
11848         rack->r_ctl.rack_rs.rs_rtt_cnt = 0;
11849         rack->r_ctl.rack_rs.rs_rtt_tot = 0;
11850 }
11851
11852 static void
11853 rack_set_pace_segments(struct tcpcb *tp, struct tcp_rack *rack, uint32_t line, uint64_t *fill_override)
11854 {
11855         uint64_t bw_est, rate_wanted;
11856         int chged = 0;
11857         uint32_t user_max, orig_min, orig_max;
11858
11859         orig_min = rack->r_ctl.rc_pace_min_segs;
11860         orig_max = rack->r_ctl.rc_pace_max_segs;
11861         user_max = ctf_fixed_maxseg(tp) * rack->rc_user_set_max_segs;
11862         if (ctf_fixed_maxseg(tp) != rack->r_ctl.rc_pace_min_segs)
11863                 chged = 1;
11864         rack->r_ctl.rc_pace_min_segs = ctf_fixed_maxseg(tp);
11865         if (rack->use_fixed_rate || rack->rc_force_max_seg) {
11866                 if (user_max != rack->r_ctl.rc_pace_max_segs)
11867                         chged = 1;
11868         }
11869         if (rack->rc_force_max_seg) {
11870                 rack->r_ctl.rc_pace_max_segs = user_max;
11871         } else if (rack->use_fixed_rate) {
11872                 bw_est = rack_get_bw(rack);
11873                 if ((rack->r_ctl.crte == NULL) ||
11874                     (bw_est != rack->r_ctl.crte->rate)) {
11875                         rack->r_ctl.rc_pace_max_segs = user_max;
11876                 } else {
11877                         /* We are pacing right at the hardware rate */
11878                         uint32_t segsiz;
11879
11880                         segsiz = min(ctf_fixed_maxseg(tp),
11881                                      rack->r_ctl.rc_pace_min_segs);
11882                         rack->r_ctl.rc_pace_max_segs = tcp_get_pacing_burst_size(
11883                                                            tp, bw_est, segsiz, 0,
11884                                                            rack->r_ctl.crte, NULL);
11885                 }
11886         } else if (rack->rc_always_pace) {
11887                 if (rack->r_ctl.gp_bw ||
11888 #ifdef NETFLIX_PEAKRATE
11889                     rack->rc_tp->t_maxpeakrate ||
11890 #endif
11891                     rack->r_ctl.init_rate) {
11892                         /* We have a rate of some sort set */
11893                         uint32_t  orig;
11894
11895                         bw_est = rack_get_bw(rack);
11896                         orig = rack->r_ctl.rc_pace_max_segs;
11897                         if (fill_override)
11898                                 rate_wanted = *fill_override;
11899                         else
11900                                 rate_wanted = rack_get_output_bw(rack, bw_est, NULL, NULL);
11901                         if (rate_wanted) {
11902                                 /* We have something */
11903                                 rack->r_ctl.rc_pace_max_segs = rack_get_pacing_len(rack,
11904                                                                                    rate_wanted,
11905                                                                                    ctf_fixed_maxseg(rack->rc_tp));
11906                         } else
11907                                 rack->r_ctl.rc_pace_max_segs = rack->r_ctl.rc_pace_min_segs;
11908                         if (orig != rack->r_ctl.rc_pace_max_segs)
11909                                 chged = 1;
11910                 } else if ((rack->r_ctl.gp_bw == 0) &&
11911                            (rack->r_ctl.rc_pace_max_segs == 0)) {
11912                         /*
11913                          * If we have nothing limit us to bursting
11914                          * out IW sized pieces.
11915                          */
11916                         chged = 1;
11917                         rack->r_ctl.rc_pace_max_segs = rc_init_window(rack);
11918                 }
11919         }
11920         if (rack->r_ctl.rc_pace_max_segs > PACE_MAX_IP_BYTES) {
11921                 chged = 1;
11922                 rack->r_ctl.rc_pace_max_segs = PACE_MAX_IP_BYTES;
11923         }
11924         if (chged)
11925                 rack_log_type_pacing_sizes(tp, rack, orig_min, orig_max, line, 2);
11926 }
11927
11928
11929 static void
11930 rack_init_fsb_block(struct tcpcb *tp, struct tcp_rack *rack)
11931 {
11932 #ifdef INET6
11933         struct ip6_hdr *ip6 = NULL;
11934 #endif
11935 #ifdef INET
11936         struct ip *ip = NULL;
11937 #endif
11938         struct udphdr *udp = NULL;
11939
11940         /* Ok lets fill in the fast block, it can only be used with no IP options! */
11941 #ifdef INET6
11942         if (rack->r_is_v6) {
11943                 rack->r_ctl.fsb.tcp_ip_hdr_len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
11944                 ip6 = (struct ip6_hdr *)rack->r_ctl.fsb.tcp_ip_hdr;
11945                 if (tp->t_port) {
11946                         rack->r_ctl.fsb.tcp_ip_hdr_len += sizeof(struct udphdr);
11947                         udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
11948                         udp->uh_sport = htons(V_tcp_udp_tunneling_port);
11949                         udp->uh_dport = tp->t_port;
11950                         rack->r_ctl.fsb.udp = udp;
11951                         rack->r_ctl.fsb.th = (struct tcphdr *)(udp + 1);
11952                 } else
11953                 {
11954                         rack->r_ctl.fsb.th = (struct tcphdr *)(ip6 + 1);
11955                         rack->r_ctl.fsb.udp = NULL;
11956                 }
11957                 tcpip_fillheaders(rack->rc_inp,
11958                                   tp->t_port,
11959                                   ip6, rack->r_ctl.fsb.th);
11960         } else
11961 #endif                          /* INET6 */
11962         {
11963                 rack->r_ctl.fsb.tcp_ip_hdr_len = sizeof(struct tcpiphdr);
11964                 ip = (struct ip *)rack->r_ctl.fsb.tcp_ip_hdr;
11965                 if (tp->t_port) {
11966                         rack->r_ctl.fsb.tcp_ip_hdr_len += sizeof(struct udphdr);
11967                         udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
11968                         udp->uh_sport = htons(V_tcp_udp_tunneling_port);
11969                         udp->uh_dport = tp->t_port;
11970                         rack->r_ctl.fsb.udp = udp;
11971                         rack->r_ctl.fsb.th = (struct tcphdr *)(udp + 1);
11972                 } else
11973                 {
11974                         rack->r_ctl.fsb.udp = NULL;
11975                         rack->r_ctl.fsb.th = (struct tcphdr *)(ip + 1);
11976                 }
11977                 tcpip_fillheaders(rack->rc_inp,
11978                                   tp->t_port,
11979                                   ip, rack->r_ctl.fsb.th);
11980         }
11981         rack->r_fsb_inited = 1;
11982 }
11983
11984 static int
11985 rack_init_fsb(struct tcpcb *tp, struct tcp_rack *rack)
11986 {
11987         /*
11988          * Allocate the larger of spaces V6 if available else just
11989          * V4 and include udphdr (overbook)
11990          */
11991 #ifdef INET6
11992         rack->r_ctl.fsb.tcp_ip_hdr_len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr) + sizeof(struct udphdr);
11993 #else
11994         rack->r_ctl.fsb.tcp_ip_hdr_len = sizeof(struct tcpiphdr) + sizeof(struct udphdr);
11995 #endif
11996         rack->r_ctl.fsb.tcp_ip_hdr = malloc(rack->r_ctl.fsb.tcp_ip_hdr_len,
11997                                             M_TCPFSB, M_NOWAIT|M_ZERO);
11998         if (rack->r_ctl.fsb.tcp_ip_hdr == NULL) {
11999                 return (ENOMEM);
12000         }
12001         rack->r_fsb_inited = 0;
12002         return (0);
12003 }
12004
12005 static int
12006 rack_init(struct tcpcb *tp)
12007 {
12008         struct tcp_rack *rack = NULL;
12009         struct rack_sendmap *insret;
12010         uint32_t iwin, snt, us_cts;
12011         int err;
12012
12013         tp->t_fb_ptr = uma_zalloc(rack_pcb_zone, M_NOWAIT);
12014         if (tp->t_fb_ptr == NULL) {
12015                 /*
12016                  * We need to allocate memory but cant. The INP and INP_INFO
12017                  * locks and they are recusive (happens during setup. So a
12018                  * scheme to drop the locks fails :(
12019                  *
12020                  */
12021                 return (ENOMEM);
12022         }
12023         memset(tp->t_fb_ptr, 0, sizeof(struct tcp_rack));
12024
12025         rack = (struct tcp_rack *)tp->t_fb_ptr;
12026         RB_INIT(&rack->r_ctl.rc_mtree);
12027         TAILQ_INIT(&rack->r_ctl.rc_free);
12028         TAILQ_INIT(&rack->r_ctl.rc_tmap);
12029         rack->rc_tp = tp;
12030         rack->rc_inp = tp->t_inpcb;
12031         /* Set the flag */
12032         rack->r_is_v6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
12033         /* Probably not needed but lets be sure */
12034         rack_clear_rate_sample(rack);
12035         /*
12036          * Save off the default values, socket options will poke
12037          * at these if pacing is not on or we have not yet
12038          * reached where pacing is on (gp_ready/fixed enabled).
12039          * When they get set into the CC module (when gp_ready
12040          * is enabled or we enable fixed) then we will set these
12041          * values into the CC and place in here the old values
12042          * so we have a restoral. Then we will set the flag
12043          * rc_pacing_cc_set. That way whenever we turn off pacing
12044          * or switch off this stack, we will know to go restore
12045          * the saved values.
12046          */
12047         rack->r_ctl.rc_saved_beta.beta = V_newreno_beta_ecn;
12048         rack->r_ctl.rc_saved_beta.beta_ecn = V_newreno_beta_ecn;
12049         /* We want abe like behavior as well */
12050         rack->r_ctl.rc_saved_beta.newreno_flags = CC_NEWRENO_BETA_ECN;
12051         rack->r_ctl.rc_reorder_fade = rack_reorder_fade;
12052         rack->rc_allow_data_af_clo = rack_ignore_data_after_close;
12053         rack->r_ctl.rc_tlp_threshold = rack_tlp_thresh;
12054         if (use_rack_rr)
12055                 rack->use_rack_rr = 1;
12056         if (V_tcp_delack_enabled)
12057                 tp->t_delayed_ack = 1;
12058         else
12059                 tp->t_delayed_ack = 0;
12060 #ifdef TCP_ACCOUNTING
12061         if (rack_tcp_accounting) {
12062                 tp->t_flags2 |= TF2_TCP_ACCOUNTING;
12063         }
12064 #endif
12065         if (rack_enable_shared_cwnd)
12066                 rack->rack_enable_scwnd = 1;
12067         rack->rc_user_set_max_segs = rack_hptsi_segments;
12068         rack->rc_force_max_seg = 0;
12069         if (rack_use_imac_dack)
12070                 rack->rc_dack_mode = 1;
12071         TAILQ_INIT(&rack->r_ctl.opt_list);
12072         rack->r_ctl.rc_reorder_shift = rack_reorder_thresh;
12073         rack->r_ctl.rc_pkt_delay = rack_pkt_delay;
12074         rack->r_ctl.rc_tlp_cwnd_reduce = rack_lower_cwnd_at_tlp;
12075         rack->r_ctl.rc_lowest_us_rtt = 0xffffffff;
12076         rack->r_ctl.rc_highest_us_rtt = 0;
12077         rack->r_ctl.bw_rate_cap = rack_bw_rate_cap;
12078         if (rack_use_cmp_acks)
12079                 rack->r_use_cmp_ack = 1;
12080         if (rack_disable_prr)
12081                 rack->rack_no_prr = 1;
12082         if (rack_gp_no_rec_chg)
12083                 rack->rc_gp_no_rec_chg = 1;
12084         if (rack_pace_every_seg && tcp_can_enable_pacing()) {
12085                 rack->rc_always_pace = 1;
12086                 if (rack->use_fixed_rate || rack->gp_ready)
12087                         rack_set_cc_pacing(rack);
12088         } else
12089                 rack->rc_always_pace = 0;
12090         if (rack_enable_mqueue_for_nonpaced || rack->r_use_cmp_ack)
12091                 rack->r_mbuf_queue = 1;
12092         else
12093                 rack->r_mbuf_queue = 0;
12094         if  (rack->r_mbuf_queue || rack->rc_always_pace || rack->r_use_cmp_ack)
12095                 tp->t_inpcb->inp_flags2 |= INP_SUPPORTS_MBUFQ;
12096         else
12097                 tp->t_inpcb->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
12098         rack_set_pace_segments(tp, rack, __LINE__, NULL);
12099         if (rack_limits_scwnd)
12100                 rack->r_limit_scw = 1;
12101         else
12102                 rack->r_limit_scw = 0;
12103         rack->rc_labc = V_tcp_abc_l_var;
12104         rack->r_ctl.rc_high_rwnd = tp->snd_wnd;
12105         rack->r_ctl.cwnd_to_use = tp->snd_cwnd;
12106         rack->r_ctl.rc_rate_sample_method = rack_rate_sample_method;
12107         rack->rack_tlp_threshold_use = rack_tlp_threshold_use;
12108         rack->r_ctl.rc_prr_sendalot = rack_send_a_lot_in_prr;
12109         rack->r_ctl.rc_min_to = rack_min_to;
12110         microuptime(&rack->r_ctl.act_rcv_time);
12111         rack->r_ctl.rc_last_time_decay = rack->r_ctl.act_rcv_time;
12112         rack->r_running_late = 0;
12113         rack->r_running_early = 0;
12114         rack->rc_init_win = rack_default_init_window;
12115         rack->r_ctl.rack_per_of_gp_ss = rack_per_of_gp_ss;
12116         if (rack_hw_up_only)
12117                 rack->r_up_only = 1;
12118         if (rack_do_dyn_mul) {
12119                 /* When dynamic adjustment is on CA needs to start at 100% */
12120                 rack->rc_gp_dyn_mul = 1;
12121                 if (rack_do_dyn_mul >= 100)
12122                         rack->r_ctl.rack_per_of_gp_ca = rack_do_dyn_mul;
12123         } else
12124                 rack->r_ctl.rack_per_of_gp_ca = rack_per_of_gp_ca;
12125         rack->r_ctl.rack_per_of_gp_rec = rack_per_of_gp_rec;
12126         rack->r_ctl.rack_per_of_gp_probertt = rack_per_of_gp_probertt;
12127         rack->r_ctl.rc_tlp_rxt_last_time = tcp_tv_to_mssectick(&rack->r_ctl.act_rcv_time);
12128         setup_time_filter_small(&rack->r_ctl.rc_gp_min_rtt, FILTER_TYPE_MIN,
12129                                 rack_probertt_filter_life);
12130         us_cts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
12131         rack->r_ctl.rc_lower_rtt_us_cts = us_cts;
12132         rack->r_ctl.rc_time_of_last_probertt = us_cts;
12133         rack->r_ctl.challenge_ack_ts = tcp_ts_getticks();
12134         rack->r_ctl.rc_time_probertt_starts = 0;
12135         /* We require at least one measurement, even if the sysctl is 0 */
12136         if (rack_req_measurements)
12137                 rack->r_ctl.req_measurements = rack_req_measurements;
12138         else
12139                 rack->r_ctl.req_measurements = 1;
12140         if (rack_enable_hw_pacing)
12141                 rack->rack_hdw_pace_ena = 1;
12142         if (rack_hw_rate_caps)
12143                 rack->r_rack_hw_rate_caps = 1;
12144         /* Do we force on detection? */
12145 #ifdef NETFLIX_EXP_DETECTION
12146         if (tcp_force_detection)
12147                 rack->do_detection = 1;
12148         else
12149 #endif
12150                 rack->do_detection = 0;
12151         if (rack_non_rxt_use_cr)
12152                 rack->rack_rec_nonrxt_use_cr = 1;
12153         err = rack_init_fsb(tp, rack);
12154         if (err) {
12155                 uma_zfree(rack_pcb_zone, tp->t_fb_ptr);
12156                 tp->t_fb_ptr = NULL;
12157                 return (err);
12158         }
12159         if (tp->snd_una != tp->snd_max) {
12160                 /* Create a send map for the current outstanding data */
12161                 struct rack_sendmap *rsm;
12162
12163                 rsm = rack_alloc(rack);
12164                 if (rsm == NULL) {
12165                         uma_zfree(rack_pcb_zone, tp->t_fb_ptr);
12166                         tp->t_fb_ptr = NULL;
12167                         return (ENOMEM);
12168                 }
12169                 rsm->r_no_rtt_allowed = 1;
12170                 rsm->r_tim_lastsent[0] = rack_to_usec_ts(&rack->r_ctl.act_rcv_time);
12171                 rsm->r_rtr_cnt = 1;
12172                 rsm->r_rtr_bytes = 0;
12173                 if (tp->t_flags & TF_SENTFIN) {
12174                         rsm->r_end = tp->snd_max - 1;
12175                         rsm->r_flags |= RACK_HAS_FIN;
12176                 } else {
12177                         rsm->r_end = tp->snd_max;
12178                 }
12179                 if (tp->snd_una == tp->iss) {
12180                         /* The data space is one beyond snd_una */
12181                         rsm->r_flags |= RACK_HAS_SYN;
12182                         rsm->r_start = tp->iss;
12183                         rsm->r_end = rsm->r_start + (tp->snd_max - tp->snd_una);
12184                 } else
12185                         rsm->r_start = tp->snd_una;
12186                 rsm->r_dupack = 0;
12187                 if (rack->rc_inp->inp_socket->so_snd.sb_mb != NULL) {
12188                         rsm->m = sbsndmbuf(&rack->rc_inp->inp_socket->so_snd, 0, &rsm->soff);
12189                         rsm->orig_m_len = rsm->m->m_len;
12190                 } else {
12191                         /*
12192                          * This can happen if we have a stand-alone FIN or
12193                          *  SYN.
12194                          */
12195                         rsm->m = NULL;
12196                         rsm->orig_m_len = 0;
12197                         rsm->soff = 0;
12198                 }
12199                 insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
12200 #ifdef INVARIANTS
12201                 if (insret != NULL) {
12202                         panic("Insert in rb tree fails ret:%p rack:%p rsm:%p",
12203                               insret, rack, rsm);
12204                 }
12205 #endif
12206                 TAILQ_INSERT_TAIL(&rack->r_ctl.rc_tmap, rsm, r_tnext);
12207                 rsm->r_in_tmap = 1;
12208         }
12209         /*
12210          * Timers in Rack are kept in microseconds so lets
12211          * convert any initial incoming variables
12212          * from ticks into usecs. Note that we
12213          * also change the values of t_srtt and t_rttvar, if
12214          * they are non-zero. They are kept with a 5
12215          * bit decimal so we have to carefully convert
12216          * these to get the full precision.
12217          */
12218         rack_convert_rtts(tp);
12219         tp->t_rttlow = TICKS_2_USEC(tp->t_rttlow);
12220         if (rack_def_profile)
12221                 rack_set_profile(rack, rack_def_profile);
12222         /* Cancel the GP measurement in progress */
12223         tp->t_flags &= ~TF_GPUTINPROG;
12224         if (SEQ_GT(tp->snd_max, tp->iss))
12225                 snt = tp->snd_max - tp->iss;
12226         else
12227                 snt = 0;
12228         iwin = rc_init_window(rack);
12229         if (snt < iwin) {
12230                 /* We are not past the initial window
12231                  * so we need to make sure cwnd is
12232                  * correct.
12233                  */
12234                 if (tp->snd_cwnd < iwin)
12235                         tp->snd_cwnd = iwin;
12236                 /*
12237                  * If we are within the initial window
12238                  * we want ssthresh to be unlimited. Setting
12239                  * it to the rwnd (which the default stack does
12240                  * and older racks) is not really a good idea
12241                  * since we want to be in SS and grow both the
12242                  * cwnd and the rwnd (via dynamic rwnd growth). If
12243                  * we set it to the rwnd then as the peer grows its
12244                  * rwnd we will be stuck in CA and never hit SS.
12245                  *
12246                  * Its far better to raise it up high (this takes the
12247                  * risk that there as been a loss already, probably
12248                  * we should have an indicator in all stacks of loss
12249                  * but we don't), but considering the normal use this
12250                  * is a risk worth taking. The consequences of not
12251                  * hitting SS are far worse than going one more time
12252                  * into it early on (before we have sent even a IW).
12253                  * It is highly unlikely that we will have had a loss
12254                  * before getting the IW out.
12255                  */
12256                 tp->snd_ssthresh = 0xffffffff;
12257         }
12258         rack_stop_all_timers(tp);
12259         /* Lets setup the fsb block */
12260         rack_start_hpts_timer(rack, tp, tcp_get_usecs(NULL), 0, 0, 0);
12261         rack_log_rtt_shrinks(rack,  us_cts,  tp->t_rxtcur,
12262                              __LINE__, RACK_RTTS_INIT);
12263         return (0);
12264 }
12265
12266 static int
12267 rack_handoff_ok(struct tcpcb *tp)
12268 {
12269         if ((tp->t_state == TCPS_CLOSED) ||
12270             (tp->t_state == TCPS_LISTEN)) {
12271                 /* Sure no problem though it may not stick */
12272                 return (0);
12273         }
12274         if ((tp->t_state == TCPS_SYN_SENT) ||
12275             (tp->t_state == TCPS_SYN_RECEIVED)) {
12276                 /*
12277                  * We really don't know if you support sack,
12278                  * you have to get to ESTAB or beyond to tell.
12279                  */
12280                 return (EAGAIN);
12281         }
12282         if ((tp->t_flags & TF_SENTFIN) && ((tp->snd_max - tp->snd_una) > 1)) {
12283                 /*
12284                  * Rack will only send a FIN after all data is acknowledged.
12285                  * So in this case we have more data outstanding. We can't
12286                  * switch stacks until either all data and only the FIN
12287                  * is left (in which case rack_init() now knows how
12288                  * to deal with that) <or> all is acknowledged and we
12289                  * are only left with incoming data, though why you
12290                  * would want to switch to rack after all data is acknowledged
12291                  * I have no idea (rrs)!
12292                  */
12293                 return (EAGAIN);
12294         }
12295         if ((tp->t_flags & TF_SACK_PERMIT) || rack_sack_not_required){
12296                 return (0);
12297         }
12298         /*
12299          * If we reach here we don't do SACK on this connection so we can
12300          * never do rack.
12301          */
12302         return (EINVAL);
12303 }
12304
12305
12306 static void
12307 rack_fini(struct tcpcb *tp, int32_t tcb_is_purged)
12308 {
12309         int ack_cmp = 0;
12310
12311         if (tp->t_fb_ptr) {
12312                 struct tcp_rack *rack;
12313                 struct rack_sendmap *rsm, *nrsm, *rm;
12314
12315                 rack = (struct tcp_rack *)tp->t_fb_ptr;
12316                 if (tp->t_in_pkt) {
12317                         /*
12318                          * Since we are switching we need to process any
12319                          * inbound packets in case a compressed ack is
12320                          * in queue or the new stack does not support
12321                          * mbuf queuing. These packets in theory should
12322                          * have been handled by the old stack anyway.
12323                          */
12324                         if ((rack->rc_inp->inp_flags & (INP_DROPPED|INP_TIMEWAIT)) ||
12325                             (rack->rc_inp->inp_flags2 & INP_FREED)) {
12326                                 /* Kill all the packets */
12327                                 struct mbuf *save, *m;
12328
12329                                 m = tp->t_in_pkt;
12330                                 tp->t_in_pkt = NULL;
12331                                 tp->t_tail_pkt = NULL;
12332                                 while (m) {
12333                                         save = m->m_nextpkt;
12334                                         m->m_nextpkt = NULL;
12335                                         m_freem(m);
12336                                         m = save;
12337                                 }
12338                         } else {
12339                                 /* Process all the packets */
12340                                 ctf_do_queued_segments(rack->rc_inp->inp_socket, rack->rc_tp, 0);
12341                         }
12342                         if ((tp->t_inpcb) &&
12343                             (tp->t_inpcb->inp_flags2 & INP_MBUF_ACKCMP))
12344                                 ack_cmp = 1;
12345                         if (ack_cmp) {
12346                                 /* Total if we used large or small (if ack-cmp was used). */
12347                                 if (rack->rc_inp->inp_flags2 & INP_MBUF_L_ACKS)
12348                                         counter_u64_add(rack_large_ackcmp, 1);
12349                                 else
12350                                         counter_u64_add(rack_small_ackcmp, 1);
12351                         }
12352                 }
12353                 tp->t_flags &= ~TF_FORCEDATA;
12354 #ifdef NETFLIX_SHARED_CWND
12355                 if (rack->r_ctl.rc_scw) {
12356                         uint32_t limit;
12357
12358                         if (rack->r_limit_scw)
12359                                 limit = max(1, rack->r_ctl.rc_lowest_us_rtt);
12360                         else
12361                                 limit = 0;
12362                         tcp_shared_cwnd_free_full(tp, rack->r_ctl.rc_scw,
12363                                                   rack->r_ctl.rc_scw_index,
12364                                                   limit);
12365                         rack->r_ctl.rc_scw = NULL;
12366                 }
12367 #endif
12368                 if (rack->r_ctl.fsb.tcp_ip_hdr) {
12369                         free(rack->r_ctl.fsb.tcp_ip_hdr, M_TCPFSB);
12370                         rack->r_ctl.fsb.tcp_ip_hdr = NULL;
12371                         rack->r_ctl.fsb.th = NULL;
12372                 }
12373                 /* Convert back to ticks, with  */
12374                 if (tp->t_srtt > 1) {
12375                         uint32_t val, frac;
12376
12377                         val = USEC_2_TICKS(tp->t_srtt);
12378                         frac = tp->t_srtt % (HPTS_USEC_IN_SEC / hz);
12379                         tp->t_srtt = val << TCP_RTT_SHIFT;
12380                         /*
12381                          * frac is the fractional part here is left
12382                          * over from converting to hz and shifting.
12383                          * We need to convert this to the 5 bit
12384                          * remainder.
12385                          */
12386                         if (frac) {
12387                                 if (hz == 1000) {
12388                                         frac = (((uint64_t)frac *  (uint64_t)TCP_RTT_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC);
12389                                 } else {
12390                                         frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE) /(uint64_t)HPTS_USEC_IN_SEC);
12391                                 }
12392                                 tp->t_srtt += frac;
12393                         }
12394                 }
12395                 if (tp->t_rttvar) {
12396                         uint32_t val, frac;
12397
12398                         val = USEC_2_TICKS(tp->t_rttvar);
12399                         frac = tp->t_srtt % (HPTS_USEC_IN_SEC / hz);
12400                         tp->t_rttvar = val <<  TCP_RTTVAR_SHIFT;
12401                         /*
12402                          * frac is the fractional part here is left
12403                          * over from converting to hz and shifting.
12404                          * We need to convert this to the 5 bit
12405                          * remainder.
12406                          */
12407                         if (frac) {
12408                                 if (hz == 1000) {
12409                                         frac = (((uint64_t)frac *  (uint64_t)TCP_RTT_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC);
12410                                 } else {
12411                                         frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE) /(uint64_t)HPTS_USEC_IN_SEC);
12412                                 }
12413                                 tp->t_rttvar += frac;
12414                         }
12415                 }
12416                 tp->t_rxtcur = USEC_2_TICKS(tp->t_rxtcur);
12417                 tp->t_rttlow = USEC_2_TICKS(tp->t_rttlow);
12418                 if (rack->rc_always_pace) {
12419                         tcp_decrement_paced_conn();
12420                         rack_undo_cc_pacing(rack);
12421                         rack->rc_always_pace = 0;
12422                 }
12423                 /* Clean up any options if they were not applied */
12424                 while (!TAILQ_EMPTY(&rack->r_ctl.opt_list)) {
12425                         struct deferred_opt_list *dol;
12426
12427                         dol = TAILQ_FIRST(&rack->r_ctl.opt_list);
12428                         TAILQ_REMOVE(&rack->r_ctl.opt_list, dol, next);
12429                         free(dol, M_TCPDO);
12430                 }
12431                 /* rack does not use force data but other stacks may clear it */
12432                 if (rack->r_ctl.crte != NULL) {
12433                         tcp_rel_pacing_rate(rack->r_ctl.crte, tp);
12434                         rack->rack_hdrw_pacing = 0;
12435                         rack->r_ctl.crte = NULL;
12436                 }
12437 #ifdef TCP_BLACKBOX
12438                 tcp_log_flowend(tp);
12439 #endif
12440                 RB_FOREACH_SAFE(rsm, rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm) {
12441                         rm = RB_REMOVE(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
12442 #ifdef INVARIANTS
12443                         if (rm != rsm) {
12444                                 panic("At fini, rack:%p rsm:%p rm:%p",
12445                                       rack, rsm, rm);
12446                         }
12447 #endif
12448                         uma_zfree(rack_zone, rsm);
12449                 }
12450                 rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
12451                 while (rsm) {
12452                         TAILQ_REMOVE(&rack->r_ctl.rc_free, rsm, r_tnext);
12453                         uma_zfree(rack_zone, rsm);
12454                         rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
12455                 }
12456                 rack->rc_free_cnt = 0;
12457                 uma_zfree(rack_pcb_zone, tp->t_fb_ptr);
12458                 tp->t_fb_ptr = NULL;
12459         }
12460         if (tp->t_inpcb) {
12461                 tp->t_inpcb->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
12462                 tp->t_inpcb->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
12463                 tp->t_inpcb->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
12464                 tp->t_inpcb->inp_flags2 &= ~INP_MBUF_ACKCMP;
12465                 /* Cancel the GP measurement in progress */
12466                 tp->t_flags &= ~TF_GPUTINPROG;
12467                 tp->t_inpcb->inp_flags2 &= ~INP_MBUF_L_ACKS;
12468         }
12469         /* Make sure snd_nxt is correctly set */
12470         tp->snd_nxt = tp->snd_max;
12471 }
12472
12473 static void
12474 rack_set_state(struct tcpcb *tp, struct tcp_rack *rack)
12475 {
12476         switch (tp->t_state) {
12477         case TCPS_SYN_SENT:
12478                 rack->r_state = TCPS_SYN_SENT;
12479                 rack->r_substate = rack_do_syn_sent;
12480                 break;
12481         case TCPS_SYN_RECEIVED:
12482                 rack->r_state = TCPS_SYN_RECEIVED;
12483                 rack->r_substate = rack_do_syn_recv;
12484                 break;
12485         case TCPS_ESTABLISHED:
12486                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
12487                 rack->r_state = TCPS_ESTABLISHED;
12488                 rack->r_substate = rack_do_established;
12489                 break;
12490         case TCPS_CLOSE_WAIT:
12491                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
12492                 rack->r_state = TCPS_CLOSE_WAIT;
12493                 rack->r_substate = rack_do_close_wait;
12494                 break;
12495         case TCPS_FIN_WAIT_1:
12496                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
12497                 rack->r_state = TCPS_FIN_WAIT_1;
12498                 rack->r_substate = rack_do_fin_wait_1;
12499                 break;
12500         case TCPS_CLOSING:
12501                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
12502                 rack->r_state = TCPS_CLOSING;
12503                 rack->r_substate = rack_do_closing;
12504                 break;
12505         case TCPS_LAST_ACK:
12506                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
12507                 rack->r_state = TCPS_LAST_ACK;
12508                 rack->r_substate = rack_do_lastack;
12509                 break;
12510         case TCPS_FIN_WAIT_2:
12511                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
12512                 rack->r_state = TCPS_FIN_WAIT_2;
12513                 rack->r_substate = rack_do_fin_wait_2;
12514                 break;
12515         case TCPS_LISTEN:
12516         case TCPS_CLOSED:
12517         case TCPS_TIME_WAIT:
12518         default:
12519                 break;
12520         };
12521         if (rack->r_use_cmp_ack && TCPS_HAVEESTABLISHED(tp->t_state))
12522                 rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
12523
12524 }
12525
12526 static void
12527 rack_timer_audit(struct tcpcb *tp, struct tcp_rack *rack, struct sockbuf *sb)
12528 {
12529         /*
12530          * We received an ack, and then did not
12531          * call send or were bounced out due to the
12532          * hpts was running. Now a timer is up as well, is
12533          * it the right timer?
12534          */
12535         struct rack_sendmap *rsm;
12536         int tmr_up;
12537
12538         tmr_up = rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
12539         if (rack->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
12540                 return;
12541         rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
12542         if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
12543             (tmr_up == PACE_TMR_RXT)) {
12544                 /* Should be an RXT */
12545                 return;
12546         }
12547         if (rsm == NULL) {
12548                 /* Nothing outstanding? */
12549                 if (tp->t_flags & TF_DELACK) {
12550                         if (tmr_up == PACE_TMR_DELACK)
12551                                 /* We are supposed to have delayed ack up and we do */
12552                                 return;
12553                 } else if (sbavail(&tp->t_inpcb->inp_socket->so_snd) && (tmr_up == PACE_TMR_RXT)) {
12554                         /*
12555                          * if we hit enobufs then we would expect the possiblity
12556                          * of nothing outstanding and the RXT up (and the hptsi timer).
12557                          */
12558                         return;
12559                 } else if (((V_tcp_always_keepalive ||
12560                              rack->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
12561                             (tp->t_state <= TCPS_CLOSING)) &&
12562                            (tmr_up == PACE_TMR_KEEP) &&
12563                            (tp->snd_max == tp->snd_una)) {
12564                         /* We should have keep alive up and we do */
12565                         return;
12566                 }
12567         }
12568         if (SEQ_GT(tp->snd_max, tp->snd_una) &&
12569                    ((tmr_up == PACE_TMR_TLP) ||
12570                     (tmr_up == PACE_TMR_RACK) ||
12571                     (tmr_up == PACE_TMR_RXT))) {
12572                 /*
12573                  * Either a Rack, TLP or RXT is fine if  we
12574                  * have outstanding data.
12575                  */
12576                 return;
12577         } else if (tmr_up == PACE_TMR_DELACK) {
12578                 /*
12579                  * If the delayed ack was going to go off
12580                  * before the rtx/tlp/rack timer were going to
12581                  * expire, then that would be the timer in control.
12582                  * Note we don't check the time here trusting the
12583                  * code is correct.
12584                  */
12585                 return;
12586         }
12587         /*
12588          * Ok the timer originally started is not what we want now.
12589          * We will force the hpts to be stopped if any, and restart
12590          * with the slot set to what was in the saved slot.
12591          */
12592         if (rack->rc_inp->inp_in_hpts) {
12593                 if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
12594                         uint32_t us_cts;
12595
12596                         us_cts = tcp_get_usecs(NULL);
12597                         if (TSTMP_GT(rack->r_ctl.rc_last_output_to, us_cts)) {
12598                                 rack->r_early = 1;
12599                                 rack->r_ctl.rc_agg_early += (rack->r_ctl.rc_last_output_to - us_cts);
12600                         }
12601                         rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
12602                 }
12603                 tcp_hpts_remove(tp->t_inpcb, HPTS_REMOVE_OUTPUT);
12604         }
12605         rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
12606         rack_start_hpts_timer(rack, tp, tcp_get_usecs(NULL), 0, 0, 0);
12607 }
12608
12609
12610 static void
12611 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)
12612 {
12613         tp->snd_wnd = tiwin;
12614         rack_validate_fo_sendwin_up(tp, rack);
12615         tp->snd_wl1 = seq;
12616         tp->snd_wl2 = ack;
12617         if (tp->snd_wnd > tp->max_sndwnd)
12618                 tp->max_sndwnd = tp->snd_wnd;
12619         if (tp->snd_wnd < (tp->snd_max - high_seq)) {
12620                 /* The peer collapsed the window */
12621                 rack_collapsed_window(rack);
12622         } else if (rack->rc_has_collapsed)
12623                 rack_un_collapse_window(rack);
12624         /* Do we exit persists? */
12625         if ((rack->rc_in_persist != 0) &&
12626             (tp->snd_wnd >= min((rack->r_ctl.rc_high_rwnd/2),
12627                                 rack->r_ctl.rc_pace_min_segs))) {
12628                 rack_exit_persist(tp, rack, cts);
12629         }
12630         /* Do we enter persists? */
12631         if ((rack->rc_in_persist == 0) &&
12632             (tp->snd_wnd < min((rack->r_ctl.rc_high_rwnd/2), rack->r_ctl.rc_pace_min_segs)) &&
12633             TCPS_HAVEESTABLISHED(tp->t_state) &&
12634             (tp->snd_max == tp->snd_una) &&
12635             sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
12636             (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
12637                 /*
12638                  * Here the rwnd is less than
12639                  * the pacing size, we are established,
12640                  * nothing is outstanding, and there is
12641                  * data to send. Enter persists.
12642                  */
12643                 rack_enter_persist(tp, rack, rack->r_ctl.rc_rcvtime);
12644         }
12645 }
12646
12647 static void
12648 rack_log_input_packet(struct tcpcb *tp, struct tcp_rack *rack, struct tcp_ackent *ae, int ackval, uint32_t high_seq)
12649 {
12650
12651         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
12652                 union tcp_log_stackspecific log;
12653                 struct timeval ltv;
12654                 char tcp_hdr_buf[60];
12655                 struct tcphdr *th;
12656                 struct timespec ts;
12657                 uint32_t orig_snd_una;
12658                 uint8_t xx = 0;
12659
12660 #ifdef NETFLIX_HTTP_LOGGING
12661                 struct http_sendfile_track *http_req;
12662
12663                 if (SEQ_GT(ae->ack, tp->snd_una)) {
12664                         http_req = tcp_http_find_req_for_seq(tp, (ae->ack-1));
12665                 } else {
12666                         http_req = tcp_http_find_req_for_seq(tp, ae->ack);
12667                 }
12668 #endif
12669                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
12670                 log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
12671                 log.u_bbr.ininput = rack->rc_inp->inp_in_input;
12672                 if (rack->rack_no_prr == 0)
12673                         log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
12674                 else
12675                         log.u_bbr.flex1 = 0;
12676                 log.u_bbr.use_lt_bw = rack->r_ent_rec_ns;
12677                 log.u_bbr.use_lt_bw <<= 1;
12678                 log.u_bbr.use_lt_bw |= rack->r_might_revert;
12679                 log.u_bbr.flex2 = rack->r_ctl.rc_num_maps_alloced;
12680                 log.u_bbr.inflight = ctf_flight_size(tp, rack->r_ctl.rc_sacked);
12681                 log.u_bbr.pkts_out = tp->t_maxseg;
12682                 log.u_bbr.flex4 = rack->r_ctl.rc_hpts_flags;
12683                 log.u_bbr.flex7 = 1;
12684                 log.u_bbr.lost = ae->flags;
12685                 log.u_bbr.cwnd_gain = ackval;
12686                 log.u_bbr.pacing_gain = 0x2;
12687                 if (ae->flags & TSTMP_HDWR) {
12688                         /* Record the hardware timestamp if present */
12689                         log.u_bbr.flex3 = M_TSTMP;
12690                         ts.tv_sec = ae->timestamp / 1000000000;
12691                         ts.tv_nsec = ae->timestamp % 1000000000;
12692                         ltv.tv_sec = ts.tv_sec;
12693                         ltv.tv_usec = ts.tv_nsec / 1000;
12694                         log.u_bbr.lt_epoch = tcp_tv_to_usectick(&ltv);
12695                 } else if (ae->flags & TSTMP_LRO) {
12696                         /* Record the LRO the arrival timestamp */
12697                         log.u_bbr.flex3 = M_TSTMP_LRO;
12698                         ts.tv_sec = ae->timestamp / 1000000000;
12699                         ts.tv_nsec = ae->timestamp % 1000000000;
12700                         ltv.tv_sec = ts.tv_sec;
12701                         ltv.tv_usec = ts.tv_nsec / 1000;
12702                         log.u_bbr.flex5 = tcp_tv_to_usectick(&ltv);
12703                 }
12704                 log.u_bbr.timeStamp = tcp_get_usecs(&ltv);
12705                 /* Log the rcv time */
12706                 log.u_bbr.delRate = ae->timestamp;
12707 #ifdef NETFLIX_HTTP_LOGGING
12708                 log.u_bbr.applimited = tp->t_http_closed;
12709                 log.u_bbr.applimited <<= 8;
12710                 log.u_bbr.applimited |= tp->t_http_open;
12711                 log.u_bbr.applimited <<= 8;
12712                 log.u_bbr.applimited |= tp->t_http_req;
12713                 if (http_req) {
12714                         /* Copy out any client req info */
12715                         /* seconds */
12716                         log.u_bbr.pkt_epoch = (http_req->localtime / HPTS_USEC_IN_SEC);
12717                         /* useconds */
12718                         log.u_bbr.delivered = (http_req->localtime % HPTS_USEC_IN_SEC);
12719                         log.u_bbr.rttProp = http_req->timestamp;
12720                         log.u_bbr.cur_del_rate = http_req->start;
12721                         if (http_req->flags & TCP_HTTP_TRACK_FLG_OPEN) {
12722                                 log.u_bbr.flex8 |= 1;
12723                         } else {
12724                                 log.u_bbr.flex8 |= 2;
12725                                 log.u_bbr.bw_inuse = http_req->end;
12726                         }
12727                         log.u_bbr.flex6 = http_req->start_seq;
12728                         if (http_req->flags & TCP_HTTP_TRACK_FLG_COMP) {
12729                                 log.u_bbr.flex8 |= 4;
12730                                 log.u_bbr.epoch = http_req->end_seq;
12731                         }
12732                 }
12733 #endif
12734                 memset(tcp_hdr_buf, 0, sizeof(tcp_hdr_buf));
12735                 th = (struct tcphdr *)tcp_hdr_buf;
12736                 th->th_seq = ae->seq;
12737                 th->th_ack = ae->ack;
12738                 th->th_win = ae->win;
12739                 /* Now fill in the ports */
12740                 th->th_sport = tp->t_inpcb->inp_fport;
12741                 th->th_dport = tp->t_inpcb->inp_lport;
12742                 th->th_flags = ae->flags & 0xff;
12743                 /* Now do we have a timestamp option? */
12744                 if (ae->flags & HAS_TSTMP) {
12745                         u_char *cp;
12746                         uint32_t val;
12747
12748                         th->th_off = ((sizeof(struct tcphdr) + TCPOLEN_TSTAMP_APPA) >> 2);
12749                         cp = (u_char *)(th + 1);
12750                         *cp = TCPOPT_NOP;
12751                         cp++;
12752                         *cp = TCPOPT_NOP;
12753                         cp++;
12754                         *cp = TCPOPT_TIMESTAMP;
12755                         cp++;
12756                         *cp = TCPOLEN_TIMESTAMP;
12757                         cp++;
12758                         val = htonl(ae->ts_value);
12759                         bcopy((char *)&val,
12760                               (char *)cp, sizeof(uint32_t));
12761                         val = htonl(ae->ts_echo);
12762                         bcopy((char *)&val,
12763                               (char *)(cp + 4), sizeof(uint32_t));
12764                 } else
12765                         th->th_off = (sizeof(struct tcphdr) >> 2);
12766
12767                 /*
12768                  * For sane logging we need to play a little trick.
12769                  * If the ack were fully processed we would have moved
12770                  * snd_una to high_seq, but since compressed acks are
12771                  * processed in two phases, at this point (logging) snd_una
12772                  * won't be advanced. So we would see multiple acks showing
12773                  * the advancement. We can prevent that by "pretending" that
12774                  * snd_una was advanced and then un-advancing it so that the
12775                  * logging code has the right value for tlb_snd_una.
12776                  */
12777                 if (tp->snd_una != high_seq) {
12778                         orig_snd_una = tp->snd_una;
12779                         tp->snd_una = high_seq;
12780                         xx = 1;
12781                 } else
12782                         xx = 0;
12783                 TCP_LOG_EVENTP(tp, th,
12784                                &tp->t_inpcb->inp_socket->so_rcv,
12785                                &tp->t_inpcb->inp_socket->so_snd, TCP_LOG_IN, 0,
12786                                0, &log, true, &ltv);
12787                 if (xx) {
12788                         tp->snd_una = orig_snd_una;
12789                 }
12790         }
12791
12792 }
12793
12794 static int
12795 rack_do_compressed_ack_processing(struct tcpcb *tp, struct socket *so, struct mbuf *m, int nxt_pkt, struct timeval *tv)
12796 {
12797         /*
12798          * Handle a "special" compressed ack mbuf. Each incoming
12799          * ack has only four possible dispositions:
12800          *
12801          * A) It moves the cum-ack forward
12802          * B) It is behind the cum-ack.
12803          * C) It is a window-update ack.
12804          * D) It is a dup-ack.
12805          *
12806          * Note that we can have between 1 -> TCP_COMP_ACK_ENTRIES
12807          * in the incoming mbuf. We also need to still pay attention
12808          * to nxt_pkt since there may be another packet after this
12809          * one.
12810          */
12811 #ifdef TCP_ACCOUNTING
12812         uint64_t ts_val;
12813         uint64_t rdstc;
12814 #endif
12815         int segsiz;
12816         struct timespec ts;
12817         struct tcp_rack *rack;
12818         struct tcp_ackent *ae;
12819         uint32_t tiwin, us_cts, cts, acked, acked_amount, high_seq, win_seq, the_win, win_upd_ack;
12820         int cnt, i, did_out, ourfinisacked = 0;
12821         int win_up_req = 0;
12822         struct tcpopt to_holder, *to = NULL;
12823         int nsegs = 0;
12824         int under_pacing = 1;
12825         int recovery = 0;
12826         int idx;
12827 #ifdef TCP_ACCOUNTING
12828         sched_pin();
12829 #endif
12830         rack = (struct tcp_rack *)tp->t_fb_ptr;
12831         if (rack->gp_ready &&
12832             (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT))
12833                 under_pacing = 0;
12834         else
12835                 under_pacing = 1;
12836
12837         if (rack->r_state != tp->t_state)
12838                 rack_set_state(tp, rack);
12839         to = &to_holder;
12840         to->to_flags = 0;
12841         KASSERT((m->m_len >= sizeof(struct tcp_ackent)),
12842                 ("tp:%p m_cmpack:%p with invalid len:%u", tp, m, m->m_len));
12843         cnt = m->m_len / sizeof(struct tcp_ackent);
12844         idx = cnt / 5;
12845         if (idx >= MAX_NUM_OF_CNTS)
12846                 idx = MAX_NUM_OF_CNTS - 1;
12847         counter_u64_add(rack_proc_comp_ack[idx], 1);
12848         counter_u64_add(rack_multi_single_eq, cnt);
12849         high_seq = tp->snd_una;
12850         the_win = tp->snd_wnd;
12851         win_seq = tp->snd_wl1;
12852         win_upd_ack = tp->snd_wl2;
12853         cts = us_cts = tcp_tv_to_usectick(tv);
12854         segsiz = ctf_fixed_maxseg(tp);
12855         if ((rack->rc_gp_dyn_mul) &&
12856             (rack->use_fixed_rate == 0) &&
12857             (rack->rc_always_pace)) {
12858                 /* Check in on probertt */
12859                 rack_check_probe_rtt(rack, us_cts);
12860         }
12861         for (i = 0; i < cnt; i++) {
12862 #ifdef TCP_ACCOUNTING
12863                 ts_val = get_cyclecount();
12864 #endif
12865                 rack_clear_rate_sample(rack);
12866                 ae = ((mtod(m, struct tcp_ackent *)) + i);
12867                 /* Setup the window */
12868                 tiwin = ae->win << tp->snd_scale;
12869                 /* figure out the type of ack */
12870                 if (SEQ_LT(ae->ack, high_seq)) {
12871                         /* Case B*/
12872                         ae->ack_val_set = ACK_BEHIND;
12873                 } else if (SEQ_GT(ae->ack, high_seq)) {
12874                         /* Case A */
12875                         ae->ack_val_set = ACK_CUMACK;
12876                 } else if (tiwin == the_win) {
12877                         /* Case D */
12878                         ae->ack_val_set = ACK_DUPACK;
12879                 } else {
12880                         /* Case C */
12881                         ae->ack_val_set = ACK_RWND;
12882                 }
12883                 rack_log_input_packet(tp, rack, ae, ae->ack_val_set, high_seq);
12884                 /* Validate timestamp */
12885                 if (ae->flags & HAS_TSTMP) {
12886                         /* Setup for a timestamp */
12887                         to->to_flags = TOF_TS;
12888                         ae->ts_echo -= tp->ts_offset;
12889                         to->to_tsecr = ae->ts_echo;
12890                         to->to_tsval = ae->ts_value;
12891                         /*
12892                          * If echoed timestamp is later than the current time, fall back to
12893                          * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
12894                          * were used when this connection was established.
12895                          */
12896                         if (TSTMP_GT(ae->ts_echo, cts))
12897                                 ae->ts_echo = 0;
12898                         if (tp->ts_recent &&
12899                             TSTMP_LT(ae->ts_value, tp->ts_recent)) {
12900                                 if (ctf_ts_check_ac(tp, (ae->flags & 0xff))) {
12901 #ifdef TCP_ACCOUNTING
12902                                         rdstc = get_cyclecount();
12903                                         if (rdstc > ts_val) {
12904                                                 counter_u64_add(tcp_proc_time[ae->ack_val_set] ,
12905                                                                 (rdstc - ts_val));
12906                                                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
12907                                                         tp->tcp_proc_time[ae->ack_val_set] += (rdstc - ts_val);
12908                                                 }
12909                                         }
12910 #endif
12911                                         continue;
12912                                 }
12913                         }
12914                         if (SEQ_LEQ(ae->seq, tp->last_ack_sent) &&
12915                             SEQ_LEQ(tp->last_ack_sent, ae->seq)) {
12916                                 tp->ts_recent_age = tcp_ts_getticks();
12917                                 tp->ts_recent = ae->ts_value;
12918                         }
12919                 } else {
12920                         /* Setup for a no options */
12921                         to->to_flags = 0;
12922                 }
12923                 /* Update the rcv time and perform idle reduction possibly */
12924                 if  (tp->t_idle_reduce &&
12925                      (tp->snd_max == tp->snd_una) &&
12926                      ((ticks - tp->t_rcvtime) >= tp->t_rxtcur)) {
12927                         counter_u64_add(rack_input_idle_reduces, 1);
12928                         rack_cc_after_idle(rack, tp);
12929                 }
12930                 tp->t_rcvtime = ticks;
12931                 /* Now what about ECN? */
12932                 if (tp->t_flags2 & TF2_ECN_PERMIT) {
12933                         if (ae->flags & TH_CWR) {
12934                                 tp->t_flags2 &= ~TF2_ECN_SND_ECE;
12935                                 tp->t_flags |= TF_ACKNOW;
12936                         }
12937                         switch (ae->codepoint & IPTOS_ECN_MASK) {
12938                         case IPTOS_ECN_CE:
12939                                 tp->t_flags2 |= TF2_ECN_SND_ECE;
12940                                 KMOD_TCPSTAT_INC(tcps_ecn_ce);
12941                                 break;
12942                         case IPTOS_ECN_ECT0:
12943                                 KMOD_TCPSTAT_INC(tcps_ecn_ect0);
12944                                 break;
12945                         case IPTOS_ECN_ECT1:
12946                                 KMOD_TCPSTAT_INC(tcps_ecn_ect1);
12947                                 break;
12948                         }
12949
12950                         /* Process a packet differently from RFC3168. */
12951                         cc_ecnpkt_handler_flags(tp, ae->flags, ae->codepoint);
12952                         /* Congestion experienced. */
12953                         if (ae->flags & TH_ECE) {
12954                                 rack_cong_signal(tp,  CC_ECN, ae->ack);
12955                         }
12956                 }
12957 #ifdef TCP_ACCOUNTING
12958                 /* Count for the specific type of ack in */
12959                 counter_u64_add(tcp_cnt_counters[ae->ack_val_set], 1);
12960                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
12961                         tp->tcp_cnt_counters[ae->ack_val_set]++;
12962                 }
12963 #endif
12964                 /*
12965                  * Note how we could move up these in the determination
12966                  * above, but we don't so that way the timestamp checks (and ECN)
12967                  * is done first before we do any processing on the ACK.
12968                  * The non-compressed path through the code has this
12969                  * weakness (noted by @jtl) that it actually does some
12970                  * processing before verifying the timestamp information.
12971                  * We don't take that path here which is why we set
12972                  * the ack_val_set first, do the timestamp and ecn
12973                  * processing, and then look at what we have setup.
12974                  */
12975                 if (ae->ack_val_set == ACK_BEHIND) {
12976                         /*
12977                          * Case B flag reordering, if window is not closed
12978                          * or it could be a keep-alive or persists
12979                          */
12980                         if (SEQ_LT(ae->ack, tp->snd_una) && (sbspace(&so->so_rcv) > segsiz)) {
12981                                 counter_u64_add(rack_reorder_seen, 1);
12982                                 rack->r_ctl.rc_reorder_ts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
12983                         }
12984                 } else if (ae->ack_val_set == ACK_DUPACK) {
12985                         /* Case D */
12986
12987                         rack_strike_dupack(rack);
12988                 } else if (ae->ack_val_set == ACK_RWND) {
12989                         /* Case C */
12990
12991                         win_up_req = 1;
12992                         win_upd_ack = ae->ack;
12993                         win_seq = ae->seq;
12994                         the_win = tiwin;
12995                 } else {
12996                         /* Case A */
12997
12998                         if (SEQ_GT(ae->ack, tp->snd_max)) {
12999                                 /*
13000                                  * We just send an ack since the incoming
13001                                  * ack is beyond the largest seq we sent.
13002                                  */
13003                                 if ((tp->t_flags & TF_ACKNOW) == 0) {
13004                                         ctf_ack_war_checks(tp, &rack->r_ctl.challenge_ack_ts, &rack->r_ctl.challenge_ack_cnt);
13005                                         if (tp->t_flags && TF_ACKNOW)
13006                                                 rack->r_wanted_output = 1;
13007                                 }
13008                         } else {
13009                                 nsegs++;
13010                                 /* If the window changed setup to update */
13011                                 if (tiwin != tp->snd_wnd) {
13012                                         win_up_req = 1;
13013                                         win_upd_ack = ae->ack;
13014                                         win_seq = ae->seq;
13015                                         the_win = tiwin;
13016                                 }
13017 #ifdef TCP_ACCOUNTING
13018                                 /* Account for the acks */
13019                                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13020                                         tp->tcp_cnt_counters[CNT_OF_ACKS_IN] += (((ae->ack - high_seq) + segsiz - 1) / segsiz);
13021                                 }
13022                                 counter_u64_add(tcp_cnt_counters[CNT_OF_ACKS_IN],
13023                                                 (((ae->ack - high_seq) + segsiz - 1) / segsiz));
13024 #endif
13025                                 high_seq = ae->ack;
13026                                 /* Setup our act_rcv_time */
13027                                 if ((ae->flags & TSTMP_LRO) || (ae->flags & TSTMP_HDWR)) {
13028                                         ts.tv_sec = ae->timestamp / 1000000000;
13029                                         ts.tv_nsec = ae->timestamp % 1000000000;
13030                                         rack->r_ctl.act_rcv_time.tv_sec = ts.tv_sec;
13031                                         rack->r_ctl.act_rcv_time.tv_usec = ts.tv_nsec/1000;
13032                                 } else {
13033                                         rack->r_ctl.act_rcv_time = *tv;
13034                                 }
13035                                 rack_process_to_cumack(tp, rack, ae->ack, cts, to);
13036                         }
13037                 }
13038                 /* And lets be sure to commit the rtt measurements for this ack */
13039                 tcp_rack_xmit_timer_commit(rack, tp);
13040 #ifdef TCP_ACCOUNTING
13041                 rdstc = get_cyclecount();
13042                 if (rdstc > ts_val) {
13043                         counter_u64_add(tcp_proc_time[ae->ack_val_set] , (rdstc - ts_val));
13044                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13045                                 tp->tcp_proc_time[ae->ack_val_set] += (rdstc - ts_val);
13046                                 if (ae->ack_val_set == ACK_CUMACK)
13047                                         tp->tcp_proc_time[CYC_HANDLE_MAP] += (rdstc - ts_val);
13048                         }
13049                 }
13050 #endif
13051         }
13052 #ifdef TCP_ACCOUNTING
13053         ts_val = get_cyclecount();
13054 #endif
13055         acked_amount = acked = (high_seq - tp->snd_una);
13056         if (win_up_req) {
13057                 rack_do_win_updates(tp, rack, the_win, win_seq, win_upd_ack, cts, high_seq);
13058         }
13059         if (acked) {
13060                 if (rack->sack_attack_disable == 0)
13061                         rack_do_decay(rack);
13062                 if (acked >= segsiz) {
13063                         /*
13064                          * You only get credit for
13065                          * MSS and greater (and you get extra
13066                          * credit for larger cum-ack moves).
13067                          */
13068                         int ac;
13069
13070                         ac = acked / segsiz;
13071                         rack->r_ctl.ack_count += ac;
13072                         counter_u64_add(rack_ack_total, ac);
13073                 }
13074                 if (rack->r_ctl.ack_count > 0xfff00000) {
13075                         /*
13076                          * reduce the number to keep us under
13077                          * a uint32_t.
13078                          */
13079                         rack->r_ctl.ack_count /= 2;
13080                         rack->r_ctl.sack_count /= 2;
13081                 }
13082                 if (tp->t_flags & TF_NEEDSYN) {
13083                         /*
13084                          * T/TCP: Connection was half-synchronized, and our SYN has
13085                          * been ACK'd (so connection is now fully synchronized).  Go
13086                          * to non-starred state, increment snd_una for ACK of SYN,
13087                          * and check if we can do window scaling.
13088                          */
13089                         tp->t_flags &= ~TF_NEEDSYN;
13090                         tp->snd_una++;
13091                         acked_amount = acked = (high_seq - tp->snd_una);
13092                 }
13093                 if (acked > sbavail(&so->so_snd))
13094                         acked_amount = sbavail(&so->so_snd);
13095 #ifdef NETFLIX_EXP_DETECTION
13096                 /*
13097                  * We only care on a cum-ack move if we are in a sack-disabled
13098                  * state. We have already added in to the ack_count, and we never
13099                  * would disable on a cum-ack move, so we only care to do the
13100                  * detection if it may "undo" it, i.e. we were in disabled already.
13101                  */
13102                 if (rack->sack_attack_disable)
13103                         rack_do_detection(tp, rack, acked_amount, segsiz);
13104 #endif
13105                 if (IN_FASTRECOVERY(tp->t_flags) &&
13106                     (rack->rack_no_prr == 0))
13107                         rack_update_prr(tp, rack, acked_amount, high_seq);
13108                 if (IN_RECOVERY(tp->t_flags)) {
13109                         if (SEQ_LT(high_seq, tp->snd_recover) &&
13110                             (SEQ_LT(high_seq, tp->snd_max))) {
13111                                 tcp_rack_partialack(tp);
13112                         } else {
13113                                 rack_post_recovery(tp, high_seq);
13114                                 recovery = 1;
13115                         }
13116                 }
13117                 /* Handle the rack-log-ack part (sendmap) */
13118                 if ((sbused(&so->so_snd) == 0) &&
13119                     (acked > acked_amount) &&
13120                     (tp->t_state >= TCPS_FIN_WAIT_1) &&
13121                     (tp->t_flags & TF_SENTFIN)) {
13122                         /*
13123                          * We must be sure our fin
13124                          * was sent and acked (we can be
13125                          * in FIN_WAIT_1 without having
13126                          * sent the fin).
13127                          */
13128                         ourfinisacked = 1;
13129                         /*
13130                          * Lets make sure snd_una is updated
13131                          * since most likely acked_amount = 0 (it
13132                          * should be).
13133                          */
13134                         tp->snd_una = high_seq;
13135                 }
13136                 /* Did we make a RTO error? */
13137                 if ((tp->t_flags & TF_PREVVALID) &&
13138                     ((tp->t_flags & TF_RCVD_TSTMP) == 0)) {
13139                         tp->t_flags &= ~TF_PREVVALID;
13140                         if (tp->t_rxtshift == 1 &&
13141                             (int)(ticks - tp->t_badrxtwin) < 0)
13142                                 rack_cong_signal(tp, CC_RTO_ERR, high_seq);
13143                 }
13144                 /* Handle the data in the socket buffer */
13145                 KMOD_TCPSTAT_ADD(tcps_rcvackpack, 1);
13146                 KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
13147                 if (acked_amount > 0) {
13148                         struct mbuf *mfree;
13149
13150                         rack_ack_received(tp, rack, high_seq, nsegs, CC_ACK, recovery);
13151                         SOCKBUF_LOCK(&so->so_snd);
13152                         mfree = sbcut_locked(&so->so_snd, acked);
13153                         tp->snd_una = high_seq;
13154                         /* Note we want to hold the sb lock through the sendmap adjust */
13155                         rack_adjust_sendmap(rack, &so->so_snd, tp->snd_una);
13156                         /* Wake up the socket if we have room to write more */
13157                         rack_log_wakeup(tp,rack, &so->so_snd, acked, 2);
13158                         SOCKBUF_UNLOCK(&so->so_snd);
13159                         tp->t_flags |= TF_WAKESOW;
13160                         m_freem(mfree);
13161                 }
13162                 /* update progress */
13163                 tp->t_acktime = ticks;
13164                 rack_log_progress_event(rack, tp, tp->t_acktime,
13165                                         PROGRESS_UPDATE, __LINE__);
13166                 /* Clear out shifts and such */
13167                 tp->t_rxtshift = 0;
13168                 RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
13169                                    rack_rto_min, rack_rto_max);
13170                 rack->rc_tlp_in_progress = 0;
13171                 rack->r_ctl.rc_tlp_cnt_out = 0;
13172                 /* Send recover and snd_nxt must be dragged along */
13173                 if (SEQ_GT(tp->snd_una, tp->snd_recover))
13174                         tp->snd_recover = tp->snd_una;
13175                 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
13176                         tp->snd_nxt = tp->snd_una;
13177                 /*
13178                  * If the RXT timer is running we want to
13179                  * stop it, so we can restart a TLP (or new RXT).
13180                  */
13181                 if (rack->r_ctl.rc_hpts_flags & PACE_TMR_RXT)
13182                         rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
13183 #ifdef NETFLIX_HTTP_LOGGING
13184                 tcp_http_check_for_comp(rack->rc_tp, high_seq);
13185 #endif
13186                 tp->snd_wl2 = high_seq;
13187                 tp->t_dupacks = 0;
13188                 if (under_pacing &&
13189                     (rack->use_fixed_rate == 0) &&
13190                     (rack->in_probe_rtt == 0) &&
13191                     rack->rc_gp_dyn_mul &&
13192                     rack->rc_always_pace) {
13193                         /* Check if we are dragging bottom */
13194                         rack_check_bottom_drag(tp, rack, so, acked);
13195                 }
13196                 if (tp->snd_una == tp->snd_max) {
13197                         tp->t_flags &= ~TF_PREVVALID;
13198                         rack->r_ctl.retran_during_recovery = 0;
13199                         rack->r_ctl.dsack_byte_cnt = 0;
13200                         rack->r_ctl.rc_went_idle_time = tcp_get_usecs(NULL);
13201                         if (rack->r_ctl.rc_went_idle_time == 0)
13202                                 rack->r_ctl.rc_went_idle_time = 1;
13203                         rack_log_progress_event(rack, tp, 0, PROGRESS_CLEAR, __LINE__);
13204                         if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
13205                                 tp->t_acktime = 0;
13206                         /* Set so we might enter persists... */
13207                         rack->r_wanted_output = 1;
13208                         rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
13209                         sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
13210                         if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
13211                             (sbavail(&so->so_snd) == 0) &&
13212                             (tp->t_flags2 & TF2_DROP_AF_DATA)) {
13213                                 /*
13214                                  * The socket was gone and the
13215                                  * peer sent data (not now in the past), time to
13216                                  * reset him.
13217                                  */
13218                                 rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
13219                                 /* tcp_close will kill the inp pre-log the Reset */
13220                                 tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
13221 #ifdef TCP_ACCOUNTING
13222                                 rdstc = get_cyclecount();
13223                                 if (rdstc > ts_val) {
13224                                         counter_u64_add(tcp_proc_time[ACK_CUMACK] , (rdstc - ts_val));
13225                                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13226                                                 tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13227                                                 tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13228                                         }
13229                                 }
13230 #endif
13231                                 m_freem(m);
13232                                 tp = tcp_close(tp);
13233                                 if (tp == NULL) {
13234 #ifdef TCP_ACCOUNTING
13235                                         sched_unpin();
13236 #endif
13237                                         return (1);
13238                                 }
13239                                 /*
13240                                  * We would normally do drop-with-reset which would
13241                                  * send back a reset. We can't since we don't have
13242                                  * all the needed bits. Instead lets arrange for
13243                                  * a call to tcp_output(). That way since we
13244                                  * are in the closed state we will generate a reset.
13245                                  *
13246                                  * Note if tcp_accounting is on we don't unpin since
13247                                  * we do that after the goto label.
13248                                  */
13249                                 goto send_out_a_rst;
13250                         }
13251                         if ((sbused(&so->so_snd) == 0) &&
13252                             (tp->t_state >= TCPS_FIN_WAIT_1) &&
13253                             (tp->t_flags & TF_SENTFIN)) {
13254                                 /*
13255                                  * If we can't receive any more data, then closing user can
13256                                  * proceed. Starting the timer is contrary to the
13257                                  * specification, but if we don't get a FIN we'll hang
13258                                  * forever.
13259                                  *
13260                                  */
13261                                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
13262                                         soisdisconnected(so);
13263                                         tcp_timer_activate(tp, TT_2MSL,
13264                                                            (tcp_fast_finwait2_recycle ?
13265                                                             tcp_finwait2_timeout :
13266                                                             TP_MAXIDLE(tp)));
13267                                 }
13268                                 if (ourfinisacked == 0) {
13269                                         /*
13270                                          * We don't change to fin-wait-2 if we have our fin acked
13271                                          * which means we are probably in TCPS_CLOSING.
13272                                          */
13273                                         tcp_state_change(tp, TCPS_FIN_WAIT_2);
13274                                 }
13275                         }
13276                 }
13277                 /* Wake up the socket if we have room to write more */
13278                 if (sbavail(&so->so_snd)) {
13279                         rack->r_wanted_output = 1;
13280                         if (ctf_progress_timeout_check(tp, true)) {
13281                                 rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
13282                                                         tp, tick, PROGRESS_DROP, __LINE__);
13283                                 tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
13284                                 /*
13285                                  * We cheat here and don't send a RST, we should send one
13286                                  * when the pacer drops the connection.
13287                                  */
13288 #ifdef TCP_ACCOUNTING
13289                                 rdstc = get_cyclecount();
13290                                 if (rdstc > ts_val) {
13291                                         counter_u64_add(tcp_proc_time[ACK_CUMACK] , (rdstc - ts_val));
13292                                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13293                                                 tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13294                                                 tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13295                                         }
13296                                 }
13297                                 sched_unpin();
13298 #endif
13299                                 INP_WUNLOCK(rack->rc_inp);
13300                                 m_freem(m);
13301                                 return (1);
13302                         }
13303                 }
13304                 if (ourfinisacked) {
13305                         switch(tp->t_state) {
13306                         case TCPS_CLOSING:
13307 #ifdef TCP_ACCOUNTING
13308                                 rdstc = get_cyclecount();
13309                                 if (rdstc > ts_val) {
13310                                         counter_u64_add(tcp_proc_time[ACK_CUMACK] ,
13311                                                         (rdstc - ts_val));
13312                                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13313                                                 tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13314                                                 tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13315                                         }
13316                                 }
13317                                 sched_unpin();
13318 #endif
13319                                 tcp_twstart(tp);
13320                                 m_freem(m);
13321                                 return (1);
13322                                 break;
13323                         case TCPS_LAST_ACK:
13324 #ifdef TCP_ACCOUNTING
13325                                 rdstc = get_cyclecount();
13326                                 if (rdstc > ts_val) {
13327                                         counter_u64_add(tcp_proc_time[ACK_CUMACK] ,
13328                                                         (rdstc - ts_val));
13329                                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13330                                                 tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13331                                                 tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13332                                         }
13333                                 }
13334                                 sched_unpin();
13335 #endif
13336                                 tp = tcp_close(tp);
13337                                 ctf_do_drop(m, tp);
13338                                 return (1);
13339                                 break;
13340                         case TCPS_FIN_WAIT_1:
13341 #ifdef TCP_ACCOUNTING
13342                                 rdstc = get_cyclecount();
13343                                 if (rdstc > ts_val) {
13344                                         counter_u64_add(tcp_proc_time[ACK_CUMACK] ,
13345                                                         (rdstc - ts_val));
13346                                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13347                                                 tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13348                                                 tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13349                                         }
13350                                 }
13351 #endif
13352                                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
13353                                         soisdisconnected(so);
13354                                         tcp_timer_activate(tp, TT_2MSL,
13355                                                            (tcp_fast_finwait2_recycle ?
13356                                                             tcp_finwait2_timeout :
13357                                                             TP_MAXIDLE(tp)));
13358                                 }
13359                                 tcp_state_change(tp, TCPS_FIN_WAIT_2);
13360                                 break;
13361                         default:
13362                                 break;
13363                         }
13364                 }
13365                 if (rack->r_fast_output) {
13366                         /*
13367                          * We re doing fast output.. can we expand that?
13368                          */
13369                         rack_gain_for_fastoutput(rack, tp, so, acked_amount);
13370                 }
13371 #ifdef TCP_ACCOUNTING
13372                 rdstc = get_cyclecount();
13373                 if (rdstc > ts_val) {
13374                         counter_u64_add(tcp_proc_time[ACK_CUMACK] , (rdstc - ts_val));
13375                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13376                                 tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13377                                 tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13378                         }
13379                 }
13380
13381         } else if (win_up_req) {
13382                 rdstc = get_cyclecount();
13383                 if (rdstc > ts_val) {
13384                         counter_u64_add(tcp_proc_time[ACK_RWND] , (rdstc - ts_val));
13385                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13386                                 tp->tcp_proc_time[ACK_RWND] += (rdstc - ts_val);
13387                         }
13388                 }
13389 #endif
13390         }
13391         /* Now is there a next packet, if so we are done */
13392         m_freem(m);
13393         did_out = 0;
13394         if (nxt_pkt) {
13395 #ifdef TCP_ACCOUNTING
13396                 sched_unpin();
13397 #endif
13398                 rack_log_doseg_done(rack, cts, nxt_pkt, did_out, 5, nsegs);
13399                 return (0);
13400         }
13401         rack_handle_might_revert(tp, rack);
13402         ctf_calc_rwin(so, tp);
13403         if ((rack->r_wanted_output != 0) || (rack->r_fast_output != 0)) {
13404         send_out_a_rst:
13405                 (void)tp->t_fb->tfb_tcp_output(tp);
13406                 did_out = 1;
13407         }
13408         rack_free_trim(rack);
13409 #ifdef TCP_ACCOUNTING
13410         sched_unpin();
13411 #endif
13412         rack_timer_audit(tp, rack, &so->so_snd);
13413         rack_log_doseg_done(rack, cts, nxt_pkt, did_out, 6, nsegs);
13414         return (0);
13415 }
13416
13417
13418 static int
13419 rack_do_segment_nounlock(struct mbuf *m, struct tcphdr *th, struct socket *so,
13420     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos,
13421     int32_t nxt_pkt, struct timeval *tv)
13422 {
13423 #ifdef TCP_ACCOUNTING
13424         uint64_t ts_val;
13425 #endif
13426         int32_t thflags, retval, did_out = 0;
13427         int32_t way_out = 0;
13428         uint32_t cts;
13429         uint32_t tiwin;
13430         struct timespec ts;
13431         struct tcpopt to;
13432         struct tcp_rack *rack;
13433         struct rack_sendmap *rsm;
13434         int32_t prev_state = 0;
13435 #ifdef TCP_ACCOUNTING
13436         int ack_val_set = 0xf;
13437 #endif
13438         uint32_t us_cts;
13439         /*
13440          * tv passed from common code is from either M_TSTMP_LRO or
13441          * tcp_get_usecs() if no LRO m_pkthdr timestamp is present.
13442          */
13443         if (m->m_flags & M_ACKCMP) {
13444                 return (rack_do_compressed_ack_processing(tp, so, m, nxt_pkt, tv));
13445         }
13446         if (m->m_flags & M_ACKCMP) {
13447                 panic("Impossible reach m has ackcmp? m:%p tp:%p", m, tp);
13448         }
13449         counter_u64_add(rack_proc_non_comp_ack, 1);
13450         thflags = th->th_flags;
13451 #ifdef TCP_ACCOUNTING
13452         sched_pin();
13453         if (thflags & TH_ACK)
13454                 ts_val = get_cyclecount();
13455 #endif
13456         cts = tcp_tv_to_usectick(tv);
13457         rack = (struct tcp_rack *)tp->t_fb_ptr;
13458
13459         if ((m->m_flags & M_TSTMP) ||
13460             (m->m_flags & M_TSTMP_LRO)) {
13461                 mbuf_tstmp2timespec(m, &ts);
13462                 rack->r_ctl.act_rcv_time.tv_sec = ts.tv_sec;
13463                 rack->r_ctl.act_rcv_time.tv_usec = ts.tv_nsec/1000;
13464         } else
13465                 rack->r_ctl.act_rcv_time = *tv;
13466         kern_prefetch(rack, &prev_state);
13467         prev_state = 0;
13468         /*
13469          * Unscale the window into a 32-bit value. For the SYN_SENT state
13470          * the scale is zero.
13471          */
13472         tiwin = th->th_win << tp->snd_scale;
13473         /*
13474          * Parse options on any incoming segment.
13475          */
13476         memset(&to, 0, sizeof(to));
13477         tcp_dooptions(&to, (u_char *)(th + 1),
13478             (th->th_off << 2) - sizeof(struct tcphdr),
13479             (thflags & TH_SYN) ? TO_SYN : 0);
13480 #ifdef TCP_ACCOUNTING
13481         if (thflags & TH_ACK) {
13482                 /*
13483                  * We have a tradeoff here. We can either do what we are
13484                  * doing i.e. pinning to this CPU and then doing the accounting
13485                  * <or> we could do a critical enter, setup the rdtsc and cpu
13486                  * as in below, and then validate we are on the same CPU on
13487                  * exit. I have choosen to not do the critical enter since
13488                  * that often will gain you a context switch, and instead lock
13489                  * us (line above this if) to the same CPU with sched_pin(). This
13490                  * means we may be context switched out for a higher priority
13491                  * interupt but we won't be moved to another CPU.
13492                  *
13493                  * If this occurs (which it won't very often since we most likely
13494                  * are running this code in interupt context and only a higher
13495                  * priority will bump us ... clock?) we will falsely add in
13496                  * to the time the interupt processing time plus the ack processing
13497                  * time. This is ok since its a rare event.
13498                  */
13499                 ack_val_set = tcp_do_ack_accounting(tp, th, &to, tiwin,
13500                                                     ctf_fixed_maxseg(tp));
13501         }
13502 #endif
13503         NET_EPOCH_ASSERT();
13504         INP_WLOCK_ASSERT(tp->t_inpcb);
13505         KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
13506             __func__));
13507         KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
13508             __func__));
13509         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
13510                 union tcp_log_stackspecific log;
13511                 struct timeval ltv;
13512 #ifdef NETFLIX_HTTP_LOGGING
13513                 struct http_sendfile_track *http_req;
13514
13515                 if (SEQ_GT(th->th_ack, tp->snd_una)) {
13516                         http_req = tcp_http_find_req_for_seq(tp, (th->th_ack-1));
13517                 } else {
13518                         http_req = tcp_http_find_req_for_seq(tp, th->th_ack);
13519                 }
13520 #endif
13521                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
13522                 log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
13523                 log.u_bbr.ininput = rack->rc_inp->inp_in_input;
13524                 if (rack->rack_no_prr == 0)
13525                         log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
13526                 else
13527                         log.u_bbr.flex1 = 0;
13528                 log.u_bbr.use_lt_bw = rack->r_ent_rec_ns;
13529                 log.u_bbr.use_lt_bw <<= 1;
13530                 log.u_bbr.use_lt_bw |= rack->r_might_revert;
13531                 log.u_bbr.flex2 = rack->r_ctl.rc_num_maps_alloced;
13532                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
13533                 log.u_bbr.pkts_out = rack->rc_tp->t_maxseg;
13534                 log.u_bbr.flex3 = m->m_flags;
13535                 log.u_bbr.flex4 = rack->r_ctl.rc_hpts_flags;
13536                 log.u_bbr.lost = thflags;
13537                 log.u_bbr.pacing_gain = 0x1;
13538 #ifdef TCP_ACCOUNTING
13539                 log.u_bbr.cwnd_gain = ack_val_set;
13540 #endif
13541                 log.u_bbr.flex7 = 2;
13542                 if (m->m_flags & M_TSTMP) {
13543                         /* Record the hardware timestamp if present */
13544                         mbuf_tstmp2timespec(m, &ts);
13545                         ltv.tv_sec = ts.tv_sec;
13546                         ltv.tv_usec = ts.tv_nsec / 1000;
13547                         log.u_bbr.lt_epoch = tcp_tv_to_usectick(&ltv);
13548                 } else if (m->m_flags & M_TSTMP_LRO) {
13549                         /* Record the LRO the arrival timestamp */
13550                         mbuf_tstmp2timespec(m, &ts);
13551                         ltv.tv_sec = ts.tv_sec;
13552                         ltv.tv_usec = ts.tv_nsec / 1000;
13553                         log.u_bbr.flex5 = tcp_tv_to_usectick(&ltv);
13554                 }
13555                 log.u_bbr.timeStamp = tcp_get_usecs(&ltv);
13556                 /* Log the rcv time */
13557                 log.u_bbr.delRate = m->m_pkthdr.rcv_tstmp;
13558 #ifdef NETFLIX_HTTP_LOGGING
13559                 log.u_bbr.applimited = tp->t_http_closed;
13560                 log.u_bbr.applimited <<= 8;
13561                 log.u_bbr.applimited |= tp->t_http_open;
13562                 log.u_bbr.applimited <<= 8;
13563                 log.u_bbr.applimited |= tp->t_http_req;
13564                 if (http_req) {
13565                         /* Copy out any client req info */
13566                         /* seconds */
13567                         log.u_bbr.pkt_epoch = (http_req->localtime / HPTS_USEC_IN_SEC);
13568                         /* useconds */
13569                         log.u_bbr.delivered = (http_req->localtime % HPTS_USEC_IN_SEC);
13570                         log.u_bbr.rttProp = http_req->timestamp;
13571                         log.u_bbr.cur_del_rate = http_req->start;
13572                         if (http_req->flags & TCP_HTTP_TRACK_FLG_OPEN) {
13573                                 log.u_bbr.flex8 |= 1;
13574                         } else {
13575                                 log.u_bbr.flex8 |= 2;
13576                                 log.u_bbr.bw_inuse = http_req->end;
13577                         }
13578                         log.u_bbr.flex6 = http_req->start_seq;
13579                         if (http_req->flags & TCP_HTTP_TRACK_FLG_COMP) {
13580                                 log.u_bbr.flex8 |= 4;
13581                                 log.u_bbr.epoch = http_req->end_seq;
13582                         }
13583                 }
13584 #endif
13585                 TCP_LOG_EVENTP(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_IN, 0,
13586                     tlen, &log, true, &ltv);
13587         }
13588         if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
13589                 way_out = 4;
13590                 retval = 0;
13591                 goto done_with_input;
13592         }
13593         /*
13594          * If a segment with the ACK-bit set arrives in the SYN-SENT state
13595          * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
13596          */
13597         if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
13598             (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
13599                 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
13600                 ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
13601 #ifdef TCP_ACCOUNTING
13602                 sched_unpin();
13603 #endif
13604                 return (1);
13605         }
13606
13607         /*
13608          * Parse options on any incoming segment.
13609          */
13610         tcp_dooptions(&to, (u_char *)(th + 1),
13611             (th->th_off << 2) - sizeof(struct tcphdr),
13612             (thflags & TH_SYN) ? TO_SYN : 0);
13613
13614         /*
13615          * If timestamps were negotiated during SYN/ACK and a
13616          * segment without a timestamp is received, silently drop
13617          * the segment, unless it is a RST segment or missing timestamps are
13618          * tolerated.
13619          * See section 3.2 of RFC 7323.
13620          */
13621         if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
13622             ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
13623                 way_out = 5;
13624                 retval = 0;
13625                 goto done_with_input;
13626         }
13627
13628         /*
13629          * Segment received on connection. Reset idle time and keep-alive
13630          * timer. XXX: This should be done after segment validation to
13631          * ignore broken/spoofed segs.
13632          */
13633         if  (tp->t_idle_reduce &&
13634              (tp->snd_max == tp->snd_una) &&
13635              ((ticks - tp->t_rcvtime) >= tp->t_rxtcur)) {
13636                 counter_u64_add(rack_input_idle_reduces, 1);
13637                 rack_cc_after_idle(rack, tp);
13638         }
13639         tp->t_rcvtime = ticks;
13640 #ifdef STATS
13641         stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
13642 #endif
13643         if (tiwin > rack->r_ctl.rc_high_rwnd)
13644                 rack->r_ctl.rc_high_rwnd = tiwin;
13645         /*
13646          * TCP ECN processing. XXXJTL: If we ever use ECN, we need to move
13647          * this to occur after we've validated the segment.
13648          */
13649         if (tp->t_flags2 & TF2_ECN_PERMIT) {
13650                 if (thflags & TH_CWR) {
13651                         tp->t_flags2 &= ~TF2_ECN_SND_ECE;
13652                         tp->t_flags |= TF_ACKNOW;
13653                 }
13654                 switch (iptos & IPTOS_ECN_MASK) {
13655                 case IPTOS_ECN_CE:
13656                         tp->t_flags2 |= TF2_ECN_SND_ECE;
13657                         KMOD_TCPSTAT_INC(tcps_ecn_ce);
13658                         break;
13659                 case IPTOS_ECN_ECT0:
13660                         KMOD_TCPSTAT_INC(tcps_ecn_ect0);
13661                         break;
13662                 case IPTOS_ECN_ECT1:
13663                         KMOD_TCPSTAT_INC(tcps_ecn_ect1);
13664                         break;
13665                 }
13666
13667                 /* Process a packet differently from RFC3168. */
13668                 cc_ecnpkt_handler(tp, th, iptos);
13669
13670                 /* Congestion experienced. */
13671                 if (thflags & TH_ECE) {
13672                         rack_cong_signal(tp, CC_ECN, th->th_ack);
13673                 }
13674         }
13675
13676         /*
13677          * If echoed timestamp is later than the current time, fall back to
13678          * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
13679          * were used when this connection was established.
13680          */
13681         if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
13682                 to.to_tsecr -= tp->ts_offset;
13683                 if (TSTMP_GT(to.to_tsecr, cts))
13684                         to.to_tsecr = 0;
13685         }
13686
13687         /*
13688          * If its the first time in we need to take care of options and
13689          * verify we can do SACK for rack!
13690          */
13691         if (rack->r_state == 0) {
13692                 /* Should be init'd by rack_init() */
13693                 KASSERT(rack->rc_inp != NULL,
13694                     ("%s: rack->rc_inp unexpectedly NULL", __func__));
13695                 if (rack->rc_inp == NULL) {
13696                         rack->rc_inp = tp->t_inpcb;
13697                 }
13698
13699                 /*
13700                  * Process options only when we get SYN/ACK back. The SYN
13701                  * case for incoming connections is handled in tcp_syncache.
13702                  * According to RFC1323 the window field in a SYN (i.e., a
13703                  * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
13704                  * this is traditional behavior, may need to be cleaned up.
13705                  */
13706                 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
13707                         /* Handle parallel SYN for ECN */
13708                         if (!(thflags & TH_ACK) &&
13709                             ((thflags & (TH_CWR | TH_ECE)) == (TH_CWR | TH_ECE)) &&
13710                             ((V_tcp_do_ecn == 1) || (V_tcp_do_ecn == 2))) {
13711                                 tp->t_flags2 |= TF2_ECN_PERMIT;
13712                                 tp->t_flags2 |= TF2_ECN_SND_ECE;
13713                                 TCPSTAT_INC(tcps_ecn_shs);
13714                         }
13715                         if ((to.to_flags & TOF_SCALE) &&
13716                             (tp->t_flags & TF_REQ_SCALE)) {
13717                                 tp->t_flags |= TF_RCVD_SCALE;
13718                                 tp->snd_scale = to.to_wscale;
13719                         } else
13720                                 tp->t_flags &= ~TF_REQ_SCALE;
13721                         /*
13722                          * Initial send window.  It will be updated with the
13723                          * next incoming segment to the scaled value.
13724                          */
13725                         tp->snd_wnd = th->th_win;
13726                         rack_validate_fo_sendwin_up(tp, rack);
13727                         if ((to.to_flags & TOF_TS) &&
13728                             (tp->t_flags & TF_REQ_TSTMP)) {
13729                                 tp->t_flags |= TF_RCVD_TSTMP;
13730                                 tp->ts_recent = to.to_tsval;
13731                                 tp->ts_recent_age = cts;
13732                         } else
13733                                 tp->t_flags &= ~TF_REQ_TSTMP;
13734                         if (to.to_flags & TOF_MSS) {
13735                                 tcp_mss(tp, to.to_mss);
13736                         }
13737                         if ((tp->t_flags & TF_SACK_PERMIT) &&
13738                             (to.to_flags & TOF_SACKPERM) == 0)
13739                                 tp->t_flags &= ~TF_SACK_PERMIT;
13740                         if (IS_FASTOPEN(tp->t_flags)) {
13741                                 if (to.to_flags & TOF_FASTOPEN) {
13742                                         uint16_t mss;
13743
13744                                         if (to.to_flags & TOF_MSS)
13745                                                 mss = to.to_mss;
13746                                         else
13747                                                 if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
13748                                                         mss = TCP6_MSS;
13749                                                 else
13750                                                         mss = TCP_MSS;
13751                                         tcp_fastopen_update_cache(tp, mss,
13752                                             to.to_tfo_len, to.to_tfo_cookie);
13753                                 } else
13754                                         tcp_fastopen_disable_path(tp);
13755                         }
13756                 }
13757                 /*
13758                  * At this point we are at the initial call. Here we decide
13759                  * if we are doing RACK or not. We do this by seeing if
13760                  * TF_SACK_PERMIT is set and the sack-not-required is clear.
13761                  * The code now does do dup-ack counting so if you don't
13762                  * switch back you won't get rack & TLP, but you will still
13763                  * get this stack.
13764                  */
13765
13766                 if ((rack_sack_not_required == 0) &&
13767                     ((tp->t_flags & TF_SACK_PERMIT) == 0)) {
13768                         tcp_switch_back_to_default(tp);
13769                         (*tp->t_fb->tfb_tcp_do_segment) (m, th, so, tp, drop_hdrlen,
13770                             tlen, iptos);
13771 #ifdef TCP_ACCOUNTING
13772                         sched_unpin();
13773 #endif
13774                         return (1);
13775                 }
13776                 tcp_set_hpts(tp->t_inpcb);
13777                 sack_filter_clear(&rack->r_ctl.rack_sf, th->th_ack);
13778         }
13779         if (thflags & TH_FIN)
13780                 tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
13781         us_cts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
13782         if ((rack->rc_gp_dyn_mul) &&
13783             (rack->use_fixed_rate == 0) &&
13784             (rack->rc_always_pace)) {
13785                 /* Check in on probertt */
13786                 rack_check_probe_rtt(rack, us_cts);
13787         }
13788         if (rack->forced_ack) {
13789                 uint32_t us_rtt;
13790
13791                 /*
13792                  * A persist or keep-alive was forced out, update our
13793                  * min rtt time. Note we do not worry about lost
13794                  * retransmissions since KEEP-ALIVES and persists
13795                  * are usually way long on times of sending (though
13796                  * if we were really paranoid or worried we could
13797                  * at least use timestamps if available to validate).
13798                  */
13799                 rack->forced_ack = 0;
13800                 us_rtt = us_cts - rack->r_ctl.forced_ack_ts;
13801                 if (us_rtt == 0)
13802                         us_rtt = 1;
13803                 rack_log_rtt_upd(tp, rack, us_rtt, 0, NULL, 3);
13804                 rack_apply_updated_usrtt(rack, us_rtt, us_cts);
13805         }
13806         /*
13807          * This is the one exception case where we set the rack state
13808          * always. All other times (timers etc) we must have a rack-state
13809          * set (so we assure we have done the checks above for SACK).
13810          */
13811         rack->r_ctl.rc_rcvtime = cts;
13812         if (rack->r_state != tp->t_state)
13813                 rack_set_state(tp, rack);
13814         if (SEQ_GT(th->th_ack, tp->snd_una) &&
13815             (rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree)) != NULL)
13816                 kern_prefetch(rsm, &prev_state);
13817         prev_state = rack->r_state;
13818         rack_clear_rate_sample(rack);
13819         retval = (*rack->r_substate) (m, th, so,
13820             tp, &to, drop_hdrlen,
13821             tlen, tiwin, thflags, nxt_pkt, iptos);
13822 #ifdef INVARIANTS
13823         if ((retval == 0) &&
13824             (tp->t_inpcb == NULL)) {
13825                 panic("retval:%d tp:%p t_inpcb:NULL state:%d",
13826                     retval, tp, prev_state);
13827         }
13828 #endif
13829         if (retval == 0) {
13830                 /*
13831                  * If retval is 1 the tcb is unlocked and most likely the tp
13832                  * is gone.
13833                  */
13834                 INP_WLOCK_ASSERT(tp->t_inpcb);
13835                 if ((rack->rc_gp_dyn_mul) &&
13836                     (rack->rc_always_pace) &&
13837                     (rack->use_fixed_rate == 0) &&
13838                     rack->in_probe_rtt &&
13839                     (rack->r_ctl.rc_time_probertt_starts == 0)) {
13840                         /*
13841                          * If we are going for target, lets recheck before
13842                          * we output.
13843                          */
13844                         rack_check_probe_rtt(rack, us_cts);
13845                 }
13846                 if (rack->set_pacing_done_a_iw == 0) {
13847                         /* How much has been acked? */
13848                         if ((tp->snd_una - tp->iss) > (ctf_fixed_maxseg(tp) * 10)) {
13849                                 /* We have enough to set in the pacing segment size */
13850                                 rack->set_pacing_done_a_iw = 1;
13851                                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
13852                         }
13853                 }
13854                 tcp_rack_xmit_timer_commit(rack, tp);
13855 #ifdef TCP_ACCOUNTING
13856                 /*
13857                  * If we set the ack_val_se to what ack processing we are doing
13858                  * we also want to track how many cycles we burned. Note
13859                  * the bits after tcp_output we let be "free". This is because
13860                  * we are also tracking the tcp_output times as well. Note the
13861                  * use of 0xf here since we only have 11 counter (0 - 0xa) and
13862                  * 0xf cannot be returned and is what we initialize it too to
13863                  * indicate we are not doing the tabulations.
13864                  */
13865                 if (ack_val_set != 0xf) {
13866                         uint64_t crtsc;
13867
13868                         crtsc = get_cyclecount();
13869                         counter_u64_add(tcp_proc_time[ack_val_set] , (crtsc - ts_val));
13870                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13871                                 tp->tcp_proc_time[ack_val_set] += (crtsc - ts_val);
13872                         }
13873                 }
13874 #endif
13875                 if (nxt_pkt == 0) {
13876                         if ((rack->r_wanted_output != 0) || (rack->r_fast_output != 0)) {
13877 do_output_now:
13878                                 did_out = 1;
13879                                 (void)tp->t_fb->tfb_tcp_output(tp);
13880                         }
13881                         rack_start_hpts_timer(rack, tp, cts, 0, 0, 0);
13882                         rack_free_trim(rack);
13883                 }
13884                 if ((nxt_pkt == 0) &&
13885                     ((rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
13886                     (SEQ_GT(tp->snd_max, tp->snd_una) ||
13887                      (tp->t_flags & TF_DELACK) ||
13888                      ((V_tcp_always_keepalive || rack->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
13889                       (tp->t_state <= TCPS_CLOSING)))) {
13890                         /* We could not send (probably in the hpts but stopped the timer earlier)? */
13891                         if ((tp->snd_max == tp->snd_una) &&
13892                             ((tp->t_flags & TF_DELACK) == 0) &&
13893                             (rack->rc_inp->inp_in_hpts) &&
13894                             (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
13895                                 /* keep alive not needed if we are hptsi output yet */
13896                                 ;
13897                         } else {
13898                                 int late = 0;
13899                                 if (rack->rc_inp->inp_in_hpts) {
13900                                         if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
13901                                                 us_cts = tcp_get_usecs(NULL);
13902                                                 if (TSTMP_GT(rack->r_ctl.rc_last_output_to, us_cts)) {
13903                                                         rack->r_early = 1;
13904                                                         rack->r_ctl.rc_agg_early += (rack->r_ctl.rc_last_output_to - us_cts);
13905                                                 } else
13906                                                         late = 1;
13907                                                 rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
13908                                         }
13909                                         tcp_hpts_remove(tp->t_inpcb, HPTS_REMOVE_OUTPUT);
13910                                 }
13911                                 if (late && (did_out == 0)) {
13912                                         /*
13913                                          * We are late in the sending
13914                                          * and we did not call the output
13915                                          * (this probably should not happen).
13916                                          */
13917                                         goto do_output_now;
13918                                 }
13919                                 rack_start_hpts_timer(rack, tp, tcp_get_usecs(NULL), 0, 0, 0);
13920                         }
13921                         way_out = 1;
13922                 } else if (nxt_pkt == 0) {
13923                         /* Do we have the correct timer running? */
13924                         rack_timer_audit(tp, rack, &so->so_snd);
13925                         way_out = 2;
13926                 }
13927         done_with_input:
13928                 rack_log_doseg_done(rack, cts, nxt_pkt, did_out, way_out, max(1, m->m_pkthdr.lro_nsegs));
13929                 if (did_out)
13930                         rack->r_wanted_output = 0;
13931 #ifdef INVARIANTS
13932                 if (tp->t_inpcb == NULL) {
13933                         panic("OP:%d retval:%d tp:%p t_inpcb:NULL state:%d",
13934                               did_out,
13935                               retval, tp, prev_state);
13936                 }
13937 #endif
13938 #ifdef TCP_ACCOUNTING
13939         } else {
13940                 /*
13941                  * Track the time (see above).
13942                  */
13943                 if (ack_val_set != 0xf) {
13944                         uint64_t crtsc;
13945
13946                         crtsc = get_cyclecount();
13947                         counter_u64_add(tcp_proc_time[ack_val_set] , (crtsc - ts_val));
13948                         /*
13949                          * Note we *DO NOT* increment the per-tcb counters since
13950                          * in the else the TP may be gone!!
13951                          */
13952                 }
13953 #endif
13954         }
13955 #ifdef TCP_ACCOUNTING
13956         sched_unpin();
13957 #endif
13958         return (retval);
13959 }
13960
13961 void
13962 rack_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
13963     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
13964 {
13965         struct timeval tv;
13966
13967         /* First lets see if we have old packets */
13968         if (tp->t_in_pkt) {
13969                 if (ctf_do_queued_segments(so, tp, 1)) {
13970                         m_freem(m);
13971                         return;
13972                 }
13973         }
13974         if (m->m_flags & M_TSTMP_LRO) {
13975                 tv.tv_sec = m->m_pkthdr.rcv_tstmp /1000000000;
13976                 tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000)/1000;
13977         } else {
13978                 /* Should not be should we kassert instead? */
13979                 tcp_get_usecs(&tv);
13980         }
13981         if (rack_do_segment_nounlock(m, th, so, tp,
13982                                      drop_hdrlen, tlen, iptos, 0, &tv) == 0) {
13983                 tcp_handle_wakeup(tp, so);
13984                 INP_WUNLOCK(tp->t_inpcb);
13985         }
13986 }
13987
13988 struct rack_sendmap *
13989 tcp_rack_output(struct tcpcb *tp, struct tcp_rack *rack, uint32_t tsused)
13990 {
13991         struct rack_sendmap *rsm = NULL;
13992         int32_t idx;
13993         uint32_t srtt = 0, thresh = 0, ts_low = 0;
13994
13995         /* Return the next guy to be re-transmitted */
13996         if (RB_EMPTY(&rack->r_ctl.rc_mtree)) {
13997                 return (NULL);
13998         }
13999         if (tp->t_flags & TF_SENTFIN) {
14000                 /* retran the end FIN? */
14001                 return (NULL);
14002         }
14003         /* ok lets look at this one */
14004         rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
14005         if (rsm && ((rsm->r_flags & RACK_ACKED) == 0)) {
14006                 goto check_it;
14007         }
14008         rsm = rack_find_lowest_rsm(rack);
14009         if (rsm == NULL) {
14010                 return (NULL);
14011         }
14012 check_it:
14013         if (((rack->rc_tp->t_flags & TF_SACK_PERMIT) == 0) &&
14014             (rsm->r_dupack >= DUP_ACK_THRESHOLD)) {
14015                 /*
14016                  * No sack so we automatically do the 3 strikes and
14017                  * retransmit (no rack timer would be started).
14018                  */
14019
14020                 return (rsm);
14021         }
14022         if (rsm->r_flags & RACK_ACKED) {
14023                 return (NULL);
14024         }
14025         if (((rsm->r_flags & RACK_SACK_PASSED) == 0) &&
14026             (rsm->r_dupack < DUP_ACK_THRESHOLD)) {
14027                 /* Its not yet ready */
14028                 return (NULL);
14029         }
14030         srtt = rack_grab_rtt(tp, rack);
14031         idx = rsm->r_rtr_cnt - 1;
14032         ts_low = (uint32_t)rsm->r_tim_lastsent[idx];
14033         thresh = rack_calc_thresh_rack(rack, srtt, tsused);
14034         if ((tsused == ts_low) ||
14035             (TSTMP_LT(tsused, ts_low))) {
14036                 /* No time since sending */
14037                 return (NULL);
14038         }
14039         if ((tsused - ts_low) < thresh) {
14040                 /* It has not been long enough yet */
14041                 return (NULL);
14042         }
14043         if ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
14044             ((rsm->r_flags & RACK_SACK_PASSED) &&
14045              (rack->sack_attack_disable == 0))) {
14046                 /*
14047                  * We have passed the dup-ack threshold <or>
14048                  * a SACK has indicated this is missing.
14049                  * Note that if you are a declared attacker
14050                  * it is only the dup-ack threshold that
14051                  * will cause retransmits.
14052                  */
14053                 /* log retransmit reason */
14054                 rack_log_retran_reason(rack, rsm, (tsused - ts_low), thresh, 1);
14055                 rack->r_fast_output = 0;
14056                 return (rsm);
14057         }
14058         return (NULL);
14059 }
14060
14061 static void
14062 rack_log_pacing_delay_calc(struct tcp_rack *rack, uint32_t len, uint32_t slot,
14063                            uint64_t bw_est, uint64_t bw, uint64_t len_time, int method,
14064                            int line, struct rack_sendmap *rsm)
14065 {
14066         if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
14067                 union tcp_log_stackspecific log;
14068                 struct timeval tv;
14069
14070                 memset(&log, 0, sizeof(log));
14071                 log.u_bbr.flex1 = slot;
14072                 log.u_bbr.flex2 = len;
14073                 log.u_bbr.flex3 = rack->r_ctl.rc_pace_min_segs;
14074                 log.u_bbr.flex4 = rack->r_ctl.rc_pace_max_segs;
14075                 log.u_bbr.flex5 = rack->r_ctl.rack_per_of_gp_ss;
14076                 log.u_bbr.flex6 = rack->r_ctl.rack_per_of_gp_ca;
14077                 log.u_bbr.use_lt_bw = rack->rc_ack_can_sendout_data;
14078                 log.u_bbr.use_lt_bw <<= 1;
14079                 log.u_bbr.use_lt_bw |= rack->r_late;
14080                 log.u_bbr.use_lt_bw <<= 1;
14081                 log.u_bbr.use_lt_bw |= rack->r_early;
14082                 log.u_bbr.use_lt_bw <<= 1;
14083                 log.u_bbr.use_lt_bw |= rack->app_limited_needs_set;
14084                 log.u_bbr.use_lt_bw <<= 1;
14085                 log.u_bbr.use_lt_bw |= rack->rc_gp_filled;
14086                 log.u_bbr.use_lt_bw <<= 1;
14087                 log.u_bbr.use_lt_bw |= rack->measure_saw_probe_rtt;
14088                 log.u_bbr.use_lt_bw <<= 1;
14089                 log.u_bbr.use_lt_bw |= rack->in_probe_rtt;
14090                 log.u_bbr.use_lt_bw <<= 1;
14091                 log.u_bbr.use_lt_bw |= rack->gp_ready;
14092                 log.u_bbr.pkt_epoch = line;
14093                 log.u_bbr.epoch = rack->r_ctl.rc_agg_delayed;
14094                 log.u_bbr.lt_epoch = rack->r_ctl.rc_agg_early;
14095                 log.u_bbr.applimited = rack->r_ctl.rack_per_of_gp_rec;
14096                 log.u_bbr.bw_inuse = bw_est;
14097                 log.u_bbr.delRate = bw;
14098                 if (rack->r_ctl.gp_bw == 0)
14099                         log.u_bbr.cur_del_rate = 0;
14100                 else
14101                         log.u_bbr.cur_del_rate = rack_get_bw(rack);
14102                 log.u_bbr.rttProp = len_time;
14103                 log.u_bbr.pkts_out = rack->r_ctl.rc_rack_min_rtt;
14104                 log.u_bbr.lost = rack->r_ctl.rc_probertt_sndmax_atexit;
14105                 log.u_bbr.pacing_gain = rack_get_output_gain(rack, rsm);
14106                 if (rack->r_ctl.cwnd_to_use < rack->rc_tp->snd_ssthresh) {
14107                         /* We are in slow start */
14108                         log.u_bbr.flex7 = 1;
14109                 } else {
14110                         /* we are on congestion avoidance */
14111                         log.u_bbr.flex7 = 0;
14112                 }
14113                 log.u_bbr.flex8 = method;
14114                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
14115                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
14116                 log.u_bbr.cwnd_gain = rack->rc_gp_saw_rec;
14117                 log.u_bbr.cwnd_gain <<= 1;
14118                 log.u_bbr.cwnd_gain |= rack->rc_gp_saw_ss;
14119                 log.u_bbr.cwnd_gain <<= 1;
14120                 log.u_bbr.cwnd_gain |= rack->rc_gp_saw_ca;
14121                 TCP_LOG_EVENTP(rack->rc_tp, NULL,
14122                     &rack->rc_inp->inp_socket->so_rcv,
14123                     &rack->rc_inp->inp_socket->so_snd,
14124                     BBR_LOG_HPTSI_CALC, 0,
14125                     0, &log, false, &tv);
14126         }
14127 }
14128
14129 static uint32_t
14130 rack_get_pacing_len(struct tcp_rack *rack, uint64_t bw, uint32_t mss)
14131 {
14132         uint32_t new_tso, user_max;
14133
14134         user_max = rack->rc_user_set_max_segs * mss;
14135         if (rack->rc_force_max_seg) {
14136                 return (user_max);
14137         }
14138         if (rack->use_fixed_rate &&
14139             ((rack->r_ctl.crte == NULL) ||
14140              (bw != rack->r_ctl.crte->rate))) {
14141                 /* Use the user mss since we are not exactly matched */
14142                 return (user_max);
14143         }
14144         new_tso = tcp_get_pacing_burst_size(rack->rc_tp, bw, mss, rack_pace_one_seg, rack->r_ctl.crte, NULL);
14145         if (new_tso > user_max)
14146                 new_tso = user_max;
14147         return (new_tso);
14148 }
14149
14150 static int32_t
14151 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)
14152 {
14153         uint64_t lentim, fill_bw;
14154
14155         /* Lets first see if we are full, if so continue with normal rate */
14156         rack->r_via_fill_cw = 0;
14157         if (ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked) > rack->r_ctl.cwnd_to_use)
14158                 return (slot);
14159         if ((ctf_outstanding(rack->rc_tp) + (segsiz-1)) > rack->rc_tp->snd_wnd)
14160                 return (slot);
14161         if (rack->r_ctl.rc_last_us_rtt == 0)
14162                 return (slot);
14163         if (rack->rc_pace_fill_if_rttin_range &&
14164             (rack->r_ctl.rc_last_us_rtt >=
14165              (get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) * rack->rtt_limit_mul))) {
14166                 /* The rtt is huge, N * smallest, lets not fill */
14167                 return (slot);
14168         }
14169         /*
14170          * first lets calculate the b/w based on the last us-rtt
14171          * and the sndwnd.
14172          */
14173         fill_bw = rack->r_ctl.cwnd_to_use;
14174         /* Take the rwnd if its smaller */
14175         if (fill_bw > rack->rc_tp->snd_wnd)
14176                 fill_bw = rack->rc_tp->snd_wnd;
14177         if (rack->r_fill_less_agg) {
14178                 /*
14179                  * Now take away the inflight (this will reduce our
14180                  * aggressiveness and yeah, if we get that much out in 1RTT
14181                  * we will have had acks come back and still be behind).
14182                  */
14183                 fill_bw -= ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
14184         }
14185         /* Now lets make it into a b/w */
14186         fill_bw *= (uint64_t)HPTS_USEC_IN_SEC;
14187         fill_bw /= (uint64_t)rack->r_ctl.rc_last_us_rtt;
14188         /* We are below the min b/w */
14189         if (non_paced)
14190                 *rate_wanted = fill_bw;
14191         if ((fill_bw < RACK_MIN_BW) || (fill_bw < *rate_wanted))
14192                 return (slot);
14193         if (rack->r_ctl.bw_rate_cap && (fill_bw > rack->r_ctl.bw_rate_cap))
14194                 fill_bw = rack->r_ctl.bw_rate_cap;
14195         rack->r_via_fill_cw = 1;
14196         if (rack->r_rack_hw_rate_caps &&
14197             (rack->r_ctl.crte != NULL)) {
14198                 uint64_t high_rate;
14199
14200                 high_rate = tcp_hw_highest_rate(rack->r_ctl.crte);
14201                 if (fill_bw > high_rate) {
14202                         /* We are capping bw at the highest rate table entry */
14203                         if (*rate_wanted > high_rate) {
14204                                 /* The original rate was also capped */
14205                                 rack->r_via_fill_cw = 0;
14206                         }
14207                         rack_log_hdwr_pacing(rack,
14208                                              fill_bw, high_rate, __LINE__,
14209                                              0, 3);
14210                         fill_bw = high_rate;
14211                         if (capped)
14212                                 *capped = 1;
14213                 }
14214         } else if ((rack->r_ctl.crte == NULL) &&
14215                    (rack->rack_hdrw_pacing == 0) &&
14216                    (rack->rack_hdw_pace_ena) &&
14217                    rack->r_rack_hw_rate_caps &&
14218                    (rack->rack_attempt_hdwr_pace == 0) &&
14219                    (rack->rc_inp->inp_route.ro_nh != NULL) &&
14220                    (rack->rc_inp->inp_route.ro_nh->nh_ifp != NULL)) {
14221                 /*
14222                  * Ok we may have a first attempt that is greater than our top rate
14223                  * lets check.
14224                  */
14225                 uint64_t high_rate;
14226
14227                 high_rate = tcp_hw_highest_rate_ifp(rack->rc_inp->inp_route.ro_nh->nh_ifp, rack->rc_inp);
14228                 if (high_rate) {
14229                         if (fill_bw > high_rate) {
14230                                 fill_bw = high_rate;
14231                                 if (capped)
14232                                         *capped = 1;
14233                         }
14234                 }
14235         }
14236         /*
14237          * Ok fill_bw holds our mythical b/w to fill the cwnd
14238          * in a rtt, what does that time wise equate too?
14239          */
14240         lentim = (uint64_t)(len) * (uint64_t)HPTS_USEC_IN_SEC;
14241         lentim /= fill_bw;
14242         *rate_wanted = fill_bw;
14243         if (non_paced || (lentim < slot)) {
14244                 rack_log_pacing_delay_calc(rack, len, slot, fill_bw,
14245                                            0, lentim, 12, __LINE__, NULL);
14246                 return ((int32_t)lentim);
14247         } else
14248                 return (slot);
14249 }
14250
14251 static int32_t
14252 rack_get_pacing_delay(struct tcp_rack *rack, struct tcpcb *tp, uint32_t len, struct rack_sendmap *rsm, uint32_t segsiz)
14253 {
14254         struct rack_sendmap *lrsm;
14255         int32_t slot = 0;
14256         int can_start_hw_pacing = 1;
14257         int err;
14258
14259         if (rack->rc_always_pace == 0) {
14260                 /*
14261                  * We use the most optimistic possible cwnd/srtt for
14262                  * sending calculations. This will make our
14263                  * calculation anticipate getting more through
14264                  * quicker then possible. But thats ok we don't want
14265                  * the peer to have a gap in data sending.
14266                  */
14267                 uint32_t srtt, cwnd, tr_perms = 0;
14268                 int32_t reduce = 0;
14269
14270         old_method:
14271                 /*
14272                  * We keep no precise pacing with the old method
14273                  * instead we use the pacer to mitigate bursts.
14274                  */
14275                 if (rack->r_ctl.rc_rack_min_rtt)
14276                         srtt = rack->r_ctl.rc_rack_min_rtt;
14277                 else
14278                         srtt = max(tp->t_srtt, 1);
14279                 if (rack->r_ctl.rc_rack_largest_cwnd)
14280                         cwnd = rack->r_ctl.rc_rack_largest_cwnd;
14281                 else
14282                         cwnd = rack->r_ctl.cwnd_to_use;
14283                 /* Inflate cwnd by 1000 so srtt of usecs is in ms */
14284                 tr_perms = (cwnd * 1000) / srtt;
14285                 if (tr_perms == 0) {
14286                         tr_perms = ctf_fixed_maxseg(tp);
14287                 }
14288                 /*
14289                  * Calculate how long this will take to drain, if
14290                  * the calculation comes out to zero, thats ok we
14291                  * will use send_a_lot to possibly spin around for
14292                  * more increasing tot_len_this_send to the point
14293                  * that its going to require a pace, or we hit the
14294                  * cwnd. Which in that case we are just waiting for
14295                  * a ACK.
14296                  */
14297                 slot = len / tr_perms;
14298                 /* Now do we reduce the time so we don't run dry? */
14299                 if (slot && rack_slot_reduction) {
14300                         reduce = (slot / rack_slot_reduction);
14301                         if (reduce < slot) {
14302                                 slot -= reduce;
14303                         } else
14304                                 slot = 0;
14305                 }
14306                 slot *= HPTS_USEC_IN_MSEC;
14307                 if (rsm == NULL) {
14308                         /*
14309                          * We always consider ourselves app limited with old style
14310                          * that are not retransmits. This could be the initial
14311                          * measurement, but thats ok its all setup and specially
14312                          * handled. If another send leaks out, then that too will
14313                          * be mark app-limited.
14314                          */
14315                         lrsm = RB_MAX(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
14316                         if (lrsm && ((lrsm->r_flags & RACK_APP_LIMITED) == 0)) {
14317                                 rack->r_ctl.rc_first_appl = lrsm;
14318                                 lrsm->r_flags |= RACK_APP_LIMITED;
14319                                 rack->r_ctl.rc_app_limited_cnt++;
14320                         }
14321                 }
14322                 if (rack->rc_pace_to_cwnd) {
14323                         uint64_t rate_wanted = 0;
14324
14325                         slot = pace_to_fill_cwnd(rack, slot, len, segsiz, NULL, &rate_wanted, 1);
14326                         rack->rc_ack_can_sendout_data = 1;
14327                         rack_log_pacing_delay_calc(rack, len, slot, rate_wanted, 0, 0, 14, __LINE__, NULL);
14328                 } else
14329                         rack_log_pacing_delay_calc(rack, len, slot, tr_perms, reduce, 0, 7, __LINE__, NULL);
14330         } else {
14331                 uint64_t bw_est, res, lentim, rate_wanted;
14332                 uint32_t orig_val, srtt, segs, oh;
14333                 int capped = 0;
14334                 int prev_fill;
14335
14336                 if ((rack->r_rr_config == 1) && rsm) {
14337                         return (rack->r_ctl.rc_min_to);
14338                 }
14339                 if (rack->use_fixed_rate) {
14340                         rate_wanted = bw_est = rack_get_fixed_pacing_bw(rack);
14341                 } else if ((rack->r_ctl.init_rate == 0) &&
14342 #ifdef NETFLIX_PEAKRATE
14343                            (rack->rc_tp->t_maxpeakrate == 0) &&
14344 #endif
14345                            (rack->r_ctl.gp_bw == 0)) {
14346                         /* no way to yet do an estimate */
14347                         bw_est = rate_wanted = 0;
14348                 } else {
14349                         bw_est = rack_get_bw(rack);
14350                         rate_wanted = rack_get_output_bw(rack, bw_est, rsm, &capped);
14351                 }
14352                 if ((bw_est == 0) || (rate_wanted == 0) ||
14353                     ((rack->gp_ready == 0) && (rack->use_fixed_rate == 0))) {
14354                         /*
14355                          * No way yet to make a b/w estimate or
14356                          * our raise is set incorrectly.
14357                          */
14358                         goto old_method;
14359                 }
14360                 /* We need to account for all the overheads */
14361                 segs = (len + segsiz - 1) / segsiz;
14362                 /*
14363                  * We need the diff between 1514 bytes (e-mtu with e-hdr)
14364                  * and how much data we put in each packet. Yes this
14365                  * means we may be off if we are larger than 1500 bytes
14366                  * or smaller. But this just makes us more conservative.
14367                  */
14368                 if (rack_hw_rate_min &&
14369                     (bw_est < rack_hw_rate_min))
14370                         can_start_hw_pacing = 0;
14371                 if (ETHERNET_SEGMENT_SIZE > segsiz)
14372                         oh = ETHERNET_SEGMENT_SIZE - segsiz;
14373                 else
14374                         oh = 0;
14375                 segs *= oh;
14376                 lentim = (uint64_t)(len + segs) * (uint64_t)HPTS_USEC_IN_SEC;
14377                 res = lentim / rate_wanted;
14378                 slot = (uint32_t)res;
14379                 orig_val = rack->r_ctl.rc_pace_max_segs;
14380                 if (rack->r_ctl.crte == NULL) {
14381                         /*
14382                          * Only do this if we are not hardware pacing
14383                          * since if we are doing hw-pacing below we will
14384                          * set make a call after setting up or changing
14385                          * the rate.
14386                          */
14387                         rack_set_pace_segments(rack->rc_tp, rack, __LINE__, NULL);
14388                 } else if (rack->rc_inp->inp_snd_tag == NULL) {
14389                         /*
14390                          * We lost our rate somehow, this can happen
14391                          * if the interface changed underneath us.
14392                          */
14393                         tcp_rel_pacing_rate(rack->r_ctl.crte, rack->rc_tp);
14394                         rack->r_ctl.crte = NULL;
14395                         /* Lets re-allow attempting to setup pacing */
14396                         rack->rack_hdrw_pacing = 0;
14397                         rack->rack_attempt_hdwr_pace = 0;
14398                         rack_log_hdwr_pacing(rack,
14399                                              rate_wanted, bw_est, __LINE__,
14400                                              0, 6);
14401                 }
14402                 /* Did we change the TSO size, if so log it */
14403                 if (rack->r_ctl.rc_pace_max_segs != orig_val)
14404                         rack_log_pacing_delay_calc(rack, len, slot, orig_val, 0, 0, 15, __LINE__, NULL);
14405                 prev_fill = rack->r_via_fill_cw;
14406                 if ((rack->rc_pace_to_cwnd) &&
14407                     (capped == 0) &&
14408                     (rack->use_fixed_rate == 0) &&
14409                     (rack->in_probe_rtt == 0) &&
14410                     (IN_FASTRECOVERY(rack->rc_tp->t_flags) == 0)) {
14411                         /*
14412                          * We want to pace at our rate *or* faster to
14413                          * fill the cwnd to the max if its not full.
14414                          */
14415                         slot = pace_to_fill_cwnd(rack, slot, (len+segs), segsiz, &capped, &rate_wanted, 0);
14416                 }
14417                 if ((rack->rc_inp->inp_route.ro_nh != NULL) &&
14418                     (rack->rc_inp->inp_route.ro_nh->nh_ifp != NULL)) {
14419                         if ((rack->rack_hdw_pace_ena) &&
14420                             (can_start_hw_pacing > 0) &&
14421                             (rack->rack_hdrw_pacing == 0) &&
14422                             (rack->rack_attempt_hdwr_pace == 0)) {
14423                                 /*
14424                                  * Lets attempt to turn on hardware pacing
14425                                  * if we can.
14426                                  */
14427                                 rack->rack_attempt_hdwr_pace = 1;
14428                                 rack->r_ctl.crte = tcp_set_pacing_rate(rack->rc_tp,
14429                                                                        rack->rc_inp->inp_route.ro_nh->nh_ifp,
14430                                                                        rate_wanted,
14431                                                                        RS_PACING_GEQ,
14432                                                                        &err, &rack->r_ctl.crte_prev_rate);
14433                                 if (rack->r_ctl.crte) {
14434                                         rack->rack_hdrw_pacing = 1;
14435                                         rack->r_ctl.rc_pace_max_segs = tcp_get_pacing_burst_size(tp, rate_wanted, segsiz,
14436                                                                                                  0, rack->r_ctl.crte,
14437                                                                                                  NULL);
14438                                         rack_log_hdwr_pacing(rack,
14439                                                              rate_wanted, rack->r_ctl.crte->rate, __LINE__,
14440                                                              err, 0);
14441                                         rack->r_ctl.last_hw_bw_req = rate_wanted;
14442                                 } else {
14443                                         counter_u64_add(rack_hw_pace_init_fail, 1);
14444                                 }
14445                         } else if (rack->rack_hdrw_pacing &&
14446                                    (rack->r_ctl.last_hw_bw_req != rate_wanted)) {
14447                                 /* Do we need to adjust our rate? */
14448                                 const struct tcp_hwrate_limit_table *nrte;
14449
14450                                 if (rack->r_up_only &&
14451                                     (rate_wanted < rack->r_ctl.crte->rate)) {
14452                                         /**
14453                                          * We have four possible states here
14454                                          * having to do with the previous time
14455                                          * and this time.
14456                                          *   previous  |  this-time
14457                                          * A)     0      |     0   -- fill_cw not in the picture
14458                                          * B)     1      |     0   -- we were doing a fill-cw but now are not
14459                                          * C)     1      |     1   -- all rates from fill_cw
14460                                          * D)     0      |     1   -- we were doing non-fill and now we are filling
14461                                          *
14462                                          * For case A, C and D we don't allow a drop. But for
14463                                          * case B where we now our on our steady rate we do
14464                                          * allow a drop.
14465                                          *
14466                                          */
14467                                         if (!((prev_fill == 1) && (rack->r_via_fill_cw == 0)))
14468                                                 goto done_w_hdwr;
14469                                 }
14470                                 if ((rate_wanted > rack->r_ctl.crte->rate) ||
14471                                     (rate_wanted <= rack->r_ctl.crte_prev_rate)) {
14472                                         if (rack_hw_rate_to_low &&
14473                                             (bw_est < rack_hw_rate_to_low)) {
14474                                                 /*
14475                                                  * The pacing rate is too low for hardware, but
14476                                                  * do allow hardware pacing to be restarted.
14477                                                  */
14478                                                 rack_log_hdwr_pacing(rack,
14479                                                              bw_est, rack->r_ctl.crte->rate, __LINE__,
14480                                                              0, 5);
14481                                                 tcp_rel_pacing_rate(rack->r_ctl.crte, rack->rc_tp);
14482                                                 rack->r_ctl.crte = NULL;
14483                                                 rack->rack_attempt_hdwr_pace = 0;
14484                                                 rack->rack_hdrw_pacing = 0;
14485                                                 rack_set_pace_segments(rack->rc_tp, rack, __LINE__, &rate_wanted);
14486                                                 goto done_w_hdwr;
14487                                         }
14488                                         nrte = tcp_chg_pacing_rate(rack->r_ctl.crte,
14489                                                                    rack->rc_tp,
14490                                                                    rack->rc_inp->inp_route.ro_nh->nh_ifp,
14491                                                                    rate_wanted,
14492                                                                    RS_PACING_GEQ,
14493                                                                    &err, &rack->r_ctl.crte_prev_rate);
14494                                         if (nrte == NULL) {
14495                                                 /* Lost the rate */
14496                                                 rack->rack_hdrw_pacing = 0;
14497                                                 rack->r_ctl.crte = NULL;
14498                                                 rack_log_hdwr_pacing(rack,
14499                                                                      rate_wanted, 0, __LINE__,
14500                                                                      err, 1);
14501                                                 rack_set_pace_segments(rack->rc_tp, rack, __LINE__, &rate_wanted);
14502                                                 counter_u64_add(rack_hw_pace_lost, 1);
14503                                         } else if (nrte != rack->r_ctl.crte) {
14504                                                 rack->r_ctl.crte = nrte;
14505                                                 rack->r_ctl.rc_pace_max_segs = tcp_get_pacing_burst_size(tp, rate_wanted,
14506                                                                                                          segsiz, 0,
14507                                                                                                          rack->r_ctl.crte,
14508                                                                                                          NULL);
14509                                                 rack_log_hdwr_pacing(rack,
14510                                                                      rate_wanted, rack->r_ctl.crte->rate, __LINE__,
14511                                                                      err, 2);
14512                                                 rack->r_ctl.last_hw_bw_req = rate_wanted;
14513                                         }
14514                                 } else {
14515                                         /* We just need to adjust the segment size */
14516                                         rack_set_pace_segments(rack->rc_tp, rack, __LINE__, &rate_wanted);
14517                                         rack_log_hdwr_pacing(rack,
14518                                                              rate_wanted, rack->r_ctl.crte->rate, __LINE__,
14519                                                              0, 4);
14520                                         rack->r_ctl.last_hw_bw_req = rate_wanted;
14521                                 }
14522                         }
14523                 }
14524                 if ((rack->r_ctl.crte != NULL) &&
14525                     (rack->r_ctl.crte->rate == rate_wanted)) {
14526                         /*
14527                          * We need to add a extra if the rates
14528                          * are exactly matched. The idea is
14529                          * we want the software to make sure the
14530                          * queue is empty before adding more, this
14531                          * gives us N MSS extra pace times where
14532                          * N is our sysctl
14533                          */
14534                         slot += (rack->r_ctl.crte->time_between * rack_hw_pace_extra_slots);
14535                 }
14536 done_w_hdwr:
14537                 if (rack_limit_time_with_srtt &&
14538                     (rack->use_fixed_rate == 0) &&
14539 #ifdef NETFLIX_PEAKRATE
14540                     (rack->rc_tp->t_maxpeakrate == 0) &&
14541 #endif
14542                     (rack->rack_hdrw_pacing == 0)) {
14543                         /*
14544                          * Sanity check, we do not allow the pacing delay
14545                          * to be longer than the SRTT of the path. If it is
14546                          * a slow path, then adding a packet should increase
14547                          * the RTT and compensate for this i.e. the srtt will
14548                          * be greater so the allowed pacing time will be greater.
14549                          *
14550                          * Note this restriction is not for where a peak rate
14551                          * is set, we are doing fixed pacing or hardware pacing.
14552                          */
14553                         if (rack->rc_tp->t_srtt)
14554                                 srtt = rack->rc_tp->t_srtt;
14555                         else
14556                                 srtt = RACK_INITIAL_RTO * HPTS_USEC_IN_MSEC;    /* its in ms convert */
14557                         if (srtt < slot) {
14558                                 rack_log_pacing_delay_calc(rack, srtt, slot, rate_wanted, bw_est, lentim, 99, __LINE__, NULL);
14559                                 slot = srtt;
14560                         }
14561                 }
14562                 rack_log_pacing_delay_calc(rack, len, slot, rate_wanted, bw_est, lentim, 2, __LINE__, rsm);
14563         }
14564         if (rack->r_ctl.crte && (rack->r_ctl.crte->rs_num_enobufs > 0)) {
14565                 /*
14566                  * If this rate is seeing enobufs when it
14567                  * goes to send then either the nic is out
14568                  * of gas or we are mis-estimating the time
14569                  * somehow and not letting the queue empty
14570                  * completely. Lets add to the pacing time.
14571                  */
14572                 int hw_boost_delay;
14573
14574                 hw_boost_delay = rack->r_ctl.crte->time_between * rack_enobuf_hw_boost_mult;
14575                 if (hw_boost_delay > rack_enobuf_hw_max)
14576                         hw_boost_delay = rack_enobuf_hw_max;
14577                 else if (hw_boost_delay < rack_enobuf_hw_min)
14578                         hw_boost_delay = rack_enobuf_hw_min;
14579                 slot += hw_boost_delay;
14580         }
14581         if (slot)
14582                 counter_u64_add(rack_calc_nonzero, 1);
14583         else
14584                 counter_u64_add(rack_calc_zero, 1);
14585         return (slot);
14586 }
14587
14588 static void
14589 rack_start_gp_measurement(struct tcpcb *tp, struct tcp_rack *rack,
14590     tcp_seq startseq, uint32_t sb_offset)
14591 {
14592         struct rack_sendmap *my_rsm = NULL;
14593         struct rack_sendmap fe;
14594
14595         if (tp->t_state < TCPS_ESTABLISHED) {
14596                 /*
14597                  * We don't start any measurements if we are
14598                  * not at least established.
14599                  */
14600                 return;
14601         }
14602         tp->t_flags |= TF_GPUTINPROG;
14603         rack->r_ctl.rc_gp_lowrtt = 0xffffffff;
14604         rack->r_ctl.rc_gp_high_rwnd = rack->rc_tp->snd_wnd;
14605         tp->gput_seq = startseq;
14606         rack->app_limited_needs_set = 0;
14607         if (rack->in_probe_rtt)
14608                 rack->measure_saw_probe_rtt = 1;
14609         else if ((rack->measure_saw_probe_rtt) &&
14610                  (SEQ_GEQ(tp->gput_seq, rack->r_ctl.rc_probertt_sndmax_atexit)))
14611                 rack->measure_saw_probe_rtt = 0;
14612         if (rack->rc_gp_filled)
14613                 tp->gput_ts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
14614         else {
14615                 /* Special case initial measurement */
14616                 struct timeval tv;
14617
14618                 tp->gput_ts = tcp_get_usecs(&tv);
14619                 rack->r_ctl.rc_gp_output_ts = rack_to_usec_ts(&tv);
14620         }
14621         /*
14622          * We take a guess out into the future,
14623          * if we have no measurement and no
14624          * initial rate, we measure the first
14625          * initial-windows worth of data to
14626          * speed up getting some GP measurement and
14627          * thus start pacing.
14628          */
14629         if ((rack->rc_gp_filled == 0) && (rack->r_ctl.init_rate == 0)) {
14630                 rack->app_limited_needs_set = 1;
14631                 tp->gput_ack = startseq + max(rc_init_window(rack),
14632                                               (MIN_GP_WIN * ctf_fixed_maxseg(tp)));
14633                 rack_log_pacing_delay_calc(rack,
14634                                            tp->gput_seq,
14635                                            tp->gput_ack,
14636                                            0,
14637                                            tp->gput_ts,
14638                                            rack->r_ctl.rc_app_limited_cnt,
14639                                            9,
14640                                            __LINE__, NULL);
14641                 return;
14642         }
14643         if (sb_offset) {
14644                 /*
14645                  * We are out somewhere in the sb
14646                  * can we use the already outstanding data?
14647                  */
14648
14649                 if (rack->r_ctl.rc_app_limited_cnt == 0) {
14650                         /*
14651                          * Yes first one is good and in this case
14652                          * the tp->gput_ts is correctly set based on
14653                          * the last ack that arrived (no need to
14654                          * set things up when an ack comes in).
14655                          */
14656                         my_rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
14657                         if ((my_rsm == NULL) ||
14658                             (my_rsm->r_rtr_cnt != 1)) {
14659                                 /* retransmission? */
14660                                 goto use_latest;
14661                         }
14662                 } else {
14663                         if (rack->r_ctl.rc_first_appl == NULL) {
14664                                 /*
14665                                  * If rc_first_appl is NULL
14666                                  * then the cnt should be 0.
14667                                  * This is probably an error, maybe
14668                                  * a KASSERT would be approprate.
14669                                  */
14670                                 goto use_latest;
14671                         }
14672                         /*
14673                          * If we have a marker pointer to the last one that is
14674                          * app limited we can use that, but we need to set
14675                          * things up so that when it gets ack'ed we record
14676                          * the ack time (if its not already acked).
14677                          */
14678                         rack->app_limited_needs_set = 1;
14679                         /*
14680                          * We want to get to the rsm that is either
14681                          * next with space i.e. over 1 MSS or the one
14682                          * after that (after the app-limited).
14683                          */
14684                         my_rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree,
14685                                          rack->r_ctl.rc_first_appl);
14686                         if (my_rsm) {
14687                                 if ((my_rsm->r_end - my_rsm->r_start) <= ctf_fixed_maxseg(tp))
14688                                         /* Have to use the next one */
14689                                         my_rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree,
14690                                                          my_rsm);
14691                                 else {
14692                                         /* Use after the first MSS of it is acked */
14693                                         tp->gput_seq = my_rsm->r_start + ctf_fixed_maxseg(tp);
14694                                         goto start_set;
14695                                 }
14696                         }
14697                         if ((my_rsm == NULL) ||
14698                             (my_rsm->r_rtr_cnt != 1)) {
14699                                 /*
14700                                  * Either its a retransmit or
14701                                  * the last is the app-limited one.
14702                                  */
14703                                 goto use_latest;
14704                         }
14705                 }
14706                 tp->gput_seq = my_rsm->r_start;
14707 start_set:
14708                 if (my_rsm->r_flags & RACK_ACKED) {
14709                         /*
14710                          * This one has been acked use the arrival ack time
14711                          */
14712                         tp->gput_ts = (uint32_t)my_rsm->r_ack_arrival;
14713                         rack->app_limited_needs_set = 0;
14714                 }
14715                 rack->r_ctl.rc_gp_output_ts = my_rsm->r_tim_lastsent[(my_rsm->r_rtr_cnt-1)];
14716                 tp->gput_ack = tp->gput_seq + rack_get_measure_window(tp, rack);
14717                 rack_log_pacing_delay_calc(rack,
14718                                            tp->gput_seq,
14719                                            tp->gput_ack,
14720                                            (uint64_t)my_rsm,
14721                                            tp->gput_ts,
14722                                            rack->r_ctl.rc_app_limited_cnt,
14723                                            9,
14724                                            __LINE__, NULL);
14725                 return;
14726         }
14727
14728 use_latest:
14729         /*
14730          * We don't know how long we may have been
14731          * idle or if this is the first-send. Lets
14732          * setup the flag so we will trim off
14733          * the first ack'd data so we get a true
14734          * measurement.
14735          */
14736         rack->app_limited_needs_set = 1;
14737         tp->gput_ack = startseq + rack_get_measure_window(tp, rack);
14738         /* Find this guy so we can pull the send time */
14739         fe.r_start = startseq;
14740         my_rsm = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
14741         if (my_rsm) {
14742                 rack->r_ctl.rc_gp_output_ts = my_rsm->r_tim_lastsent[(my_rsm->r_rtr_cnt-1)];
14743                 if (my_rsm->r_flags & RACK_ACKED) {
14744                         /*
14745                          * Unlikely since its probably what was
14746                          * just transmitted (but I am paranoid).
14747                          */
14748                         tp->gput_ts = (uint32_t)my_rsm->r_ack_arrival;
14749                         rack->app_limited_needs_set = 0;
14750                 }
14751                 if (SEQ_LT(my_rsm->r_start, tp->gput_seq)) {
14752                         /* This also is unlikely */
14753                         tp->gput_seq = my_rsm->r_start;
14754                 }
14755         } else {
14756                 /*
14757                  * TSNH unless we have some send-map limit,
14758                  * and even at that it should not be hitting
14759                  * that limit (we should have stopped sending).
14760                  */
14761                 struct timeval tv;
14762
14763                 microuptime(&tv);
14764                 rack->r_ctl.rc_gp_output_ts = rack_to_usec_ts(&tv);
14765         }
14766         rack_log_pacing_delay_calc(rack,
14767                                    tp->gput_seq,
14768                                    tp->gput_ack,
14769                                    (uint64_t)my_rsm,
14770                                    tp->gput_ts,
14771                                    rack->r_ctl.rc_app_limited_cnt,
14772                                    9, __LINE__, NULL);
14773 }
14774
14775 static inline uint32_t
14776 rack_what_can_we_send(struct tcpcb *tp, struct tcp_rack *rack,  uint32_t cwnd_to_use,
14777     uint32_t avail, int32_t sb_offset)
14778 {
14779         uint32_t len;
14780         uint32_t sendwin;
14781
14782         if (tp->snd_wnd > cwnd_to_use)
14783                 sendwin = cwnd_to_use;
14784         else
14785                 sendwin = tp->snd_wnd;
14786         if (ctf_outstanding(tp) >= tp->snd_wnd) {
14787                 /* We never want to go over our peers rcv-window */
14788                 len = 0;
14789         } else {
14790                 uint32_t flight;
14791
14792                 flight = ctf_flight_size(tp, rack->r_ctl.rc_sacked);
14793                 if (flight >= sendwin) {
14794                         /*
14795                          * We have in flight what we are allowed by cwnd (if
14796                          * it was rwnd blocking it would have hit above out
14797                          * >= tp->snd_wnd).
14798                          */
14799                         return (0);
14800                 }
14801                 len = sendwin - flight;
14802                 if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
14803                         /* We would send too much (beyond the rwnd) */
14804                         len = tp->snd_wnd - ctf_outstanding(tp);
14805                 }
14806                 if ((len + sb_offset) > avail) {
14807                         /*
14808                          * We don't have that much in the SB, how much is
14809                          * there?
14810                          */
14811                         len = avail - sb_offset;
14812                 }
14813         }
14814         return (len);
14815 }
14816
14817 static void
14818 rack_log_fsb(struct tcp_rack *rack, struct tcpcb *tp, struct socket *so, uint32_t flags,
14819              unsigned ipoptlen, int32_t orig_len, int32_t len, int error,
14820              int rsm_is_null, int optlen, int line, uint16_t mode)
14821 {
14822         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
14823                 union tcp_log_stackspecific log;
14824                 struct timeval tv;
14825
14826                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
14827                 log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
14828                 log.u_bbr.ininput = rack->rc_inp->inp_in_input;
14829                 log.u_bbr.flex1 = error;
14830                 log.u_bbr.flex2 = flags;
14831                 log.u_bbr.flex3 = rsm_is_null;
14832                 log.u_bbr.flex4 = ipoptlen;
14833                 log.u_bbr.flex5 = tp->rcv_numsacks;
14834                 log.u_bbr.flex6 = rack->r_ctl.rc_agg_early;
14835                 log.u_bbr.flex7 = optlen;
14836                 log.u_bbr.flex8 = rack->r_fsb_inited;
14837                 log.u_bbr.applimited = rack->r_fast_output;
14838                 log.u_bbr.bw_inuse = rack_get_bw(rack);
14839                 log.u_bbr.pacing_gain = rack_get_output_gain(rack, NULL);
14840                 log.u_bbr.cwnd_gain = mode;
14841                 log.u_bbr.pkts_out = orig_len;
14842                 log.u_bbr.lt_epoch = len;
14843                 log.u_bbr.delivered = line;
14844                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
14845                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
14846                 tcp_log_event_(tp, NULL, &so->so_rcv, &so->so_snd, TCP_LOG_FSB, 0,
14847                                len, &log, false, NULL, NULL, 0, &tv);
14848         }
14849 }
14850
14851
14852 static struct mbuf *
14853 rack_fo_base_copym(struct mbuf *the_m, uint32_t the_off, int32_t *plen,
14854                    struct rack_fast_send_blk *fsb,
14855                    int32_t seglimit, int32_t segsize)
14856 {
14857 #ifdef KERN_TLS
14858         struct ktls_session *tls, *ntls;
14859         struct mbuf *start;
14860 #endif
14861         struct mbuf *m, *n, **np, *smb;
14862         struct mbuf *top;
14863         int32_t off, soff;
14864         int32_t len = *plen;
14865         int32_t fragsize;
14866         int32_t len_cp = 0;
14867         uint32_t mlen, frags;
14868
14869         soff = off = the_off;
14870         smb = m = the_m;
14871         np = &top;
14872         top = NULL;
14873 #ifdef KERN_TLS
14874         if (hw_tls && (m->m_flags & M_EXTPG))
14875                 tls = m->m_epg_tls;
14876         else
14877                 tls = NULL;
14878         start = m;
14879 #endif
14880         while (len > 0) {
14881                 if (m == NULL) {
14882                         *plen = len_cp;
14883                         break;
14884                 }
14885 #ifdef KERN_TLS
14886                 if (hw_tls) {
14887                         if (m->m_flags & M_EXTPG)
14888                                 ntls = m->m_epg_tls;
14889                         else
14890                                 ntls = NULL;
14891
14892                         /*
14893                          * Avoid mixing TLS records with handshake
14894                          * data or TLS records from different
14895                          * sessions.
14896                          */
14897                         if (tls != ntls) {
14898                                 MPASS(m != start);
14899                                 *plen = len_cp;
14900                                 break;
14901                         }
14902                 }
14903 #endif
14904                 mlen = min(len, m->m_len - off);
14905                 if (seglimit) {
14906                         /*
14907                          * For M_EXTPG mbufs, add 3 segments
14908                          * + 1 in case we are crossing page boundaries
14909                          * + 2 in case the TLS hdr/trailer are used
14910                          * It is cheaper to just add the segments
14911                          * than it is to take the cache miss to look
14912                          * at the mbuf ext_pgs state in detail.
14913                          */
14914                         if (m->m_flags & M_EXTPG) {
14915                                 fragsize = min(segsize, PAGE_SIZE);
14916                                 frags = 3;
14917                         } else {
14918                                 fragsize = segsize;
14919                                 frags = 0;
14920                         }
14921
14922                         /* Break if we really can't fit anymore. */
14923                         if ((frags + 1) >= seglimit) {
14924                                 *plen = len_cp;
14925                                 break;
14926                         }
14927
14928                         /*
14929                          * Reduce size if you can't copy the whole
14930                          * mbuf. If we can't copy the whole mbuf, also
14931                          * adjust len so the loop will end after this
14932                          * mbuf.
14933                          */
14934                         if ((frags + howmany(mlen, fragsize)) >= seglimit) {
14935                                 mlen = (seglimit - frags - 1) * fragsize;
14936                                 len = mlen;
14937                                 *plen = len_cp + len;
14938                         }
14939                         frags += howmany(mlen, fragsize);
14940                         if (frags == 0)
14941                                 frags++;
14942                         seglimit -= frags;
14943                         KASSERT(seglimit > 0,
14944                             ("%s: seglimit went too low", __func__));
14945                 }
14946                 n = m_get(M_NOWAIT, m->m_type);
14947                 *np = n;
14948                 if (n == NULL)
14949                         goto nospace;
14950                 n->m_len = mlen;
14951                 soff += mlen;
14952                 len_cp += n->m_len;
14953                 if (m->m_flags & (M_EXT|M_EXTPG)) {
14954                         n->m_data = m->m_data + off;
14955                         mb_dupcl(n, m);
14956                 } else {
14957                         bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
14958                             (u_int)n->m_len);
14959                 }
14960                 len -= n->m_len;
14961                 off = 0;
14962                 m = m->m_next;
14963                 np = &n->m_next;
14964                 if (len || (soff == smb->m_len)) {
14965                         /*
14966                          * We have more so we move forward  or
14967                          * we have consumed the entire mbuf and
14968                          * len has fell to 0.
14969                          */
14970                         soff = 0;
14971                         smb = m;
14972                 }
14973
14974         }
14975         if (fsb != NULL) {
14976                 fsb->m = smb;
14977                 fsb->off = soff;
14978                 if (smb) {
14979                         /*
14980                          * Save off the size of the mbuf. We do
14981                          * this so that we can recognize when it
14982                          * has been trimmed by sbcut() as acks
14983                          * come in.
14984                          */
14985                         fsb->o_m_len = smb->m_len;
14986                 } else {
14987                         /*
14988                          * This is the case where the next mbuf went to NULL. This
14989                          * means with this copy we have sent everything in the sb.
14990                          * In theory we could clear the fast_output flag, but lets
14991                          * not since its possible that we could get more added
14992                          * and acks that call the extend function which would let
14993                          * us send more.
14994                          */
14995                         fsb->o_m_len = 0;
14996                 }
14997         }
14998         return (top);
14999 nospace:
15000         if (top)
15001                 m_freem(top);
15002         return (NULL);
15003
15004 }
15005
15006 /*
15007  * This is a copy of m_copym(), taking the TSO segment size/limit
15008  * constraints into account, and advancing the sndptr as it goes.
15009  */
15010 static struct mbuf *
15011 rack_fo_m_copym(struct tcp_rack *rack, int32_t *plen,
15012                 int32_t seglimit, int32_t segsize, struct mbuf **s_mb, int *s_soff)
15013 {
15014         struct mbuf *m, *n;
15015         int32_t soff;
15016
15017         soff = rack->r_ctl.fsb.off;
15018         m = rack->r_ctl.fsb.m;
15019         if (rack->r_ctl.fsb.o_m_len != m->m_len) {
15020                 /*
15021                  * The mbuf had the front of it chopped off by an ack
15022                  * we need to adjust the soff/off by that difference.
15023                  */
15024                 uint32_t delta;
15025
15026                 delta = rack->r_ctl.fsb.o_m_len - m->m_len;
15027                 soff -= delta;
15028         }
15029         KASSERT(soff >= 0, ("%s, negative off %d", __FUNCTION__, soff));
15030         KASSERT(*plen >= 0, ("%s, negative len %d", __FUNCTION__, *plen));
15031         KASSERT(soff < m->m_len, ("%s rack:%p len:%u m:%p m->m_len:%u < off?",
15032                                  __FUNCTION__,
15033                                  rack, *plen, m, m->m_len));
15034         /* Save off the right location before we copy and advance */
15035         *s_soff = soff;
15036         *s_mb = rack->r_ctl.fsb.m;
15037         n = rack_fo_base_copym(m, soff, plen,
15038                                &rack->r_ctl.fsb,
15039                                seglimit, segsize);
15040         return (n);
15041 }
15042
15043 static int
15044 rack_fast_rsm_output(struct tcpcb *tp, struct tcp_rack *rack, struct rack_sendmap *rsm,
15045                      uint64_t ts_val, uint32_t cts, uint32_t ms_cts, struct timeval *tv, int len)
15046 {
15047         /*
15048          * Enter the fast retransmit path. We are given that a sched_pin is
15049          * in place (if accounting is compliled in) and the cycle count taken
15050          * at the entry is in the ts_val. The concept her is that the rsm
15051          * now holds the mbuf offsets and such so we can directly transmit
15052          * without a lot of overhead, the len field is already set for
15053          * us to prohibit us from sending too much (usually its 1MSS).
15054          */
15055         struct ip *ip = NULL;
15056         struct udphdr *udp = NULL;
15057         struct tcphdr *th = NULL;
15058         struct mbuf *m = NULL;
15059         struct inpcb *inp;
15060         uint8_t *cpto;
15061         struct tcp_log_buffer *lgb;
15062 #ifdef TCP_ACCOUNTING
15063         uint64_t crtsc;
15064         int cnt_thru = 1;
15065 #endif
15066         int doing_tlp = 0;
15067         struct tcpopt to;
15068         u_char opt[TCP_MAXOLEN];
15069         uint32_t hdrlen, optlen;
15070         int32_t slot, segsiz, max_val, tso = 0, error, flags, ulen = 0;
15071         uint32_t us_cts;
15072         uint32_t if_hw_tsomaxsegcount = 0, startseq;
15073         uint32_t if_hw_tsomaxsegsize;
15074 #ifdef INET6
15075         struct ip6_hdr *ip6 = NULL;
15076
15077         if (rack->r_is_v6) {
15078                 ip6 = (struct ip6_hdr *)rack->r_ctl.fsb.tcp_ip_hdr;
15079                 hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
15080         } else
15081 #endif                          /* INET6 */
15082         {
15083                 ip = (struct ip *)rack->r_ctl.fsb.tcp_ip_hdr;
15084                 hdrlen = sizeof(struct tcpiphdr);
15085         }
15086         if (tp->t_port && (V_tcp_udp_tunneling_port == 0)) {
15087                 goto failed;
15088         }
15089         if (rsm->r_flags & RACK_TLP)
15090                 doing_tlp = 1;
15091         startseq = rsm->r_start;
15092         segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
15093         inp = rack->rc_inp;
15094         to.to_flags = 0;
15095         flags = tcp_outflags[tp->t_state];
15096         if (flags & (TH_SYN|TH_RST)) {
15097                 goto failed;
15098         }
15099         if (rsm->r_flags & RACK_HAS_FIN) {
15100                 /* We can't send a FIN here */
15101                 goto failed;
15102         }
15103         if (flags & TH_FIN) {
15104                 /* We never send a FIN */
15105                 flags &= ~TH_FIN;
15106         }
15107         if (tp->t_flags & TF_RCVD_TSTMP) {
15108                 to.to_tsval = ms_cts + tp->ts_offset;
15109                 to.to_tsecr = tp->ts_recent;
15110                 to.to_flags = TOF_TS;
15111         }
15112         optlen = tcp_addoptions(&to, opt);
15113         hdrlen += optlen;
15114         udp = rack->r_ctl.fsb.udp;
15115         if (udp)
15116                 hdrlen += sizeof(struct udphdr);
15117         if (rack->r_ctl.rc_pace_max_segs)
15118                 max_val = rack->r_ctl.rc_pace_max_segs;
15119         else if (rack->rc_user_set_max_segs)
15120                 max_val = rack->rc_user_set_max_segs * segsiz;
15121         else
15122                 max_val = len;
15123         if ((tp->t_flags & TF_TSO) &&
15124             V_tcp_do_tso &&
15125             (len > segsiz) &&
15126             (tp->t_port == 0))
15127                 tso = 1;
15128 #ifdef INET6
15129         if (MHLEN < hdrlen + max_linkhdr)
15130                 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
15131         else
15132 #endif
15133                 m = m_gethdr(M_NOWAIT, MT_DATA);
15134         if (m == NULL)
15135                 goto failed;
15136         m->m_data += max_linkhdr;
15137         m->m_len = hdrlen;
15138         th = rack->r_ctl.fsb.th;
15139         /* Establish the len to send */
15140         if (len > max_val)
15141                 len = max_val;
15142         if ((tso) && (len + optlen > tp->t_maxseg)) {
15143                 uint32_t if_hw_tsomax;
15144                 int32_t max_len;
15145
15146                 /* extract TSO information */
15147                 if_hw_tsomax = tp->t_tsomax;
15148                 if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
15149                 if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
15150                 /*
15151                  * Check if we should limit by maximum payload
15152                  * length:
15153                  */
15154                 if (if_hw_tsomax != 0) {
15155                         /* compute maximum TSO length */
15156                         max_len = (if_hw_tsomax - hdrlen -
15157                                    max_linkhdr);
15158                         if (max_len <= 0) {
15159                                 goto failed;
15160                         } else if (len > max_len) {
15161                                 len = max_len;
15162                         }
15163                 }
15164                 if (len <= segsiz) {
15165                         /*
15166                          * In case there are too many small fragments don't
15167                          * use TSO:
15168                          */
15169                         tso = 0;
15170                 }
15171         } else {
15172                 tso = 0;
15173         }
15174         if ((tso == 0) && (len > segsiz))
15175                 len = segsiz;
15176         us_cts = tcp_get_usecs(tv);
15177         if ((len == 0) ||
15178             (len <= MHLEN - hdrlen - max_linkhdr)) {
15179                 goto failed;
15180         }
15181         th->th_seq = htonl(rsm->r_start);
15182         th->th_ack = htonl(tp->rcv_nxt);
15183         if(rsm->r_flags & RACK_HAD_PUSH)
15184                 flags |= TH_PUSH;
15185         th->th_flags = flags;
15186         th->th_win = htons((u_short)(rack->r_ctl.fsb.recwin >> tp->rcv_scale));
15187         if (th->th_win == 0) {
15188                 tp->t_sndzerowin++;
15189                 tp->t_flags |= TF_RXWIN0SENT;
15190         } else
15191                 tp->t_flags &= ~TF_RXWIN0SENT;
15192         if (rsm->r_flags & RACK_TLP) {
15193                 /*
15194                  * TLP should not count in retran count, but
15195                  * in its own bin
15196                  */
15197                 counter_u64_add(rack_tlp_retran, 1);
15198                 counter_u64_add(rack_tlp_retran_bytes, len);
15199         } else {
15200                 tp->t_sndrexmitpack++;
15201                 KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
15202                 KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
15203         }
15204 #ifdef STATS
15205         stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
15206                                  len);
15207 #endif
15208         if (rsm->m == NULL)
15209                 goto failed;
15210         if (rsm->orig_m_len != rsm->m->m_len) {
15211                 /* Fix up the orig_m_len and possibly the mbuf offset */
15212                 rack_adjust_orig_mlen(rsm);
15213         }
15214         m->m_next = rack_fo_base_copym(rsm->m, rsm->soff, &len, NULL, if_hw_tsomaxsegcount, if_hw_tsomaxsegsize);
15215         if (len <= segsiz) {
15216                 /*
15217                  * Must have ran out of mbufs for the copy
15218                  * shorten it to no longer need tso. Lets
15219                  * not put on sendalot since we are low on
15220                  * mbufs.
15221                  */
15222                 tso = 0;
15223         }
15224         if ((m->m_next == NULL) || (len <= 0)){
15225                 goto failed;
15226         }
15227         if (udp) {
15228                 if (rack->r_is_v6)
15229                         ulen = hdrlen + len - sizeof(struct ip6_hdr);
15230                 else
15231                         ulen = hdrlen + len - sizeof(struct ip);
15232                 udp->uh_ulen = htons(ulen);
15233         }
15234         m->m_pkthdr.rcvif = (struct ifnet *)0;
15235         m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
15236 #ifdef INET6
15237         if (rack->r_is_v6) {
15238                 if (tp->t_port) {
15239                         m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
15240                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
15241                         udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
15242                         th->th_sum = htons(0);
15243                         UDPSTAT_INC(udps_opackets);
15244                 } else {
15245                         m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
15246                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
15247                         th->th_sum = in6_cksum_pseudo(ip6,
15248                                                       sizeof(struct tcphdr) + optlen + len, IPPROTO_TCP,
15249                                                       0);
15250                 }
15251         }
15252 #endif
15253 #if defined(INET6) && defined(INET)
15254         else
15255 #endif
15256 #ifdef INET
15257         {
15258                 if (tp->t_port) {
15259                         m->m_pkthdr.csum_flags = CSUM_UDP;
15260                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
15261                         udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
15262                                                 ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
15263                         th->th_sum = htons(0);
15264                         UDPSTAT_INC(udps_opackets);
15265                 } else {
15266                         m->m_pkthdr.csum_flags = CSUM_TCP;
15267                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
15268                         th->th_sum = in_pseudo(ip->ip_src.s_addr,
15269                                                ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
15270                                                                         IPPROTO_TCP + len + optlen));
15271                 }
15272                 /* IP version must be set here for ipv4/ipv6 checking later */
15273                 KASSERT(ip->ip_v == IPVERSION,
15274                         ("%s: IP version incorrect: %d", __func__, ip->ip_v));
15275         }
15276 #endif
15277         if (tso) {
15278                 KASSERT(len > tp->t_maxseg - optlen,
15279                         ("%s: len <= tso_segsz tp:%p", __func__, tp));
15280                 m->m_pkthdr.csum_flags |= CSUM_TSO;
15281                 m->m_pkthdr.tso_segsz = tp->t_maxseg - optlen;
15282         }
15283 #ifdef INET6
15284         if (rack->r_is_v6) {
15285                 ip6->ip6_hlim = rack->r_ctl.fsb.hoplimit;
15286                 ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
15287                 if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss)
15288                         tp->t_flags2 |= TF2_PLPMTU_PMTUD;
15289                 else
15290                         tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
15291         }
15292 #endif
15293 #if defined(INET) && defined(INET6)
15294         else
15295 #endif
15296 #ifdef INET
15297         {
15298                 ip->ip_len = htons(m->m_pkthdr.len);
15299                 ip->ip_ttl = rack->r_ctl.fsb.hoplimit;
15300                 if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
15301                         tp->t_flags2 |= TF2_PLPMTU_PMTUD;
15302                         if (tp->t_port == 0 || len < V_tcp_minmss) {
15303                                 ip->ip_off |= htons(IP_DF);
15304                         }
15305                 } else {
15306                         tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
15307                 }
15308         }
15309 #endif
15310         /* Time to copy in our header */
15311         cpto = mtod(m, uint8_t *);
15312         memcpy(cpto, rack->r_ctl.fsb.tcp_ip_hdr, rack->r_ctl.fsb.tcp_ip_hdr_len);
15313         th = (struct tcphdr *)(cpto + ((uint8_t *)rack->r_ctl.fsb.th - rack->r_ctl.fsb.tcp_ip_hdr));
15314         if (optlen) {
15315                 bcopy(opt, th + 1, optlen);
15316                 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
15317         } else {
15318                 th->th_off = sizeof(struct tcphdr) >> 2;
15319         }
15320         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
15321                 union tcp_log_stackspecific log;
15322
15323                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
15324                 log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
15325                 log.u_bbr.ininput = rack->rc_inp->inp_in_input;
15326                 if (rack->rack_no_prr)
15327                         log.u_bbr.flex1 = 0;
15328                 else
15329                         log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
15330                 log.u_bbr.flex2 = rack->r_ctl.rc_pace_min_segs;
15331                 log.u_bbr.flex3 = rack->r_ctl.rc_pace_max_segs;
15332                 log.u_bbr.flex4 = max_val;
15333                 log.u_bbr.flex5 = 0;
15334                 /* Save off the early/late values */
15335                 log.u_bbr.flex6 = rack->r_ctl.rc_agg_early;
15336                 log.u_bbr.applimited = rack->r_ctl.rc_agg_delayed;
15337                 log.u_bbr.bw_inuse = rack_get_bw(rack);
15338                 log.u_bbr.flex8 = 1;
15339                 log.u_bbr.pacing_gain = rack_get_output_gain(rack, NULL);
15340                 log.u_bbr.flex7 = 55;
15341                 log.u_bbr.pkts_out = tp->t_maxseg;
15342                 log.u_bbr.timeStamp = cts;
15343                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
15344                 log.u_bbr.lt_epoch = rack->r_ctl.cwnd_to_use;
15345                 log.u_bbr.delivered = 0;
15346                 lgb = tcp_log_event_(tp, th, NULL, NULL, TCP_LOG_OUT, ERRNO_UNK,
15347                                      len, &log, false, NULL, NULL, 0, tv);
15348         } else
15349                 lgb = NULL;
15350 #ifdef INET6
15351         if (rack->r_is_v6) {
15352                 error = ip6_output(m, NULL,
15353                                    &inp->inp_route6,
15354                                    0, NULL, NULL, inp);
15355         }
15356 #endif
15357 #if defined(INET) && defined(INET6)
15358         else
15359 #endif
15360 #ifdef INET
15361         {
15362                 error = ip_output(m, NULL,
15363                                   &inp->inp_route,
15364                                   0, 0, inp);
15365         }
15366 #endif
15367         m = NULL;
15368         if (lgb) {
15369                 lgb->tlb_errno = error;
15370                 lgb = NULL;
15371         }
15372         if (error) {
15373                 goto failed;
15374         }
15375         rack_log_output(tp, &to, len, rsm->r_start, flags, error, rack_to_usec_ts(tv),
15376                         rsm, RACK_SENT_FP, rsm->m, rsm->soff);
15377         if (doing_tlp && (rack->fast_rsm_hack == 0)) {
15378                 rack->rc_tlp_in_progress = 1;
15379                 rack->r_ctl.rc_tlp_cnt_out++;
15380         }
15381         tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
15382         rack->forced_ack = 0;   /* If we send something zap the FA flag */
15383         if (IN_FASTRECOVERY(tp->t_flags) && rsm)
15384                 rack->r_ctl.retran_during_recovery += len;
15385         {
15386                 int idx;
15387
15388                 idx = (len / segsiz) + 3;
15389                 if (idx >= TCP_MSS_ACCT_ATIMER)
15390                         counter_u64_add(rack_out_size[(TCP_MSS_ACCT_ATIMER-1)], 1);
15391                 else
15392                         counter_u64_add(rack_out_size[idx], 1);
15393         }
15394         if (tp->t_rtttime == 0) {
15395                 tp->t_rtttime = ticks;
15396                 tp->t_rtseq = startseq;
15397                 KMOD_TCPSTAT_INC(tcps_segstimed);
15398         }
15399         counter_u64_add(rack_fto_rsm_send, 1);
15400         if (error && (error == ENOBUFS)) {
15401                 slot = ((1 + rack->rc_enobuf) * HPTS_USEC_IN_MSEC);
15402                 if (rack->rc_enobuf < 0x7f)
15403                         rack->rc_enobuf++;
15404                 if (slot < (10 * HPTS_USEC_IN_MSEC))
15405                         slot = 10 * HPTS_USEC_IN_MSEC;
15406         } else
15407                 slot = rack_get_pacing_delay(rack, tp, len, NULL, segsiz);
15408         if ((slot == 0) ||
15409             (rack->rc_always_pace == 0) ||
15410             (rack->r_rr_config == 1)) {
15411                 /*
15412                  * We have no pacing set or we
15413                  * are using old-style rack or
15414                  * we are overriden to use the old 1ms pacing.
15415                  */
15416                 slot = rack->r_ctl.rc_min_to;
15417         }
15418         rack_start_hpts_timer(rack, tp, cts, slot, len, 0);
15419         if (rack->r_must_retran) {
15420                 rack->r_ctl.rc_out_at_rto -= (rsm->r_end - rsm->r_start);
15421                 if (SEQ_GEQ(rsm->r_end, rack->r_ctl.rc_snd_max_at_rto)) {
15422                         /*
15423                          * We have retransmitted all we need.
15424                          */
15425                         rack->r_must_retran = 0;
15426                         rack->r_ctl.rc_out_at_rto = 0;
15427                 }
15428         }
15429 #ifdef TCP_ACCOUNTING
15430         crtsc = get_cyclecount();
15431         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
15432                 tp->tcp_cnt_counters[SND_OUT_DATA] += cnt_thru;
15433         }
15434         counter_u64_add(tcp_cnt_counters[SND_OUT_DATA], cnt_thru);
15435         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
15436                 tp->tcp_proc_time[SND_OUT_DATA] += (crtsc - ts_val);
15437         }
15438         counter_u64_add(tcp_proc_time[SND_OUT_DATA], (crtsc - ts_val));
15439         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
15440                 tp->tcp_cnt_counters[CNT_OF_MSS_OUT] += ((len + segsiz - 1) / segsiz);
15441         }
15442         counter_u64_add(tcp_cnt_counters[CNT_OF_MSS_OUT], ((len + segsiz - 1) / segsiz));
15443         sched_unpin();
15444 #endif
15445         return (0);
15446 failed:
15447         if (m)
15448                 m_free(m);
15449         return (-1);
15450 }
15451
15452 static void
15453 rack_sndbuf_autoscale(struct tcp_rack *rack)
15454 {
15455         /*
15456          * Automatic sizing of send socket buffer.  Often the send buffer
15457          * size is not optimally adjusted to the actual network conditions
15458          * at hand (delay bandwidth product).  Setting the buffer size too
15459          * small limits throughput on links with high bandwidth and high
15460          * delay (eg. trans-continental/oceanic links).  Setting the
15461          * buffer size too big consumes too much real kernel memory,
15462          * especially with many connections on busy servers.
15463          *
15464          * The criteria to step up the send buffer one notch are:
15465          *  1. receive window of remote host is larger than send buffer
15466          *     (with a fudge factor of 5/4th);
15467          *  2. send buffer is filled to 7/8th with data (so we actually
15468          *     have data to make use of it);
15469          *  3. send buffer fill has not hit maximal automatic size;
15470          *  4. our send window (slow start and cogestion controlled) is
15471          *     larger than sent but unacknowledged data in send buffer.
15472          *
15473          * Note that the rack version moves things much faster since
15474          * we want to avoid hitting cache lines in the rack_fast_output()
15475          * path so this is called much less often and thus moves
15476          * the SB forward by a percentage.
15477          */
15478         struct socket *so;
15479         struct tcpcb *tp;
15480         uint32_t sendwin, scaleup;
15481
15482         tp = rack->rc_tp;
15483         so = rack->rc_inp->inp_socket;
15484         sendwin = min(rack->r_ctl.cwnd_to_use, tp->snd_wnd);
15485         if (V_tcp_do_autosndbuf && so->so_snd.sb_flags & SB_AUTOSIZE) {
15486                 if ((tp->snd_wnd / 4 * 5) >= so->so_snd.sb_hiwat &&
15487                     sbused(&so->so_snd) >=
15488                     (so->so_snd.sb_hiwat / 8 * 7) &&
15489                     sbused(&so->so_snd) < V_tcp_autosndbuf_max &&
15490                     sendwin >= (sbused(&so->so_snd) -
15491                     (tp->snd_nxt - tp->snd_una))) {
15492                         if (rack_autosndbuf_inc)
15493                                 scaleup = (rack_autosndbuf_inc * so->so_snd.sb_hiwat) / 100;
15494                         else
15495                                 scaleup = V_tcp_autosndbuf_inc;
15496                         if (scaleup < V_tcp_autosndbuf_inc)
15497                                 scaleup = V_tcp_autosndbuf_inc;
15498                         scaleup += so->so_snd.sb_hiwat;
15499                         if (scaleup > V_tcp_autosndbuf_max)
15500                                 scaleup = V_tcp_autosndbuf_max;
15501                         if (!sbreserve_locked(&so->so_snd, scaleup, so, curthread))
15502                                 so->so_snd.sb_flags &= ~SB_AUTOSIZE;
15503                 }
15504         }
15505 }
15506
15507 static int
15508 rack_fast_output(struct tcpcb *tp, struct tcp_rack *rack, uint64_t ts_val,
15509                  uint32_t cts, uint32_t ms_cts, struct timeval *tv, long tot_len, int *send_err)
15510 {
15511         /*
15512          * Enter to do fast output. We are given that the sched_pin is
15513          * in place (if accounting is compiled in) and the cycle count taken
15514          * at entry is in place in ts_val. The idea here is that
15515          * we know how many more bytes needs to be sent (presumably either
15516          * during pacing or to fill the cwnd and that was greater than
15517          * the max-burst). We have how much to send and all the info we
15518          * need to just send.
15519          */
15520         struct ip *ip = NULL;
15521         struct udphdr *udp = NULL;
15522         struct tcphdr *th = NULL;
15523         struct mbuf *m, *s_mb;
15524         struct inpcb *inp;
15525         uint8_t *cpto;
15526         struct tcp_log_buffer *lgb;
15527 #ifdef TCP_ACCOUNTING
15528         uint64_t crtsc;
15529 #endif
15530         struct tcpopt to;
15531         u_char opt[TCP_MAXOLEN];
15532         uint32_t hdrlen, optlen;
15533         int cnt_thru = 1;
15534         int32_t slot, segsiz, len, max_val, tso = 0, sb_offset, error, flags, ulen = 0;
15535         uint32_t us_cts, s_soff;
15536         uint32_t if_hw_tsomaxsegcount = 0, startseq;
15537         uint32_t if_hw_tsomaxsegsize;
15538         uint16_t add_flag = RACK_SENT_FP;
15539 #ifdef INET6
15540         struct ip6_hdr *ip6 = NULL;
15541
15542         if (rack->r_is_v6) {
15543                 ip6 = (struct ip6_hdr *)rack->r_ctl.fsb.tcp_ip_hdr;
15544                 hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
15545         } else
15546 #endif                          /* INET6 */
15547         {
15548                 ip = (struct ip *)rack->r_ctl.fsb.tcp_ip_hdr;
15549                 hdrlen = sizeof(struct tcpiphdr);
15550         }
15551         if (tp->t_port && (V_tcp_udp_tunneling_port == 0)) {
15552                 m = NULL;
15553                 goto failed;
15554         }
15555         startseq = tp->snd_max;
15556         segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
15557         inp = rack->rc_inp;
15558         len = rack->r_ctl.fsb.left_to_send;
15559         to.to_flags = 0;
15560         flags = rack->r_ctl.fsb.tcp_flags;
15561         if (tp->t_flags & TF_RCVD_TSTMP) {
15562                 to.to_tsval = ms_cts + tp->ts_offset;
15563                 to.to_tsecr = tp->ts_recent;
15564                 to.to_flags = TOF_TS;
15565         }
15566         optlen = tcp_addoptions(&to, opt);
15567         hdrlen += optlen;
15568         udp = rack->r_ctl.fsb.udp;
15569         if (udp)
15570                 hdrlen += sizeof(struct udphdr);
15571         if (rack->r_ctl.rc_pace_max_segs)
15572                 max_val = rack->r_ctl.rc_pace_max_segs;
15573         else if (rack->rc_user_set_max_segs)
15574                 max_val = rack->rc_user_set_max_segs * segsiz;
15575         else
15576                 max_val = len;
15577         if ((tp->t_flags & TF_TSO) &&
15578             V_tcp_do_tso &&
15579             (len > segsiz) &&
15580             (tp->t_port == 0))
15581                 tso = 1;
15582 again:
15583 #ifdef INET6
15584         if (MHLEN < hdrlen + max_linkhdr)
15585                 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
15586         else
15587 #endif
15588                 m = m_gethdr(M_NOWAIT, MT_DATA);
15589         if (m == NULL)
15590                 goto failed;
15591         m->m_data += max_linkhdr;
15592         m->m_len = hdrlen;
15593         th = rack->r_ctl.fsb.th;
15594         /* Establish the len to send */
15595         if (len > max_val)
15596                 len = max_val;
15597         if ((tso) && (len + optlen > tp->t_maxseg)) {
15598                 uint32_t if_hw_tsomax;
15599                 int32_t max_len;
15600
15601                 /* extract TSO information */
15602                 if_hw_tsomax = tp->t_tsomax;
15603                 if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
15604                 if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
15605                 /*
15606                  * Check if we should limit by maximum payload
15607                  * length:
15608                  */
15609                 if (if_hw_tsomax != 0) {
15610                         /* compute maximum TSO length */
15611                         max_len = (if_hw_tsomax - hdrlen -
15612                                    max_linkhdr);
15613                         if (max_len <= 0) {
15614                                 goto failed;
15615                         } else if (len > max_len) {
15616                                 len = max_len;
15617                         }
15618                 }
15619                 if (len <= segsiz) {
15620                         /*
15621                          * In case there are too many small fragments don't
15622                          * use TSO:
15623                          */
15624                         tso = 0;
15625                 }
15626         } else {
15627                 tso = 0;
15628         }
15629         if ((tso == 0) && (len > segsiz))
15630                 len = segsiz;
15631         us_cts = tcp_get_usecs(tv);
15632         if ((len == 0) ||
15633             (len <= MHLEN - hdrlen - max_linkhdr)) {
15634                 goto failed;
15635         }
15636         sb_offset = tp->snd_max - tp->snd_una;
15637         th->th_seq = htonl(tp->snd_max);
15638         th->th_ack = htonl(tp->rcv_nxt);
15639         th->th_flags = flags;
15640         th->th_win = htons((u_short)(rack->r_ctl.fsb.recwin >> tp->rcv_scale));
15641         if (th->th_win == 0) {
15642                 tp->t_sndzerowin++;
15643                 tp->t_flags |= TF_RXWIN0SENT;
15644         } else
15645                 tp->t_flags &= ~TF_RXWIN0SENT;
15646         tp->snd_up = tp->snd_una;       /* drag it along, its deprecated */
15647         KMOD_TCPSTAT_INC(tcps_sndpack);
15648         KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
15649 #ifdef STATS
15650         stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
15651                                  len);
15652 #endif
15653         if (rack->r_ctl.fsb.m == NULL)
15654                 goto failed;
15655
15656         /* s_mb and s_soff are saved for rack_log_output */
15657         m->m_next = rack_fo_m_copym(rack, &len, if_hw_tsomaxsegcount, if_hw_tsomaxsegsize, &s_mb, &s_soff);
15658         if (len <= segsiz) {
15659                 /*
15660                  * Must have ran out of mbufs for the copy
15661                  * shorten it to no longer need tso. Lets
15662                  * not put on sendalot since we are low on
15663                  * mbufs.
15664                  */
15665                 tso = 0;
15666         }
15667         if (rack->r_ctl.fsb.rfo_apply_push &&
15668             (len == rack->r_ctl.fsb.left_to_send)) {
15669                 th->th_flags |= TH_PUSH;
15670                 add_flag |= RACK_HAD_PUSH;
15671         }
15672         if ((m->m_next == NULL) || (len <= 0)){
15673                 goto failed;
15674         }
15675         if (udp) {
15676                 if (rack->r_is_v6)
15677                         ulen = hdrlen + len - sizeof(struct ip6_hdr);
15678                 else
15679                         ulen = hdrlen + len - sizeof(struct ip);
15680                 udp->uh_ulen = htons(ulen);
15681         }
15682         m->m_pkthdr.rcvif = (struct ifnet *)0;
15683         if (tp->t_state == TCPS_ESTABLISHED &&
15684             (tp->t_flags2 & TF2_ECN_PERMIT)) {
15685                 /*
15686                  * If the peer has ECN, mark data packets with ECN capable
15687                  * transmission (ECT). Ignore pure ack packets,
15688                  * retransmissions.
15689                  */
15690                 if (len > 0 && SEQ_GEQ(tp->snd_nxt, tp->snd_max)) {
15691 #ifdef INET6
15692                         if (rack->r_is_v6)
15693                                 ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
15694                         else
15695 #endif
15696                                 ip->ip_tos |= IPTOS_ECN_ECT0;
15697                         KMOD_TCPSTAT_INC(tcps_ecn_ect0);
15698                         /*
15699                          * Reply with proper ECN notifications.
15700                          * Only set CWR on new data segments.
15701                          */
15702                         if (tp->t_flags2 & TF2_ECN_SND_CWR) {
15703                                 flags |= TH_CWR;
15704                                 tp->t_flags2 &= ~TF2_ECN_SND_CWR;
15705                         }
15706                 }
15707                 if (tp->t_flags2 & TF2_ECN_SND_ECE)
15708                         flags |= TH_ECE;
15709         }
15710         m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
15711 #ifdef INET6
15712         if (rack->r_is_v6) {
15713                 if (tp->t_port) {
15714                         m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
15715                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
15716                         udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
15717                         th->th_sum = htons(0);
15718                         UDPSTAT_INC(udps_opackets);
15719                 } else {
15720                         m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
15721                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
15722                         th->th_sum = in6_cksum_pseudo(ip6,
15723                                                       sizeof(struct tcphdr) + optlen + len, IPPROTO_TCP,
15724                                                       0);
15725                 }
15726         }
15727 #endif
15728 #if defined(INET6) && defined(INET)
15729         else
15730 #endif
15731 #ifdef INET
15732         {
15733                 if (tp->t_port) {
15734                         m->m_pkthdr.csum_flags = CSUM_UDP;
15735                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
15736                         udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
15737                                                 ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
15738                         th->th_sum = htons(0);
15739                         UDPSTAT_INC(udps_opackets);
15740                 } else {
15741                         m->m_pkthdr.csum_flags = CSUM_TCP;
15742                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
15743                         th->th_sum = in_pseudo(ip->ip_src.s_addr,
15744                                                ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
15745                                                                         IPPROTO_TCP + len + optlen));
15746                 }
15747                 /* IP version must be set here for ipv4/ipv6 checking later */
15748                 KASSERT(ip->ip_v == IPVERSION,
15749                         ("%s: IP version incorrect: %d", __func__, ip->ip_v));
15750         }
15751 #endif
15752         if (tso) {
15753                 KASSERT(len > tp->t_maxseg - optlen,
15754                         ("%s: len <= tso_segsz tp:%p", __func__, tp));
15755                 m->m_pkthdr.csum_flags |= CSUM_TSO;
15756                 m->m_pkthdr.tso_segsz = tp->t_maxseg - optlen;
15757         }
15758 #ifdef INET6
15759         if (rack->r_is_v6) {
15760                 ip6->ip6_hlim = rack->r_ctl.fsb.hoplimit;
15761                 ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
15762                 if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss)
15763                         tp->t_flags2 |= TF2_PLPMTU_PMTUD;
15764                 else
15765                         tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
15766         }
15767 #endif
15768 #if defined(INET) && defined(INET6)
15769         else
15770 #endif
15771 #ifdef INET
15772         {
15773                 ip->ip_len = htons(m->m_pkthdr.len);
15774                 ip->ip_ttl = rack->r_ctl.fsb.hoplimit;
15775                 if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
15776                         tp->t_flags2 |= TF2_PLPMTU_PMTUD;
15777                         if (tp->t_port == 0 || len < V_tcp_minmss) {
15778                                 ip->ip_off |= htons(IP_DF);
15779                         }
15780                 } else {
15781                         tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
15782                 }
15783         }
15784 #endif
15785         /* Time to copy in our header */
15786         cpto = mtod(m, uint8_t *);
15787         memcpy(cpto, rack->r_ctl.fsb.tcp_ip_hdr, rack->r_ctl.fsb.tcp_ip_hdr_len);
15788         th = (struct tcphdr *)(cpto + ((uint8_t *)rack->r_ctl.fsb.th - rack->r_ctl.fsb.tcp_ip_hdr));
15789         if (optlen) {
15790                 bcopy(opt, th + 1, optlen);
15791                 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
15792         } else {
15793                 th->th_off = sizeof(struct tcphdr) >> 2;
15794         }
15795         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
15796                 union tcp_log_stackspecific log;
15797
15798                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
15799                 log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
15800                 log.u_bbr.ininput = rack->rc_inp->inp_in_input;
15801                 if (rack->rack_no_prr)
15802                         log.u_bbr.flex1 = 0;
15803                 else
15804                         log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
15805                 log.u_bbr.flex2 = rack->r_ctl.rc_pace_min_segs;
15806                 log.u_bbr.flex3 = rack->r_ctl.rc_pace_max_segs;
15807                 log.u_bbr.flex4 = max_val;
15808                 log.u_bbr.flex5 = 0;
15809                 /* Save off the early/late values */
15810                 log.u_bbr.flex6 = rack->r_ctl.rc_agg_early;
15811                 log.u_bbr.applimited = rack->r_ctl.rc_agg_delayed;
15812                 log.u_bbr.bw_inuse = rack_get_bw(rack);
15813                 log.u_bbr.flex8 = 0;
15814                 log.u_bbr.pacing_gain = rack_get_output_gain(rack, NULL);
15815                 log.u_bbr.flex7 = 44;
15816                 log.u_bbr.pkts_out = tp->t_maxseg;
15817                 log.u_bbr.timeStamp = cts;
15818                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
15819                 log.u_bbr.lt_epoch = rack->r_ctl.cwnd_to_use;
15820                 log.u_bbr.delivered = 0;
15821                 lgb = tcp_log_event_(tp, th, NULL, NULL, TCP_LOG_OUT, ERRNO_UNK,
15822                                      len, &log, false, NULL, NULL, 0, tv);
15823         } else
15824                 lgb = NULL;
15825 #ifdef INET6
15826         if (rack->r_is_v6) {
15827                 error = ip6_output(m, NULL,
15828                                    &inp->inp_route6,
15829                                    0, NULL, NULL, inp);
15830         }
15831 #endif
15832 #if defined(INET) && defined(INET6)
15833         else
15834 #endif
15835 #ifdef INET
15836         {
15837                 error = ip_output(m, NULL,
15838                                   &inp->inp_route,
15839                                   0, 0, inp);
15840         }
15841 #endif
15842         if (lgb) {
15843                 lgb->tlb_errno = error;
15844                 lgb = NULL;
15845         }
15846         if (error) {
15847                 *send_err = error;
15848                 m = NULL;
15849                 goto failed;
15850         }
15851         rack_log_output(tp, &to, len, tp->snd_max, flags, error, rack_to_usec_ts(tv),
15852                         NULL, add_flag, s_mb, s_soff);
15853         m = NULL;
15854         if (tp->snd_una == tp->snd_max) {
15855                 rack->r_ctl.rc_tlp_rxt_last_time = cts;
15856                 rack_log_progress_event(rack, tp, ticks, PROGRESS_START, __LINE__);
15857                 tp->t_acktime = ticks;
15858         }
15859         rack->forced_ack = 0;   /* If we send something zap the FA flag */
15860         tot_len += len;
15861         if ((tp->t_flags & TF_GPUTINPROG) == 0)
15862                 rack_start_gp_measurement(tp, rack, tp->snd_max, sb_offset);
15863         tp->snd_max += len;
15864         tp->snd_nxt = tp->snd_max;
15865         {
15866                 int idx;
15867
15868                 idx = (len / segsiz) + 3;
15869                 if (idx >= TCP_MSS_ACCT_ATIMER)
15870                         counter_u64_add(rack_out_size[(TCP_MSS_ACCT_ATIMER-1)], 1);
15871                 else
15872                         counter_u64_add(rack_out_size[idx], 1);
15873         }
15874         if (len <= rack->r_ctl.fsb.left_to_send)
15875                 rack->r_ctl.fsb.left_to_send -= len;
15876         else
15877                 rack->r_ctl.fsb.left_to_send = 0;
15878         if (rack->r_ctl.fsb.left_to_send < segsiz) {
15879                 rack->r_fast_output = 0;
15880                 rack->r_ctl.fsb.left_to_send = 0;
15881                 /* At the end of fast_output scale up the sb */
15882                 SOCKBUF_LOCK(&rack->rc_inp->inp_socket->so_snd);
15883                 rack_sndbuf_autoscale(rack);
15884                 SOCKBUF_UNLOCK(&rack->rc_inp->inp_socket->so_snd);
15885         }
15886         if (tp->t_rtttime == 0) {
15887                 tp->t_rtttime = ticks;
15888                 tp->t_rtseq = startseq;
15889                 KMOD_TCPSTAT_INC(tcps_segstimed);
15890         }
15891         if ((rack->r_ctl.fsb.left_to_send >= segsiz) &&
15892             (max_val > len) &&
15893             (tso == 0)) {
15894                 max_val -= len;
15895                 len = segsiz;
15896                 th = rack->r_ctl.fsb.th;
15897                 cnt_thru++;
15898                 goto again;
15899         }
15900         tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
15901         counter_u64_add(rack_fto_send, 1);
15902         slot = rack_get_pacing_delay(rack, tp, tot_len, NULL, segsiz);
15903         rack_start_hpts_timer(rack, tp, cts, slot, tot_len, 0);
15904 #ifdef TCP_ACCOUNTING
15905         crtsc = get_cyclecount();
15906         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
15907                 tp->tcp_cnt_counters[SND_OUT_DATA] += cnt_thru;
15908         }
15909         counter_u64_add(tcp_cnt_counters[SND_OUT_DATA], cnt_thru);
15910         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
15911                 tp->tcp_proc_time[SND_OUT_DATA] += (crtsc - ts_val);
15912         }
15913         counter_u64_add(tcp_proc_time[SND_OUT_DATA], (crtsc - ts_val));
15914         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
15915                 tp->tcp_cnt_counters[CNT_OF_MSS_OUT] += ((tot_len + segsiz - 1) / segsiz);
15916         }
15917         counter_u64_add(tcp_cnt_counters[CNT_OF_MSS_OUT], ((tot_len + segsiz - 1) / segsiz));
15918         sched_unpin();
15919 #endif
15920         return (0);
15921 failed:
15922         if (m)
15923                 m_free(m);
15924         rack->r_fast_output = 0;
15925         return (-1);
15926 }
15927
15928 static int
15929 rack_output(struct tcpcb *tp)
15930 {
15931         struct socket *so;
15932         uint32_t recwin;
15933         uint32_t sb_offset, s_moff = 0;
15934         int32_t len, flags, error = 0;
15935         struct mbuf *m, *s_mb = NULL;
15936         struct mbuf *mb;
15937         uint32_t if_hw_tsomaxsegcount = 0;
15938         uint32_t if_hw_tsomaxsegsize;
15939         int32_t segsiz, minseg;
15940         long tot_len_this_send = 0;
15941 #ifdef INET
15942         struct ip *ip = NULL;
15943 #endif
15944 #ifdef TCPDEBUG
15945         struct ipovly *ipov = NULL;
15946 #endif
15947         struct udphdr *udp = NULL;
15948         struct tcp_rack *rack;
15949         struct tcphdr *th;
15950         uint8_t pass = 0;
15951         uint8_t mark = 0;
15952         uint8_t wanted_cookie = 0;
15953         u_char opt[TCP_MAXOLEN];
15954         unsigned ipoptlen, optlen, hdrlen, ulen=0;
15955         uint32_t rack_seq;
15956
15957 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
15958         unsigned ipsec_optlen = 0;
15959
15960 #endif
15961         int32_t idle, sendalot;
15962         int32_t sub_from_prr = 0;
15963         volatile int32_t sack_rxmit;
15964         struct rack_sendmap *rsm = NULL;
15965         int32_t tso, mtu;
15966         struct tcpopt to;
15967         int32_t slot = 0;
15968         int32_t sup_rack = 0;
15969         uint32_t cts, ms_cts, delayed, early;
15970         uint16_t add_flag = RACK_SENT_SP;
15971         uint8_t hpts_calling,  doing_tlp = 0;
15972         uint32_t cwnd_to_use, pace_max_seg;
15973         int32_t do_a_prefetch = 0;
15974         int32_t prefetch_rsm = 0;
15975         int32_t orig_len = 0;
15976         struct timeval tv;
15977         int32_t prefetch_so_done = 0;
15978         struct tcp_log_buffer *lgb;
15979         struct inpcb *inp;
15980         struct sockbuf *sb;
15981         uint64_t ts_val = 0;
15982 #ifdef TCP_ACCOUNTING
15983         uint64_t crtsc;
15984 #endif
15985 #ifdef INET6
15986         struct ip6_hdr *ip6 = NULL;
15987         int32_t isipv6;
15988 #endif
15989         uint8_t filled_all = 0;
15990         bool hw_tls = false;
15991
15992         /* setup and take the cache hits here */
15993         rack = (struct tcp_rack *)tp->t_fb_ptr;
15994 #ifdef TCP_ACCOUNTING
15995         sched_pin();
15996         ts_val = get_cyclecount();
15997 #endif
15998         hpts_calling = rack->rc_inp->inp_hpts_calls;
15999         NET_EPOCH_ASSERT();
16000         INP_WLOCK_ASSERT(rack->rc_inp);
16001 #ifdef TCP_OFFLOAD
16002         if (tp->t_flags & TF_TOE) {
16003 #ifdef TCP_ACCOUNTING
16004                 sched_unpin();
16005 #endif
16006                 return (tcp_offload_output(tp));
16007         }
16008 #endif
16009         /*
16010          * For TFO connections in SYN_RECEIVED, only allow the initial
16011          * SYN|ACK and those sent by the retransmit timer.
16012          */
16013         if (IS_FASTOPEN(tp->t_flags) &&
16014             (tp->t_state == TCPS_SYN_RECEIVED) &&
16015             SEQ_GT(tp->snd_max, tp->snd_una) &&    /* initial SYN|ACK sent */
16016             (rack->r_ctl.rc_resend == NULL)) {         /* not a retransmit */
16017 #ifdef TCP_ACCOUNTING
16018                 sched_unpin();
16019 #endif
16020                 return (0);
16021         }
16022 #ifdef INET6
16023         if (rack->r_state) {
16024                 /* Use the cache line loaded if possible */
16025                 isipv6 = rack->r_is_v6;
16026         } else {
16027                 isipv6 = (rack->rc_inp->inp_vflag & INP_IPV6) != 0;
16028         }
16029 #endif
16030         early = 0;
16031         cts = tcp_get_usecs(&tv);
16032         ms_cts = tcp_tv_to_mssectick(&tv);
16033         if (((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
16034             rack->rc_inp->inp_in_hpts) {
16035                 /*
16036                  * We are on the hpts for some timer but not hptsi output.
16037                  * Remove from the hpts unconditionally.
16038                  */
16039                 rack_timer_cancel(tp, rack, cts, __LINE__);
16040         }
16041         /* Are we pacing and late? */
16042         if ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
16043             TSTMP_GEQ(cts, rack->r_ctl.rc_last_output_to)) {
16044                 /* We are delayed */
16045                 delayed = cts - rack->r_ctl.rc_last_output_to;
16046         } else {
16047                 delayed = 0;
16048         }
16049         /* Do the timers, which may override the pacer */
16050         if (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
16051                 if (rack_process_timers(tp, rack, cts, hpts_calling)) {
16052                         counter_u64_add(rack_out_size[TCP_MSS_ACCT_ATIMER], 1);
16053 #ifdef TCP_ACCOUNTING
16054                         sched_unpin();
16055 #endif
16056                         return (0);
16057                 }
16058         }
16059         if (rack->rc_in_persist) {
16060                 if (rack->rc_inp->inp_in_hpts == 0) {
16061                         /* Timer is not running */
16062                         rack_start_hpts_timer(rack, tp, cts, 0, 0, 0);
16063                 }
16064 #ifdef TCP_ACCOUNTING
16065                 sched_unpin();
16066 #endif
16067                 return (0);
16068         }
16069         if ((rack->r_timer_override) ||
16070             (rack->rc_ack_can_sendout_data) ||
16071             (delayed) ||
16072             (tp->t_state < TCPS_ESTABLISHED)) {
16073                 rack->rc_ack_can_sendout_data = 0;
16074                 if (rack->rc_inp->inp_in_hpts)
16075                         tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
16076         } else if (rack->rc_inp->inp_in_hpts) {
16077                 /*
16078                  * On the hpts you can't pass even if ACKNOW is on, we will
16079                  * when the hpts fires.
16080                  */
16081 #ifdef TCP_ACCOUNTING
16082                 crtsc = get_cyclecount();
16083                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16084                         tp->tcp_proc_time[SND_BLOCKED] += (crtsc - ts_val);
16085                 }
16086                 counter_u64_add(tcp_proc_time[SND_BLOCKED], (crtsc - ts_val));
16087                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16088                         tp->tcp_cnt_counters[SND_BLOCKED]++;
16089                 }
16090                 counter_u64_add(tcp_cnt_counters[SND_BLOCKED], 1);
16091                 sched_unpin();
16092 #endif
16093                 counter_u64_add(rack_out_size[TCP_MSS_ACCT_INPACE], 1);
16094                 return (0);
16095         }
16096         rack->rc_inp->inp_hpts_calls = 0;
16097         /* Finish out both pacing early and late accounting */
16098         if ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
16099             TSTMP_GT(rack->r_ctl.rc_last_output_to, cts)) {
16100                 early = rack->r_ctl.rc_last_output_to - cts;
16101         } else
16102                 early = 0;
16103         if (delayed) {
16104                 rack->r_ctl.rc_agg_delayed += delayed;
16105                 rack->r_late = 1;
16106         } else if (early) {
16107                 rack->r_ctl.rc_agg_early += early;
16108                 rack->r_early = 1;
16109         }
16110         /* Now that early/late accounting is done turn off the flag */
16111         rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
16112         rack->r_wanted_output = 0;
16113         rack->r_timer_override = 0;
16114         if ((tp->t_state != rack->r_state) &&
16115             TCPS_HAVEESTABLISHED(tp->t_state)) {
16116                 rack_set_state(tp, rack);
16117         }
16118         if ((rack->r_fast_output) &&
16119             (tp->rcv_numsacks == 0)) {
16120                 int ret;
16121
16122                 error = 0;
16123                 ret = rack_fast_output(tp, rack, ts_val, cts, ms_cts, &tv, tot_len_this_send, &error);
16124                 if (ret >= 0)
16125                         return(ret);
16126                 else if (error) {
16127                         inp = rack->rc_inp;
16128                         so = inp->inp_socket;
16129                         sb = &so->so_snd;
16130                         goto nomore;
16131                 }
16132         }
16133         inp = rack->rc_inp;
16134         /*
16135          * For TFO connections in SYN_SENT or SYN_RECEIVED,
16136          * only allow the initial SYN or SYN|ACK and those sent
16137          * by the retransmit timer.
16138          */
16139         if (IS_FASTOPEN(tp->t_flags) &&
16140             ((tp->t_state == TCPS_SYN_RECEIVED) ||
16141              (tp->t_state == TCPS_SYN_SENT)) &&
16142             SEQ_GT(tp->snd_max, tp->snd_una) && /* initial SYN or SYN|ACK sent */
16143             (tp->t_rxtshift == 0)) {              /* not a retransmit */
16144                 cwnd_to_use = rack->r_ctl.cwnd_to_use = tp->snd_cwnd;
16145                 so = inp->inp_socket;
16146                 sb = &so->so_snd;
16147                 goto just_return_nolock;
16148         }
16149         /*
16150          * Determine length of data that should be transmitted, and flags
16151          * that will be used. If there is some data or critical controls
16152          * (SYN, RST) to send, then transmit; otherwise, investigate
16153          * further.
16154          */
16155         idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
16156         if (tp->t_idle_reduce) {
16157                 if (idle && ((ticks - tp->t_rcvtime) >= tp->t_rxtcur))
16158                         rack_cc_after_idle(rack, tp);
16159         }
16160         tp->t_flags &= ~TF_LASTIDLE;
16161         if (idle) {
16162                 if (tp->t_flags & TF_MORETOCOME) {
16163                         tp->t_flags |= TF_LASTIDLE;
16164                         idle = 0;
16165                 }
16166         }
16167         if ((tp->snd_una == tp->snd_max) &&
16168             rack->r_ctl.rc_went_idle_time &&
16169             TSTMP_GT(cts, rack->r_ctl.rc_went_idle_time)) {
16170                 idle = cts - rack->r_ctl.rc_went_idle_time;
16171                 if (idle > rack_min_probertt_hold) {
16172                         /* Count as a probe rtt */
16173                         if (rack->in_probe_rtt == 0) {
16174                                 rack->r_ctl.rc_lower_rtt_us_cts = cts;
16175                                 rack->r_ctl.rc_time_probertt_entered = rack->r_ctl.rc_lower_rtt_us_cts;
16176                                 rack->r_ctl.rc_time_probertt_starts = rack->r_ctl.rc_lower_rtt_us_cts;
16177                                 rack->r_ctl.rc_time_of_last_probertt = rack->r_ctl.rc_lower_rtt_us_cts;
16178                         } else {
16179                                 rack_exit_probertt(rack, cts);
16180                         }
16181                 }
16182                 idle = 0;
16183         }
16184         if (rack_use_fsb && (rack->r_fsb_inited == 0))
16185                 rack_init_fsb_block(tp, rack);
16186 again:
16187         /*
16188          * If we've recently taken a timeout, snd_max will be greater than
16189          * snd_nxt.  There may be SACK information that allows us to avoid
16190          * resending already delivered data.  Adjust snd_nxt accordingly.
16191          */
16192         sendalot = 0;
16193         cts = tcp_get_usecs(&tv);
16194         ms_cts = tcp_tv_to_mssectick(&tv);
16195         tso = 0;
16196         mtu = 0;
16197         segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
16198         minseg = segsiz;
16199         if (rack->r_ctl.rc_pace_max_segs == 0)
16200                 pace_max_seg = rack->rc_user_set_max_segs * segsiz;
16201         else
16202                 pace_max_seg = rack->r_ctl.rc_pace_max_segs;
16203         sb_offset = tp->snd_max - tp->snd_una;
16204         cwnd_to_use = rack->r_ctl.cwnd_to_use = tp->snd_cwnd;
16205         flags = tcp_outflags[tp->t_state];
16206         while (rack->rc_free_cnt < rack_free_cache) {
16207                 rsm = rack_alloc(rack);
16208                 if (rsm == NULL) {
16209                         if (inp->inp_hpts_calls)
16210                                 /* Retry in a ms */
16211                                 slot = (1 * HPTS_USEC_IN_MSEC);
16212                         so = inp->inp_socket;
16213                         sb = &so->so_snd;
16214                         goto just_return_nolock;
16215                 }
16216                 TAILQ_INSERT_TAIL(&rack->r_ctl.rc_free, rsm, r_tnext);
16217                 rack->rc_free_cnt++;
16218                 rsm = NULL;
16219         }
16220         if (inp->inp_hpts_calls)
16221                 inp->inp_hpts_calls = 0;
16222         sack_rxmit = 0;
16223         len = 0;
16224         rsm = NULL;
16225         if (flags & TH_RST) {
16226                 SOCKBUF_LOCK(&inp->inp_socket->so_snd);
16227                 so = inp->inp_socket;
16228                 sb = &so->so_snd;
16229                 goto send;
16230         }
16231         if (rack->r_ctl.rc_resend) {
16232                 /* Retransmit timer */
16233                 rsm = rack->r_ctl.rc_resend;
16234                 rack->r_ctl.rc_resend = NULL;
16235                 rsm->r_flags &= ~RACK_TLP;
16236                 len = rsm->r_end - rsm->r_start;
16237                 sack_rxmit = 1;
16238                 sendalot = 0;
16239                 KASSERT(SEQ_LEQ(tp->snd_una, rsm->r_start),
16240                         ("%s:%d: r.start:%u < SND.UNA:%u; tp:%p, rack:%p, rsm:%p",
16241                          __func__, __LINE__,
16242                          rsm->r_start, tp->snd_una, tp, rack, rsm));
16243                 sb_offset = rsm->r_start - tp->snd_una;
16244                 if (len >= segsiz)
16245                         len = segsiz;
16246         } else if ((rsm = tcp_rack_output(tp, rack, cts)) != NULL) {
16247                 /* We have a retransmit that takes precedence */
16248                 rsm->r_flags &= ~RACK_TLP;
16249                 if ((!IN_FASTRECOVERY(tp->t_flags)) &&
16250                     ((tp->t_flags & TF_WASFRECOVERY) == 0)) {
16251                         /* Enter recovery if not induced by a time-out */
16252                         rack->r_ctl.rc_rsm_start = rsm->r_start;
16253                         rack->r_ctl.rc_cwnd_at = tp->snd_cwnd;
16254                         rack->r_ctl.rc_ssthresh_at = tp->snd_ssthresh;
16255                         rack_cong_signal(tp, CC_NDUPACK, tp->snd_una);
16256                 }
16257 #ifdef INVARIANTS
16258                 if (SEQ_LT(rsm->r_start, tp->snd_una)) {
16259                         panic("Huh, tp:%p rack:%p rsm:%p start:%u < snd_una:%u\n",
16260                               tp, rack, rsm, rsm->r_start, tp->snd_una);
16261                 }
16262 #endif
16263                 len = rsm->r_end - rsm->r_start;
16264                 KASSERT(SEQ_LEQ(tp->snd_una, rsm->r_start),
16265                         ("%s:%d: r.start:%u < SND.UNA:%u; tp:%p, rack:%p, rsm:%p",
16266                          __func__, __LINE__,
16267                          rsm->r_start, tp->snd_una, tp, rack, rsm));
16268                 sb_offset = rsm->r_start - tp->snd_una;
16269                 sendalot = 0;
16270                 if (len >= segsiz)
16271                         len = segsiz;
16272                 if (len > 0) {
16273                         sack_rxmit = 1;
16274                         KMOD_TCPSTAT_INC(tcps_sack_rexmits);
16275                         KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
16276                             min(len, segsiz));
16277                         counter_u64_add(rack_rtm_prr_retran, 1);
16278                 }
16279         } else if (rack->r_ctl.rc_tlpsend) {
16280                 /* Tail loss probe */
16281                 long cwin;
16282                 long tlen;
16283
16284                 doing_tlp = 1;
16285                 /*
16286                  * Check if we can do a TLP with a RACK'd packet
16287                  * this can happen if we are not doing the rack
16288                  * cheat and we skipped to a TLP and it
16289                  * went off.
16290                  */
16291                 rsm = rack->r_ctl.rc_tlpsend;
16292                 rsm->r_flags |= RACK_TLP;
16293
16294                 rack->r_ctl.rc_tlpsend = NULL;
16295                 sack_rxmit = 1;
16296                 tlen = rsm->r_end - rsm->r_start;
16297                 if (tlen > segsiz)
16298                         tlen = segsiz;
16299                 tp->t_sndtlppack++;
16300                 tp->t_sndtlpbyte += tlen;
16301                 KASSERT(SEQ_LEQ(tp->snd_una, rsm->r_start),
16302                         ("%s:%d: r.start:%u < SND.UNA:%u; tp:%p, rack:%p, rsm:%p",
16303                          __func__, __LINE__,
16304                          rsm->r_start, tp->snd_una, tp, rack, rsm));
16305                 sb_offset = rsm->r_start - tp->snd_una;
16306                 cwin = min(tp->snd_wnd, tlen);
16307                 len = cwin;
16308         }
16309         if (rack->r_must_retran &&
16310             (rsm == NULL)) {
16311                 /*
16312                  * Non-Sack and we had a RTO or MTU change, we
16313                  * need to retransmit until we reach
16314                  * the former snd_max (rack->r_ctl.rc_snd_max_at_rto).
16315                  */
16316                 if (SEQ_GT(tp->snd_max, tp->snd_una)) {
16317                         int sendwin, flight;
16318
16319                         sendwin = min(tp->snd_wnd, tp->snd_cwnd);
16320                         flight = ctf_flight_size(tp, rack->r_ctl.rc_out_at_rto);
16321                         if (flight >= sendwin) {
16322                                 so = inp->inp_socket;
16323                                 sb = &so->so_snd;
16324                                 goto just_return_nolock;
16325                         }
16326                         rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
16327                         KASSERT(rsm != NULL, ("rsm is NULL rack:%p r_must_retran set", rack));
16328                         if (rsm == NULL) {
16329                                 /* TSNH */
16330                                 rack->r_must_retran = 0;
16331                                 rack->r_ctl.rc_out_at_rto = 0;
16332                                 rack->r_must_retran = 0;
16333                                 so = inp->inp_socket;
16334                                 sb = &so->so_snd;
16335                                 goto just_return_nolock;
16336                         }
16337                         sack_rxmit = 1;
16338                         len = rsm->r_end - rsm->r_start;
16339                         sendalot = 0;
16340                         sb_offset = rsm->r_start - tp->snd_una;
16341                         if (len >= segsiz)
16342                                 len = segsiz;
16343                 } else {
16344                         /* We must be done if there is nothing outstanding */
16345                         rack->r_must_retran = 0;
16346                         rack->r_ctl.rc_out_at_rto = 0;
16347                 }
16348         }
16349         /*
16350          * Enforce a connection sendmap count limit if set
16351          * as long as we are not retransmiting.
16352          */
16353         if ((rsm == NULL) &&
16354             (rack->do_detection == 0) &&
16355             (V_tcp_map_entries_limit > 0) &&
16356             (rack->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
16357                 counter_u64_add(rack_to_alloc_limited, 1);
16358                 if (!rack->alloc_limit_reported) {
16359                         rack->alloc_limit_reported = 1;
16360                         counter_u64_add(rack_alloc_limited_conns, 1);
16361                 }
16362                 so = inp->inp_socket;
16363                 sb = &so->so_snd;
16364                 goto just_return_nolock;
16365         }
16366         if (rsm && (rsm->r_flags & RACK_HAS_FIN)) {
16367                 /* we are retransmitting the fin */
16368                 len--;
16369                 if (len) {
16370                         /*
16371                          * When retransmitting data do *not* include the
16372                          * FIN. This could happen from a TLP probe.
16373                          */
16374                         flags &= ~TH_FIN;
16375                 }
16376         }
16377 #ifdef INVARIANTS
16378         /* For debugging */
16379         rack->r_ctl.rc_rsm_at_retran = rsm;
16380 #endif
16381         if (rsm && rack->r_fsb_inited && rack_use_rsm_rfo &&
16382             ((rsm->r_flags & RACK_HAS_FIN) == 0)) {
16383                 int ret;
16384
16385                 ret = rack_fast_rsm_output(tp, rack, rsm, ts_val, cts, ms_cts, &tv, len);
16386                 if (ret == 0)
16387                         return (0);
16388         }
16389         so = inp->inp_socket;
16390         sb = &so->so_snd;
16391         if (do_a_prefetch == 0) {
16392                 kern_prefetch(sb, &do_a_prefetch);
16393                 do_a_prefetch = 1;
16394         }
16395 #ifdef NETFLIX_SHARED_CWND
16396         if ((tp->t_flags2 & TF2_TCP_SCWND_ALLOWED) &&
16397             rack->rack_enable_scwnd) {
16398                 /* We are doing cwnd sharing */
16399                 if (rack->gp_ready &&
16400                     (rack->rack_attempted_scwnd == 0) &&
16401                     (rack->r_ctl.rc_scw == NULL) &&
16402                     tp->t_lib) {
16403                         /* The pcbid is in, lets make an attempt */
16404                         counter_u64_add(rack_try_scwnd, 1);
16405                         rack->rack_attempted_scwnd = 1;
16406                         rack->r_ctl.rc_scw = tcp_shared_cwnd_alloc(tp,
16407                                                                    &rack->r_ctl.rc_scw_index,
16408                                                                    segsiz);
16409                 }
16410                 if (rack->r_ctl.rc_scw &&
16411                     (rack->rack_scwnd_is_idle == 1) &&
16412                     sbavail(&so->so_snd)) {
16413                         /* we are no longer out of data */
16414                         tcp_shared_cwnd_active(rack->r_ctl.rc_scw, rack->r_ctl.rc_scw_index);
16415                         rack->rack_scwnd_is_idle = 0;
16416                 }
16417                 if (rack->r_ctl.rc_scw) {
16418                         /* First lets update and get the cwnd */
16419                         rack->r_ctl.cwnd_to_use = cwnd_to_use = tcp_shared_cwnd_update(rack->r_ctl.rc_scw,
16420                                                                     rack->r_ctl.rc_scw_index,
16421                                                                     tp->snd_cwnd, tp->snd_wnd, segsiz);
16422                 }
16423         }
16424 #endif
16425         /*
16426          * Get standard flags, and add SYN or FIN if requested by 'hidden'
16427          * state flags.
16428          */
16429         if (tp->t_flags & TF_NEEDFIN)
16430                 flags |= TH_FIN;
16431         if (tp->t_flags & TF_NEEDSYN)
16432                 flags |= TH_SYN;
16433         if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
16434                 void *end_rsm;
16435                 end_rsm = TAILQ_LAST_FAST(&rack->r_ctl.rc_tmap, rack_sendmap, r_tnext);
16436                 if (end_rsm)
16437                         kern_prefetch(end_rsm, &prefetch_rsm);
16438                 prefetch_rsm = 1;
16439         }
16440         SOCKBUF_LOCK(sb);
16441         /*
16442          * If snd_nxt == snd_max and we have transmitted a FIN, the
16443          * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
16444          * negative length.  This can also occur when TCP opens up its
16445          * congestion window while receiving additional duplicate acks after
16446          * fast-retransmit because TCP will reset snd_nxt to snd_max after
16447          * the fast-retransmit.
16448          *
16449          * In the normal retransmit-FIN-only case, however, snd_nxt will be
16450          * set to snd_una, the sb_offset will be 0, and the length may wind
16451          * up 0.
16452          *
16453          * If sack_rxmit is true we are retransmitting from the scoreboard
16454          * in which case len is already set.
16455          */
16456         if ((sack_rxmit == 0) &&
16457             (TCPS_HAVEESTABLISHED(tp->t_state) || IS_FASTOPEN(tp->t_flags))) {
16458                 uint32_t avail;
16459
16460                 avail = sbavail(sb);
16461                 if (SEQ_GT(tp->snd_nxt, tp->snd_una) && avail)
16462                         sb_offset = tp->snd_nxt - tp->snd_una;
16463                 else
16464                         sb_offset = 0;
16465                 if ((IN_FASTRECOVERY(tp->t_flags) == 0) || rack->rack_no_prr) {
16466                         if (rack->r_ctl.rc_tlp_new_data) {
16467                                 /* TLP is forcing out new data */
16468                                 if (rack->r_ctl.rc_tlp_new_data > (uint32_t) (avail - sb_offset)) {
16469                                         rack->r_ctl.rc_tlp_new_data = (uint32_t) (avail - sb_offset);
16470                                 }
16471                                 if ((rack->r_ctl.rc_tlp_new_data + sb_offset) > tp->snd_wnd) {
16472                                         if (tp->snd_wnd > sb_offset)
16473                                                 len = tp->snd_wnd - sb_offset;
16474                                         else
16475                                                 len = 0;
16476                                 } else {
16477                                         len = rack->r_ctl.rc_tlp_new_data;
16478                                 }
16479                                 rack->r_ctl.rc_tlp_new_data = 0;
16480                                 doing_tlp = 1;
16481                         }  else {
16482                                 len = rack_what_can_we_send(tp, rack, cwnd_to_use, avail, sb_offset);
16483                         }
16484                         if ((rack->r_ctl.crte == NULL) && IN_FASTRECOVERY(tp->t_flags) && (len > segsiz)) {
16485                                 /*
16486                                  * For prr=off, we need to send only 1 MSS
16487                                  * at a time. We do this because another sack could
16488                                  * be arriving that causes us to send retransmits and
16489                                  * we don't want to be on a long pace due to a larger send
16490                                  * that keeps us from sending out the retransmit.
16491                                  */
16492                                 len = segsiz;
16493                         }
16494                 } else {
16495                         uint32_t outstanding;
16496                         /*
16497                          * We are inside of a Fast recovery episode, this
16498                          * is caused by a SACK or 3 dup acks. At this point
16499                          * we have sent all the retransmissions and we rely
16500                          * on PRR to dictate what we will send in the form of
16501                          * new data.
16502                          */
16503
16504                         outstanding = tp->snd_max - tp->snd_una;
16505                         if ((rack->r_ctl.rc_prr_sndcnt + outstanding) > tp->snd_wnd) {
16506                                 if (tp->snd_wnd > outstanding) {
16507                                         len = tp->snd_wnd - outstanding;
16508                                         /* Check to see if we have the data */
16509                                         if ((sb_offset + len) > avail) {
16510                                                 /* It does not all fit */
16511                                                 if (avail > sb_offset)
16512                                                         len = avail - sb_offset;
16513                                                 else
16514                                                         len = 0;
16515                                         }
16516                                 } else {
16517                                         len = 0;
16518                                 }
16519                         } else if (avail > sb_offset) {
16520                                 len = avail - sb_offset;
16521                         } else {
16522                                 len = 0;
16523                         }
16524                         if (len > 0) {
16525                                 if (len > rack->r_ctl.rc_prr_sndcnt) {
16526                                         len = rack->r_ctl.rc_prr_sndcnt;
16527                                 }
16528                                 if (len > 0) {
16529                                         sub_from_prr = 1;
16530                                         counter_u64_add(rack_rtm_prr_newdata, 1);
16531                                 }
16532                         }
16533                         if (len > segsiz) {
16534                                 /*
16535                                  * We should never send more than a MSS when
16536                                  * retransmitting or sending new data in prr
16537                                  * mode unless the override flag is on. Most
16538                                  * likely the PRR algorithm is not going to
16539                                  * let us send a lot as well :-)
16540                                  */
16541                                 if (rack->r_ctl.rc_prr_sendalot == 0) {
16542                                         len = segsiz;
16543                                 }
16544                         } else if (len < segsiz) {
16545                                 /*
16546                                  * Do we send any? The idea here is if the
16547                                  * send empty's the socket buffer we want to
16548                                  * do it. However if not then lets just wait
16549                                  * for our prr_sndcnt to get bigger.
16550                                  */
16551                                 long leftinsb;
16552
16553                                 leftinsb = sbavail(sb) - sb_offset;
16554                                 if (leftinsb > len) {
16555                                         /* This send does not empty the sb */
16556                                         len = 0;
16557                                 }
16558                         }
16559                 }
16560         } else if (!TCPS_HAVEESTABLISHED(tp->t_state)) {
16561                 /*
16562                  * If you have not established
16563                  * and are not doing FAST OPEN
16564                  * no data please.
16565                  */
16566                 if ((sack_rxmit == 0) &&
16567                     (!IS_FASTOPEN(tp->t_flags))){
16568                         len = 0;
16569                         sb_offset = 0;
16570                 }
16571         }
16572         if (prefetch_so_done == 0) {
16573                 kern_prefetch(so, &prefetch_so_done);
16574                 prefetch_so_done = 1;
16575         }
16576         /*
16577          * Lop off SYN bit if it has already been sent.  However, if this is
16578          * SYN-SENT state and if segment contains data and if we don't know
16579          * that foreign host supports TAO, suppress sending segment.
16580          */
16581         if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una) &&
16582             ((sack_rxmit == 0) && (tp->t_rxtshift == 0))) {
16583                 /*
16584                  * When sending additional segments following a TFO SYN|ACK,
16585                  * do not include the SYN bit.
16586                  */
16587                 if (IS_FASTOPEN(tp->t_flags) &&
16588                     (tp->t_state == TCPS_SYN_RECEIVED))
16589                         flags &= ~TH_SYN;
16590         }
16591         /*
16592          * Be careful not to send data and/or FIN on SYN segments. This
16593          * measure is needed to prevent interoperability problems with not
16594          * fully conformant TCP implementations.
16595          */
16596         if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
16597                 len = 0;
16598                 flags &= ~TH_FIN;
16599         }
16600         /*
16601          * On TFO sockets, ensure no data is sent in the following cases:
16602          *
16603          *  - When retransmitting SYN|ACK on a passively-created socket
16604          *
16605          *  - When retransmitting SYN on an actively created socket
16606          *
16607          *  - When sending a zero-length cookie (cookie request) on an
16608          *    actively created socket
16609          *
16610          *  - When the socket is in the CLOSED state (RST is being sent)
16611          */
16612         if (IS_FASTOPEN(tp->t_flags) &&
16613             (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
16614              ((tp->t_state == TCPS_SYN_SENT) &&
16615               (tp->t_tfo_client_cookie_len == 0)) ||
16616              (flags & TH_RST))) {
16617                 sack_rxmit = 0;
16618                 len = 0;
16619         }
16620         /* Without fast-open there should never be data sent on a SYN */
16621         if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags))) {
16622                 tp->snd_nxt = tp->iss;
16623                 len = 0;
16624         }
16625         if ((len > segsiz) && (tcp_dsack_block_exists(tp))) {
16626                 /* We only send 1 MSS if we have a DSACK block */
16627                 add_flag |= RACK_SENT_W_DSACK;
16628                 len = segsiz;
16629         }
16630         orig_len = len;
16631         if (len <= 0) {
16632                 /*
16633                  * If FIN has been sent but not acked, but we haven't been
16634                  * called to retransmit, len will be < 0.  Otherwise, window
16635                  * shrank after we sent into it.  If window shrank to 0,
16636                  * cancel pending retransmit, pull snd_nxt back to (closed)
16637                  * window, and set the persist timer if it isn't already
16638                  * going.  If the window didn't close completely, just wait
16639                  * for an ACK.
16640                  *
16641                  * We also do a general check here to ensure that we will
16642                  * set the persist timer when we have data to send, but a
16643                  * 0-byte window. This makes sure the persist timer is set
16644                  * even if the packet hits one of the "goto send" lines
16645                  * below.
16646                  */
16647                 len = 0;
16648                 if ((tp->snd_wnd == 0) &&
16649                     (TCPS_HAVEESTABLISHED(tp->t_state)) &&
16650                     (tp->snd_una == tp->snd_max) &&
16651                     (sb_offset < (int)sbavail(sb))) {
16652                         rack_enter_persist(tp, rack, cts);
16653                 }
16654         } else if ((rsm == NULL) &&
16655                    (doing_tlp == 0) &&
16656                    (len < pace_max_seg)) {
16657                 /*
16658                  * We are not sending a maximum sized segment for
16659                  * some reason. Should we not send anything (think
16660                  * sws or persists)?
16661                  */
16662                 if ((tp->snd_wnd < min((rack->r_ctl.rc_high_rwnd/2), minseg)) &&
16663                     (TCPS_HAVEESTABLISHED(tp->t_state)) &&
16664                     (len < minseg) &&
16665                     (len < (int)(sbavail(sb) - sb_offset))) {
16666                         /*
16667                          * Here the rwnd is less than
16668                          * the minimum pacing size, this is not a retransmit,
16669                          * we are established and
16670                          * the send is not the last in the socket buffer
16671                          * we send nothing, and we may enter persists
16672                          * if nothing is outstanding.
16673                          */
16674                         len = 0;
16675                         if (tp->snd_max == tp->snd_una) {
16676                                 /*
16677                                  * Nothing out we can
16678                                  * go into persists.
16679                                  */
16680                                 rack_enter_persist(tp, rack, cts);
16681                         }
16682                      } else if ((cwnd_to_use >= max(minseg, (segsiz * 4))) &&
16683                            (ctf_flight_size(tp, rack->r_ctl.rc_sacked) > (2 * segsiz)) &&
16684                            (len < (int)(sbavail(sb) - sb_offset)) &&
16685                            (len < minseg)) {
16686                         /*
16687                          * Here we are not retransmitting, and
16688                          * the cwnd is not so small that we could
16689                          * not send at least a min size (rxt timer
16690                          * not having gone off), We have 2 segments or
16691                          * more already in flight, its not the tail end
16692                          * of the socket buffer  and the cwnd is blocking
16693                          * us from sending out a minimum pacing segment size.
16694                          * Lets not send anything.
16695                          */
16696                         len = 0;
16697                 } else if (((tp->snd_wnd - ctf_outstanding(tp)) <
16698                             min((rack->r_ctl.rc_high_rwnd/2), minseg)) &&
16699                            (ctf_flight_size(tp, rack->r_ctl.rc_sacked) > (2 * segsiz)) &&
16700                            (len < (int)(sbavail(sb) - sb_offset)) &&
16701                            (TCPS_HAVEESTABLISHED(tp->t_state))) {
16702                         /*
16703                          * Here we have a send window but we have
16704                          * filled it up and we can't send another pacing segment.
16705                          * We also have in flight more than 2 segments
16706                          * and we are not completing the sb i.e. we allow
16707                          * the last bytes of the sb to go out even if
16708                          * its not a full pacing segment.
16709                          */
16710                         len = 0;
16711                 } else if ((rack->r_ctl.crte != NULL) &&
16712                            (tp->snd_wnd >= (pace_max_seg * max(1, rack_hw_rwnd_factor))) &&
16713                            (cwnd_to_use >= (pace_max_seg + (4 * segsiz))) &&
16714                            (ctf_flight_size(tp, rack->r_ctl.rc_sacked) >= (2 * segsiz)) &&
16715                            (len < (int)(sbavail(sb) - sb_offset))) {
16716                         /*
16717                          * Here we are doing hardware pacing, this is not a TLP,
16718                          * we are not sending a pace max segment size, there is rwnd
16719                          * room to send at least N pace_max_seg, the cwnd is greater
16720                          * than or equal to a full pacing segments plus 4 mss and we have 2 or
16721                          * more segments in flight and its not the tail of the socket buffer.
16722                          *
16723                          * We don't want to send instead we need to get more ack's in to
16724                          * allow us to send a full pacing segment. Normally, if we are pacing
16725                          * about the right speed, we should have finished our pacing
16726                          * send as most of the acks have come back if we are at the
16727                          * right rate. This is a bit fuzzy since return path delay
16728                          * can delay the acks, which is why we want to make sure we
16729                          * have cwnd space to have a bit more than a max pace segments in flight.
16730                          *
16731                          * If we have not gotten our acks back we are pacing at too high a
16732                          * rate delaying will not hurt and will bring our GP estimate down by
16733                          * injecting the delay. If we don't do this we will send
16734                          * 2 MSS out in response to the acks being clocked in which
16735                          * defeats the point of hw-pacing (i.e. to help us get
16736                          * larger TSO's out).
16737                          */
16738                         len = 0;
16739
16740                 }
16741
16742         }
16743         /* len will be >= 0 after this point. */
16744         KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
16745         rack_sndbuf_autoscale(rack);
16746         /*
16747          * Decide if we can use TCP Segmentation Offloading (if supported by
16748          * hardware).
16749          *
16750          * TSO may only be used if we are in a pure bulk sending state.  The
16751          * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
16752          * options prevent using TSO.  With TSO the TCP header is the same
16753          * (except for the sequence number) for all generated packets.  This
16754          * makes it impossible to transmit any options which vary per
16755          * generated segment or packet.
16756          *
16757          * IPv4 handling has a clear separation of ip options and ip header
16758          * flags while IPv6 combines both in in6p_outputopts. ip6_optlen() does
16759          * the right thing below to provide length of just ip options and thus
16760          * checking for ipoptlen is enough to decide if ip options are present.
16761          */
16762         ipoptlen = 0;
16763 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
16764         /*
16765          * Pre-calculate here as we save another lookup into the darknesses
16766          * of IPsec that way and can actually decide if TSO is ok.
16767          */
16768 #ifdef INET6
16769         if (isipv6 && IPSEC_ENABLED(ipv6))
16770                 ipsec_optlen = IPSEC_HDRSIZE(ipv6, tp->t_inpcb);
16771 #ifdef INET
16772         else
16773 #endif
16774 #endif                          /* INET6 */
16775 #ifdef INET
16776                 if (IPSEC_ENABLED(ipv4))
16777                         ipsec_optlen = IPSEC_HDRSIZE(ipv4, tp->t_inpcb);
16778 #endif                          /* INET */
16779 #endif
16780
16781 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
16782         ipoptlen += ipsec_optlen;
16783 #endif
16784         if ((tp->t_flags & TF_TSO) && V_tcp_do_tso && len > segsiz &&
16785             (tp->t_port == 0) &&
16786             ((tp->t_flags & TF_SIGNATURE) == 0) &&
16787             tp->rcv_numsacks == 0 && sack_rxmit == 0 &&
16788             ipoptlen == 0)
16789                 tso = 1;
16790         {
16791                 uint32_t outstanding;
16792
16793                 outstanding = tp->snd_max - tp->snd_una;
16794                 if (tp->t_flags & TF_SENTFIN) {
16795                         /*
16796                          * If we sent a fin, snd_max is 1 higher than
16797                          * snd_una
16798                          */
16799                         outstanding--;
16800                 }
16801                 if (sack_rxmit) {
16802                         if ((rsm->r_flags & RACK_HAS_FIN) == 0)
16803                                 flags &= ~TH_FIN;
16804                 } else {
16805                         if (SEQ_LT(tp->snd_nxt + len, tp->snd_una +
16806                                    sbused(sb)))
16807                                 flags &= ~TH_FIN;
16808                 }
16809         }
16810         recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
16811             (long)TCP_MAXWIN << tp->rcv_scale);
16812
16813         /*
16814          * Sender silly window avoidance.   We transmit under the following
16815          * conditions when len is non-zero:
16816          *
16817          * - We have a full segment (or more with TSO) - This is the last
16818          * buffer in a write()/send() and we are either idle or running
16819          * NODELAY - we've timed out (e.g. persist timer) - we have more
16820          * then 1/2 the maximum send window's worth of data (receiver may be
16821          * limited the window size) - we need to retransmit
16822          */
16823         if (len) {
16824                 if (len >= segsiz) {
16825                         goto send;
16826                 }
16827                 /*
16828                  * NOTE! on localhost connections an 'ack' from the remote
16829                  * end may occur synchronously with the output and cause us
16830                  * to flush a buffer queued with moretocome.  XXX
16831                  *
16832                  */
16833                 if (!(tp->t_flags & TF_MORETOCOME) &&   /* normal case */
16834                     (idle || (tp->t_flags & TF_NODELAY)) &&
16835                     ((uint32_t)len + (uint32_t)sb_offset >= sbavail(sb)) &&
16836                     (tp->t_flags & TF_NOPUSH) == 0) {
16837                         pass = 2;
16838                         goto send;
16839                 }
16840                 if ((tp->snd_una == tp->snd_max) && len) {      /* Nothing outstanding */
16841                         pass = 22;
16842                         goto send;
16843                 }
16844                 if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
16845                         pass = 4;
16846                         goto send;
16847                 }
16848                 if (SEQ_LT(tp->snd_nxt, tp->snd_max)) { /* retransmit case */
16849                         pass = 5;
16850                         goto send;
16851                 }
16852                 if (sack_rxmit) {
16853                         pass = 6;
16854                         goto send;
16855                 }
16856                 if (((tp->snd_wnd - ctf_outstanding(tp)) < segsiz) &&
16857                     (ctf_outstanding(tp) < (segsiz * 2))) {
16858                         /*
16859                          * We have less than two MSS outstanding (delayed ack)
16860                          * and our rwnd will not let us send a full sized
16861                          * MSS. Lets go ahead and let this small segment
16862                          * out because we want to try to have at least two
16863                          * packets inflight to not be caught by delayed ack.
16864                          */
16865                         pass = 12;
16866                         goto send;
16867                 }
16868         }
16869         /*
16870          * Sending of standalone window updates.
16871          *
16872          * Window updates are important when we close our window due to a
16873          * full socket buffer and are opening it again after the application
16874          * reads data from it.  Once the window has opened again and the
16875          * remote end starts to send again the ACK clock takes over and
16876          * provides the most current window information.
16877          *
16878          * We must avoid the silly window syndrome whereas every read from
16879          * the receive buffer, no matter how small, causes a window update
16880          * to be sent.  We also should avoid sending a flurry of window
16881          * updates when the socket buffer had queued a lot of data and the
16882          * application is doing small reads.
16883          *
16884          * Prevent a flurry of pointless window updates by only sending an
16885          * update when we can increase the advertized window by more than
16886          * 1/4th of the socket buffer capacity.  When the buffer is getting
16887          * full or is very small be more aggressive and send an update
16888          * whenever we can increase by two mss sized segments. In all other
16889          * situations the ACK's to new incoming data will carry further
16890          * window increases.
16891          *
16892          * Don't send an independent window update if a delayed ACK is
16893          * pending (it will get piggy-backed on it) or the remote side
16894          * already has done a half-close and won't send more data.  Skip
16895          * this if the connection is in T/TCP half-open state.
16896          */
16897         if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
16898             !(tp->t_flags & TF_DELACK) &&
16899             !TCPS_HAVERCVDFIN(tp->t_state)) {
16900                 /*
16901                  * "adv" is the amount we could increase the window, taking
16902                  * into account that we are limited by TCP_MAXWIN <<
16903                  * tp->rcv_scale.
16904                  */
16905                 int32_t adv;
16906                 int oldwin;
16907
16908                 adv = recwin;
16909                 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
16910                         oldwin = (tp->rcv_adv - tp->rcv_nxt);
16911                         if (adv > oldwin)
16912                             adv -= oldwin;
16913                         else {
16914                                 /* We can't increase the window */
16915                                 adv = 0;
16916                         }
16917                 } else
16918                         oldwin = 0;
16919
16920                 /*
16921                  * If the new window size ends up being the same as or less
16922                  * than the old size when it is scaled, then don't force
16923                  * a window update.
16924                  */
16925                 if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
16926                         goto dontupdate;
16927
16928                 if (adv >= (int32_t)(2 * segsiz) &&
16929                     (adv >= (int32_t)(so->so_rcv.sb_hiwat / 4) ||
16930                      recwin <= (int32_t)(so->so_rcv.sb_hiwat / 8) ||
16931                      so->so_rcv.sb_hiwat <= 8 * segsiz)) {
16932                         pass = 7;
16933                         goto send;
16934                 }
16935                 if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat) {
16936                         pass = 23;
16937                         goto send;
16938                 }
16939         }
16940 dontupdate:
16941
16942         /*
16943          * Send if we owe the peer an ACK, RST, SYN, or urgent data.  ACKNOW
16944          * is also a catch-all for the retransmit timer timeout case.
16945          */
16946         if (tp->t_flags & TF_ACKNOW) {
16947                 pass = 8;
16948                 goto send;
16949         }
16950         if (((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0)) {
16951                 pass = 9;
16952                 goto send;
16953         }
16954         /*
16955          * If our state indicates that FIN should be sent and we have not
16956          * yet done so, then we need to send.
16957          */
16958         if ((flags & TH_FIN) &&
16959             (tp->snd_nxt == tp->snd_una)) {
16960                 pass = 11;
16961                 goto send;
16962         }
16963         /*
16964          * No reason to send a segment, just return.
16965          */
16966 just_return:
16967         SOCKBUF_UNLOCK(sb);
16968 just_return_nolock:
16969         {
16970                 int app_limited = CTF_JR_SENT_DATA;
16971
16972                 if (tot_len_this_send > 0) {
16973                         /* Make sure snd_nxt is up to max */
16974                         rack->r_ctl.fsb.recwin = recwin;
16975                         slot = rack_get_pacing_delay(rack, tp, tot_len_this_send, NULL, segsiz);
16976                         if ((error == 0) &&
16977                             rack_use_rfo &&
16978                             ((flags & (TH_SYN|TH_FIN)) == 0) &&
16979                             (ipoptlen == 0) &&
16980                             (tp->snd_nxt == tp->snd_max) &&
16981                             (tp->rcv_numsacks == 0) &&
16982                             rack->r_fsb_inited &&
16983                             TCPS_HAVEESTABLISHED(tp->t_state) &&
16984                             (rack->r_must_retran == 0) &&
16985                             ((tp->t_flags & TF_NEEDFIN) == 0) &&
16986                             (len > 0) && (orig_len > 0) &&
16987                             (orig_len > len) &&
16988                             ((orig_len - len) >= segsiz) &&
16989                             ((optlen == 0) ||
16990                              ((optlen == TCPOLEN_TSTAMP_APPA) && (to.to_flags & TOF_TS)))) {
16991                                 /* We can send at least one more MSS using our fsb */
16992
16993                                 rack->r_fast_output = 1;
16994                                 rack->r_ctl.fsb.m = sbsndmbuf(sb, (tp->snd_max - tp->snd_una), &rack->r_ctl.fsb.off);
16995                                 rack->r_ctl.fsb.o_m_len = rack->r_ctl.fsb.m->m_len;
16996                                 rack->r_ctl.fsb.tcp_flags = flags;
16997                                 rack->r_ctl.fsb.left_to_send = orig_len - len;
16998                                 KASSERT((rack->r_ctl.fsb.left_to_send <= (sbavail(sb) - (tp->snd_max - tp->snd_una))),
16999                                         ("rack:%p left_to_send:%u sbavail:%u out:%u",
17000                                         rack, rack->r_ctl.fsb.left_to_send, sbavail(sb),
17001                                          (tp->snd_max - tp->snd_una)));
17002                                 if (rack->r_ctl.fsb.left_to_send < segsiz)
17003                                         rack->r_fast_output = 0;
17004                                 else {
17005                                         if (rack->r_ctl.fsb.left_to_send == (sbavail(sb) - (tp->snd_max - tp->snd_una)))
17006                                                 rack->r_ctl.fsb.rfo_apply_push = 1;
17007                                         else
17008                                                 rack->r_ctl.fsb.rfo_apply_push = 0;
17009                                 }
17010                         } else
17011                                 rack->r_fast_output = 0;
17012
17013
17014                         rack_log_fsb(rack, tp, so, flags,
17015                                      ipoptlen, orig_len, len, 0,
17016                                      1, optlen, __LINE__, 1);
17017                         if (SEQ_GT(tp->snd_max, tp->snd_nxt))
17018                                 tp->snd_nxt = tp->snd_max;
17019                 } else {
17020                         int end_window = 0;
17021                         uint32_t seq = tp->gput_ack;
17022
17023                         rsm = RB_MAX(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
17024                         if (rsm) {
17025                                 /*
17026                                  * Mark the last sent that we just-returned (hinting
17027                                  * that delayed ack may play a role in any rtt measurement).
17028                                  */
17029                                 rsm->r_just_ret = 1;
17030                         }
17031                         counter_u64_add(rack_out_size[TCP_MSS_ACCT_JUSTRET], 1);
17032                         rack->r_ctl.rc_agg_delayed = 0;
17033                         rack->r_early = 0;
17034                         rack->r_late = 0;
17035                         rack->r_ctl.rc_agg_early = 0;
17036                         if ((ctf_outstanding(tp) +
17037                              min(max(segsiz, (rack->r_ctl.rc_high_rwnd/2)),
17038                                  minseg)) >= tp->snd_wnd) {
17039                                 /* We are limited by the rwnd */
17040                                 app_limited = CTF_JR_RWND_LIMITED;
17041                                 if (IN_FASTRECOVERY(tp->t_flags))
17042                                     rack->r_ctl.rc_prr_sndcnt = 0;
17043                         } else if (ctf_outstanding(tp) >= sbavail(sb)) {
17044                                 /* We are limited by whats available -- app limited */
17045                                 app_limited = CTF_JR_APP_LIMITED;
17046                                 if (IN_FASTRECOVERY(tp->t_flags))
17047                                     rack->r_ctl.rc_prr_sndcnt = 0;
17048                         } else if ((idle == 0) &&
17049                                    ((tp->t_flags & TF_NODELAY) == 0) &&
17050                                    ((uint32_t)len + (uint32_t)sb_offset >= sbavail(sb)) &&
17051                                    (len < segsiz)) {
17052                                 /*
17053                                  * No delay is not on and the
17054                                  * user is sending less than 1MSS. This
17055                                  * brings out SWS avoidance so we
17056                                  * don't send. Another app-limited case.
17057                                  */
17058                                 app_limited = CTF_JR_APP_LIMITED;
17059                         } else if (tp->t_flags & TF_NOPUSH) {
17060                                 /*
17061                                  * The user has requested no push of
17062                                  * the last segment and we are
17063                                  * at the last segment. Another app
17064                                  * limited case.
17065                                  */
17066                                 app_limited = CTF_JR_APP_LIMITED;
17067                         } else if ((ctf_outstanding(tp) + minseg) > cwnd_to_use) {
17068                                 /* Its the cwnd */
17069                                 app_limited = CTF_JR_CWND_LIMITED;
17070                         } else if (IN_FASTRECOVERY(tp->t_flags) &&
17071                                    (rack->rack_no_prr == 0) &&
17072                                    (rack->r_ctl.rc_prr_sndcnt < segsiz)) {
17073                                 app_limited = CTF_JR_PRR;
17074                         } else {
17075                                 /* Now why here are we not sending? */
17076 #ifdef NOW
17077 #ifdef INVARIANTS
17078                                 panic("rack:%p hit JR_ASSESSING case cwnd_to_use:%u?", rack, cwnd_to_use);
17079 #endif
17080 #endif
17081                                 app_limited = CTF_JR_ASSESSING;
17082                         }
17083                         /*
17084                          * App limited in some fashion, for our pacing GP
17085                          * measurements we don't want any gap (even cwnd).
17086                          * Close  down the measurement window.
17087                          */
17088                         if (rack_cwnd_block_ends_measure &&
17089                             ((app_limited == CTF_JR_CWND_LIMITED) ||
17090                              (app_limited == CTF_JR_PRR))) {
17091                                 /*
17092                                  * The reason we are not sending is
17093                                  * the cwnd (or prr). We have been configured
17094                                  * to end the measurement window in
17095                                  * this case.
17096                                  */
17097                                 end_window = 1;
17098                         } else if (rack_rwnd_block_ends_measure &&
17099                                    (app_limited == CTF_JR_RWND_LIMITED)) {
17100                                 /*
17101                                  * We are rwnd limited and have been
17102                                  * configured to end the measurement
17103                                  * window in this case.
17104                                  */
17105                                 end_window = 1;
17106                         } else if (app_limited == CTF_JR_APP_LIMITED) {
17107                                 /*
17108                                  * A true application limited period, we have
17109                                  * ran out of data.
17110                                  */
17111                                 end_window = 1;
17112                         } else if (app_limited == CTF_JR_ASSESSING) {
17113                                 /*
17114                                  * In the assessing case we hit the end of
17115                                  * the if/else and had no known reason
17116                                  * This will panic us under invariants..
17117                                  *
17118                                  * If we get this out in logs we need to
17119                                  * investagate which reason we missed.
17120                                  */
17121                                 end_window = 1;
17122                         }
17123                         if (end_window) {
17124                                 uint8_t log = 0;
17125
17126                                 if ((tp->t_flags & TF_GPUTINPROG) &&
17127                                     SEQ_GT(tp->gput_ack, tp->snd_max)) {
17128                                         /* Mark the last packet has app limited */
17129                                         tp->gput_ack = tp->snd_max;
17130                                         log = 1;
17131                                 }
17132                                 rsm = RB_MAX(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
17133                                 if (rsm && ((rsm->r_flags & RACK_APP_LIMITED) == 0)) {
17134                                         if (rack->r_ctl.rc_app_limited_cnt == 0)
17135                                                 rack->r_ctl.rc_end_appl = rack->r_ctl.rc_first_appl = rsm;
17136                                         else {
17137                                                 /*
17138                                                  * Go out to the end app limited and mark
17139                                                  * this new one as next and move the end_appl up
17140                                                  * to this guy.
17141                                                  */
17142                                                 if (rack->r_ctl.rc_end_appl)
17143                                                         rack->r_ctl.rc_end_appl->r_nseq_appl = rsm->r_start;
17144                                                 rack->r_ctl.rc_end_appl = rsm;
17145                                         }
17146                                         rsm->r_flags |= RACK_APP_LIMITED;
17147                                         rack->r_ctl.rc_app_limited_cnt++;
17148                                 }
17149                                 if (log)
17150                                         rack_log_pacing_delay_calc(rack,
17151                                                                    rack->r_ctl.rc_app_limited_cnt, seq,
17152                                                                    tp->gput_ack, 0, 0, 4, __LINE__, NULL);
17153                         }
17154                 }
17155                 if (slot) {
17156                         /* set the rack tcb into the slot N */
17157                         counter_u64_add(rack_paced_segments, 1);
17158                 } else if (tot_len_this_send) {
17159                         counter_u64_add(rack_unpaced_segments, 1);
17160                 }
17161                 /* Check if we need to go into persists or not */
17162                 if ((tp->snd_max == tp->snd_una) &&
17163                     TCPS_HAVEESTABLISHED(tp->t_state) &&
17164                     sbavail(sb) &&
17165                     (sbavail(sb) > tp->snd_wnd) &&
17166                     (tp->snd_wnd < min((rack->r_ctl.rc_high_rwnd/2), minseg))) {
17167                         /* Yes lets make sure to move to persist before timer-start */
17168                         rack_enter_persist(tp, rack, rack->r_ctl.rc_rcvtime);
17169                 }
17170                 rack_start_hpts_timer(rack, tp, cts, slot, tot_len_this_send, sup_rack);
17171                 rack_log_type_just_return(rack, cts, tot_len_this_send, slot, hpts_calling, app_limited, cwnd_to_use);
17172         }
17173 #ifdef NETFLIX_SHARED_CWND
17174         if ((sbavail(sb) == 0) &&
17175             rack->r_ctl.rc_scw) {
17176                 tcp_shared_cwnd_idle(rack->r_ctl.rc_scw, rack->r_ctl.rc_scw_index);
17177                 rack->rack_scwnd_is_idle = 1;
17178         }
17179 #endif
17180 #ifdef TCP_ACCOUNTING
17181         if (tot_len_this_send > 0) {
17182                 crtsc = get_cyclecount();
17183                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
17184                         tp->tcp_cnt_counters[SND_OUT_DATA]++;
17185                 }
17186                 counter_u64_add(tcp_cnt_counters[SND_OUT_DATA], 1);
17187                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
17188                         tp->tcp_proc_time[SND_OUT_DATA] += (crtsc - ts_val);
17189                 }
17190                 counter_u64_add(tcp_proc_time[SND_OUT_DATA], (crtsc - ts_val));
17191                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
17192                         tp->tcp_cnt_counters[CNT_OF_MSS_OUT] += ((tot_len_this_send + segsiz - 1) / segsiz);
17193                 }
17194                 counter_u64_add(tcp_cnt_counters[CNT_OF_MSS_OUT], ((tot_len_this_send + segsiz - 1) / segsiz));
17195         } else {
17196                 crtsc = get_cyclecount();
17197                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
17198                         tp->tcp_cnt_counters[SND_LIMITED]++;
17199                 }
17200                 counter_u64_add(tcp_cnt_counters[SND_LIMITED], 1);
17201                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
17202                         tp->tcp_proc_time[SND_LIMITED] += (crtsc - ts_val);
17203                 }
17204                 counter_u64_add(tcp_proc_time[SND_LIMITED], (crtsc - ts_val));
17205         }
17206         sched_unpin();
17207 #endif
17208         return (0);
17209
17210 send:
17211         if (rsm || sack_rxmit)
17212                 counter_u64_add(rack_nfto_resend, 1);
17213         else
17214                 counter_u64_add(rack_non_fto_send, 1);
17215         if ((flags & TH_FIN) &&
17216             sbavail(sb)) {
17217                 /*
17218                  * We do not transmit a FIN
17219                  * with data outstanding. We
17220                  * need to make it so all data
17221                  * is acked first.
17222                  */
17223                 flags &= ~TH_FIN;
17224         }
17225         /* Enforce stack imposed max seg size if we have one */
17226         if (rack->r_ctl.rc_pace_max_segs &&
17227             (len > rack->r_ctl.rc_pace_max_segs)) {
17228                 mark = 1;
17229                 len = rack->r_ctl.rc_pace_max_segs;
17230         }
17231         SOCKBUF_LOCK_ASSERT(sb);
17232         if (len > 0) {
17233                 if (len >= segsiz)
17234                         tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
17235                 else
17236                         tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
17237         }
17238         /*
17239          * Before ESTABLISHED, force sending of initial options unless TCP
17240          * set not to do any options. NOTE: we assume that the IP/TCP header
17241          * plus TCP options always fit in a single mbuf, leaving room for a
17242          * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
17243          * + optlen <= MCLBYTES
17244          */
17245         optlen = 0;
17246 #ifdef INET6
17247         if (isipv6)
17248                 hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
17249         else
17250 #endif
17251                 hdrlen = sizeof(struct tcpiphdr);
17252
17253         /*
17254          * Compute options for segment. We only have to care about SYN and
17255          * established connection segments.  Options for SYN-ACK segments
17256          * are handled in TCP syncache.
17257          */
17258         to.to_flags = 0;
17259         if ((tp->t_flags & TF_NOOPT) == 0) {
17260                 /* Maximum segment size. */
17261                 if (flags & TH_SYN) {
17262                         tp->snd_nxt = tp->iss;
17263                         to.to_mss = tcp_mssopt(&inp->inp_inc);
17264                         if (tp->t_port)
17265                                 to.to_mss -= V_tcp_udp_tunneling_overhead;
17266                         to.to_flags |= TOF_MSS;
17267
17268                         /*
17269                          * On SYN or SYN|ACK transmits on TFO connections,
17270                          * only include the TFO option if it is not a
17271                          * retransmit, as the presence of the TFO option may
17272                          * have caused the original SYN or SYN|ACK to have
17273                          * been dropped by a middlebox.
17274                          */
17275                         if (IS_FASTOPEN(tp->t_flags) &&
17276                             (tp->t_rxtshift == 0)) {
17277                                 if (tp->t_state == TCPS_SYN_RECEIVED) {
17278                                         to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
17279                                         to.to_tfo_cookie =
17280                                                 (u_int8_t *)&tp->t_tfo_cookie.server;
17281                                         to.to_flags |= TOF_FASTOPEN;
17282                                         wanted_cookie = 1;
17283                                 } else if (tp->t_state == TCPS_SYN_SENT) {
17284                                         to.to_tfo_len =
17285                                                 tp->t_tfo_client_cookie_len;
17286                                         to.to_tfo_cookie =
17287                                                 tp->t_tfo_cookie.client;
17288                                         to.to_flags |= TOF_FASTOPEN;
17289                                         wanted_cookie = 1;
17290                                         /*
17291                                          * If we wind up having more data to
17292                                          * send with the SYN than can fit in
17293                                          * one segment, don't send any more
17294                                          * until the SYN|ACK comes back from
17295                                          * the other end.
17296                                          */
17297                                         sendalot = 0;
17298                                 }
17299                         }
17300                 }
17301                 /* Window scaling. */
17302                 if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
17303                         to.to_wscale = tp->request_r_scale;
17304                         to.to_flags |= TOF_SCALE;
17305                 }
17306                 /* Timestamps. */
17307                 if ((tp->t_flags & TF_RCVD_TSTMP) ||
17308                     ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
17309                         to.to_tsval = ms_cts + tp->ts_offset;
17310                         to.to_tsecr = tp->ts_recent;
17311                         to.to_flags |= TOF_TS;
17312                 }
17313                 /* Set receive buffer autosizing timestamp. */
17314                 if (tp->rfbuf_ts == 0 &&
17315                     (so->so_rcv.sb_flags & SB_AUTOSIZE))
17316                         tp->rfbuf_ts = tcp_ts_getticks();
17317                 /* Selective ACK's. */
17318                 if (tp->t_flags & TF_SACK_PERMIT) {
17319                         if (flags & TH_SYN)
17320                                 to.to_flags |= TOF_SACKPERM;
17321                         else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
17322                                  tp->rcv_numsacks > 0) {
17323                                 to.to_flags |= TOF_SACK;
17324                                 to.to_nsacks = tp->rcv_numsacks;
17325                                 to.to_sacks = (u_char *)tp->sackblks;
17326                         }
17327                 }
17328 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
17329                 /* TCP-MD5 (RFC2385). */
17330                 if (tp->t_flags & TF_SIGNATURE)
17331                         to.to_flags |= TOF_SIGNATURE;
17332 #endif                          /* TCP_SIGNATURE */
17333
17334                 /* Processing the options. */
17335                 hdrlen += optlen = tcp_addoptions(&to, opt);
17336                 /*
17337                  * If we wanted a TFO option to be added, but it was unable
17338                  * to fit, ensure no data is sent.
17339                  */
17340                 if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
17341                     !(to.to_flags & TOF_FASTOPEN))
17342                         len = 0;
17343         }
17344         if (tp->t_port) {
17345                 if (V_tcp_udp_tunneling_port == 0) {
17346                         /* The port was removed?? */
17347                         SOCKBUF_UNLOCK(&so->so_snd);
17348 #ifdef TCP_ACCOUNTING
17349                         crtsc = get_cyclecount();
17350                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
17351                                 tp->tcp_cnt_counters[SND_OUT_FAIL]++;
17352                         }
17353                         counter_u64_add(tcp_cnt_counters[SND_OUT_FAIL], 1);
17354                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
17355                                 tp->tcp_proc_time[SND_OUT_FAIL] += (crtsc - ts_val);
17356                         }
17357                         counter_u64_add(tcp_proc_time[SND_OUT_FAIL], (crtsc - ts_val));
17358                         sched_unpin();
17359 #endif
17360                         return (EHOSTUNREACH);
17361                 }
17362                 hdrlen += sizeof(struct udphdr);
17363         }
17364 #ifdef INET6
17365         if (isipv6)
17366                 ipoptlen = ip6_optlen(tp->t_inpcb);
17367         else
17368 #endif
17369                 if (tp->t_inpcb->inp_options)
17370                         ipoptlen = tp->t_inpcb->inp_options->m_len -
17371                                 offsetof(struct ipoption, ipopt_list);
17372                 else
17373                         ipoptlen = 0;
17374 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
17375         ipoptlen += ipsec_optlen;
17376 #endif
17377
17378         /*
17379          * Adjust data length if insertion of options will bump the packet
17380          * length beyond the t_maxseg length. Clear the FIN bit because we
17381          * cut off the tail of the segment.
17382          */
17383         if (len + optlen + ipoptlen > tp->t_maxseg) {
17384                 if (tso) {
17385                         uint32_t if_hw_tsomax;
17386                         uint32_t moff;
17387                         int32_t max_len;
17388
17389                         /* extract TSO information */
17390                         if_hw_tsomax = tp->t_tsomax;
17391                         if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
17392                         if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
17393                         KASSERT(ipoptlen == 0,
17394                                 ("%s: TSO can't do IP options", __func__));
17395
17396                         /*
17397                          * Check if we should limit by maximum payload
17398                          * length:
17399                          */
17400                         if (if_hw_tsomax != 0) {
17401                                 /* compute maximum TSO length */
17402                                 max_len = (if_hw_tsomax - hdrlen -
17403                                            max_linkhdr);
17404                                 if (max_len <= 0) {
17405                                         len = 0;
17406                                 } else if (len > max_len) {
17407                                         sendalot = 1;
17408                                         len = max_len;
17409                                         mark = 2;
17410                                 }
17411                         }
17412                         /*
17413                          * Prevent the last segment from being fractional
17414                          * unless the send sockbuf can be emptied:
17415                          */
17416                         max_len = (tp->t_maxseg - optlen);
17417                         if ((sb_offset + len) < sbavail(sb)) {
17418                                 moff = len % (u_int)max_len;
17419                                 if (moff != 0) {
17420                                         mark = 3;
17421                                         len -= moff;
17422                                 }
17423                         }
17424                         /*
17425                          * In case there are too many small fragments don't
17426                          * use TSO:
17427                          */
17428                         if (len <= segsiz) {
17429                                 mark = 4;
17430                                 tso = 0;
17431                         }
17432                         /*
17433                          * Send the FIN in a separate segment after the bulk
17434                          * sending is done. We don't trust the TSO
17435                          * implementations to clear the FIN flag on all but
17436                          * the last segment.
17437                          */
17438                         if (tp->t_flags & TF_NEEDFIN) {
17439                                 sendalot = 4;
17440                         }
17441                 } else {
17442                         mark = 5;
17443                         if (optlen + ipoptlen >= tp->t_maxseg) {
17444                                 /*
17445                                  * Since we don't have enough space to put
17446                                  * the IP header chain and the TCP header in
17447                                  * one packet as required by RFC 7112, don't
17448                                  * send it. Also ensure that at least one
17449                                  * byte of the payload can be put into the
17450                                  * TCP segment.
17451                                  */
17452                                 SOCKBUF_UNLOCK(&so->so_snd);
17453                                 error = EMSGSIZE;
17454                                 sack_rxmit = 0;
17455                                 goto out;
17456                         }
17457                         len = tp->t_maxseg - optlen - ipoptlen;
17458                         sendalot = 5;
17459                 }
17460         } else {
17461                 tso = 0;
17462                 mark = 6;
17463         }
17464         KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
17465                 ("%s: len > IP_MAXPACKET", __func__));
17466 #ifdef DIAGNOSTIC
17467 #ifdef INET6
17468         if (max_linkhdr + hdrlen > MCLBYTES)
17469 #else
17470                 if (max_linkhdr + hdrlen > MHLEN)
17471 #endif
17472                         panic("tcphdr too big");
17473 #endif
17474
17475         /*
17476          * This KASSERT is here to catch edge cases at a well defined place.
17477          * Before, those had triggered (random) panic conditions further
17478          * down.
17479          */
17480         KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
17481         if ((len == 0) &&
17482             (flags & TH_FIN) &&
17483             (sbused(sb))) {
17484                 /*
17485                  * We have outstanding data, don't send a fin by itself!.
17486                  */
17487                 goto just_return;
17488         }
17489         /*
17490          * Grab a header mbuf, attaching a copy of data to be transmitted,
17491          * and initialize the header from the template for sends on this
17492          * connection.
17493          */
17494         hw_tls = (sb->sb_flags & SB_TLS_IFNET) != 0;
17495         if (len) {
17496                 uint32_t max_val;
17497                 uint32_t moff;
17498
17499                 if (rack->r_ctl.rc_pace_max_segs)
17500                         max_val = rack->r_ctl.rc_pace_max_segs;
17501                 else if (rack->rc_user_set_max_segs)
17502                         max_val = rack->rc_user_set_max_segs * segsiz;
17503                 else
17504                         max_val = len;
17505                 /*
17506                  * We allow a limit on sending with hptsi.
17507                  */
17508                 if (len > max_val) {
17509                         mark = 7;
17510                         len = max_val;
17511                 }
17512 #ifdef INET6
17513                 if (MHLEN < hdrlen + max_linkhdr)
17514                         m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
17515                 else
17516 #endif
17517                         m = m_gethdr(M_NOWAIT, MT_DATA);
17518
17519                 if (m == NULL) {
17520                         SOCKBUF_UNLOCK(sb);
17521                         error = ENOBUFS;
17522                         sack_rxmit = 0;
17523                         goto out;
17524                 }
17525                 m->m_data += max_linkhdr;
17526                 m->m_len = hdrlen;
17527
17528                 /*
17529                  * Start the m_copy functions from the closest mbuf to the
17530                  * sb_offset in the socket buffer chain.
17531                  */
17532                 mb = sbsndptr_noadv(sb, sb_offset, &moff);
17533                 s_mb = mb;
17534                 s_moff = moff;
17535                 if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
17536                         m_copydata(mb, moff, (int)len,
17537                                    mtod(m, caddr_t)+hdrlen);
17538                         if (SEQ_LT(tp->snd_nxt, tp->snd_max))
17539                                 sbsndptr_adv(sb, mb, len);
17540                         m->m_len += len;
17541                 } else {
17542                         struct sockbuf *msb;
17543
17544                         if (SEQ_LT(tp->snd_nxt, tp->snd_max))
17545                                 msb = NULL;
17546                         else
17547                                 msb = sb;
17548                         m->m_next = tcp_m_copym(
17549                                 mb, moff, &len,
17550                                 if_hw_tsomaxsegcount, if_hw_tsomaxsegsize, msb,
17551                                 ((rsm == NULL) ? hw_tls : 0)
17552 #ifdef NETFLIX_COPY_ARGS
17553                                 , &filled_all
17554 #endif
17555                                 );
17556                         if (len <= (tp->t_maxseg - optlen)) {
17557                                 /*
17558                                  * Must have ran out of mbufs for the copy
17559                                  * shorten it to no longer need tso. Lets
17560                                  * not put on sendalot since we are low on
17561                                  * mbufs.
17562                                  */
17563                                 tso = 0;
17564                         }
17565                         if (m->m_next == NULL) {
17566                                 SOCKBUF_UNLOCK(sb);
17567                                 (void)m_free(m);
17568                                 error = ENOBUFS;
17569                                 sack_rxmit = 0;
17570                                 goto out;
17571                         }
17572                 }
17573                 if (SEQ_LT(tp->snd_nxt, tp->snd_max) || sack_rxmit) {
17574                         if (rsm && (rsm->r_flags & RACK_TLP)) {
17575                                 /*
17576                                  * TLP should not count in retran count, but
17577                                  * in its own bin
17578                                  */
17579                                 counter_u64_add(rack_tlp_retran, 1);
17580                                 counter_u64_add(rack_tlp_retran_bytes, len);
17581                         } else {
17582                                 tp->t_sndrexmitpack++;
17583                                 KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
17584                                 KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
17585                         }
17586 #ifdef STATS
17587                         stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
17588                                                  len);
17589 #endif
17590                 } else {
17591                         KMOD_TCPSTAT_INC(tcps_sndpack);
17592                         KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
17593 #ifdef STATS
17594                         stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
17595                                                  len);
17596 #endif
17597                 }
17598                 /*
17599                  * If we're sending everything we've got, set PUSH. (This
17600                  * will keep happy those implementations which only give
17601                  * data to the user when a buffer fills or a PUSH comes in.)
17602                  */
17603                 if (sb_offset + len == sbused(sb) &&
17604                     sbused(sb) &&
17605                     !(flags & TH_SYN)) {
17606                         flags |= TH_PUSH;
17607                         add_flag |= RACK_HAD_PUSH;
17608                 }
17609
17610                 SOCKBUF_UNLOCK(sb);
17611         } else {
17612                 SOCKBUF_UNLOCK(sb);
17613                 if (tp->t_flags & TF_ACKNOW)
17614                         KMOD_TCPSTAT_INC(tcps_sndacks);
17615                 else if (flags & (TH_SYN | TH_FIN | TH_RST))
17616                         KMOD_TCPSTAT_INC(tcps_sndctrl);
17617                 else
17618                         KMOD_TCPSTAT_INC(tcps_sndwinup);
17619
17620                 m = m_gethdr(M_NOWAIT, MT_DATA);
17621                 if (m == NULL) {
17622                         error = ENOBUFS;
17623                         sack_rxmit = 0;
17624                         goto out;
17625                 }
17626 #ifdef INET6
17627                 if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
17628                     MHLEN >= hdrlen) {
17629                         M_ALIGN(m, hdrlen);
17630                 } else
17631 #endif
17632                         m->m_data += max_linkhdr;
17633                 m->m_len = hdrlen;
17634         }
17635         SOCKBUF_UNLOCK_ASSERT(sb);
17636         m->m_pkthdr.rcvif = (struct ifnet *)0;
17637 #ifdef MAC
17638         mac_inpcb_create_mbuf(inp, m);
17639 #endif
17640         if ((ipoptlen == 0) && (rack->r_ctl.fsb.tcp_ip_hdr) &&  rack->r_fsb_inited) {
17641 #ifdef INET6
17642                 if (isipv6)
17643                         ip6 = (struct ip6_hdr *)rack->r_ctl.fsb.tcp_ip_hdr;
17644                 else
17645 #endif                          /* INET6 */
17646                         ip = (struct ip *)rack->r_ctl.fsb.tcp_ip_hdr;
17647                 th = rack->r_ctl.fsb.th;
17648                 udp = rack->r_ctl.fsb.udp;
17649                 if (udp) {
17650                         if (isipv6)
17651                                 ulen = hdrlen + len - sizeof(struct ip6_hdr);
17652                         else
17653                                 ulen = hdrlen + len - sizeof(struct ip);
17654                         udp->uh_ulen = htons(ulen);
17655                 }
17656         } else {
17657 #ifdef INET6
17658                 if (isipv6) {
17659                         ip6 = mtod(m, struct ip6_hdr *);
17660                         if (tp->t_port) {
17661                                 udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
17662                                 udp->uh_sport = htons(V_tcp_udp_tunneling_port);
17663                                 udp->uh_dport = tp->t_port;
17664                                 ulen = hdrlen + len - sizeof(struct ip6_hdr);
17665                                 udp->uh_ulen = htons(ulen);
17666                                 th = (struct tcphdr *)(udp + 1);
17667                         } else
17668                                 th = (struct tcphdr *)(ip6 + 1);
17669                         tcpip_fillheaders(inp, tp->t_port, ip6, th);
17670                 } else
17671 #endif                          /* INET6 */
17672                 {
17673                         ip = mtod(m, struct ip *);
17674 #ifdef TCPDEBUG
17675                         ipov = (struct ipovly *)ip;
17676 #endif
17677                         if (tp->t_port) {
17678                                 udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
17679                                 udp->uh_sport = htons(V_tcp_udp_tunneling_port);
17680                                 udp->uh_dport = tp->t_port;
17681                                 ulen = hdrlen + len - sizeof(struct ip);
17682                                 udp->uh_ulen = htons(ulen);
17683                                 th = (struct tcphdr *)(udp + 1);
17684                         } else
17685                                 th = (struct tcphdr *)(ip + 1);
17686                         tcpip_fillheaders(inp, tp->t_port, ip, th);
17687                 }
17688         }
17689         /*
17690          * Fill in fields, remembering maximum advertised window for use in
17691          * delaying messages about window sizes. If resending a FIN, be sure
17692          * not to use a new sequence number.
17693          */
17694         if (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&
17695             tp->snd_nxt == tp->snd_max)
17696                 tp->snd_nxt--;
17697         /*
17698          * If we are starting a connection, send ECN setup SYN packet. If we
17699          * are on a retransmit, we may resend those bits a number of times
17700          * as per RFC 3168.
17701          */
17702         if (tp->t_state == TCPS_SYN_SENT && V_tcp_do_ecn == 1) {
17703                 if (tp->t_rxtshift >= 1) {
17704                         if (tp->t_rxtshift <= V_tcp_ecn_maxretries)
17705                                 flags |= TH_ECE | TH_CWR;
17706                 } else
17707                         flags |= TH_ECE | TH_CWR;
17708         }
17709         /* Handle parallel SYN for ECN */
17710         if ((tp->t_state == TCPS_SYN_RECEIVED) &&
17711             (tp->t_flags2 & TF2_ECN_SND_ECE)) {
17712                 flags |= TH_ECE;
17713                 tp->t_flags2 &= ~TF2_ECN_SND_ECE;
17714         }
17715         if (TCPS_HAVEESTABLISHED(tp->t_state) &&
17716             (tp->t_flags2 & TF2_ECN_PERMIT)) {
17717                 /*
17718                  * If the peer has ECN, mark data packets with ECN capable
17719                  * transmission (ECT). Ignore pure ack packets,
17720                  * retransmissions.
17721                  */
17722                 if (len > 0 && SEQ_GEQ(tp->snd_nxt, tp->snd_max) &&
17723                     (sack_rxmit == 0)) {
17724 #ifdef INET6
17725                         if (isipv6)
17726                                 ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
17727                         else
17728 #endif
17729                                 ip->ip_tos |= IPTOS_ECN_ECT0;
17730                         KMOD_TCPSTAT_INC(tcps_ecn_ect0);
17731                         /*
17732                          * Reply with proper ECN notifications.
17733                          * Only set CWR on new data segments.
17734                          */
17735                         if (tp->t_flags2 & TF2_ECN_SND_CWR) {
17736                                 flags |= TH_CWR;
17737                                 tp->t_flags2 &= ~TF2_ECN_SND_CWR;
17738                         }
17739                 }
17740                 if (tp->t_flags2 & TF2_ECN_SND_ECE)
17741                         flags |= TH_ECE;
17742         }
17743         /*
17744          * If we are doing retransmissions, then snd_nxt will not reflect
17745          * the first unsent octet.  For ACK only packets, we do not want the
17746          * sequence number of the retransmitted packet, we want the sequence
17747          * number of the next unsent octet.  So, if there is no data (and no
17748          * SYN or FIN), use snd_max instead of snd_nxt when filling in
17749          * ti_seq.  But if we are in persist state, snd_max might reflect
17750          * one byte beyond the right edge of the window, so use snd_nxt in
17751          * that case, since we know we aren't doing a retransmission.
17752          * (retransmit and persist are mutually exclusive...)
17753          */
17754         if (sack_rxmit == 0) {
17755                 if (len || (flags & (TH_SYN | TH_FIN))) {
17756                         th->th_seq = htonl(tp->snd_nxt);
17757                         rack_seq = tp->snd_nxt;
17758                 } else {
17759                         th->th_seq = htonl(tp->snd_max);
17760                         rack_seq = tp->snd_max;
17761                 }
17762         } else {
17763                 th->th_seq = htonl(rsm->r_start);
17764                 rack_seq = rsm->r_start;
17765         }
17766         th->th_ack = htonl(tp->rcv_nxt);
17767         th->th_flags = flags;
17768         /*
17769          * Calculate receive window.  Don't shrink window, but avoid silly
17770          * window syndrome.
17771          * If a RST segment is sent, advertise a window of zero.
17772          */
17773         if (flags & TH_RST) {
17774                 recwin = 0;
17775         } else {
17776                 if (recwin < (long)(so->so_rcv.sb_hiwat / 4) &&
17777                     recwin < (long)segsiz) {
17778                         recwin = 0;
17779                 }
17780                 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
17781                     recwin < (long)(tp->rcv_adv - tp->rcv_nxt))
17782                         recwin = (long)(tp->rcv_adv - tp->rcv_nxt);
17783         }
17784
17785         /*
17786          * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
17787          * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
17788          * handled in syncache.
17789          */
17790         if (flags & TH_SYN)
17791                 th->th_win = htons((u_short)
17792                                    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
17793         else {
17794                 /* Avoid shrinking window with window scaling. */
17795                 recwin = roundup2(recwin, 1 << tp->rcv_scale);
17796                 th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
17797         }
17798         /*
17799          * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
17800          * window.  This may cause the remote transmitter to stall.  This
17801          * flag tells soreceive() to disable delayed acknowledgements when
17802          * draining the buffer.  This can occur if the receiver is
17803          * attempting to read more data than can be buffered prior to
17804          * transmitting on the connection.
17805          */
17806         if (th->th_win == 0) {
17807                 tp->t_sndzerowin++;
17808                 tp->t_flags |= TF_RXWIN0SENT;
17809         } else
17810                 tp->t_flags &= ~TF_RXWIN0SENT;
17811         tp->snd_up = tp->snd_una;       /* drag it along, its deprecated */
17812         /* Now are we using fsb?, if so copy the template data to the mbuf */
17813         if ((ipoptlen == 0) && (rack->r_ctl.fsb.tcp_ip_hdr) && rack->r_fsb_inited) {
17814                 uint8_t *cpto;
17815
17816                 cpto = mtod(m, uint8_t *);
17817                 memcpy(cpto, rack->r_ctl.fsb.tcp_ip_hdr, rack->r_ctl.fsb.tcp_ip_hdr_len);
17818                 /*
17819                  * We have just copied in:
17820                  * IP/IP6
17821                  * <optional udphdr>
17822                  * tcphdr (no options)
17823                  *
17824                  * We need to grab the correct pointers into the mbuf
17825                  * for both the tcp header, and possibly the udp header (if tunneling).
17826                  * We do this by using the offset in the copy buffer and adding it
17827                  * to the mbuf base pointer (cpto).
17828                  */
17829 #ifdef INET6
17830                 if (isipv6)
17831                         ip6 = mtod(m, struct ip6_hdr *);
17832                 else
17833 #endif                          /* INET6 */
17834                         ip = mtod(m, struct ip *);
17835                 th = (struct tcphdr *)(cpto + ((uint8_t *)rack->r_ctl.fsb.th - rack->r_ctl.fsb.tcp_ip_hdr));
17836                 /* If we have a udp header lets set it into the mbuf as well */
17837                 if (udp)
17838                         udp = (struct udphdr *)(cpto + ((uint8_t *)rack->r_ctl.fsb.udp - rack->r_ctl.fsb.tcp_ip_hdr));
17839         }
17840 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
17841         if (to.to_flags & TOF_SIGNATURE) {
17842                 /*
17843                  * Calculate MD5 signature and put it into the place
17844                  * determined before.
17845                  * NOTE: since TCP options buffer doesn't point into
17846                  * mbuf's data, calculate offset and use it.
17847                  */
17848                 if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
17849                                                        (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
17850                         /*
17851                          * Do not send segment if the calculation of MD5
17852                          * digest has failed.
17853                          */
17854                         goto out;
17855                 }
17856         }
17857 #endif
17858         if (optlen) {
17859                 bcopy(opt, th + 1, optlen);
17860                 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
17861         }
17862         /*
17863          * Put TCP length in extended header, and then checksum extended
17864          * header and data.
17865          */
17866         m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
17867 #ifdef INET6
17868         if (isipv6) {
17869                 /*
17870                  * ip6_plen is not need to be filled now, and will be filled
17871                  * in ip6_output.
17872                  */
17873                 if (tp->t_port) {
17874                         m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
17875                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
17876                         udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
17877                         th->th_sum = htons(0);
17878                         UDPSTAT_INC(udps_opackets);
17879                 } else {
17880                         m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
17881                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
17882                         th->th_sum = in6_cksum_pseudo(ip6,
17883                                                       sizeof(struct tcphdr) + optlen + len, IPPROTO_TCP,
17884                                                       0);
17885                 }
17886         }
17887 #endif
17888 #if defined(INET6) && defined(INET)
17889         else
17890 #endif
17891 #ifdef INET
17892         {
17893                 if (tp->t_port) {
17894                         m->m_pkthdr.csum_flags = CSUM_UDP;
17895                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
17896                         udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
17897                                                 ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
17898                         th->th_sum = htons(0);
17899                         UDPSTAT_INC(udps_opackets);
17900                 } else {
17901                         m->m_pkthdr.csum_flags = CSUM_TCP;
17902                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
17903                         th->th_sum = in_pseudo(ip->ip_src.s_addr,
17904                                                ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
17905                                                                         IPPROTO_TCP + len + optlen));
17906                 }
17907                 /* IP version must be set here for ipv4/ipv6 checking later */
17908                 KASSERT(ip->ip_v == IPVERSION,
17909                         ("%s: IP version incorrect: %d", __func__, ip->ip_v));
17910         }
17911 #endif
17912         /*
17913          * Enable TSO and specify the size of the segments. The TCP pseudo
17914          * header checksum is always provided. XXX: Fixme: This is currently
17915          * not the case for IPv6.
17916          */
17917         if (tso) {
17918                 KASSERT(len > tp->t_maxseg - optlen,
17919                         ("%s: len <= tso_segsz", __func__));
17920                 m->m_pkthdr.csum_flags |= CSUM_TSO;
17921                 m->m_pkthdr.tso_segsz = tp->t_maxseg - optlen;
17922         }
17923         KASSERT(len + hdrlen == m_length(m, NULL),
17924                 ("%s: mbuf chain different than expected: %d + %u != %u",
17925                  __func__, len, hdrlen, m_length(m, NULL)));
17926
17927 #ifdef TCP_HHOOK
17928         /* Run HHOOK_TCP_ESTABLISHED_OUT helper hooks. */
17929         hhook_run_tcp_est_out(tp, th, &to, len, tso);
17930 #endif
17931         /* We're getting ready to send; log now. */
17932         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
17933                 union tcp_log_stackspecific log;
17934
17935                 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
17936                 log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
17937                 log.u_bbr.ininput = rack->rc_inp->inp_in_input;
17938                 if (rack->rack_no_prr)
17939                         log.u_bbr.flex1 = 0;
17940                 else
17941                         log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
17942                 log.u_bbr.flex2 = rack->r_ctl.rc_pace_min_segs;
17943                 log.u_bbr.flex3 = rack->r_ctl.rc_pace_max_segs;
17944                 log.u_bbr.flex4 = orig_len;
17945                 if (filled_all)
17946                         log.u_bbr.flex5 = 0x80000000;
17947                 else
17948                         log.u_bbr.flex5 = 0;
17949                 /* Save off the early/late values */
17950                 log.u_bbr.flex6 = rack->r_ctl.rc_agg_early;
17951                 log.u_bbr.applimited = rack->r_ctl.rc_agg_delayed;
17952                 log.u_bbr.bw_inuse = rack_get_bw(rack);
17953                 if (rsm || sack_rxmit) {
17954                         if (doing_tlp)
17955                                 log.u_bbr.flex8 = 2;
17956                         else
17957                                 log.u_bbr.flex8 = 1;
17958                 } else {
17959                         log.u_bbr.flex8 = 0;
17960                 }
17961                 log.u_bbr.pacing_gain = rack_get_output_gain(rack, rsm);
17962                 log.u_bbr.flex7 = mark;
17963                 log.u_bbr.flex7 <<= 8;
17964                 log.u_bbr.flex7 |= pass;
17965                 log.u_bbr.pkts_out = tp->t_maxseg;
17966                 log.u_bbr.timeStamp = cts;
17967                 log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
17968                 log.u_bbr.lt_epoch = cwnd_to_use;
17969                 log.u_bbr.delivered = sendalot;
17970                 lgb = tcp_log_event_(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
17971                                      len, &log, false, NULL, NULL, 0, &tv);
17972         } else
17973                 lgb = NULL;
17974
17975         /*
17976          * Fill in IP length and desired time to live and send to IP level.
17977          * There should be a better way to handle ttl and tos; we could keep
17978          * them in the template, but need a way to checksum without them.
17979          */
17980         /*
17981          * m->m_pkthdr.len should have been set before cksum calcuration,
17982          * because in6_cksum() need it.
17983          */
17984 #ifdef INET6
17985         if (isipv6) {
17986                 /*
17987                  * we separately set hoplimit for every segment, since the
17988                  * user might want to change the value via setsockopt. Also,
17989                  * desired default hop limit might be changed via Neighbor
17990                  * Discovery.
17991                  */
17992                 rack->r_ctl.fsb.hoplimit = ip6->ip6_hlim = in6_selecthlim(inp, NULL);
17993
17994                 /*
17995                  * Set the packet size here for the benefit of DTrace
17996                  * probes. ip6_output() will set it properly; it's supposed
17997                  * to include the option header lengths as well.
17998                  */
17999                 ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
18000
18001                 if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss)
18002                         tp->t_flags2 |= TF2_PLPMTU_PMTUD;
18003                 else
18004                         tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
18005
18006                 if (tp->t_state == TCPS_SYN_SENT)
18007                         TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
18008
18009                 TCP_PROBE5(send, NULL, tp, ip6, tp, th);
18010                 /* TODO: IPv6 IP6TOS_ECT bit on */
18011                 error = ip6_output(m,
18012 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
18013                                    inp->in6p_outputopts,
18014 #else
18015                                    NULL,
18016 #endif
18017                                    &inp->inp_route6,
18018                                    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
18019                                    NULL, NULL, inp);
18020
18021                 if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
18022                         mtu = inp->inp_route6.ro_nh->nh_mtu;
18023         }
18024 #endif                          /* INET6 */
18025 #if defined(INET) && defined(INET6)
18026         else
18027 #endif
18028 #ifdef INET
18029         {
18030                 ip->ip_len = htons(m->m_pkthdr.len);
18031 #ifdef INET6
18032                 if (inp->inp_vflag & INP_IPV6PROTO)
18033                         ip->ip_ttl = in6_selecthlim(inp, NULL);
18034 #endif                          /* INET6 */
18035                 rack->r_ctl.fsb.hoplimit = ip->ip_ttl;
18036                 /*
18037                  * If we do path MTU discovery, then we set DF on every
18038                  * packet. This might not be the best thing to do according
18039                  * to RFC3390 Section 2. However the tcp hostcache migitates
18040                  * the problem so it affects only the first tcp connection
18041                  * with a host.
18042                  *
18043                  * NB: Don't set DF on small MTU/MSS to have a safe
18044                  * fallback.
18045                  */
18046                 if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
18047                         tp->t_flags2 |= TF2_PLPMTU_PMTUD;
18048                         if (tp->t_port == 0 || len < V_tcp_minmss) {
18049                                 ip->ip_off |= htons(IP_DF);
18050                         }
18051                 } else {
18052                         tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
18053                 }
18054
18055                 if (tp->t_state == TCPS_SYN_SENT)
18056                         TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
18057
18058                 TCP_PROBE5(send, NULL, tp, ip, tp, th);
18059
18060                 error = ip_output(m,
18061 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
18062                                   inp->inp_options,
18063 #else
18064                                   NULL,
18065 #endif
18066                                   &inp->inp_route,
18067                                   ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
18068                                   inp);
18069                 if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
18070                         mtu = inp->inp_route.ro_nh->nh_mtu;
18071         }
18072 #endif                          /* INET */
18073
18074 out:
18075         if (lgb) {
18076                 lgb->tlb_errno = error;
18077                 lgb = NULL;
18078         }
18079         /*
18080          * In transmit state, time the transmission and arrange for the
18081          * retransmit.  In persist state, just set snd_max.
18082          */
18083         if (error == 0) {
18084                 rack->forced_ack = 0;   /* If we send something zap the FA flag */
18085                 if (rsm && (doing_tlp == 0)) {
18086                         /* Set we retransmitted */
18087                         rack->rc_gp_saw_rec = 1;
18088                 } else {
18089                         if (cwnd_to_use > tp->snd_ssthresh) {
18090                                 /* Set we sent in CA */
18091                                 rack->rc_gp_saw_ca = 1;
18092                         } else {
18093                                 /* Set we sent in SS */
18094                                 rack->rc_gp_saw_ss = 1;
18095                         }
18096                 }
18097                 if (TCPS_HAVEESTABLISHED(tp->t_state) &&
18098                     (tp->t_flags & TF_SACK_PERMIT) &&
18099                     tp->rcv_numsacks > 0)
18100                         tcp_clean_dsack_blocks(tp);
18101                 tot_len_this_send += len;
18102                 if (len == 0)
18103                         counter_u64_add(rack_out_size[TCP_MSS_ACCT_SNDACK], 1);
18104                 else if (len == 1) {
18105                         counter_u64_add(rack_out_size[TCP_MSS_ACCT_PERSIST], 1);
18106                 } else if (len > 1) {
18107                         int idx;
18108
18109                         idx = (len / segsiz) + 3;
18110                         if (idx >= TCP_MSS_ACCT_ATIMER)
18111                                 counter_u64_add(rack_out_size[(TCP_MSS_ACCT_ATIMER-1)], 1);
18112                         else
18113                                 counter_u64_add(rack_out_size[idx], 1);
18114                 }
18115         }
18116         if ((rack->rack_no_prr == 0) &&
18117             sub_from_prr &&
18118             (error == 0)) {
18119                 if (rack->r_ctl.rc_prr_sndcnt >= len)
18120                         rack->r_ctl.rc_prr_sndcnt -= len;
18121                 else
18122                         rack->r_ctl.rc_prr_sndcnt = 0;
18123         }
18124         sub_from_prr = 0;
18125         if (doing_tlp && (rsm == NULL)) {
18126                 /* New send doing a TLP */
18127                 add_flag |= RACK_TLP;
18128                 tp->t_sndtlppack++;
18129                 tp->t_sndtlpbyte += len;
18130         }
18131         rack_log_output(tp, &to, len, rack_seq, (uint8_t) flags, error,
18132                         rack_to_usec_ts(&tv),
18133                         rsm, add_flag, s_mb, s_moff);
18134
18135
18136         if ((error == 0) &&
18137             (len > 0) &&
18138             (tp->snd_una == tp->snd_max))
18139                 rack->r_ctl.rc_tlp_rxt_last_time = cts;
18140         {
18141                 tcp_seq startseq = tp->snd_nxt;
18142
18143                 /* Track our lost count */
18144                 if (rsm && (doing_tlp == 0))
18145                         rack->r_ctl.rc_loss_count += rsm->r_end - rsm->r_start;
18146                 /*
18147                  * Advance snd_nxt over sequence space of this segment.
18148                  */
18149                 if (error)
18150                         /* We don't log or do anything with errors */
18151                         goto nomore;
18152                 if (doing_tlp == 0) {
18153                         if (rsm == NULL) {
18154                                 /*
18155                                  * Not a retransmission of some
18156                                  * sort, new data is going out so
18157                                  * clear our TLP count and flag.
18158                                  */
18159                                 rack->rc_tlp_in_progress = 0;
18160                                 rack->r_ctl.rc_tlp_cnt_out = 0;
18161                         }
18162                 } else {
18163                         /*
18164                          * We have just sent a TLP, mark that it is true
18165                          * and make sure our in progress is set so we
18166                          * continue to check the count.
18167                          */
18168                         rack->rc_tlp_in_progress = 1;
18169                         rack->r_ctl.rc_tlp_cnt_out++;
18170                 }
18171                 if (flags & (TH_SYN | TH_FIN)) {
18172                         if (flags & TH_SYN)
18173                                 tp->snd_nxt++;
18174                         if (flags & TH_FIN) {
18175                                 tp->snd_nxt++;
18176                                 tp->t_flags |= TF_SENTFIN;
18177                         }
18178                 }
18179                 /* In the ENOBUFS case we do *not* update snd_max */
18180                 if (sack_rxmit)
18181                         goto nomore;
18182
18183                 tp->snd_nxt += len;
18184                 if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
18185                         if (tp->snd_una == tp->snd_max) {
18186                                 /*
18187                                  * Update the time we just added data since
18188                                  * none was outstanding.
18189                                  */
18190                                 rack_log_progress_event(rack, tp, ticks, PROGRESS_START, __LINE__);
18191                                 tp->t_acktime = ticks;
18192                         }
18193                         tp->snd_max = tp->snd_nxt;
18194                         /*
18195                          * Time this transmission if not a retransmission and
18196                          * not currently timing anything.
18197                          * This is only relevant in case of switching back to
18198                          * the base stack.
18199                          */
18200                         if (tp->t_rtttime == 0) {
18201                                 tp->t_rtttime = ticks;
18202                                 tp->t_rtseq = startseq;
18203                                 KMOD_TCPSTAT_INC(tcps_segstimed);
18204                         }
18205                         if (len &&
18206                             ((tp->t_flags & TF_GPUTINPROG) == 0))
18207                                 rack_start_gp_measurement(tp, rack, startseq, sb_offset);
18208                 }
18209                 /*
18210                  * If we are doing FO we need to update the mbuf position and subtract
18211                  * this happens when the peer sends us duplicate information and
18212                  * we thus want to send a DSACK.
18213                  *
18214                  * XXXRRS: This brings to mind a ?, when we send a DSACK block is TSO
18215                  * turned off? If not then we are going to echo multiple DSACK blocks
18216                  * out (with the TSO), which we should not be doing.
18217                  */
18218                 if (rack->r_fast_output && len) {
18219                         if (rack->r_ctl.fsb.left_to_send > len)
18220                                 rack->r_ctl.fsb.left_to_send -= len;
18221                         else
18222                                 rack->r_ctl.fsb.left_to_send = 0;
18223                         if (rack->r_ctl.fsb.left_to_send < segsiz)
18224                                 rack->r_fast_output = 0;
18225                         if (rack->r_fast_output) {
18226                                 rack->r_ctl.fsb.m = sbsndmbuf(sb, (tp->snd_max - tp->snd_una), &rack->r_ctl.fsb.off);
18227                                 rack->r_ctl.fsb.o_m_len = rack->r_ctl.fsb.m->m_len;
18228                         }
18229                 }
18230         }
18231 nomore:
18232         if (error) {
18233                 rack->r_ctl.rc_agg_delayed = 0;
18234                 rack->r_early = 0;
18235                 rack->r_late = 0;
18236                 rack->r_ctl.rc_agg_early = 0;
18237                 SOCKBUF_UNLOCK_ASSERT(sb);      /* Check gotos. */
18238                 /*
18239                  * Failures do not advance the seq counter above. For the
18240                  * case of ENOBUFS we will fall out and retry in 1ms with
18241                  * the hpts. Everything else will just have to retransmit
18242                  * with the timer.
18243                  *
18244                  * In any case, we do not want to loop around for another
18245                  * send without a good reason.
18246                  */
18247                 sendalot = 0;
18248                 switch (error) {
18249                 case EPERM:
18250                         tp->t_softerror = error;
18251 #ifdef TCP_ACCOUNTING
18252                         crtsc = get_cyclecount();
18253                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18254                                 tp->tcp_cnt_counters[SND_OUT_FAIL]++;
18255                         }
18256                         counter_u64_add(tcp_cnt_counters[SND_OUT_FAIL], 1);
18257                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18258                                 tp->tcp_proc_time[SND_OUT_FAIL] += (crtsc - ts_val);
18259                         }
18260                         counter_u64_add(tcp_proc_time[SND_OUT_FAIL], (crtsc - ts_val));
18261                         sched_unpin();
18262 #endif
18263                         return (error);
18264                 case ENOBUFS:
18265                         /*
18266                          * Pace us right away to retry in a some
18267                          * time
18268                          */
18269                         slot = ((1 + rack->rc_enobuf) * HPTS_USEC_IN_MSEC);
18270                         if (rack->rc_enobuf < 0x7f)
18271                                 rack->rc_enobuf++;
18272                         if (slot < (10 * HPTS_USEC_IN_MSEC))
18273                                 slot = 10 * HPTS_USEC_IN_MSEC;
18274                         if (rack->r_ctl.crte != NULL) {
18275                                 counter_u64_add(rack_saw_enobuf_hw, 1);
18276                                 tcp_rl_log_enobuf(rack->r_ctl.crte);
18277                         }
18278                         counter_u64_add(rack_saw_enobuf, 1);
18279                         goto enobufs;
18280                 case EMSGSIZE:
18281                         /*
18282                          * For some reason the interface we used initially
18283                          * to send segments changed to another or lowered
18284                          * its MTU. If TSO was active we either got an
18285                          * interface without TSO capabilits or TSO was
18286                          * turned off. If we obtained mtu from ip_output()
18287                          * then update it and try again.
18288                          */
18289                         if (tso)
18290                                 tp->t_flags &= ~TF_TSO;
18291                         if (mtu != 0) {
18292                                 tcp_mss_update(tp, -1, mtu, NULL, NULL);
18293                                 goto again;
18294                         }
18295                         slot = 10 * HPTS_USEC_IN_MSEC;
18296                         rack_start_hpts_timer(rack, tp, cts, slot, 0, 0);
18297 #ifdef TCP_ACCOUNTING
18298                         crtsc = get_cyclecount();
18299                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18300                                 tp->tcp_cnt_counters[SND_OUT_FAIL]++;
18301                         }
18302                         counter_u64_add(tcp_cnt_counters[SND_OUT_FAIL], 1);
18303                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18304                                 tp->tcp_proc_time[SND_OUT_FAIL] += (crtsc - ts_val);
18305                         }
18306                         counter_u64_add(tcp_proc_time[SND_OUT_FAIL], (crtsc - ts_val));
18307                         sched_unpin();
18308 #endif
18309                         return (error);
18310                 case ENETUNREACH:
18311                         counter_u64_add(rack_saw_enetunreach, 1);
18312                 case EHOSTDOWN:
18313                 case EHOSTUNREACH:
18314                 case ENETDOWN:
18315                         if (TCPS_HAVERCVDSYN(tp->t_state)) {
18316                                 tp->t_softerror = error;
18317                         }
18318                         /* FALLTHROUGH */
18319                 default:
18320                         slot = 10 * HPTS_USEC_IN_MSEC;
18321                         rack_start_hpts_timer(rack, tp, cts, slot, 0, 0);
18322 #ifdef TCP_ACCOUNTING
18323                         crtsc = get_cyclecount();
18324                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18325                                 tp->tcp_cnt_counters[SND_OUT_FAIL]++;
18326                         }
18327                         counter_u64_add(tcp_cnt_counters[SND_OUT_FAIL], 1);
18328                         if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18329                                 tp->tcp_proc_time[SND_OUT_FAIL] += (crtsc - ts_val);
18330                         }
18331                         counter_u64_add(tcp_proc_time[SND_OUT_FAIL], (crtsc - ts_val));
18332                         sched_unpin();
18333 #endif
18334                         return (error);
18335                 }
18336         } else {
18337                 rack->rc_enobuf = 0;
18338                 if (IN_FASTRECOVERY(tp->t_flags) && rsm)
18339                         rack->r_ctl.retran_during_recovery += len;
18340         }
18341         KMOD_TCPSTAT_INC(tcps_sndtotal);
18342
18343         /*
18344          * Data sent (as far as we can tell). If this advertises a larger
18345          * window than any other segment, then remember the size of the
18346          * advertised window. Any pending ACK has now been sent.
18347          */
18348         if (recwin > 0 && SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
18349                 tp->rcv_adv = tp->rcv_nxt + recwin;
18350
18351         tp->last_ack_sent = tp->rcv_nxt;
18352         tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
18353 enobufs:
18354         if (sendalot) {
18355                 /* Do we need to turn off sendalot? */
18356                 if (rack->r_ctl.rc_pace_max_segs &&
18357                     (tot_len_this_send >= rack->r_ctl.rc_pace_max_segs)) {
18358                         /* We hit our max. */
18359                         sendalot = 0;
18360                 } else if ((rack->rc_user_set_max_segs) &&
18361                            (tot_len_this_send >= (rack->rc_user_set_max_segs * segsiz))) {
18362                         /* We hit the user defined max */
18363                         sendalot = 0;
18364                 }
18365         }
18366         if ((error == 0) && (flags & TH_FIN))
18367                 tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
18368         if (flags & TH_RST) {
18369                 /*
18370                  * We don't send again after sending a RST.
18371                  */
18372                 slot = 0;
18373                 sendalot = 0;
18374                 if (error == 0)
18375                         tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
18376         } else if ((slot == 0) && (sendalot == 0) && tot_len_this_send) {
18377                 /*
18378                  * Get our pacing rate, if an error
18379                  * occurred in sending (ENOBUF) we would
18380                  * hit the else if with slot preset. Other
18381                  * errors return.
18382                  */
18383                 slot = rack_get_pacing_delay(rack, tp, tot_len_this_send, rsm, segsiz);
18384         }
18385         if (rsm &&
18386             (rsm->r_flags & RACK_HAS_SYN) == 0 &&
18387             rack->use_rack_rr) {
18388                 /* Its a retransmit and we use the rack cheat? */
18389                 if ((slot == 0) ||
18390                     (rack->rc_always_pace == 0) ||
18391                     (rack->r_rr_config == 1)) {
18392                         /*
18393                          * We have no pacing set or we
18394                          * are using old-style rack or
18395                          * we are overriden to use the old 1ms pacing.
18396                          */
18397                         slot = rack->r_ctl.rc_min_to;
18398                 }
18399         }
18400         /* We have sent clear the flag */
18401         rack->r_ent_rec_ns = 0;
18402         if (rack->r_must_retran) {
18403                 if (rsm) {
18404                         rack->r_ctl.rc_out_at_rto -= (rsm->r_end - rsm->r_start);
18405                         if (SEQ_GEQ(rsm->r_end, rack->r_ctl.rc_snd_max_at_rto)) {
18406                                 /*
18407                                  * We have retransmitted all.
18408                                  */
18409                                 rack->r_must_retran = 0;
18410                                 rack->r_ctl.rc_out_at_rto = 0;
18411                         }
18412                 } else if (SEQ_GEQ(tp->snd_max, rack->r_ctl.rc_snd_max_at_rto)) {
18413                         /*
18414                          * Sending new data will also kill
18415                          * the loop.
18416                          */
18417                         rack->r_must_retran = 0;
18418                         rack->r_ctl.rc_out_at_rto = 0;
18419                 }
18420         }
18421         rack->r_ctl.fsb.recwin = recwin;
18422         if ((tp->t_flags & (TF_WASCRECOVERY|TF_WASFRECOVERY)) &&
18423             SEQ_GT(tp->snd_max, rack->r_ctl.rc_snd_max_at_rto)) {
18424                 /*
18425                  * We hit an RTO and now have past snd_max at the RTO
18426                  * clear all the WAS flags.
18427                  */
18428                 tp->t_flags &= ~(TF_WASCRECOVERY|TF_WASFRECOVERY);
18429         }
18430         if (slot) {
18431                 /* set the rack tcb into the slot N */
18432                 counter_u64_add(rack_paced_segments, 1);
18433                 if ((error == 0) &&
18434                     rack_use_rfo &&
18435                     ((flags & (TH_SYN|TH_FIN)) == 0) &&
18436                     (rsm == NULL) &&
18437                     (tp->snd_nxt == tp->snd_max) &&
18438                     (ipoptlen == 0) &&
18439                     (tp->rcv_numsacks == 0) &&
18440                     rack->r_fsb_inited &&
18441                     TCPS_HAVEESTABLISHED(tp->t_state) &&
18442                     (rack->r_must_retran == 0) &&
18443                     ((tp->t_flags & TF_NEEDFIN) == 0) &&
18444                     (len > 0) && (orig_len > 0) &&
18445                     (orig_len > len) &&
18446                     ((orig_len - len) >= segsiz) &&
18447                     ((optlen == 0) ||
18448                      ((optlen == TCPOLEN_TSTAMP_APPA) && (to.to_flags & TOF_TS)))) {
18449                         /* We can send at least one more MSS using our fsb */
18450
18451                         rack->r_fast_output = 1;
18452                         rack->r_ctl.fsb.m = sbsndmbuf(sb, (tp->snd_max - tp->snd_una), &rack->r_ctl.fsb.off);
18453                         rack->r_ctl.fsb.o_m_len = rack->r_ctl.fsb.m->m_len;
18454                         rack->r_ctl.fsb.tcp_flags = flags;
18455                         rack->r_ctl.fsb.left_to_send = orig_len - len;
18456                         KASSERT((rack->r_ctl.fsb.left_to_send <= (sbavail(sb) - (tp->snd_max - tp->snd_una))),
18457                                 ("rack:%p left_to_send:%u sbavail:%u out:%u",
18458                                  rack, rack->r_ctl.fsb.left_to_send, sbavail(sb),
18459                                  (tp->snd_max - tp->snd_una)));
18460                         if (rack->r_ctl.fsb.left_to_send < segsiz)
18461                                 rack->r_fast_output = 0;
18462                         else {
18463                                 if (rack->r_ctl.fsb.left_to_send == (sbavail(sb) - (tp->snd_max - tp->snd_una)))
18464                                         rack->r_ctl.fsb.rfo_apply_push = 1;
18465                                 else
18466                                         rack->r_ctl.fsb.rfo_apply_push = 0;
18467                         }
18468                 } else
18469                         rack->r_fast_output = 0;
18470                 rack_log_fsb(rack, tp, so, flags,
18471                              ipoptlen, orig_len, len, error,
18472                              (rsm == NULL), optlen, __LINE__, 2);
18473         } else if (sendalot) {
18474                 int ret;
18475
18476                 if (len)
18477                         counter_u64_add(rack_unpaced_segments, 1);
18478                 sack_rxmit = 0;
18479                 if ((error == 0) &&
18480                     rack_use_rfo &&
18481                     ((flags & (TH_SYN|TH_FIN)) == 0) &&
18482                     (rsm == NULL) &&
18483                     (ipoptlen == 0) &&
18484                     (tp->rcv_numsacks == 0) &&
18485                     (tp->snd_nxt == tp->snd_max) &&
18486                     (rack->r_must_retran == 0) &&
18487                     rack->r_fsb_inited &&
18488                     TCPS_HAVEESTABLISHED(tp->t_state) &&
18489                     ((tp->t_flags & TF_NEEDFIN) == 0) &&
18490                     (len > 0) && (orig_len > 0) &&
18491                     (orig_len > len) &&
18492                     ((orig_len - len) >= segsiz) &&
18493                     ((optlen == 0) ||
18494                      ((optlen == TCPOLEN_TSTAMP_APPA) && (to.to_flags & TOF_TS)))) {
18495                         /* we can use fast_output for more */
18496
18497                         rack->r_fast_output = 1;
18498                         rack->r_ctl.fsb.m = sbsndmbuf(sb, (tp->snd_max - tp->snd_una), &rack->r_ctl.fsb.off);
18499                         rack->r_ctl.fsb.o_m_len = rack->r_ctl.fsb.m->m_len;
18500                         rack->r_ctl.fsb.tcp_flags = flags;
18501                         rack->r_ctl.fsb.left_to_send = orig_len - len;
18502                         KASSERT((rack->r_ctl.fsb.left_to_send <= (sbavail(sb) - (tp->snd_max - tp->snd_una))),
18503                                 ("rack:%p left_to_send:%u sbavail:%u out:%u",
18504                                  rack, rack->r_ctl.fsb.left_to_send, sbavail(sb),
18505                                  (tp->snd_max - tp->snd_una)));
18506                         if (rack->r_ctl.fsb.left_to_send < segsiz) {
18507                                 rack->r_fast_output = 0;
18508                         }
18509                         if (rack->r_fast_output) {
18510                                 if (rack->r_ctl.fsb.left_to_send == (sbavail(sb) - (tp->snd_max - tp->snd_una)))
18511                                         rack->r_ctl.fsb.rfo_apply_push = 1;
18512                                 else
18513                                         rack->r_ctl.fsb.rfo_apply_push = 0;
18514                                 rack_log_fsb(rack, tp, so, flags,
18515                                              ipoptlen, orig_len, len, error,
18516                                              (rsm == NULL), optlen, __LINE__, 3);
18517                                 error = 0;
18518                                 ret = rack_fast_output(tp, rack, ts_val, cts, ms_cts, &tv, tot_len_this_send, &error);
18519                                 if (ret >= 0)
18520                                         return (ret);
18521                                 else if (error)
18522                                         goto nomore;
18523
18524                         }
18525                 }
18526                 goto again;
18527         } else if (len) {
18528                 counter_u64_add(rack_unpaced_segments, 1);
18529         }
18530         /* Assure when we leave that snd_nxt will point to top */
18531         if (SEQ_GT(tp->snd_max, tp->snd_nxt))
18532                 tp->snd_nxt = tp->snd_max;
18533         rack_start_hpts_timer(rack, tp, cts, slot, tot_len_this_send, 0);
18534 #ifdef TCP_ACCOUNTING
18535         crtsc = get_cyclecount() - ts_val;
18536         if (tot_len_this_send) {
18537                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18538                         tp->tcp_cnt_counters[SND_OUT_DATA]++;
18539                 }
18540                 counter_u64_add(tcp_cnt_counters[SND_OUT_DATA], 1);
18541                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18542                         tp->tcp_proc_time[SND_OUT_DATA] += crtsc;
18543                 }
18544                 counter_u64_add(tcp_proc_time[SND_OUT_DATA], crtsc);
18545                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18546                         tp->tcp_cnt_counters[CNT_OF_MSS_OUT] += ((tot_len_this_send + segsiz - 1) /segsiz);
18547                 }
18548                 counter_u64_add(tcp_cnt_counters[CNT_OF_MSS_OUT], ((tot_len_this_send + segsiz - 1) /segsiz));
18549         } else {
18550                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18551                         tp->tcp_cnt_counters[SND_OUT_ACK]++;
18552                 }
18553                 counter_u64_add(tcp_cnt_counters[SND_OUT_ACK], 1);
18554                 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18555                         tp->tcp_proc_time[SND_OUT_ACK] += crtsc;
18556                 }
18557                 counter_u64_add(tcp_proc_time[SND_OUT_ACK], crtsc);
18558         }
18559         sched_unpin();
18560 #endif
18561         if (error == ENOBUFS)
18562                 error = 0;
18563         return (error);
18564 }
18565
18566 static void
18567 rack_update_seg(struct tcp_rack *rack)
18568 {
18569         uint32_t orig_val;
18570
18571         orig_val = rack->r_ctl.rc_pace_max_segs;
18572         rack_set_pace_segments(rack->rc_tp, rack, __LINE__, NULL);
18573         if (orig_val != rack->r_ctl.rc_pace_max_segs)
18574                 rack_log_pacing_delay_calc(rack, 0, 0, orig_val, 0, 0, 15, __LINE__, NULL);
18575 }
18576
18577 static void
18578 rack_mtu_change(struct tcpcb *tp)
18579 {
18580         /*
18581          * The MSS may have changed
18582          */
18583         struct tcp_rack *rack;
18584
18585         rack = (struct tcp_rack *)tp->t_fb_ptr;
18586         if (rack->r_ctl.rc_pace_min_segs != ctf_fixed_maxseg(tp)) {
18587                 /*
18588                  * The MTU has changed we need to resend everything
18589                  * since all we have sent is lost. We first fix
18590                  * up the mtu though.
18591                  */
18592                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
18593                 /* We treat this like a full retransmit timeout without the cwnd adjustment */
18594                 rack_remxt_tmr(tp);
18595                 rack->r_fast_output = 0;
18596                 rack->r_ctl.rc_out_at_rto = ctf_flight_size(tp,
18597                                                 rack->r_ctl.rc_sacked);
18598                 rack->r_ctl.rc_snd_max_at_rto = tp->snd_max;
18599                 rack->r_must_retran = 1;
18600
18601         }
18602         sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
18603         /* We don't use snd_nxt to retransmit */
18604         tp->snd_nxt = tp->snd_max;
18605 }
18606
18607 static int
18608 rack_set_profile(struct tcp_rack *rack, int prof)
18609 {
18610         int err = EINVAL;
18611         if (prof == 1) {
18612                 /* pace_always=1 */
18613                 if (rack->rc_always_pace == 0) {
18614                         if (tcp_can_enable_pacing() == 0)
18615                                 return (EBUSY);
18616                 }
18617                 rack->rc_always_pace = 1;
18618                 if (rack->use_fixed_rate || rack->gp_ready)
18619                         rack_set_cc_pacing(rack);
18620                 rack->rc_inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
18621                 rack->rack_attempt_hdwr_pace = 0;
18622                 /* cmpack=1 */
18623                 if (rack_use_cmp_acks)
18624                         rack->r_use_cmp_ack = 1;
18625                 if (TCPS_HAVEESTABLISHED(rack->rc_tp->t_state) &&
18626                     rack->r_use_cmp_ack)
18627                         rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
18628                 /* scwnd=1 */
18629                 rack->rack_enable_scwnd = 1;
18630                 /* dynamic=100 */
18631                 rack->rc_gp_dyn_mul = 1;
18632                 /* gp_inc_ca */
18633                 rack->r_ctl.rack_per_of_gp_ca = 100;
18634                 /* rrr_conf=3 */
18635                 rack->r_rr_config = 3;
18636                 /* npush=2 */
18637                 rack->r_ctl.rc_no_push_at_mrtt = 2;
18638                 /* fillcw=1 */
18639                 rack->rc_pace_to_cwnd = 1;
18640                 rack->rc_pace_fill_if_rttin_range = 0;
18641                 rack->rtt_limit_mul = 0;
18642                 /* noprr=1 */
18643                 rack->rack_no_prr = 1;
18644                 /* lscwnd=1 */
18645                 rack->r_limit_scw = 1;
18646                 /* gp_inc_rec */
18647                 rack->r_ctl.rack_per_of_gp_rec = 90;
18648                 err = 0;
18649
18650         } else if (prof == 3) {
18651                 /* Same as profile one execept fill_cw becomes 2 (less aggressive set) */
18652                 /* pace_always=1 */
18653                 if (rack->rc_always_pace == 0) {
18654                         if (tcp_can_enable_pacing() == 0)
18655                                 return (EBUSY);
18656                 }
18657                 rack->rc_always_pace = 1;
18658                 if (rack->use_fixed_rate || rack->gp_ready)
18659                         rack_set_cc_pacing(rack);
18660                 rack->rc_inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
18661                 rack->rack_attempt_hdwr_pace = 0;
18662                 /* cmpack=1 */
18663                 if (rack_use_cmp_acks)
18664                         rack->r_use_cmp_ack = 1;
18665                 if (TCPS_HAVEESTABLISHED(rack->rc_tp->t_state) &&
18666                     rack->r_use_cmp_ack)
18667                         rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
18668                 /* scwnd=1 */
18669                 rack->rack_enable_scwnd = 1;
18670                 /* dynamic=100 */
18671                 rack->rc_gp_dyn_mul = 1;
18672                 /* gp_inc_ca */
18673                 rack->r_ctl.rack_per_of_gp_ca = 100;
18674                 /* rrr_conf=3 */
18675                 rack->r_rr_config = 3;
18676                 /* npush=2 */
18677                 rack->r_ctl.rc_no_push_at_mrtt = 2;
18678                 /* fillcw=2 */
18679                 rack->rc_pace_to_cwnd = 1;
18680                 rack->r_fill_less_agg = 1;
18681                 rack->rc_pace_fill_if_rttin_range = 0;
18682                 rack->rtt_limit_mul = 0;
18683                 /* noprr=1 */
18684                 rack->rack_no_prr = 1;
18685                 /* lscwnd=1 */
18686                 rack->r_limit_scw = 1;
18687                 /* gp_inc_rec */
18688                 rack->r_ctl.rack_per_of_gp_rec = 90;
18689                 err = 0;
18690
18691
18692         } else if (prof == 2) {
18693                 /* cmpack=1 */
18694                 if (rack->rc_always_pace == 0) {
18695                         if (tcp_can_enable_pacing() == 0)
18696                                 return (EBUSY);
18697                 }
18698                 rack->rc_always_pace = 1;
18699                 if (rack->use_fixed_rate || rack->gp_ready)
18700                         rack_set_cc_pacing(rack);
18701                 rack->r_use_cmp_ack = 1;
18702                 if (TCPS_HAVEESTABLISHED(rack->rc_tp->t_state))
18703                         rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
18704                 /* pace_always=1 */
18705                 rack->rc_inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
18706                 /* scwnd=1 */
18707                 rack->rack_enable_scwnd = 1;
18708                 /* dynamic=100 */
18709                 rack->rc_gp_dyn_mul = 1;
18710                 rack->r_ctl.rack_per_of_gp_ca = 100;
18711                 /* rrr_conf=3 */
18712                 rack->r_rr_config = 3;
18713                 /* npush=2 */
18714                 rack->r_ctl.rc_no_push_at_mrtt = 2;
18715                 /* fillcw=1 */
18716                 rack->rc_pace_to_cwnd = 1;
18717                 rack->rc_pace_fill_if_rttin_range = 0;
18718                 rack->rtt_limit_mul = 0;
18719                 /* noprr=1 */
18720                 rack->rack_no_prr = 1;
18721                 /* lscwnd=0 */
18722                 rack->r_limit_scw = 0;
18723                 err = 0;
18724         } else if (prof == 0) {
18725                 /* This changes things back to the default settings */
18726                 err = 0;
18727                 if (rack->rc_always_pace) {
18728                         tcp_decrement_paced_conn();
18729                         rack_undo_cc_pacing(rack);
18730                         rack->rc_always_pace = 0;
18731                 }
18732                 if (rack_pace_every_seg && tcp_can_enable_pacing()) {
18733                         rack->rc_always_pace = 1;
18734                         if (rack->use_fixed_rate || rack->gp_ready)
18735                                 rack_set_cc_pacing(rack);
18736                 } else
18737                         rack->rc_always_pace = 0;
18738                 if (rack_use_cmp_acks)
18739                         rack->r_use_cmp_ack = 1;
18740                 else
18741                         rack->r_use_cmp_ack = 0;
18742                 if (rack_disable_prr)
18743                         rack->rack_no_prr = 1;
18744                 else
18745                         rack->rack_no_prr = 0;
18746                 if (rack_gp_no_rec_chg)
18747                         rack->rc_gp_no_rec_chg = 1;
18748                 else
18749                         rack->rc_gp_no_rec_chg = 0;
18750                 if (rack_enable_mqueue_for_nonpaced || rack->r_use_cmp_ack) {
18751                         rack->r_mbuf_queue = 1;
18752                         if (TCPS_HAVEESTABLISHED(rack->rc_tp->t_state))
18753                                 rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
18754                         rack->rc_inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
18755                 } else {
18756                         rack->r_mbuf_queue = 0;
18757                         rack->rc_inp->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
18758                 }
18759                 if (rack_enable_shared_cwnd)
18760                         rack->rack_enable_scwnd = 1;
18761                 else
18762                         rack->rack_enable_scwnd = 0;
18763                 if (rack_do_dyn_mul) {
18764                         /* When dynamic adjustment is on CA needs to start at 100% */
18765                         rack->rc_gp_dyn_mul = 1;
18766                         if (rack_do_dyn_mul >= 100)
18767                                 rack->r_ctl.rack_per_of_gp_ca = rack_do_dyn_mul;
18768                 } else {
18769                         rack->r_ctl.rack_per_of_gp_ca = rack_per_of_gp_ca;
18770                         rack->rc_gp_dyn_mul = 0;
18771                 }
18772                 rack->r_rr_config = 0;
18773                 rack->r_ctl.rc_no_push_at_mrtt = 0;
18774                 rack->rc_pace_to_cwnd = 0;
18775                 rack->rc_pace_fill_if_rttin_range = 0;
18776                 rack->rtt_limit_mul = 0;
18777
18778                 if (rack_enable_hw_pacing)
18779                         rack->rack_hdw_pace_ena = 1;
18780                 else
18781                         rack->rack_hdw_pace_ena = 0;
18782                 if (rack_disable_prr)
18783                         rack->rack_no_prr = 1;
18784                 else
18785                         rack->rack_no_prr = 0;
18786                 if (rack_limits_scwnd)
18787                         rack->r_limit_scw  = 1;
18788                 else
18789                         rack->r_limit_scw  = 0;
18790                 err = 0;
18791         }
18792         return (err);
18793 }
18794
18795 static int
18796 rack_add_deferred_option(struct tcp_rack *rack, int sopt_name, uint64_t loptval)
18797 {
18798         struct deferred_opt_list *dol;
18799
18800         dol = malloc(sizeof(struct deferred_opt_list),
18801                      M_TCPFSB, M_NOWAIT|M_ZERO);
18802         if (dol == NULL) {
18803                 /*
18804                  * No space yikes -- fail out..
18805                  */
18806                 return (0);
18807         }
18808         dol->optname = sopt_name;
18809         dol->optval = loptval;
18810         TAILQ_INSERT_TAIL(&rack->r_ctl.opt_list, dol, next);
18811         return (1);
18812 }
18813
18814 static int
18815 rack_process_option(struct tcpcb *tp, struct tcp_rack *rack, int sopt_name,
18816                     uint32_t optval, uint64_t loptval)
18817 {
18818         struct epoch_tracker et;
18819         struct sockopt sopt;
18820         struct cc_newreno_opts opt;
18821         uint64_t val;
18822         int error = 0;
18823         uint16_t ca, ss;
18824
18825         switch (sopt_name) {
18826
18827         case TCP_RACK_PACING_BETA:
18828                 RACK_OPTS_INC(tcp_rack_beta);
18829                 if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0) {
18830                         /* This only works for newreno. */
18831                         error = EINVAL;
18832                         break;
18833                 }
18834                 if (rack->rc_pacing_cc_set) {
18835                         /*
18836                          * Set them into the real CC module
18837                          * whats in the rack pcb is the old values
18838                          * to be used on restoral/
18839                          */
18840                         sopt.sopt_dir = SOPT_SET;
18841                         opt.name = CC_NEWRENO_BETA;
18842                         opt.val = optval;
18843                         if (CC_ALGO(tp)->ctl_output != NULL)
18844                                 error = CC_ALGO(tp)->ctl_output(tp->ccv, &sopt, &opt);
18845                         else {
18846                                 error = ENOENT;
18847                                 break;
18848                         }
18849                 } else {
18850                         /*
18851                          * Not pacing yet so set it into our local
18852                          * rack pcb storage.
18853                          */
18854                         rack->r_ctl.rc_saved_beta.beta = optval;
18855                 }
18856                 break;
18857         case TCP_RACK_PACING_BETA_ECN:
18858                 RACK_OPTS_INC(tcp_rack_beta_ecn);
18859                 if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0) {
18860                         /* This only works for newreno. */
18861                         error = EINVAL;
18862                         break;
18863                 }
18864                 if (rack->rc_pacing_cc_set) {
18865                         /*
18866                          * Set them into the real CC module
18867                          * whats in the rack pcb is the old values
18868                          * to be used on restoral/
18869                          */
18870                         sopt.sopt_dir = SOPT_SET;
18871                         opt.name = CC_NEWRENO_BETA_ECN;
18872                         opt.val = optval;
18873                         if (CC_ALGO(tp)->ctl_output != NULL)
18874                                 error = CC_ALGO(tp)->ctl_output(tp->ccv, &sopt, &opt);
18875                         else
18876                                 error = ENOENT;
18877                 } else {
18878                         /*
18879                          * Not pacing yet so set it into our local
18880                          * rack pcb storage.
18881                          */
18882                         rack->r_ctl.rc_saved_beta.beta_ecn = optval;
18883                         rack->r_ctl.rc_saved_beta.newreno_flags = CC_NEWRENO_BETA_ECN;
18884                 }
18885                 break;
18886         case TCP_DEFER_OPTIONS:
18887                 RACK_OPTS_INC(tcp_defer_opt);
18888                 if (optval) {
18889                         if (rack->gp_ready) {
18890                                 /* Too late */
18891                                 error = EINVAL;
18892                                 break;
18893                         }
18894                         rack->defer_options = 1;
18895                 } else
18896                         rack->defer_options = 0;
18897                 break;
18898         case TCP_RACK_MEASURE_CNT:
18899                 RACK_OPTS_INC(tcp_rack_measure_cnt);
18900                 if (optval && (optval <= 0xff)) {
18901                         rack->r_ctl.req_measurements = optval;
18902                 } else
18903                         error = EINVAL;
18904                 break;
18905         case TCP_REC_ABC_VAL:
18906                 RACK_OPTS_INC(tcp_rec_abc_val);
18907                 if (optval > 0)
18908                         rack->r_use_labc_for_rec = 1;
18909                 else
18910                         rack->r_use_labc_for_rec = 0;
18911                 break;
18912         case TCP_RACK_ABC_VAL:
18913                 RACK_OPTS_INC(tcp_rack_abc_val);
18914                 if ((optval > 0) && (optval < 255))
18915                         rack->rc_labc = optval;
18916                 else
18917                         error = EINVAL;
18918                 break;
18919         case TCP_HDWR_UP_ONLY:
18920                 RACK_OPTS_INC(tcp_pacing_up_only);
18921                 if (optval)
18922                         rack->r_up_only = 1;
18923                 else
18924                         rack->r_up_only = 0;
18925                 break;
18926         case TCP_PACING_RATE_CAP:
18927                 RACK_OPTS_INC(tcp_pacing_rate_cap);
18928                 rack->r_ctl.bw_rate_cap = loptval;
18929                 break;
18930         case TCP_RACK_PROFILE:
18931                 RACK_OPTS_INC(tcp_profile);
18932                 error = rack_set_profile(rack, optval);
18933                 break;
18934         case TCP_USE_CMP_ACKS:
18935                 RACK_OPTS_INC(tcp_use_cmp_acks);
18936                 if ((optval == 0) && (rack->rc_inp->inp_flags2 & INP_MBUF_ACKCMP)) {
18937                         /* You can't turn it off once its on! */
18938                         error = EINVAL;
18939                 } else if ((optval == 1) && (rack->r_use_cmp_ack == 0)) {
18940                         rack->r_use_cmp_ack = 1;
18941                         rack->r_mbuf_queue = 1;
18942                         tp->t_inpcb->inp_flags2 |= INP_SUPPORTS_MBUFQ;
18943                 }
18944                 if (rack->r_use_cmp_ack && TCPS_HAVEESTABLISHED(tp->t_state))
18945                         rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
18946                 break;
18947         case TCP_SHARED_CWND_TIME_LIMIT:
18948                 RACK_OPTS_INC(tcp_lscwnd);
18949                 if (optval)
18950                         rack->r_limit_scw = 1;
18951                 else
18952                         rack->r_limit_scw = 0;
18953                 break;
18954         case TCP_RACK_PACE_TO_FILL:
18955                 RACK_OPTS_INC(tcp_fillcw);
18956                 if (optval == 0)
18957                         rack->rc_pace_to_cwnd = 0;
18958                 else {
18959                         rack->rc_pace_to_cwnd = 1;
18960                         if (optval > 1)
18961                                 rack->r_fill_less_agg = 1;
18962                 }
18963                 if ((optval >= rack_gp_rtt_maxmul) &&
18964                     rack_gp_rtt_maxmul &&
18965                     (optval < 0xf)) {
18966                         rack->rc_pace_fill_if_rttin_range = 1;
18967                         rack->rtt_limit_mul = optval;
18968                 } else {
18969                         rack->rc_pace_fill_if_rttin_range = 0;
18970                         rack->rtt_limit_mul = 0;
18971                 }
18972                 break;
18973         case TCP_RACK_NO_PUSH_AT_MAX:
18974                 RACK_OPTS_INC(tcp_npush);
18975                 if (optval == 0)
18976                         rack->r_ctl.rc_no_push_at_mrtt = 0;
18977                 else if (optval < 0xff)
18978                         rack->r_ctl.rc_no_push_at_mrtt = optval;
18979                 else
18980                         error = EINVAL;
18981                 break;
18982         case TCP_SHARED_CWND_ENABLE:
18983                 RACK_OPTS_INC(tcp_rack_scwnd);
18984                 if (optval == 0)
18985                         rack->rack_enable_scwnd = 0;
18986                 else
18987                         rack->rack_enable_scwnd = 1;
18988                 break;
18989         case TCP_RACK_MBUF_QUEUE:
18990                 /* Now do we use the LRO mbuf-queue feature */
18991                 RACK_OPTS_INC(tcp_rack_mbufq);
18992                 if (optval || rack->r_use_cmp_ack)
18993                         rack->r_mbuf_queue = 1;
18994                 else
18995                         rack->r_mbuf_queue = 0;
18996                 if  (rack->r_mbuf_queue || rack->rc_always_pace || rack->r_use_cmp_ack)
18997                         tp->t_inpcb->inp_flags2 |= INP_SUPPORTS_MBUFQ;
18998                 else
18999                         tp->t_inpcb->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
19000                 break;
19001         case TCP_RACK_NONRXT_CFG_RATE:
19002                 RACK_OPTS_INC(tcp_rack_cfg_rate);
19003                 if (optval == 0)
19004                         rack->rack_rec_nonrxt_use_cr = 0;
19005                 else
19006                         rack->rack_rec_nonrxt_use_cr = 1;
19007                 break;
19008         case TCP_NO_PRR:
19009                 RACK_OPTS_INC(tcp_rack_noprr);
19010                 if (optval == 0)
19011                         rack->rack_no_prr = 0;
19012                 else if (optval == 1)
19013                         rack->rack_no_prr = 1;
19014                 else if (optval == 2)
19015                         rack->no_prr_addback = 1;
19016                 else
19017                         error = EINVAL;
19018                 break;
19019         case TCP_TIMELY_DYN_ADJ:
19020                 RACK_OPTS_INC(tcp_timely_dyn);
19021                 if (optval == 0)
19022                         rack->rc_gp_dyn_mul = 0;
19023                 else {
19024                         rack->rc_gp_dyn_mul = 1;
19025                         if (optval >= 100) {
19026                                 /*
19027                                  * If the user sets something 100 or more
19028                                  * its the gp_ca value.
19029                                  */
19030                                 rack->r_ctl.rack_per_of_gp_ca  = optval;
19031                         }
19032                 }
19033                 break;
19034         case TCP_RACK_DO_DETECTION:
19035                 RACK_OPTS_INC(tcp_rack_do_detection);
19036                 if (optval == 0)
19037                         rack->do_detection = 0;
19038                 else
19039                         rack->do_detection = 1;
19040                 break;
19041         case TCP_RACK_TLP_USE:
19042                 if ((optval < TLP_USE_ID) || (optval > TLP_USE_TWO_TWO)) {
19043                         error = EINVAL;
19044                         break;
19045                 }
19046                 RACK_OPTS_INC(tcp_tlp_use);
19047                 rack->rack_tlp_threshold_use = optval;
19048                 break;
19049         case TCP_RACK_TLP_REDUCE:
19050                 /* RACK TLP cwnd reduction (bool) */
19051                 RACK_OPTS_INC(tcp_rack_tlp_reduce);
19052                 rack->r_ctl.rc_tlp_cwnd_reduce = optval;
19053                 break;
19054         /*  Pacing related ones */
19055         case TCP_RACK_PACE_ALWAYS:
19056                 /*
19057                  * zero is old rack method, 1 is new
19058                  * method using a pacing rate.
19059                  */
19060                 RACK_OPTS_INC(tcp_rack_pace_always);
19061                 if (optval > 0) {
19062                         if (rack->rc_always_pace) {
19063                                 error = EALREADY;
19064                                 break;
19065                         } else if (tcp_can_enable_pacing()) {
19066                                 rack->rc_always_pace = 1;
19067                                 if (rack->use_fixed_rate || rack->gp_ready)
19068                                         rack_set_cc_pacing(rack);
19069                         }
19070                         else {
19071                                 error = ENOSPC;
19072                                 break;
19073                         }
19074                 } else {
19075                         if (rack->rc_always_pace) {
19076                                 tcp_decrement_paced_conn();
19077                                 rack->rc_always_pace = 0;
19078                                 rack_undo_cc_pacing(rack);
19079                         }
19080                 }
19081                 if  (rack->r_mbuf_queue || rack->rc_always_pace || rack->r_use_cmp_ack)
19082                         tp->t_inpcb->inp_flags2 |= INP_SUPPORTS_MBUFQ;
19083                 else
19084                         tp->t_inpcb->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
19085                 /* A rate may be set irate or other, if so set seg size */
19086                 rack_update_seg(rack);
19087                 break;
19088         case TCP_BBR_RACK_INIT_RATE:
19089                 RACK_OPTS_INC(tcp_initial_rate);
19090                 val = optval;
19091                 /* Change from kbits per second to bytes per second */
19092                 val *= 1000;
19093                 val /= 8;
19094                 rack->r_ctl.init_rate = val;
19095                 if (rack->rc_init_win != rack_default_init_window) {
19096                         uint32_t win, snt;
19097
19098                         /*
19099                          * Options don't always get applied
19100                          * in the order you think. So in order
19101                          * to assure we update a cwnd we need
19102                          * to check and see if we are still
19103                          * where we should raise the cwnd.
19104                          */
19105                         win = rc_init_window(rack);
19106                         if (SEQ_GT(tp->snd_max, tp->iss))
19107                                 snt = tp->snd_max - tp->iss;
19108                         else
19109                                 snt = 0;
19110                         if ((snt < win) &&
19111                             (tp->snd_cwnd < win))
19112                                 tp->snd_cwnd = win;
19113                 }
19114                 if (rack->rc_always_pace)
19115                         rack_update_seg(rack);
19116                 break;
19117         case TCP_BBR_IWINTSO:
19118                 RACK_OPTS_INC(tcp_initial_win);
19119                 if (optval && (optval <= 0xff)) {
19120                         uint32_t win, snt;
19121
19122                         rack->rc_init_win = optval;
19123                         win = rc_init_window(rack);
19124                         if (SEQ_GT(tp->snd_max, tp->iss))
19125                                 snt = tp->snd_max - tp->iss;
19126                         else
19127                                 snt = 0;
19128                         if ((snt < win) &&
19129                             (tp->t_srtt |
19130 #ifdef NETFLIX_PEAKRATE
19131                              tp->t_maxpeakrate |
19132 #endif
19133                              rack->r_ctl.init_rate)) {
19134                                 /*
19135                                  * We are not past the initial window
19136                                  * and we have some bases for pacing,
19137                                  * so we need to possibly adjust up
19138                                  * the cwnd. Note even if we don't set
19139                                  * the cwnd, its still ok to raise the rc_init_win
19140                                  * which can be used coming out of idle when we
19141                                  * would have a rate.
19142                                  */
19143                                 if (tp->snd_cwnd < win)
19144                                         tp->snd_cwnd = win;
19145                         }
19146                         if (rack->rc_always_pace)
19147                                 rack_update_seg(rack);
19148                 } else
19149                         error = EINVAL;
19150                 break;
19151         case TCP_RACK_FORCE_MSEG:
19152                 RACK_OPTS_INC(tcp_rack_force_max_seg);
19153                 if (optval)
19154                         rack->rc_force_max_seg = 1;
19155                 else
19156                         rack->rc_force_max_seg = 0;
19157                 break;
19158         case TCP_RACK_PACE_MAX_SEG:
19159                 /* Max segments size in a pace in bytes */
19160                 RACK_OPTS_INC(tcp_rack_max_seg);
19161                 rack->rc_user_set_max_segs = optval;
19162                 rack_set_pace_segments(tp, rack, __LINE__, NULL);
19163                 break;
19164         case TCP_RACK_PACE_RATE_REC:
19165                 /* Set the fixed pacing rate in Bytes per second ca */
19166                 RACK_OPTS_INC(tcp_rack_pace_rate_rec);
19167                 rack->r_ctl.rc_fixed_pacing_rate_rec = optval;
19168                 if (rack->r_ctl.rc_fixed_pacing_rate_ca == 0)
19169                         rack->r_ctl.rc_fixed_pacing_rate_ca = optval;
19170                 if (rack->r_ctl.rc_fixed_pacing_rate_ss == 0)
19171                         rack->r_ctl.rc_fixed_pacing_rate_ss = optval;
19172                 rack->use_fixed_rate = 1;
19173                 if (rack->rc_always_pace)
19174                         rack_set_cc_pacing(rack);
19175                 rack_log_pacing_delay_calc(rack,
19176                                            rack->r_ctl.rc_fixed_pacing_rate_ss,
19177                                            rack->r_ctl.rc_fixed_pacing_rate_ca,
19178                                            rack->r_ctl.rc_fixed_pacing_rate_rec, 0, 0, 8,
19179                                            __LINE__, NULL);
19180                 break;
19181
19182         case TCP_RACK_PACE_RATE_SS:
19183                 /* Set the fixed pacing rate in Bytes per second ca */
19184                 RACK_OPTS_INC(tcp_rack_pace_rate_ss);
19185                 rack->r_ctl.rc_fixed_pacing_rate_ss = optval;
19186                 if (rack->r_ctl.rc_fixed_pacing_rate_ca == 0)
19187                         rack->r_ctl.rc_fixed_pacing_rate_ca = optval;
19188                 if (rack->r_ctl.rc_fixed_pacing_rate_rec == 0)
19189                         rack->r_ctl.rc_fixed_pacing_rate_rec = optval;
19190                 rack->use_fixed_rate = 1;
19191                 if (rack->rc_always_pace)
19192                         rack_set_cc_pacing(rack);
19193                 rack_log_pacing_delay_calc(rack,
19194                                            rack->r_ctl.rc_fixed_pacing_rate_ss,
19195                                            rack->r_ctl.rc_fixed_pacing_rate_ca,
19196                                            rack->r_ctl.rc_fixed_pacing_rate_rec, 0, 0, 8,
19197                                            __LINE__, NULL);
19198                 break;
19199
19200         case TCP_RACK_PACE_RATE_CA:
19201                 /* Set the fixed pacing rate in Bytes per second ca */
19202                 RACK_OPTS_INC(tcp_rack_pace_rate_ca);
19203                 rack->r_ctl.rc_fixed_pacing_rate_ca = optval;
19204                 if (rack->r_ctl.rc_fixed_pacing_rate_ss == 0)
19205                         rack->r_ctl.rc_fixed_pacing_rate_ss = optval;
19206                 if (rack->r_ctl.rc_fixed_pacing_rate_rec == 0)
19207                         rack->r_ctl.rc_fixed_pacing_rate_rec = optval;
19208                 rack->use_fixed_rate = 1;
19209                 if (rack->rc_always_pace)
19210                         rack_set_cc_pacing(rack);
19211                 rack_log_pacing_delay_calc(rack,
19212                                            rack->r_ctl.rc_fixed_pacing_rate_ss,
19213                                            rack->r_ctl.rc_fixed_pacing_rate_ca,
19214                                            rack->r_ctl.rc_fixed_pacing_rate_rec, 0, 0, 8,
19215                                            __LINE__, NULL);
19216                 break;
19217         case TCP_RACK_GP_INCREASE_REC:
19218                 RACK_OPTS_INC(tcp_gp_inc_rec);
19219                 rack->r_ctl.rack_per_of_gp_rec = optval;
19220                 rack_log_pacing_delay_calc(rack,
19221                                            rack->r_ctl.rack_per_of_gp_ss,
19222                                            rack->r_ctl.rack_per_of_gp_ca,
19223                                            rack->r_ctl.rack_per_of_gp_rec, 0, 0, 1,
19224                                            __LINE__, NULL);
19225                 break;
19226         case TCP_RACK_GP_INCREASE_CA:
19227                 RACK_OPTS_INC(tcp_gp_inc_ca);
19228                 ca = optval;
19229                 if (ca < 100) {
19230                         /*
19231                          * We don't allow any reduction
19232                          * over the GP b/w.
19233                          */
19234                         error = EINVAL;
19235                         break;
19236                 }
19237                 rack->r_ctl.rack_per_of_gp_ca = ca;
19238                 rack_log_pacing_delay_calc(rack,
19239                                            rack->r_ctl.rack_per_of_gp_ss,
19240                                            rack->r_ctl.rack_per_of_gp_ca,
19241                                            rack->r_ctl.rack_per_of_gp_rec, 0, 0, 1,
19242                                            __LINE__, NULL);
19243                 break;
19244         case TCP_RACK_GP_INCREASE_SS:
19245                 RACK_OPTS_INC(tcp_gp_inc_ss);
19246                 ss = optval;
19247                 if (ss < 100) {
19248                         /*
19249                          * We don't allow any reduction
19250                          * over the GP b/w.
19251                          */
19252                         error = EINVAL;
19253                         break;
19254                 }
19255                 rack->r_ctl.rack_per_of_gp_ss = ss;
19256                 rack_log_pacing_delay_calc(rack,
19257                                            rack->r_ctl.rack_per_of_gp_ss,
19258                                            rack->r_ctl.rack_per_of_gp_ca,
19259                                            rack->r_ctl.rack_per_of_gp_rec, 0, 0, 1,
19260                                            __LINE__, NULL);
19261                 break;
19262         case TCP_RACK_RR_CONF:
19263                 RACK_OPTS_INC(tcp_rack_rrr_no_conf_rate);
19264                 if (optval && optval <= 3)
19265                         rack->r_rr_config = optval;
19266                 else
19267                         rack->r_rr_config = 0;
19268                 break;
19269         case TCP_HDWR_RATE_CAP:
19270                 RACK_OPTS_INC(tcp_hdwr_rate_cap);
19271                 if (optval) {
19272                         if (rack->r_rack_hw_rate_caps == 0)
19273                                 rack->r_rack_hw_rate_caps = 1;
19274                         else
19275                                 error = EALREADY;
19276                 } else {
19277                         rack->r_rack_hw_rate_caps = 0;
19278                 }
19279                 break;
19280         case TCP_BBR_HDWR_PACE:
19281                 RACK_OPTS_INC(tcp_hdwr_pacing);
19282                 if (optval){
19283                         if (rack->rack_hdrw_pacing == 0) {
19284                                 rack->rack_hdw_pace_ena = 1;
19285                                 rack->rack_attempt_hdwr_pace = 0;
19286                         } else
19287                                 error = EALREADY;
19288                 } else {
19289                         rack->rack_hdw_pace_ena = 0;
19290 #ifdef RATELIMIT
19291                         if (rack->r_ctl.crte != NULL) {
19292                                 rack->rack_hdrw_pacing = 0;
19293                                 rack->rack_attempt_hdwr_pace = 0;
19294                                 tcp_rel_pacing_rate(rack->r_ctl.crte, tp);
19295                                 rack->r_ctl.crte = NULL;
19296                         }
19297 #endif
19298                 }
19299                 break;
19300         /*  End Pacing related ones */
19301         case TCP_RACK_PRR_SENDALOT:
19302                 /* Allow PRR to send more than one seg */
19303                 RACK_OPTS_INC(tcp_rack_prr_sendalot);
19304                 rack->r_ctl.rc_prr_sendalot = optval;
19305                 break;
19306         case TCP_RACK_MIN_TO:
19307                 /* Minimum time between rack t-o's in ms */
19308                 RACK_OPTS_INC(tcp_rack_min_to);
19309                 rack->r_ctl.rc_min_to = optval;
19310                 break;
19311         case TCP_RACK_EARLY_SEG:
19312                 /* If early recovery max segments */
19313                 RACK_OPTS_INC(tcp_rack_early_seg);
19314                 rack->r_ctl.rc_early_recovery_segs = optval;
19315                 break;
19316         case TCP_RACK_REORD_THRESH:
19317                 /* RACK reorder threshold (shift amount) */
19318                 RACK_OPTS_INC(tcp_rack_reord_thresh);
19319                 if ((optval > 0) && (optval < 31))
19320                         rack->r_ctl.rc_reorder_shift = optval;
19321                 else
19322                         error = EINVAL;
19323                 break;
19324         case TCP_RACK_REORD_FADE:
19325                 /* Does reordering fade after ms time */
19326                 RACK_OPTS_INC(tcp_rack_reord_fade);
19327                 rack->r_ctl.rc_reorder_fade = optval;
19328                 break;
19329         case TCP_RACK_TLP_THRESH:
19330                 /* RACK TLP theshold i.e. srtt+(srtt/N) */
19331                 RACK_OPTS_INC(tcp_rack_tlp_thresh);
19332                 if (optval)
19333                         rack->r_ctl.rc_tlp_threshold = optval;
19334                 else
19335                         error = EINVAL;
19336                 break;
19337         case TCP_BBR_USE_RACK_RR:
19338                 RACK_OPTS_INC(tcp_rack_rr);
19339                 if (optval)
19340                         rack->use_rack_rr = 1;
19341                 else
19342                         rack->use_rack_rr = 0;
19343                 break;
19344         case TCP_FAST_RSM_HACK:
19345                 RACK_OPTS_INC(tcp_rack_fastrsm_hack);
19346                 if (optval)
19347                         rack->fast_rsm_hack = 1;
19348                 else
19349                         rack->fast_rsm_hack = 0;
19350                 break;
19351         case TCP_RACK_PKT_DELAY:
19352                 /* RACK added ms i.e. rack-rtt + reord + N */
19353                 RACK_OPTS_INC(tcp_rack_pkt_delay);
19354                 rack->r_ctl.rc_pkt_delay = optval;
19355                 break;
19356         case TCP_DELACK:
19357                 RACK_OPTS_INC(tcp_rack_delayed_ack);
19358                 if (optval == 0)
19359                         tp->t_delayed_ack = 0;
19360                 else
19361                         tp->t_delayed_ack = 1;
19362                 if (tp->t_flags & TF_DELACK) {
19363                         tp->t_flags &= ~TF_DELACK;
19364                         tp->t_flags |= TF_ACKNOW;
19365                         NET_EPOCH_ENTER(et);
19366                         rack_output(tp);
19367                         NET_EPOCH_EXIT(et);
19368                 }
19369                 break;
19370
19371         case TCP_BBR_RACK_RTT_USE:
19372                 RACK_OPTS_INC(tcp_rack_rtt_use);
19373                 if ((optval != USE_RTT_HIGH) &&
19374                     (optval != USE_RTT_LOW) &&
19375                     (optval != USE_RTT_AVG))
19376                         error = EINVAL;
19377                 else
19378                         rack->r_ctl.rc_rate_sample_method = optval;
19379                 break;
19380         case TCP_DATA_AFTER_CLOSE:
19381                 RACK_OPTS_INC(tcp_data_after_close);
19382                 if (optval)
19383                         rack->rc_allow_data_af_clo = 1;
19384                 else
19385                         rack->rc_allow_data_af_clo = 0;
19386                 break;
19387         default:
19388                 break;
19389         }
19390 #ifdef NETFLIX_STATS
19391         tcp_log_socket_option(tp, sopt_name, optval, error);
19392 #endif
19393         return (error);
19394 }
19395
19396
19397 static void
19398 rack_apply_deferred_options(struct tcp_rack *rack)
19399 {
19400         struct deferred_opt_list *dol, *sdol;
19401         uint32_t s_optval;
19402
19403         TAILQ_FOREACH_SAFE(dol, &rack->r_ctl.opt_list, next, sdol) {
19404                 TAILQ_REMOVE(&rack->r_ctl.opt_list, dol, next);
19405                 /* Disadvantage of deferal is you loose the error return */
19406                 s_optval = (uint32_t)dol->optval;
19407                 (void)rack_process_option(rack->rc_tp, rack, dol->optname, s_optval, dol->optval);
19408                 free(dol, M_TCPDO);
19409         }
19410 }
19411
19412 /*
19413  * rack_ctloutput() must drop the inpcb lock before performing copyin on
19414  * socket option arguments.  When it re-acquires the lock after the copy, it
19415  * has to revalidate that the connection is still valid for the socket
19416  * option.
19417  */
19418 static int
19419 rack_set_sockopt(struct socket *so, struct sockopt *sopt,
19420     struct inpcb *inp, struct tcpcb *tp, struct tcp_rack *rack)
19421 {
19422         uint64_t loptval;
19423         int32_t error = 0, optval;
19424
19425         switch (sopt->sopt_name) {
19426         case TCP_RACK_TLP_REDUCE:               /*  URL:tlp_reduce */
19427         /*  Pacing related ones */
19428         case TCP_RACK_PACE_ALWAYS:              /*  URL:pace_always */
19429         case TCP_BBR_RACK_INIT_RATE:            /*  URL:irate */
19430         case TCP_BBR_IWINTSO:                   /*  URL:tso_iwin */
19431         case TCP_RACK_PACE_MAX_SEG:             /*  URL:pace_max_seg */
19432         case TCP_RACK_FORCE_MSEG:               /*  URL:force_max_seg */
19433         case TCP_RACK_PACE_RATE_CA:             /*  URL:pr_ca */
19434         case TCP_RACK_PACE_RATE_SS:             /*  URL:pr_ss*/
19435         case TCP_RACK_PACE_RATE_REC:            /*  URL:pr_rec */
19436         case TCP_RACK_GP_INCREASE_CA:           /*  URL:gp_inc_ca */
19437         case TCP_RACK_GP_INCREASE_SS:           /*  URL:gp_inc_ss */
19438         case TCP_RACK_GP_INCREASE_REC:          /*  URL:gp_inc_rec */
19439         case TCP_RACK_RR_CONF:                  /*  URL:rrr_conf */
19440         case TCP_BBR_HDWR_PACE:                 /*  URL:hdwrpace */
19441         case TCP_HDWR_RATE_CAP:                 /*  URL: hdwrcap boolean */
19442         case TCP_PACING_RATE_CAP:               /*  URL:cap-- used by side-channel */
19443         case TCP_HDWR_UP_ONLY:                  /*  URL:uponly -- hardware pacing  boolean */
19444        /* End pacing related */
19445         case TCP_FAST_RSM_HACK:                 /*  URL:frsm_hack */
19446         case TCP_DELACK:                        /*  URL:delack (in base TCP i.e. tcp_hints along with cc etc ) */
19447         case TCP_RACK_PRR_SENDALOT:             /*  URL:prr_sendalot */
19448         case TCP_RACK_MIN_TO:                   /*  URL:min_to */
19449         case TCP_RACK_EARLY_SEG:                /*  URL:early_seg */
19450         case TCP_RACK_REORD_THRESH:             /*  URL:reord_thresh */
19451         case TCP_RACK_REORD_FADE:               /*  URL:reord_fade */
19452         case TCP_RACK_TLP_THRESH:               /*  URL:tlp_thresh */
19453         case TCP_RACK_PKT_DELAY:                /*  URL:pkt_delay */
19454         case TCP_RACK_TLP_USE:                  /*  URL:tlp_use */
19455         case TCP_BBR_RACK_RTT_USE:              /*  URL:rttuse */
19456         case TCP_BBR_USE_RACK_RR:               /*  URL:rackrr */
19457         case TCP_RACK_DO_DETECTION:             /*  URL:detect */
19458         case TCP_NO_PRR:                        /*  URL:noprr */
19459         case TCP_TIMELY_DYN_ADJ:                /*  URL:dynamic */
19460         case TCP_DATA_AFTER_CLOSE:              /*  no URL */
19461         case TCP_RACK_NONRXT_CFG_RATE:          /*  URL:nonrxtcr */
19462         case TCP_SHARED_CWND_ENABLE:            /*  URL:scwnd */
19463         case TCP_RACK_MBUF_QUEUE:               /*  URL:mqueue */
19464         case TCP_RACK_NO_PUSH_AT_MAX:           /*  URL:npush */
19465         case TCP_RACK_PACE_TO_FILL:             /*  URL:fillcw */
19466         case TCP_SHARED_CWND_TIME_LIMIT:        /*  URL:lscwnd */
19467         case TCP_RACK_PROFILE:                  /*  URL:profile */
19468         case TCP_USE_CMP_ACKS:                  /*  URL:cmpack */
19469         case TCP_RACK_ABC_VAL:                  /*  URL:labc */
19470         case TCP_REC_ABC_VAL:                   /*  URL:reclabc */
19471         case TCP_RACK_MEASURE_CNT:              /*  URL:measurecnt */
19472         case TCP_DEFER_OPTIONS:                 /*  URL:defer */
19473         case TCP_RACK_PACING_BETA:              /*  URL:pacing_beta */
19474         case TCP_RACK_PACING_BETA_ECN:          /*  URL:pacing_beta_ecn */
19475                 break;
19476         default:
19477                 /* Filter off all unknown options to the base stack */
19478                 return (tcp_default_ctloutput(so, sopt, inp, tp));
19479                 break;
19480         }
19481         INP_WUNLOCK(inp);
19482         if (sopt->sopt_name == TCP_PACING_RATE_CAP) {
19483                 error = sooptcopyin(sopt, &loptval, sizeof(loptval), sizeof(loptval));
19484                 /*
19485                  * We truncate it down to 32 bits for the socket-option trace this
19486                  * means rates > 34Gbps won't show right, but thats probably ok.
19487                  */
19488                 optval = (uint32_t)loptval;
19489         } else {
19490                 error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
19491                 /* Save it in 64 bit form too */
19492                 loptval = optval;
19493         }
19494         if (error)
19495                 return (error);
19496         INP_WLOCK(inp);
19497         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
19498                 INP_WUNLOCK(inp);
19499                 return (ECONNRESET);
19500         }
19501         if (rack->defer_options && (rack->gp_ready == 0) &&
19502             (sopt->sopt_name != TCP_DEFER_OPTIONS) &&
19503             (sopt->sopt_name != TCP_RACK_PACING_BETA) &&
19504             (sopt->sopt_name != TCP_RACK_PACING_BETA_ECN) &&
19505             (sopt->sopt_name != TCP_RACK_MEASURE_CNT)) {
19506                 /* Options are beind deferred */
19507                 if (rack_add_deferred_option(rack, sopt->sopt_name, loptval)) {
19508                         INP_WUNLOCK(inp);
19509                         return (0);
19510                 } else {
19511                         /* No memory to defer, fail */
19512                         INP_WUNLOCK(inp);
19513                         return (ENOMEM);
19514                 }
19515         }
19516         error = rack_process_option(tp, rack, sopt->sopt_name, optval, loptval);
19517         INP_WUNLOCK(inp);
19518         return (error);
19519 }
19520
19521 static void
19522 rack_fill_info(struct tcpcb *tp, struct tcp_info *ti)
19523 {
19524
19525         INP_WLOCK_ASSERT(tp->t_inpcb);
19526         bzero(ti, sizeof(*ti));
19527
19528         ti->tcpi_state = tp->t_state;
19529         if ((tp->t_flags & TF_REQ_TSTMP) && (tp->t_flags & TF_RCVD_TSTMP))
19530                 ti->tcpi_options |= TCPI_OPT_TIMESTAMPS;
19531         if (tp->t_flags & TF_SACK_PERMIT)
19532                 ti->tcpi_options |= TCPI_OPT_SACK;
19533         if ((tp->t_flags & TF_REQ_SCALE) && (tp->t_flags & TF_RCVD_SCALE)) {
19534                 ti->tcpi_options |= TCPI_OPT_WSCALE;
19535                 ti->tcpi_snd_wscale = tp->snd_scale;
19536                 ti->tcpi_rcv_wscale = tp->rcv_scale;
19537         }
19538         if (tp->t_flags2 & TF2_ECN_PERMIT)
19539                 ti->tcpi_options |= TCPI_OPT_ECN;
19540         if (tp->t_flags & TF_FASTOPEN)
19541                 ti->tcpi_options |= TCPI_OPT_TFO;
19542         /* still kept in ticks is t_rcvtime */
19543         ti->tcpi_last_data_recv = ((uint32_t)ticks - tp->t_rcvtime) * tick;
19544         /* Since we hold everything in precise useconds this is easy */
19545         ti->tcpi_rtt = tp->t_srtt;
19546         ti->tcpi_rttvar = tp->t_rttvar;
19547         ti->tcpi_rto = tp->t_rxtcur;
19548         ti->tcpi_snd_ssthresh = tp->snd_ssthresh;
19549         ti->tcpi_snd_cwnd = tp->snd_cwnd;
19550         /*
19551          * FreeBSD-specific extension fields for tcp_info.
19552          */
19553         ti->tcpi_rcv_space = tp->rcv_wnd;
19554         ti->tcpi_rcv_nxt = tp->rcv_nxt;
19555         ti->tcpi_snd_wnd = tp->snd_wnd;
19556         ti->tcpi_snd_bwnd = 0;          /* Unused, kept for compat. */
19557         ti->tcpi_snd_nxt = tp->snd_nxt;
19558         ti->tcpi_snd_mss = tp->t_maxseg;
19559         ti->tcpi_rcv_mss = tp->t_maxseg;
19560         ti->tcpi_snd_rexmitpack = tp->t_sndrexmitpack;
19561         ti->tcpi_rcv_ooopack = tp->t_rcvoopack;
19562         ti->tcpi_snd_zerowin = tp->t_sndzerowin;
19563 #ifdef NETFLIX_STATS
19564         ti->tcpi_total_tlp = tp->t_sndtlppack;
19565         ti->tcpi_total_tlp_bytes = tp->t_sndtlpbyte;
19566         memcpy(&ti->tcpi_rxsyninfo, &tp->t_rxsyninfo, sizeof(struct tcpsyninfo));
19567 #endif
19568 #ifdef TCP_OFFLOAD
19569         if (tp->t_flags & TF_TOE) {
19570                 ti->tcpi_options |= TCPI_OPT_TOE;
19571                 tcp_offload_tcp_info(tp, ti);
19572         }
19573 #endif
19574 }
19575
19576 static int
19577 rack_get_sockopt(struct socket *so, struct sockopt *sopt,
19578     struct inpcb *inp, struct tcpcb *tp, struct tcp_rack *rack)
19579 {
19580         int32_t error, optval;
19581         uint64_t val, loptval;
19582         struct  tcp_info ti;
19583         /*
19584          * Because all our options are either boolean or an int, we can just
19585          * pull everything into optval and then unlock and copy. If we ever
19586          * add a option that is not a int, then this will have quite an
19587          * impact to this routine.
19588          */
19589         error = 0;
19590         switch (sopt->sopt_name) {
19591         case TCP_INFO:
19592                 /* First get the info filled */
19593                 rack_fill_info(tp, &ti);
19594                 /* Fix up the rtt related fields if needed */
19595                 INP_WUNLOCK(inp);
19596                 error = sooptcopyout(sopt, &ti, sizeof ti);
19597                 return (error);
19598         /*
19599          * Beta is the congestion control value for NewReno that influences how
19600          * much of a backoff happens when loss is detected. It is normally set
19601          * to 50 for 50% i.e. the cwnd is reduced to 50% of its previous value
19602          * when you exit recovery.
19603          */
19604         case TCP_RACK_PACING_BETA:
19605                 if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0)
19606                         error = EINVAL;
19607                 else if (rack->rc_pacing_cc_set == 0)
19608                         optval = rack->r_ctl.rc_saved_beta.beta;
19609                 else {
19610                         /*
19611                          * Reach out into the CC data and report back what
19612                          * I have previously set. Yeah it looks hackish but
19613                          * we don't want to report the saved values.
19614                          */
19615                         if (tp->ccv->cc_data)
19616                                 optval = ((struct newreno *)tp->ccv->cc_data)->beta;
19617                         else
19618                                 error = EINVAL;
19619                 }
19620                 break;
19621                 /*
19622                  * Beta_ecn is the congestion control value for NewReno that influences how
19623                  * much of a backoff happens when a ECN mark is detected. It is normally set
19624                  * to 80 for 80% i.e. the cwnd is reduced by 20% of its previous value when
19625                  * you exit recovery. Note that classic ECN has a beta of 50, it is only
19626                  * ABE Ecn that uses this "less" value, but we do too with pacing :)
19627                  */
19628
19629         case TCP_RACK_PACING_BETA_ECN:
19630                 if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0)
19631                         error = EINVAL;
19632                 else if (rack->rc_pacing_cc_set == 0)
19633                         optval = rack->r_ctl.rc_saved_beta.beta_ecn;
19634                 else {
19635                         /*
19636                          * Reach out into the CC data and report back what
19637                          * I have previously set. Yeah it looks hackish but
19638                          * we don't want to report the saved values.
19639                          */
19640                         if (tp->ccv->cc_data)
19641                                 optval = ((struct newreno *)tp->ccv->cc_data)->beta_ecn;
19642                         else
19643                                 error = EINVAL;
19644                 }
19645                 break;
19646         case TCP_FAST_RSM_HACK:
19647                 optval = rack->fast_rsm_hack;
19648                 break;
19649         case TCP_DEFER_OPTIONS:
19650                 optval = rack->defer_options;
19651                 break;
19652         case TCP_RACK_MEASURE_CNT:
19653                 optval = rack->r_ctl.req_measurements;
19654                 break;
19655         case TCP_REC_ABC_VAL:
19656                 optval = rack->r_use_labc_for_rec;
19657                 break;
19658         case TCP_RACK_ABC_VAL:
19659                 optval = rack->rc_labc;
19660                 break;
19661         case TCP_HDWR_UP_ONLY:
19662                 optval= rack->r_up_only;
19663                 break;
19664         case TCP_PACING_RATE_CAP:
19665                 loptval = rack->r_ctl.bw_rate_cap;
19666                 break;
19667         case TCP_RACK_PROFILE:
19668                 /* You cannot retrieve a profile, its write only */
19669                 error = EINVAL;
19670                 break;
19671         case TCP_USE_CMP_ACKS:
19672                 optval = rack->r_use_cmp_ack;
19673                 break;
19674         case TCP_RACK_PACE_TO_FILL:
19675                 optval = rack->rc_pace_to_cwnd;
19676                 if (optval && rack->r_fill_less_agg)
19677                         optval++;
19678                 break;
19679         case TCP_RACK_NO_PUSH_AT_MAX:
19680                 optval = rack->r_ctl.rc_no_push_at_mrtt;
19681                 break;
19682         case TCP_SHARED_CWND_ENABLE:
19683                 optval = rack->rack_enable_scwnd;
19684                 break;
19685         case TCP_RACK_NONRXT_CFG_RATE:
19686                 optval = rack->rack_rec_nonrxt_use_cr;
19687                 break;
19688         case TCP_NO_PRR:
19689                 if (rack->rack_no_prr  == 1)
19690                         optval = 1;
19691                 else if (rack->no_prr_addback == 1)
19692                         optval = 2;
19693                 else
19694                         optval = 0;
19695                 break;
19696         case TCP_RACK_DO_DETECTION:
19697                 optval = rack->do_detection;
19698                 break;
19699         case TCP_RACK_MBUF_QUEUE:
19700                 /* Now do we use the LRO mbuf-queue feature */
19701                 optval = rack->r_mbuf_queue;
19702                 break;
19703         case TCP_TIMELY_DYN_ADJ:
19704                 optval = rack->rc_gp_dyn_mul;
19705                 break;
19706         case TCP_BBR_IWINTSO:
19707                 optval = rack->rc_init_win;
19708                 break;
19709         case TCP_RACK_TLP_REDUCE:
19710                 /* RACK TLP cwnd reduction (bool) */
19711                 optval = rack->r_ctl.rc_tlp_cwnd_reduce;
19712                 break;
19713         case TCP_BBR_RACK_INIT_RATE:
19714                 val = rack->r_ctl.init_rate;
19715                 /* convert to kbits per sec */
19716                 val *= 8;
19717                 val /= 1000;
19718                 optval = (uint32_t)val;
19719                 break;
19720         case TCP_RACK_FORCE_MSEG:
19721                 optval = rack->rc_force_max_seg;
19722                 break;
19723         case TCP_RACK_PACE_MAX_SEG:
19724                 /* Max segments in a pace */
19725                 optval = rack->rc_user_set_max_segs;
19726                 break;
19727         case TCP_RACK_PACE_ALWAYS:
19728                 /* Use the always pace method */
19729                 optval = rack->rc_always_pace;
19730                 break;
19731         case TCP_RACK_PRR_SENDALOT:
19732                 /* Allow PRR to send more than one seg */
19733                 optval = rack->r_ctl.rc_prr_sendalot;
19734                 break;
19735         case TCP_RACK_MIN_TO:
19736                 /* Minimum time between rack t-o's in ms */
19737                 optval = rack->r_ctl.rc_min_to;
19738                 break;
19739         case TCP_RACK_EARLY_SEG:
19740                 /* If early recovery max segments */
19741                 optval = rack->r_ctl.rc_early_recovery_segs;
19742                 break;
19743         case TCP_RACK_REORD_THRESH:
19744                 /* RACK reorder threshold (shift amount) */
19745                 optval = rack->r_ctl.rc_reorder_shift;
19746                 break;
19747         case TCP_RACK_REORD_FADE:
19748                 /* Does reordering fade after ms time */
19749                 optval = rack->r_ctl.rc_reorder_fade;
19750                 break;
19751         case TCP_BBR_USE_RACK_RR:
19752                 /* Do we use the rack cheat for rxt */
19753                 optval = rack->use_rack_rr;
19754                 break;
19755         case TCP_RACK_RR_CONF:
19756                 optval = rack->r_rr_config;
19757                 break;
19758         case TCP_HDWR_RATE_CAP:
19759                 optval = rack->r_rack_hw_rate_caps;
19760                 break;
19761         case TCP_BBR_HDWR_PACE:
19762                 optval = rack->rack_hdw_pace_ena;
19763                 break;
19764         case TCP_RACK_TLP_THRESH:
19765                 /* RACK TLP theshold i.e. srtt+(srtt/N) */
19766                 optval = rack->r_ctl.rc_tlp_threshold;
19767                 break;
19768         case TCP_RACK_PKT_DELAY:
19769                 /* RACK added ms i.e. rack-rtt + reord + N */
19770                 optval = rack->r_ctl.rc_pkt_delay;
19771                 break;
19772         case TCP_RACK_TLP_USE:
19773                 optval = rack->rack_tlp_threshold_use;
19774                 break;
19775         case TCP_RACK_PACE_RATE_CA:
19776                 optval = rack->r_ctl.rc_fixed_pacing_rate_ca;
19777                 break;
19778         case TCP_RACK_PACE_RATE_SS:
19779                 optval = rack->r_ctl.rc_fixed_pacing_rate_ss;
19780                 break;
19781         case TCP_RACK_PACE_RATE_REC:
19782                 optval = rack->r_ctl.rc_fixed_pacing_rate_rec;
19783                 break;
19784         case TCP_RACK_GP_INCREASE_SS:
19785                 optval = rack->r_ctl.rack_per_of_gp_ca;
19786                 break;
19787         case TCP_RACK_GP_INCREASE_CA:
19788                 optval = rack->r_ctl.rack_per_of_gp_ss;
19789                 break;
19790         case TCP_BBR_RACK_RTT_USE:
19791                 optval = rack->r_ctl.rc_rate_sample_method;
19792                 break;
19793         case TCP_DELACK:
19794                 optval = tp->t_delayed_ack;
19795                 break;
19796         case TCP_DATA_AFTER_CLOSE:
19797                 optval = rack->rc_allow_data_af_clo;
19798                 break;
19799         case TCP_SHARED_CWND_TIME_LIMIT:
19800                 optval = rack->r_limit_scw;
19801                 break;
19802         default:
19803                 return (tcp_default_ctloutput(so, sopt, inp, tp));
19804                 break;
19805         }
19806         INP_WUNLOCK(inp);
19807         if (error == 0) {
19808                 if (TCP_PACING_RATE_CAP)
19809                         error = sooptcopyout(sopt, &loptval, sizeof loptval);
19810                 else
19811                         error = sooptcopyout(sopt, &optval, sizeof optval);
19812         }
19813         return (error);
19814 }
19815
19816 static int
19817 rack_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp, struct tcpcb *tp)
19818 {
19819         int32_t error = EINVAL;
19820         struct tcp_rack *rack;
19821
19822         rack = (struct tcp_rack *)tp->t_fb_ptr;
19823         if (rack == NULL) {
19824                 /* Huh? */
19825                 goto out;
19826         }
19827         if (sopt->sopt_dir == SOPT_SET) {
19828                 return (rack_set_sockopt(so, sopt, inp, tp, rack));
19829         } else if (sopt->sopt_dir == SOPT_GET) {
19830                 return (rack_get_sockopt(so, sopt, inp, tp, rack));
19831         }
19832 out:
19833         INP_WUNLOCK(inp);
19834         return (error);
19835 }
19836
19837 static int
19838 rack_pru_options(struct tcpcb *tp, int flags)
19839 {
19840         if (flags & PRUS_OOB)
19841                 return (EOPNOTSUPP);
19842         return (0);
19843 }
19844
19845 static struct tcp_function_block __tcp_rack = {
19846         .tfb_tcp_block_name = __XSTRING(STACKNAME),
19847         .tfb_tcp_output = rack_output,
19848         .tfb_do_queued_segments = ctf_do_queued_segments,
19849         .tfb_do_segment_nounlock = rack_do_segment_nounlock,
19850         .tfb_tcp_do_segment = rack_do_segment,
19851         .tfb_tcp_ctloutput = rack_ctloutput,
19852         .tfb_tcp_fb_init = rack_init,
19853         .tfb_tcp_fb_fini = rack_fini,
19854         .tfb_tcp_timer_stop_all = rack_stopall,
19855         .tfb_tcp_timer_activate = rack_timer_activate,
19856         .tfb_tcp_timer_active = rack_timer_active,
19857         .tfb_tcp_timer_stop = rack_timer_stop,
19858         .tfb_tcp_rexmit_tmr = rack_remxt_tmr,
19859         .tfb_tcp_handoff_ok = rack_handoff_ok,
19860         .tfb_tcp_mtu_chg = rack_mtu_change,
19861         .tfb_pru_options = rack_pru_options,
19862
19863 };
19864
19865 static const char *rack_stack_names[] = {
19866         __XSTRING(STACKNAME),
19867 #ifdef STACKALIAS
19868         __XSTRING(STACKALIAS),
19869 #endif
19870 };
19871
19872 static int
19873 rack_ctor(void *mem, int32_t size, void *arg, int32_t how)
19874 {
19875         memset(mem, 0, size);
19876         return (0);
19877 }
19878
19879 static void
19880 rack_dtor(void *mem, int32_t size, void *arg)
19881 {
19882
19883 }
19884
19885 static bool rack_mod_inited = false;
19886
19887 static int
19888 tcp_addrack(module_t mod, int32_t type, void *data)
19889 {
19890         int32_t err = 0;
19891         int num_stacks;
19892
19893         switch (type) {
19894         case MOD_LOAD:
19895                 rack_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
19896                     sizeof(struct rack_sendmap),
19897                     rack_ctor, rack_dtor, NULL, NULL, UMA_ALIGN_PTR, 0);
19898
19899                 rack_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
19900                     sizeof(struct tcp_rack),
19901                     rack_ctor, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
19902
19903                 sysctl_ctx_init(&rack_sysctl_ctx);
19904                 rack_sysctl_root = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
19905                     SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
19906                     OID_AUTO,
19907 #ifdef STACKALIAS
19908                     __XSTRING(STACKALIAS),
19909 #else
19910                     __XSTRING(STACKNAME),
19911 #endif
19912                     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
19913                     "");
19914                 if (rack_sysctl_root == NULL) {
19915                         printf("Failed to add sysctl node\n");
19916                         err = EFAULT;
19917                         goto free_uma;
19918                 }
19919                 rack_init_sysctls();
19920                 num_stacks = nitems(rack_stack_names);
19921                 err = register_tcp_functions_as_names(&__tcp_rack, M_WAITOK,
19922                     rack_stack_names, &num_stacks);
19923                 if (err) {
19924                         printf("Failed to register %s stack name for "
19925                             "%s module\n", rack_stack_names[num_stacks],
19926                             __XSTRING(MODNAME));
19927                         sysctl_ctx_free(&rack_sysctl_ctx);
19928 free_uma:
19929                         uma_zdestroy(rack_zone);
19930                         uma_zdestroy(rack_pcb_zone);
19931                         rack_counter_destroy();
19932                         printf("Failed to register rack module -- err:%d\n", err);
19933                         return (err);
19934                 }
19935                 tcp_lro_reg_mbufq();
19936                 rack_mod_inited = true;
19937                 break;
19938         case MOD_QUIESCE:
19939                 err = deregister_tcp_functions(&__tcp_rack, true, false);
19940                 break;
19941         case MOD_UNLOAD:
19942                 err = deregister_tcp_functions(&__tcp_rack, false, true);
19943                 if (err == EBUSY)
19944                         break;
19945                 if (rack_mod_inited) {
19946                         uma_zdestroy(rack_zone);
19947                         uma_zdestroy(rack_pcb_zone);
19948                         sysctl_ctx_free(&rack_sysctl_ctx);
19949                         rack_counter_destroy();
19950                         rack_mod_inited = false;
19951                 }
19952                 tcp_lro_dereg_mbufq();
19953                 err = 0;
19954                 break;
19955         default:
19956                 return (EOPNOTSUPP);
19957         }
19958         return (err);
19959 }
19960
19961 static moduledata_t tcp_rack = {
19962         .name = __XSTRING(MODNAME),
19963         .evhand = tcp_addrack,
19964         .priv = 0
19965 };
19966
19967 MODULE_VERSION(MODNAME, 1);
19968 DECLARE_MODULE(MODNAME, tcp_rack, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
19969 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);