xref: /freebsd/sys/netinet/tcp_stacks/rack.c (revision e008cf3eb58f57efc484c8aaef1fbc9f8f146036)
1 /*-
2  * Copyright (c) 2016-2019
3  *	Netflix Inc.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33 #include "opt_ipsec.h"
34 #include "opt_tcpdebug.h"
35 
36 #include <sys/param.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 #ifdef NETFLIX_STATS
49 #include <sys/qmath.h>
50 #endif
51 #include <sys/socket.h>
52 #include <sys/socketvar.h>
53 #include <sys/sysctl.h>
54 #include <sys/systm.h>
55 #include <sys/tree.h>
56 #ifdef NETFLIX_STATS
57 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
58 #endif
59 #include <sys/refcount.h>
60 #include <sys/queue.h>
61 #include <sys/smp.h>
62 #include <sys/kthread.h>
63 #include <sys/kern_prefetch.h>
64 
65 #include <vm/uma.h>
66 
67 #include <net/route.h>
68 #include <net/vnet.h>
69 
70 #define TCPSTATES		/* for logging */
71 
72 #include <netinet/in.h>
73 #include <netinet/in_kdtrace.h>
74 #include <netinet/in_pcb.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
77 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
78 #include <netinet/ip_var.h>
79 #include <netinet/ip6.h>
80 #include <netinet6/in6_pcb.h>
81 #include <netinet6/ip6_var.h>
82 #define	TCPOUTFLAGS
83 #include <netinet/tcp.h>
84 #include <netinet/tcp_fsm.h>
85 #include <netinet/tcp_log_buf.h>
86 #include <netinet/tcp_seq.h>
87 #include <netinet/tcp_timer.h>
88 #include <netinet/tcp_var.h>
89 #include <netinet/tcp_hpts.h>
90 #include <netinet/tcpip.h>
91 #include <netinet/cc/cc.h>
92 #include <netinet/tcp_fastopen.h>
93 #ifdef TCPDEBUG
94 #include <netinet/tcp_debug.h>
95 #endif				/* TCPDEBUG */
96 #ifdef TCP_OFFLOAD
97 #include <netinet/tcp_offload.h>
98 #endif
99 #ifdef INET6
100 #include <netinet6/tcp6_var.h>
101 #endif
102 
103 #include <netipsec/ipsec_support.h>
104 
105 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
106 #include <netipsec/ipsec.h>
107 #include <netipsec/ipsec6.h>
108 #endif				/* IPSEC */
109 
110 #include <netinet/udp.h>
111 #include <netinet/udp_var.h>
112 #include <machine/in_cksum.h>
113 
114 #ifdef MAC
115 #include <security/mac/mac_framework.h>
116 #endif
117 #include "sack_filter.h"
118 #include "tcp_rack.h"
119 #include "rack_bbr_common.h"
120 
121 uma_zone_t rack_zone;
122 uma_zone_t rack_pcb_zone;
123 
124 #ifndef TICKS2SBT
125 #define	TICKS2SBT(__t)	(tick_sbt * ((sbintime_t)(__t)))
126 #endif
127 
128 struct sysctl_ctx_list rack_sysctl_ctx;
129 struct sysctl_oid *rack_sysctl_root;
130 
131 #define CUM_ACKED 1
132 #define SACKED 2
133 
134 /*
135  * The RACK module incorporates a number of
136  * TCP ideas that have been put out into the IETF
137  * over the last few years:
138  * - Matt Mathis's Rate Halving which slowly drops
139  *    the congestion window so that the ack clock can
140  *    be maintained during a recovery.
141  * - Yuchung Cheng's RACK TCP (for which its named) that
142  *    will stop us using the number of dup acks and instead
143  *    use time as the gage of when we retransmit.
144  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
145  *    of Dukkipati et.al.
146  * RACK depends on SACK, so if an endpoint arrives that
147  * cannot do SACK the state machine below will shuttle the
148  * connection back to using the "default" TCP stack that is
149  * in FreeBSD.
150  *
151  * To implement RACK the original TCP stack was first decomposed
152  * into a functional state machine with individual states
153  * for each of the possible TCP connection states. The do_segement
154  * functions role in life is to mandate the connection supports SACK
155  * initially and then assure that the RACK state matches the conenction
156  * state before calling the states do_segment function. Each
157  * state is simplified due to the fact that the original do_segment
158  * has been decomposed and we *know* what state we are in (no
159  * switches on the state) and all tests for SACK are gone. This
160  * greatly simplifies what each state does.
161  *
162  * TCP output is also over-written with a new version since it
163  * must maintain the new rack scoreboard.
164  *
165  */
166 static int32_t rack_precache = 1;
167 static int32_t rack_tlp_thresh = 1;
168 static int32_t rack_reorder_thresh = 2;
169 static int32_t rack_reorder_fade = 60000;	/* 0 - never fade, def 60,000
170 						 * - 60 seconds */
171 static int32_t rack_pkt_delay = 1;
172 static int32_t rack_inc_var = 0;/* For TLP */
173 static int32_t rack_reduce_largest_on_idle = 0;
174 static int32_t rack_min_pace_time = 0;
175 static int32_t rack_min_pace_time_seg_req=6;
176 static int32_t rack_early_recovery = 1;
177 static int32_t rack_early_recovery_max_seg = 6;
178 static int32_t rack_send_a_lot_in_prr = 1;
179 static int32_t rack_min_to = 1;	/* Number of ms minimum timeout */
180 static int32_t rack_tlp_in_recovery = 1;	/* Can we do TLP in recovery? */
181 static int32_t rack_verbose_logging = 0;
182 static int32_t rack_ignore_data_after_close = 1;
183 static int32_t rack_map_entries_limit = 1024;
184 static int32_t rack_map_split_limit = 256;
185 
186 /*
187  * Currently regular tcp has a rto_min of 30ms
188  * the backoff goes 12 times so that ends up
189  * being a total of 122.850 seconds before a
190  * connection is killed.
191  */
192 static int32_t rack_tlp_min = 10;
193 static int32_t rack_rto_min = 30;	/* 30ms same as main freebsd */
194 static int32_t rack_rto_max = 30000;	/* 30 seconds */
195 static const int32_t rack_free_cache = 2;
196 static int32_t rack_hptsi_segments = 40;
197 static int32_t rack_rate_sample_method = USE_RTT_LOW;
198 static int32_t rack_pace_every_seg = 1;
199 static int32_t rack_delayed_ack_time = 200;	/* 200ms */
200 static int32_t rack_slot_reduction = 4;
201 static int32_t rack_lower_cwnd_at_tlp = 0;
202 static int32_t rack_use_proportional_reduce = 0;
203 static int32_t rack_proportional_rate = 10;
204 static int32_t rack_tlp_max_resend = 2;
205 static int32_t rack_limited_retran = 0;
206 static int32_t rack_always_send_oldest = 0;
207 static int32_t rack_sack_block_limit = 128;
208 static int32_t rack_use_sack_filter = 1;
209 static int32_t rack_tlp_threshold_use = TLP_USE_TWO_ONE;
210 
211 /* Rack specific counters */
212 counter_u64_t rack_badfr;
213 counter_u64_t rack_badfr_bytes;
214 counter_u64_t rack_rtm_prr_retran;
215 counter_u64_t rack_rtm_prr_newdata;
216 counter_u64_t rack_timestamp_mismatch;
217 counter_u64_t rack_reorder_seen;
218 counter_u64_t rack_paced_segments;
219 counter_u64_t rack_unpaced_segments;
220 counter_u64_t rack_saw_enobuf;
221 counter_u64_t rack_saw_enetunreach;
222 
223 /* Tail loss probe counters */
224 counter_u64_t rack_tlp_tot;
225 counter_u64_t rack_tlp_newdata;
226 counter_u64_t rack_tlp_retran;
227 counter_u64_t rack_tlp_retran_bytes;
228 counter_u64_t rack_tlp_retran_fail;
229 counter_u64_t rack_to_tot;
230 counter_u64_t rack_to_arm_rack;
231 counter_u64_t rack_to_arm_tlp;
232 counter_u64_t rack_to_alloc;
233 counter_u64_t rack_to_alloc_hard;
234 counter_u64_t rack_to_alloc_emerg;
235 counter_u64_t rack_to_alloc_limited;
236 counter_u64_t rack_alloc_limited_conns;
237 counter_u64_t rack_split_limited;
238 
239 counter_u64_t rack_sack_proc_all;
240 counter_u64_t rack_sack_proc_short;
241 counter_u64_t rack_sack_proc_restart;
242 counter_u64_t rack_runt_sacks;
243 counter_u64_t rack_used_tlpmethod;
244 counter_u64_t rack_used_tlpmethod2;
245 counter_u64_t rack_enter_tlp_calc;
246 counter_u64_t rack_input_idle_reduces;
247 counter_u64_t rack_tlp_does_nada;
248 
249 /* Temp CPU counters */
250 counter_u64_t rack_find_high;
251 
252 counter_u64_t rack_progress_drops;
253 counter_u64_t rack_out_size[TCP_MSS_ACCT_SIZE];
254 counter_u64_t rack_opts_arry[RACK_OPTS_SIZE];
255 
256 /*
257  * This was originally defined in tcp_timer.c, but is now reproduced here given
258  * the unification of the SYN and non-SYN retransmit timer exponents combined
259  * with wanting to retain previous behaviour for previously deployed stack
260  * versions.
261  */
262 int	tcp_syn_backoff[TCP_MAXRXTSHIFT + 1] =
263     { 1, 1, 1, 1, 1, 2, 4, 8, 16, 32, 64, 64, 64 };
264 
265 static void
266 rack_log_progress_event(struct tcp_rack *rack, struct tcpcb *tp, uint32_t tick,  int event, int line);
267 
268 static int
269 rack_process_ack(struct mbuf *m, struct tcphdr *th,
270     struct socket *so, struct tcpcb *tp, struct tcpopt *to,
271     uint32_t tiwin, int32_t tlen, int32_t * ofia, int32_t thflags, int32_t * ret_val);
272 static int
273 rack_process_data(struct mbuf *m, struct tcphdr *th,
274     struct socket *so, struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
275     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
276 static void
277 rack_ack_received(struct tcpcb *tp, struct tcp_rack *rack,
278     struct tcphdr *th, uint16_t nsegs, uint16_t type, int32_t recovery);
279 static struct rack_sendmap *rack_alloc(struct tcp_rack *rack);
280 static struct rack_sendmap *rack_alloc_limit(struct tcp_rack *rack,
281     uint8_t limit_type);
282 static struct rack_sendmap *
283 rack_check_recovery_mode(struct tcpcb *tp,
284     uint32_t tsused);
285 static void
286 rack_cong_signal(struct tcpcb *tp, struct tcphdr *th,
287     uint32_t type);
288 static void rack_counter_destroy(void);
289 static int
290 rack_ctloutput(struct socket *so, struct sockopt *sopt,
291     struct inpcb *inp, struct tcpcb *tp);
292 static int32_t rack_ctor(void *mem, int32_t size, void *arg, int32_t how);
293 static void
294 rack_do_segment(struct mbuf *m, struct tcphdr *th,
295     struct socket *so, struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
296     uint8_t iptos);
297 static void rack_dtor(void *mem, int32_t size, void *arg);
298 static void
299 rack_earlier_retran(struct tcpcb *tp, struct rack_sendmap *rsm,
300     uint32_t t, uint32_t cts);
301 static struct rack_sendmap *
302 rack_find_high_nonack(struct tcp_rack *rack,
303     struct rack_sendmap *rsm);
304 static struct rack_sendmap *rack_find_lowest_rsm(struct tcp_rack *rack);
305 static void rack_free(struct tcp_rack *rack, struct rack_sendmap *rsm);
306 static void rack_fini(struct tcpcb *tp, int32_t tcb_is_purged);
307 static int
308 rack_get_sockopt(struct socket *so, struct sockopt *sopt,
309     struct inpcb *inp, struct tcpcb *tp, struct tcp_rack *rack);
310 static int32_t rack_handoff_ok(struct tcpcb *tp);
311 static int32_t rack_init(struct tcpcb *tp);
312 static void rack_init_sysctls(void);
313 static void
314 rack_log_ack(struct tcpcb *tp, struct tcpopt *to,
315     struct tcphdr *th);
316 static void
317 rack_log_output(struct tcpcb *tp, struct tcpopt *to, int32_t len,
318     uint32_t seq_out, uint8_t th_flags, int32_t err, uint32_t ts,
319     uint8_t pass, struct rack_sendmap *hintrsm);
320 static void
321 rack_log_sack_passed(struct tcpcb *tp, struct tcp_rack *rack,
322     struct rack_sendmap *rsm);
323 static void rack_log_to_event(struct tcp_rack *rack, int32_t to_num);
324 static int32_t rack_output(struct tcpcb *tp);
325 static void
326 rack_hpts_do_segment(struct mbuf *m, struct tcphdr *th,
327     struct socket *so, struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
328     uint8_t iptos, int32_t nxt_pkt, struct timeval *tv);
329 
330 static uint32_t
331 rack_proc_sack_blk(struct tcpcb *tp, struct tcp_rack *rack,
332     struct sackblk *sack, struct tcpopt *to, struct rack_sendmap **prsm,
333     uint32_t cts);
334 static void rack_post_recovery(struct tcpcb *tp, struct tcphdr *th);
335 static void rack_remxt_tmr(struct tcpcb *tp);
336 static int
337 rack_set_sockopt(struct socket *so, struct sockopt *sopt,
338     struct inpcb *inp, struct tcpcb *tp, struct tcp_rack *rack);
339 static void rack_set_state(struct tcpcb *tp, struct tcp_rack *rack);
340 static int32_t rack_stopall(struct tcpcb *tp);
341 static void
342 rack_timer_activate(struct tcpcb *tp, uint32_t timer_type,
343     uint32_t delta);
344 static int32_t rack_timer_active(struct tcpcb *tp, uint32_t timer_type);
345 static void rack_timer_cancel(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, int line);
346 static void rack_timer_stop(struct tcpcb *tp, uint32_t timer_type);
347 static uint32_t
348 rack_update_entry(struct tcpcb *tp, struct tcp_rack *rack,
349     struct rack_sendmap *rsm, uint32_t ts, int32_t * lenp);
350 static void
351 rack_update_rsm(struct tcpcb *tp, struct tcp_rack *rack,
352     struct rack_sendmap *rsm, uint32_t ts);
353 static int
354 rack_update_rtt(struct tcpcb *tp, struct tcp_rack *rack,
355     struct rack_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type);
356 static int32_t tcp_addrack(module_t mod, int32_t type, void *data);
357 static void
358 rack_challenge_ack(struct mbuf *m, struct tcphdr *th,
359     struct tcpcb *tp, int32_t * ret_val);
360 static int
361 rack_do_close_wait(struct mbuf *m, struct tcphdr *th,
362     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
363     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
364 static int
365 rack_do_closing(struct mbuf *m, struct tcphdr *th,
366     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
367     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
368 static void rack_do_drop(struct mbuf *m, struct tcpcb *tp);
369 static void
370 rack_do_dropafterack(struct mbuf *m, struct tcpcb *tp,
371     struct tcphdr *th, int32_t thflags, int32_t tlen, int32_t * ret_val);
372 static void
373 rack_do_dropwithreset(struct mbuf *m, struct tcpcb *tp,
374     struct tcphdr *th, int32_t rstreason, int32_t tlen);
375 static int
376 rack_do_established(struct mbuf *m, struct tcphdr *th,
377     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
378     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
379 static int
380 rack_do_fastnewdata(struct mbuf *m, struct tcphdr *th,
381     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
382     int32_t tlen, uint32_t tiwin, int32_t nxt_pkt);
383 static int
384 rack_do_fin_wait_1(struct mbuf *m, struct tcphdr *th,
385     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
386     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
387 static int
388 rack_do_fin_wait_2(struct mbuf *m, struct tcphdr *th,
389     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
390     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
391 static int
392 rack_do_lastack(struct mbuf *m, struct tcphdr *th,
393     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
394     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
395 static int
396 rack_do_syn_recv(struct mbuf *m, struct tcphdr *th,
397     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
398     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
399 static int
400 rack_do_syn_sent(struct mbuf *m, struct tcphdr *th,
401     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
402     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
403 static int
404 rack_drop_checks(struct tcpopt *to, struct mbuf *m,
405     struct tcphdr *th, struct tcpcb *tp, int32_t * tlenp, int32_t * thf,
406     int32_t * drop_hdrlen, int32_t * ret_val);
407 static int
408 rack_process_rst(struct mbuf *m, struct tcphdr *th,
409     struct socket *so, struct tcpcb *tp);
410 struct rack_sendmap *
411 tcp_rack_output(struct tcpcb *tp, struct tcp_rack *rack,
412     uint32_t tsused);
413 static void tcp_rack_xmit_timer(struct tcp_rack *rack, int32_t rtt);
414 static void
415      tcp_rack_partialack(struct tcpcb *tp, struct tcphdr *th);
416 
417 static int
418 rack_ts_check(struct mbuf *m, struct tcphdr *th,
419     struct tcpcb *tp, int32_t tlen, int32_t thflags, int32_t * ret_val);
420 
421 int32_t rack_clear_counter=0;
422 
423 
424 static int
425 sysctl_rack_clear(SYSCTL_HANDLER_ARGS)
426 {
427 	uint32_t stat;
428 	int32_t error;
429 
430 	error = SYSCTL_OUT(req, &rack_clear_counter, sizeof(uint32_t));
431 	if (error || req->newptr == NULL)
432 		return error;
433 
434 	error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
435 	if (error)
436 		return (error);
437 	if (stat == 1) {
438 #ifdef INVARIANTS
439 		printf("Clearing RACK counters\n");
440 #endif
441 		counter_u64_zero(rack_badfr);
442 		counter_u64_zero(rack_badfr_bytes);
443 		counter_u64_zero(rack_rtm_prr_retran);
444 		counter_u64_zero(rack_rtm_prr_newdata);
445 		counter_u64_zero(rack_timestamp_mismatch);
446 		counter_u64_zero(rack_reorder_seen);
447 		counter_u64_zero(rack_tlp_tot);
448 		counter_u64_zero(rack_tlp_newdata);
449 		counter_u64_zero(rack_tlp_retran);
450 		counter_u64_zero(rack_tlp_retran_bytes);
451 		counter_u64_zero(rack_tlp_retran_fail);
452 		counter_u64_zero(rack_to_tot);
453 		counter_u64_zero(rack_to_arm_rack);
454 		counter_u64_zero(rack_to_arm_tlp);
455 		counter_u64_zero(rack_paced_segments);
456 		counter_u64_zero(rack_unpaced_segments);
457 		counter_u64_zero(rack_saw_enobuf);
458 		counter_u64_zero(rack_saw_enetunreach);
459 		counter_u64_zero(rack_to_alloc_hard);
460 		counter_u64_zero(rack_to_alloc_emerg);
461 		counter_u64_zero(rack_sack_proc_all);
462 		counter_u64_zero(rack_sack_proc_short);
463 		counter_u64_zero(rack_sack_proc_restart);
464 		counter_u64_zero(rack_to_alloc);
465 		counter_u64_zero(rack_to_alloc_limited);
466 		counter_u64_zero(rack_alloc_limited_conns);
467 		counter_u64_zero(rack_split_limited);
468 		counter_u64_zero(rack_find_high);
469 		counter_u64_zero(rack_runt_sacks);
470 		counter_u64_zero(rack_used_tlpmethod);
471 		counter_u64_zero(rack_used_tlpmethod2);
472 		counter_u64_zero(rack_enter_tlp_calc);
473 		counter_u64_zero(rack_progress_drops);
474 		counter_u64_zero(rack_tlp_does_nada);
475 	}
476 	rack_clear_counter = 0;
477 	return (0);
478 }
479 
480 
481 
482 static void
483 rack_init_sysctls()
484 {
485 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
486 	    SYSCTL_CHILDREN(rack_sysctl_root),
487 	    OID_AUTO, "map_limit", CTLFLAG_RW,
488 	    &rack_map_entries_limit , 1024,
489 	    "Is there a limit on how big the sendmap can grow? ");
490 
491 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
492 	    SYSCTL_CHILDREN(rack_sysctl_root),
493 	    OID_AUTO, "map_splitlimit", CTLFLAG_RW,
494 	    &rack_map_split_limit , 256,
495 	    "Is there a limit on how much splitting a peer can do?");
496 
497 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
498 	    SYSCTL_CHILDREN(rack_sysctl_root),
499 	    OID_AUTO, "rate_sample_method", CTLFLAG_RW,
500 	    &rack_rate_sample_method , USE_RTT_LOW,
501 	    "What method should we use for rate sampling 0=high, 1=low ");
502 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
503 	    SYSCTL_CHILDREN(rack_sysctl_root),
504 	    OID_AUTO, "data_after_close", CTLFLAG_RW,
505 	    &rack_ignore_data_after_close, 0,
506 	    "Do we hold off sending a RST until all pending data is ack'd");
507 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
508 	    SYSCTL_CHILDREN(rack_sysctl_root),
509 	    OID_AUTO, "tlpmethod", CTLFLAG_RW,
510 	    &rack_tlp_threshold_use, TLP_USE_TWO_ONE,
511 	    "What method do we do for TLP time calc 0=no-de-ack-comp, 1=ID, 2=2.1, 3=2.2");
512 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
513 	    SYSCTL_CHILDREN(rack_sysctl_root),
514 	    OID_AUTO, "min_pace_time", CTLFLAG_RW,
515 	    &rack_min_pace_time, 0,
516 	    "Should we enforce a minimum pace time of 1ms");
517 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
518 	    SYSCTL_CHILDREN(rack_sysctl_root),
519 	    OID_AUTO, "min_pace_segs", CTLFLAG_RW,
520 	    &rack_min_pace_time_seg_req, 6,
521 	    "How many segments have to be in the len to enforce min-pace-time");
522 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
523 	    SYSCTL_CHILDREN(rack_sysctl_root),
524 	    OID_AUTO, "idle_reduce_high", CTLFLAG_RW,
525 	    &rack_reduce_largest_on_idle, 0,
526 	    "Should we reduce the largest cwnd seen to IW on idle reduction");
527 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
528 	    SYSCTL_CHILDREN(rack_sysctl_root),
529 	    OID_AUTO, "bb_verbose", CTLFLAG_RW,
530 	    &rack_verbose_logging, 0,
531 	    "Should RACK black box logging be verbose");
532 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
533 	    SYSCTL_CHILDREN(rack_sysctl_root),
534 	    OID_AUTO, "sackfiltering", CTLFLAG_RW,
535 	    &rack_use_sack_filter, 1,
536 	    "Do we use sack filtering?");
537 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
538 	    SYSCTL_CHILDREN(rack_sysctl_root),
539 	    OID_AUTO, "delayed_ack", CTLFLAG_RW,
540 	    &rack_delayed_ack_time, 200,
541 	    "Delayed ack time (200ms)");
542 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
543 	    SYSCTL_CHILDREN(rack_sysctl_root),
544 	    OID_AUTO, "tlpminto", CTLFLAG_RW,
545 	    &rack_tlp_min, 10,
546 	    "TLP minimum timeout per the specification (10ms)");
547 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
548 	    SYSCTL_CHILDREN(rack_sysctl_root),
549 	    OID_AUTO, "precache", CTLFLAG_RW,
550 	    &rack_precache, 0,
551 	    "Where should we precache the mcopy (0 is not at all)");
552 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
553 	    SYSCTL_CHILDREN(rack_sysctl_root),
554 	    OID_AUTO, "sblklimit", CTLFLAG_RW,
555 	    &rack_sack_block_limit, 128,
556 	    "When do we start paying attention to small sack blocks");
557 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
558 	    SYSCTL_CHILDREN(rack_sysctl_root),
559 	    OID_AUTO, "send_oldest", CTLFLAG_RW,
560 	    &rack_always_send_oldest, 1,
561 	    "Should we always send the oldest TLP and RACK-TLP");
562 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
563 	    SYSCTL_CHILDREN(rack_sysctl_root),
564 	    OID_AUTO, "rack_tlp_in_recovery", CTLFLAG_RW,
565 	    &rack_tlp_in_recovery, 1,
566 	    "Can we do a TLP during recovery?");
567 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
568 	    SYSCTL_CHILDREN(rack_sysctl_root),
569 	    OID_AUTO, "rack_tlimit", CTLFLAG_RW,
570 	    &rack_limited_retran, 0,
571 	    "How many times can a rack timeout drive out sends");
572 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
573 	    SYSCTL_CHILDREN(rack_sysctl_root),
574 	    OID_AUTO, "minrto", CTLFLAG_RW,
575 	    &rack_rto_min, 0,
576 	    "Minimum RTO in ms -- set with caution below 1000 due to TLP");
577 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
578 	    SYSCTL_CHILDREN(rack_sysctl_root),
579 	    OID_AUTO, "maxrto", CTLFLAG_RW,
580 	    &rack_rto_max, 0,
581 	    "Maxiumum RTO in ms -- should be at least as large as min_rto");
582 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
583 	    SYSCTL_CHILDREN(rack_sysctl_root),
584 	    OID_AUTO, "tlp_retry", CTLFLAG_RW,
585 	    &rack_tlp_max_resend, 2,
586 	    "How many times does TLP retry a single segment or multiple with no ACK");
587 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
588 	    SYSCTL_CHILDREN(rack_sysctl_root),
589 	    OID_AUTO, "recovery_loss_prop", CTLFLAG_RW,
590 	    &rack_use_proportional_reduce, 0,
591 	    "Should we proportionaly reduce cwnd based on the number of losses ");
592 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
593 	    SYSCTL_CHILDREN(rack_sysctl_root),
594 	    OID_AUTO, "recovery_prop", CTLFLAG_RW,
595 	    &rack_proportional_rate, 10,
596 	    "What percent reduction per loss");
597 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
598 	    SYSCTL_CHILDREN(rack_sysctl_root),
599 	    OID_AUTO, "tlp_cwnd_flag", CTLFLAG_RW,
600 	    &rack_lower_cwnd_at_tlp, 0,
601 	    "When a TLP completes a retran should we enter recovery?");
602 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
603 	    SYSCTL_CHILDREN(rack_sysctl_root),
604 	    OID_AUTO, "hptsi_reduces", CTLFLAG_RW,
605 	    &rack_slot_reduction, 4,
606 	    "When setting a slot should we reduce by divisor");
607 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
608 	    SYSCTL_CHILDREN(rack_sysctl_root),
609 	    OID_AUTO, "hptsi_every_seg", CTLFLAG_RW,
610 	    &rack_pace_every_seg, 1,
611 	    "Should we pace out every segment hptsi");
612 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
613 	    SYSCTL_CHILDREN(rack_sysctl_root),
614 	    OID_AUTO, "hptsi_seg_max", CTLFLAG_RW,
615 	    &rack_hptsi_segments, 6,
616 	    "Should we pace out only a limited size of segments");
617 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
618 	    SYSCTL_CHILDREN(rack_sysctl_root),
619 	    OID_AUTO, "prr_sendalot", CTLFLAG_RW,
620 	    &rack_send_a_lot_in_prr, 1,
621 	    "Send a lot in prr");
622 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
623 	    SYSCTL_CHILDREN(rack_sysctl_root),
624 	    OID_AUTO, "minto", CTLFLAG_RW,
625 	    &rack_min_to, 1,
626 	    "Minimum rack timeout in milliseconds");
627 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
628 	    SYSCTL_CHILDREN(rack_sysctl_root),
629 	    OID_AUTO, "earlyrecoveryseg", CTLFLAG_RW,
630 	    &rack_early_recovery_max_seg, 6,
631 	    "Max segments in early recovery");
632 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
633 	    SYSCTL_CHILDREN(rack_sysctl_root),
634 	    OID_AUTO, "earlyrecovery", CTLFLAG_RW,
635 	    &rack_early_recovery, 1,
636 	    "Do we do early recovery with rack");
637 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
638 	    SYSCTL_CHILDREN(rack_sysctl_root),
639 	    OID_AUTO, "reorder_thresh", CTLFLAG_RW,
640 	    &rack_reorder_thresh, 2,
641 	    "What factor for rack will be added when seeing reordering (shift right)");
642 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
643 	    SYSCTL_CHILDREN(rack_sysctl_root),
644 	    OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
645 	    &rack_tlp_thresh, 1,
646 	    "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
647 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
648 	    SYSCTL_CHILDREN(rack_sysctl_root),
649 	    OID_AUTO, "reorder_fade", CTLFLAG_RW,
650 	    &rack_reorder_fade, 0,
651 	    "Does reorder detection fade, if so how many ms (0 means never)");
652 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
653 	    SYSCTL_CHILDREN(rack_sysctl_root),
654 	    OID_AUTO, "pktdelay", CTLFLAG_RW,
655 	    &rack_pkt_delay, 1,
656 	    "Extra RACK time (in ms) besides reordering thresh");
657 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
658 	    SYSCTL_CHILDREN(rack_sysctl_root),
659 	    OID_AUTO, "inc_var", CTLFLAG_RW,
660 	    &rack_inc_var, 0,
661 	    "Should rack add to the TLP timer the variance in rtt calculation");
662 	rack_badfr = counter_u64_alloc(M_WAITOK);
663 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
664 	    SYSCTL_CHILDREN(rack_sysctl_root),
665 	    OID_AUTO, "badfr", CTLFLAG_RD,
666 	    &rack_badfr, "Total number of bad FRs");
667 	rack_badfr_bytes = counter_u64_alloc(M_WAITOK);
668 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
669 	    SYSCTL_CHILDREN(rack_sysctl_root),
670 	    OID_AUTO, "badfr_bytes", CTLFLAG_RD,
671 	    &rack_badfr_bytes, "Total number of bad FRs");
672 	rack_rtm_prr_retran = counter_u64_alloc(M_WAITOK);
673 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
674 	    SYSCTL_CHILDREN(rack_sysctl_root),
675 	    OID_AUTO, "prrsndret", CTLFLAG_RD,
676 	    &rack_rtm_prr_retran,
677 	    "Total number of prr based retransmits");
678 	rack_rtm_prr_newdata = counter_u64_alloc(M_WAITOK);
679 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
680 	    SYSCTL_CHILDREN(rack_sysctl_root),
681 	    OID_AUTO, "prrsndnew", CTLFLAG_RD,
682 	    &rack_rtm_prr_newdata,
683 	    "Total number of prr based new transmits");
684 	rack_timestamp_mismatch = counter_u64_alloc(M_WAITOK);
685 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
686 	    SYSCTL_CHILDREN(rack_sysctl_root),
687 	    OID_AUTO, "tsnf", CTLFLAG_RD,
688 	    &rack_timestamp_mismatch,
689 	    "Total number of timestamps that we could not find the reported ts");
690 	rack_find_high = counter_u64_alloc(M_WAITOK);
691 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
692 	    SYSCTL_CHILDREN(rack_sysctl_root),
693 	    OID_AUTO, "findhigh", CTLFLAG_RD,
694 	    &rack_find_high,
695 	    "Total number of FIN causing find-high");
696 	rack_reorder_seen = counter_u64_alloc(M_WAITOK);
697 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
698 	    SYSCTL_CHILDREN(rack_sysctl_root),
699 	    OID_AUTO, "reordering", CTLFLAG_RD,
700 	    &rack_reorder_seen,
701 	    "Total number of times we added delay due to reordering");
702 	rack_tlp_tot = counter_u64_alloc(M_WAITOK);
703 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
704 	    SYSCTL_CHILDREN(rack_sysctl_root),
705 	    OID_AUTO, "tlp_to_total", CTLFLAG_RD,
706 	    &rack_tlp_tot,
707 	    "Total number of tail loss probe expirations");
708 	rack_tlp_newdata = counter_u64_alloc(M_WAITOK);
709 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
710 	    SYSCTL_CHILDREN(rack_sysctl_root),
711 	    OID_AUTO, "tlp_new", CTLFLAG_RD,
712 	    &rack_tlp_newdata,
713 	    "Total number of tail loss probe sending new data");
714 
715 	rack_tlp_retran = counter_u64_alloc(M_WAITOK);
716 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
717 	    SYSCTL_CHILDREN(rack_sysctl_root),
718 	    OID_AUTO, "tlp_retran", CTLFLAG_RD,
719 	    &rack_tlp_retran,
720 	    "Total number of tail loss probe sending retransmitted data");
721 	rack_tlp_retran_bytes = counter_u64_alloc(M_WAITOK);
722 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
723 	    SYSCTL_CHILDREN(rack_sysctl_root),
724 	    OID_AUTO, "tlp_retran_bytes", CTLFLAG_RD,
725 	    &rack_tlp_retran_bytes,
726 	    "Total bytes of tail loss probe sending retransmitted data");
727 	rack_tlp_retran_fail = counter_u64_alloc(M_WAITOK);
728 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
729 	    SYSCTL_CHILDREN(rack_sysctl_root),
730 	    OID_AUTO, "tlp_retran_fail", CTLFLAG_RD,
731 	    &rack_tlp_retran_fail,
732 	    "Total number of tail loss probe sending retransmitted data that failed (wait for t3)");
733 	rack_to_tot = counter_u64_alloc(M_WAITOK);
734 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
735 	    SYSCTL_CHILDREN(rack_sysctl_root),
736 	    OID_AUTO, "rack_to_tot", CTLFLAG_RD,
737 	    &rack_to_tot,
738 	    "Total number of times the rack to expired?");
739 	rack_to_arm_rack = counter_u64_alloc(M_WAITOK);
740 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
741 	    SYSCTL_CHILDREN(rack_sysctl_root),
742 	    OID_AUTO, "arm_rack", CTLFLAG_RD,
743 	    &rack_to_arm_rack,
744 	    "Total number of times the rack timer armed?");
745 	rack_to_arm_tlp = counter_u64_alloc(M_WAITOK);
746 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
747 	    SYSCTL_CHILDREN(rack_sysctl_root),
748 	    OID_AUTO, "arm_tlp", CTLFLAG_RD,
749 	    &rack_to_arm_tlp,
750 	    "Total number of times the tlp timer armed?");
751 	rack_paced_segments = counter_u64_alloc(M_WAITOK);
752 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
753 	    SYSCTL_CHILDREN(rack_sysctl_root),
754 	    OID_AUTO, "paced", CTLFLAG_RD,
755 	    &rack_paced_segments,
756 	    "Total number of times a segment send caused hptsi");
757 	rack_unpaced_segments = counter_u64_alloc(M_WAITOK);
758 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
759 	    SYSCTL_CHILDREN(rack_sysctl_root),
760 	    OID_AUTO, "unpaced", CTLFLAG_RD,
761 	    &rack_unpaced_segments,
762 	    "Total number of times a segment did not cause hptsi");
763 	rack_saw_enobuf = counter_u64_alloc(M_WAITOK);
764 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
765 	    SYSCTL_CHILDREN(rack_sysctl_root),
766 	    OID_AUTO, "saw_enobufs", CTLFLAG_RD,
767 	    &rack_saw_enobuf,
768 	    "Total number of times a segment did not cause hptsi");
769 	rack_saw_enetunreach = counter_u64_alloc(M_WAITOK);
770 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
771 	    SYSCTL_CHILDREN(rack_sysctl_root),
772 	    OID_AUTO, "saw_enetunreach", CTLFLAG_RD,
773 	    &rack_saw_enetunreach,
774 	    "Total number of times a segment did not cause hptsi");
775 	rack_to_alloc = counter_u64_alloc(M_WAITOK);
776 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
777 	    SYSCTL_CHILDREN(rack_sysctl_root),
778 	    OID_AUTO, "allocs", CTLFLAG_RD,
779 	    &rack_to_alloc,
780 	    "Total allocations of tracking structures");
781 	rack_to_alloc_hard = counter_u64_alloc(M_WAITOK);
782 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
783 	    SYSCTL_CHILDREN(rack_sysctl_root),
784 	    OID_AUTO, "allochard", CTLFLAG_RD,
785 	    &rack_to_alloc_hard,
786 	    "Total allocations done with sleeping the hard way");
787 	rack_to_alloc_emerg = counter_u64_alloc(M_WAITOK);
788 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
789 	    SYSCTL_CHILDREN(rack_sysctl_root),
790 	    OID_AUTO, "allocemerg", CTLFLAG_RD,
791 	    &rack_to_alloc_emerg,
792 	    "Total allocations done from emergency cache");
793 	rack_to_alloc_limited = counter_u64_alloc(M_WAITOK);
794 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
795 	    SYSCTL_CHILDREN(rack_sysctl_root),
796 	    OID_AUTO, "alloc_limited", CTLFLAG_RD,
797 	    &rack_to_alloc_limited,
798 	    "Total allocations dropped due to limit");
799 	rack_alloc_limited_conns = counter_u64_alloc(M_WAITOK);
800 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
801 	    SYSCTL_CHILDREN(rack_sysctl_root),
802 	    OID_AUTO, "alloc_limited_conns", CTLFLAG_RD,
803 	    &rack_alloc_limited_conns,
804 	    "Connections with allocations dropped due to limit");
805 	rack_split_limited = counter_u64_alloc(M_WAITOK);
806 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
807 	    SYSCTL_CHILDREN(rack_sysctl_root),
808 	    OID_AUTO, "split_limited", CTLFLAG_RD,
809 	    &rack_split_limited,
810 	    "Split allocations dropped due to limit");
811 	rack_sack_proc_all = counter_u64_alloc(M_WAITOK);
812 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
813 	    SYSCTL_CHILDREN(rack_sysctl_root),
814 	    OID_AUTO, "sack_long", CTLFLAG_RD,
815 	    &rack_sack_proc_all,
816 	    "Total times we had to walk whole list for sack processing");
817 
818 	rack_sack_proc_restart = counter_u64_alloc(M_WAITOK);
819 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
820 	    SYSCTL_CHILDREN(rack_sysctl_root),
821 	    OID_AUTO, "sack_restart", CTLFLAG_RD,
822 	    &rack_sack_proc_restart,
823 	    "Total times we had to walk whole list due to a restart");
824 	rack_sack_proc_short = counter_u64_alloc(M_WAITOK);
825 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
826 	    SYSCTL_CHILDREN(rack_sysctl_root),
827 	    OID_AUTO, "sack_short", CTLFLAG_RD,
828 	    &rack_sack_proc_short,
829 	    "Total times we took shortcut for sack processing");
830 	rack_enter_tlp_calc = counter_u64_alloc(M_WAITOK);
831 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
832 	    SYSCTL_CHILDREN(rack_sysctl_root),
833 	    OID_AUTO, "tlp_calc_entered", CTLFLAG_RD,
834 	    &rack_enter_tlp_calc,
835 	    "Total times we called calc-tlp");
836 	rack_used_tlpmethod = counter_u64_alloc(M_WAITOK);
837 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
838 	    SYSCTL_CHILDREN(rack_sysctl_root),
839 	    OID_AUTO, "hit_tlp_method", CTLFLAG_RD,
840 	    &rack_used_tlpmethod,
841 	    "Total number of runt sacks");
842 	rack_used_tlpmethod2 = counter_u64_alloc(M_WAITOK);
843 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
844 	    SYSCTL_CHILDREN(rack_sysctl_root),
845 	    OID_AUTO, "hit_tlp_method2", CTLFLAG_RD,
846 	    &rack_used_tlpmethod2,
847 	    "Total number of runt sacks 2");
848 	rack_runt_sacks = counter_u64_alloc(M_WAITOK);
849 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
850 	    SYSCTL_CHILDREN(rack_sysctl_root),
851 	    OID_AUTO, "runtsacks", CTLFLAG_RD,
852 	    &rack_runt_sacks,
853 	    "Total number of runt sacks");
854 	rack_progress_drops = counter_u64_alloc(M_WAITOK);
855 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
856 	    SYSCTL_CHILDREN(rack_sysctl_root),
857 	    OID_AUTO, "prog_drops", CTLFLAG_RD,
858 	    &rack_progress_drops,
859 	    "Total number of progress drops");
860 	rack_input_idle_reduces = counter_u64_alloc(M_WAITOK);
861 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
862 	    SYSCTL_CHILDREN(rack_sysctl_root),
863 	    OID_AUTO, "idle_reduce_oninput", CTLFLAG_RD,
864 	    &rack_input_idle_reduces,
865 	    "Total number of idle reductions on input");
866 	rack_tlp_does_nada = counter_u64_alloc(M_WAITOK);
867 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
868 	    SYSCTL_CHILDREN(rack_sysctl_root),
869 	    OID_AUTO, "tlp_nada", CTLFLAG_RD,
870 	    &rack_tlp_does_nada,
871 	    "Total number of nada tlp calls");
872 	COUNTER_ARRAY_ALLOC(rack_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
873 	SYSCTL_ADD_COUNTER_U64_ARRAY(&rack_sysctl_ctx, SYSCTL_CHILDREN(rack_sysctl_root),
874 	    OID_AUTO, "outsize", CTLFLAG_RD,
875 	    rack_out_size, TCP_MSS_ACCT_SIZE, "MSS send sizes");
876 	COUNTER_ARRAY_ALLOC(rack_opts_arry, RACK_OPTS_SIZE, M_WAITOK);
877 	SYSCTL_ADD_COUNTER_U64_ARRAY(&rack_sysctl_ctx, SYSCTL_CHILDREN(rack_sysctl_root),
878 	    OID_AUTO, "opts", CTLFLAG_RD,
879 	    rack_opts_arry, RACK_OPTS_SIZE, "RACK Option Stats");
880 	SYSCTL_ADD_PROC(&rack_sysctl_ctx,
881 	    SYSCTL_CHILDREN(rack_sysctl_root),
882 	    OID_AUTO, "clear", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
883 	    &rack_clear_counter, 0, sysctl_rack_clear, "IU", "Clear counters");
884 }
885 
886 static inline int32_t
887 rack_progress_timeout_check(struct tcpcb *tp)
888 {
889 #ifdef NETFLIX_PROGRESS
890 	if (tp->t_maxunacktime && tp->t_acktime && TSTMP_GT(ticks, tp->t_acktime)) {
891 		if ((ticks - tp->t_acktime) >= tp->t_maxunacktime) {
892 			/*
893 			 * There is an assumption that the caller
894 			 * will drop the connection so we will
895 			 * increment the counters here.
896 			 */
897 			struct tcp_rack *rack;
898 			rack = (struct tcp_rack *)tp->t_fb_ptr;
899 			counter_u64_add(rack_progress_drops, 1);
900 			TCPSTAT_INC(tcps_progdrops);
901 			rack_log_progress_event(rack, tp, ticks, PROGRESS_DROP, __LINE__);
902 			return (1);
903 		}
904 	}
905 #endif
906 	return (0);
907 }
908 
909 
910 static void
911 rack_log_to_start(struct tcp_rack *rack, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
912 {
913 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
914 		union tcp_log_stackspecific log;
915 
916 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
917 		log.u_bbr.flex1 = TICKS_2_MSEC(rack->rc_tp->t_srtt >> TCP_RTT_SHIFT);
918 		log.u_bbr.flex2 = to;
919 		log.u_bbr.flex3 = rack->r_ctl.rc_hpts_flags;
920 		log.u_bbr.flex4 = slot;
921 		log.u_bbr.flex5 = rack->rc_inp->inp_hptsslot;
922 		log.u_bbr.flex6 = rack->rc_tp->t_rxtcur;
923 		log.u_bbr.flex8 = which;
924 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
925 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
926 		TCP_LOG_EVENT(rack->rc_tp, NULL,
927 		    &rack->rc_inp->inp_socket->so_rcv,
928 		    &rack->rc_inp->inp_socket->so_snd,
929 		    BBR_LOG_TIMERSTAR, 0,
930 		    0, &log, false);
931 	}
932 }
933 
934 static void
935 rack_log_to_event(struct tcp_rack *rack, int32_t to_num)
936 {
937 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
938 		union tcp_log_stackspecific log;
939 
940 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
941 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
942 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
943 		log.u_bbr.flex8 = to_num;
944 		log.u_bbr.flex1 = rack->r_ctl.rc_rack_min_rtt;
945 		log.u_bbr.flex2 = rack->rc_rack_rtt;
946 		TCP_LOG_EVENT(rack->rc_tp, NULL,
947 		    &rack->rc_inp->inp_socket->so_rcv,
948 		    &rack->rc_inp->inp_socket->so_snd,
949 		    BBR_LOG_RTO, 0,
950 		    0, &log, false);
951 	}
952 }
953 
954 static void
955 rack_log_rtt_upd(struct tcpcb *tp, struct tcp_rack *rack, int32_t t,
956     uint32_t o_srtt, uint32_t o_var)
957 {
958 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
959 		union tcp_log_stackspecific log;
960 
961 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
962 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
963 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
964 		log.u_bbr.flex1 = t;
965 		log.u_bbr.flex2 = o_srtt;
966 		log.u_bbr.flex3 = o_var;
967 		log.u_bbr.flex4 = rack->r_ctl.rack_rs.rs_rtt_lowest;
968 		log.u_bbr.flex5 = rack->r_ctl.rack_rs.rs_rtt_highest;
969 		log.u_bbr.flex6 = rack->r_ctl.rack_rs.rs_rtt_cnt;
970 		log.u_bbr.rttProp = rack->r_ctl.rack_rs.rs_rtt_tot;
971 		log.u_bbr.flex8 = rack->r_ctl.rc_rate_sample_method;
972 		TCP_LOG_EVENT(tp, NULL,
973 		    &rack->rc_inp->inp_socket->so_rcv,
974 		    &rack->rc_inp->inp_socket->so_snd,
975 		    BBR_LOG_BBRRTT, 0,
976 		    0, &log, false);
977 	}
978 }
979 
980 static void
981 rack_log_rtt_sample(struct tcp_rack *rack, uint32_t rtt)
982 {
983 	/*
984 	 * Log the rtt sample we are
985 	 * applying to the srtt algorithm in
986 	 * useconds.
987 	 */
988 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
989 		union tcp_log_stackspecific log;
990 		struct timeval tv;
991 
992 		memset(&log, 0, sizeof(log));
993 		/* Convert our ms to a microsecond */
994 		log.u_bbr.flex1 = rtt * 1000;
995 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
996 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
997 		    &rack->rc_inp->inp_socket->so_rcv,
998 		    &rack->rc_inp->inp_socket->so_snd,
999 		    TCP_LOG_RTT, 0,
1000 		    0, &log, false, &tv);
1001 	}
1002 }
1003 
1004 
1005 static inline void
1006 rack_log_progress_event(struct tcp_rack *rack, struct tcpcb *tp, uint32_t tick,  int event, int line)
1007 {
1008 	if (rack_verbose_logging && (tp->t_logstate != TCP_LOG_STATE_OFF)) {
1009 		union tcp_log_stackspecific log;
1010 
1011 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
1012 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
1013 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
1014 		log.u_bbr.flex1 = line;
1015 		log.u_bbr.flex2 = tick;
1016 		log.u_bbr.flex3 = tp->t_maxunacktime;
1017 		log.u_bbr.flex4 = tp->t_acktime;
1018 		log.u_bbr.flex8 = event;
1019 		TCP_LOG_EVENT(tp, NULL,
1020 		    &rack->rc_inp->inp_socket->so_rcv,
1021 		    &rack->rc_inp->inp_socket->so_snd,
1022 		    BBR_LOG_PROGRESS, 0,
1023 		    0, &log, false);
1024 	}
1025 }
1026 
1027 static void
1028 rack_log_type_bbrsnd(struct tcp_rack *rack, uint32_t len, uint32_t slot, uint32_t cts)
1029 {
1030 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1031 		union tcp_log_stackspecific log;
1032 
1033 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
1034 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
1035 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
1036 		log.u_bbr.flex1 = slot;
1037 		log.u_bbr.flex7 = (0x0000ffff & rack->r_ctl.rc_hpts_flags);
1038 		log.u_bbr.flex8 = rack->rc_in_persist;
1039 		TCP_LOG_EVENT(rack->rc_tp, NULL,
1040 		    &rack->rc_inp->inp_socket->so_rcv,
1041 		    &rack->rc_inp->inp_socket->so_snd,
1042 		    BBR_LOG_BBRSND, 0,
1043 		    0, &log, false);
1044 	}
1045 }
1046 
1047 static void
1048 rack_log_doseg_done(struct tcp_rack *rack, uint32_t cts, int32_t nxt_pkt, int32_t did_out, int way_out)
1049 {
1050 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1051 		union tcp_log_stackspecific log;
1052 
1053 		memset(&log, 0, sizeof(log));
1054 		log.u_bbr.flex1 = did_out;
1055 		log.u_bbr.flex2 = nxt_pkt;
1056 		log.u_bbr.flex3 = way_out;
1057 		log.u_bbr.flex4 = rack->r_ctl.rc_hpts_flags;
1058 		log.u_bbr.flex7 = rack->r_wanted_output;
1059 		log.u_bbr.flex8 = rack->rc_in_persist;
1060 		TCP_LOG_EVENT(rack->rc_tp, NULL,
1061 		    &rack->rc_inp->inp_socket->so_rcv,
1062 		    &rack->rc_inp->inp_socket->so_snd,
1063 		    BBR_LOG_DOSEG_DONE, 0,
1064 		    0, &log, false);
1065 	}
1066 }
1067 
1068 
1069 static void
1070 rack_log_type_just_return(struct tcp_rack *rack, uint32_t cts, uint32_t tlen, uint32_t slot, uint8_t hpts_calling)
1071 {
1072 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1073 		union tcp_log_stackspecific log;
1074 
1075 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
1076 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
1077 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
1078 		log.u_bbr.flex1 = slot;
1079 		log.u_bbr.flex2 = rack->r_ctl.rc_hpts_flags;
1080 		log.u_bbr.flex7 = hpts_calling;
1081 		log.u_bbr.flex8 = rack->rc_in_persist;
1082 		TCP_LOG_EVENT(rack->rc_tp, NULL,
1083 		    &rack->rc_inp->inp_socket->so_rcv,
1084 		    &rack->rc_inp->inp_socket->so_snd,
1085 		    BBR_LOG_JUSTRET, 0,
1086 		    tlen, &log, false);
1087 	}
1088 }
1089 
1090 static void
1091 rack_log_to_cancel(struct tcp_rack *rack, int32_t hpts_removed, int line)
1092 {
1093 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1094 		union tcp_log_stackspecific log;
1095 
1096 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
1097 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
1098 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
1099 		log.u_bbr.flex1 = line;
1100 		log.u_bbr.flex2 = 0;
1101 		log.u_bbr.flex3 = rack->r_ctl.rc_hpts_flags;
1102 		log.u_bbr.flex4 = 0;
1103 		log.u_bbr.flex6 = rack->rc_tp->t_rxtcur;
1104 		log.u_bbr.flex8 = hpts_removed;
1105 		TCP_LOG_EVENT(rack->rc_tp, NULL,
1106 		    &rack->rc_inp->inp_socket->so_rcv,
1107 		    &rack->rc_inp->inp_socket->so_snd,
1108 		    BBR_LOG_TIMERCANC, 0,
1109 		    0, &log, false);
1110 	}
1111 }
1112 
1113 static void
1114 rack_log_to_processing(struct tcp_rack *rack, uint32_t cts, int32_t ret, int32_t timers)
1115 {
1116 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1117 		union tcp_log_stackspecific log;
1118 
1119 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
1120 		log.u_bbr.flex1 = timers;
1121 		log.u_bbr.flex2 = ret;
1122 		log.u_bbr.flex3 = rack->r_ctl.rc_timer_exp;
1123 		log.u_bbr.flex4 = rack->r_ctl.rc_hpts_flags;
1124 		log.u_bbr.flex5 = cts;
1125 		TCP_LOG_EVENT(rack->rc_tp, NULL,
1126 		    &rack->rc_inp->inp_socket->so_rcv,
1127 		    &rack->rc_inp->inp_socket->so_snd,
1128 		    BBR_LOG_TO_PROCESS, 0,
1129 		    0, &log, false);
1130 	}
1131 }
1132 
1133 static void
1134 rack_counter_destroy()
1135 {
1136 	counter_u64_free(rack_badfr);
1137 	counter_u64_free(rack_badfr_bytes);
1138 	counter_u64_free(rack_rtm_prr_retran);
1139 	counter_u64_free(rack_rtm_prr_newdata);
1140 	counter_u64_free(rack_timestamp_mismatch);
1141 	counter_u64_free(rack_reorder_seen);
1142 	counter_u64_free(rack_tlp_tot);
1143 	counter_u64_free(rack_tlp_newdata);
1144 	counter_u64_free(rack_tlp_retran);
1145 	counter_u64_free(rack_tlp_retran_bytes);
1146 	counter_u64_free(rack_tlp_retran_fail);
1147 	counter_u64_free(rack_to_tot);
1148 	counter_u64_free(rack_to_arm_rack);
1149 	counter_u64_free(rack_to_arm_tlp);
1150 	counter_u64_free(rack_paced_segments);
1151 	counter_u64_free(rack_unpaced_segments);
1152 	counter_u64_free(rack_saw_enobuf);
1153 	counter_u64_free(rack_saw_enetunreach);
1154 	counter_u64_free(rack_to_alloc_hard);
1155 	counter_u64_free(rack_to_alloc_emerg);
1156 	counter_u64_free(rack_sack_proc_all);
1157 	counter_u64_free(rack_sack_proc_short);
1158 	counter_u64_free(rack_sack_proc_restart);
1159 	counter_u64_free(rack_to_alloc);
1160 	counter_u64_free(rack_to_alloc_limited);
1161 	counter_u64_free(rack_split_limited);
1162 	counter_u64_free(rack_find_high);
1163 	counter_u64_free(rack_runt_sacks);
1164 	counter_u64_free(rack_enter_tlp_calc);
1165 	counter_u64_free(rack_used_tlpmethod);
1166 	counter_u64_free(rack_used_tlpmethod2);
1167 	counter_u64_free(rack_progress_drops);
1168 	counter_u64_free(rack_input_idle_reduces);
1169 	counter_u64_free(rack_tlp_does_nada);
1170 	COUNTER_ARRAY_FREE(rack_out_size, TCP_MSS_ACCT_SIZE);
1171 	COUNTER_ARRAY_FREE(rack_opts_arry, RACK_OPTS_SIZE);
1172 }
1173 
1174 static struct rack_sendmap *
1175 rack_alloc(struct tcp_rack *rack)
1176 {
1177 	struct rack_sendmap *rsm;
1178 
1179 	rsm = uma_zalloc(rack_zone, M_NOWAIT);
1180 	if (rsm) {
1181 		rack->r_ctl.rc_num_maps_alloced++;
1182 		counter_u64_add(rack_to_alloc, 1);
1183 		return (rsm);
1184 	}
1185 	if (rack->rc_free_cnt) {
1186 		counter_u64_add(rack_to_alloc_emerg, 1);
1187 		rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
1188 		TAILQ_REMOVE(&rack->r_ctl.rc_free, rsm, r_next);
1189 		rack->rc_free_cnt--;
1190 		return (rsm);
1191 	}
1192 	return (NULL);
1193 }
1194 
1195 static struct rack_sendmap *
1196 rack_alloc_full_limit(struct tcp_rack *rack)
1197 {
1198 	if ((rack_map_entries_limit > 0) &&
1199 	    (rack->r_ctl.rc_num_maps_alloced >= rack_map_entries_limit)) {
1200 		counter_u64_add(rack_to_alloc_limited, 1);
1201 		if (!rack->alloc_limit_reported) {
1202 			rack->alloc_limit_reported = 1;
1203 			counter_u64_add(rack_alloc_limited_conns, 1);
1204 		}
1205 		return (NULL);
1206 	}
1207 	return (rack_alloc(rack));
1208 }
1209 
1210 /* wrapper to allocate a sendmap entry, subject to a specific limit */
1211 static struct rack_sendmap *
1212 rack_alloc_limit(struct tcp_rack *rack, uint8_t limit_type)
1213 {
1214 	struct rack_sendmap *rsm;
1215 
1216 	if (limit_type) {
1217 		/* currently there is only one limit type */
1218 		if (rack_map_split_limit > 0 &&
1219 		    rack->r_ctl.rc_num_split_allocs >= rack_map_split_limit) {
1220 			counter_u64_add(rack_split_limited, 1);
1221 			if (!rack->alloc_limit_reported) {
1222 				rack->alloc_limit_reported = 1;
1223 				counter_u64_add(rack_alloc_limited_conns, 1);
1224 			}
1225 			return (NULL);
1226 		}
1227 	}
1228 
1229 	/* allocate and mark in the limit type, if set */
1230 	rsm = rack_alloc(rack);
1231 	if (rsm != NULL && limit_type) {
1232 		rsm->r_limit_type = limit_type;
1233 		rack->r_ctl.rc_num_split_allocs++;
1234 	}
1235 	return (rsm);
1236 }
1237 
1238 static void
1239 rack_free(struct tcp_rack *rack, struct rack_sendmap *rsm)
1240 {
1241 	if (rsm->r_limit_type) {
1242 		/* currently there is only one limit type */
1243 		rack->r_ctl.rc_num_split_allocs--;
1244 	}
1245 	if (rack->r_ctl.rc_tlpsend == rsm)
1246 		rack->r_ctl.rc_tlpsend = NULL;
1247 	if (rack->r_ctl.rc_next == rsm)
1248 		rack->r_ctl.rc_next = NULL;
1249 	if (rack->r_ctl.rc_sacklast == rsm)
1250 		rack->r_ctl.rc_sacklast = NULL;
1251 	if (rack->rc_free_cnt < rack_free_cache) {
1252 		memset(rsm, 0, sizeof(struct rack_sendmap));
1253 		TAILQ_INSERT_TAIL(&rack->r_ctl.rc_free, rsm, r_next);
1254 		rsm->r_limit_type = 0;
1255 		rack->rc_free_cnt++;
1256 		return;
1257 	}
1258 	rack->r_ctl.rc_num_maps_alloced--;
1259 	uma_zfree(rack_zone, rsm);
1260 }
1261 
1262 /*
1263  * CC wrapper hook functions
1264  */
1265 static void
1266 rack_ack_received(struct tcpcb *tp, struct tcp_rack *rack, struct tcphdr *th, uint16_t nsegs,
1267     uint16_t type, int32_t recovery)
1268 {
1269 #ifdef NETFLIX_STATS
1270 	int32_t gput;
1271 #endif
1272 
1273 	INP_WLOCK_ASSERT(tp->t_inpcb);
1274 
1275 	tp->ccv->nsegs = nsegs;
1276 	tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
1277 	if ((recovery) && (rack->r_ctl.rc_early_recovery_segs)) {
1278 		uint32_t max;
1279 
1280 		max = rack->r_ctl.rc_early_recovery_segs * tp->t_maxseg;
1281 		if (tp->ccv->bytes_this_ack > max) {
1282 			tp->ccv->bytes_this_ack = max;
1283 		}
1284 	}
1285 	if (tp->snd_cwnd <= tp->snd_wnd)
1286 		tp->ccv->flags |= CCF_CWND_LIMITED;
1287 	else
1288 		tp->ccv->flags &= ~CCF_CWND_LIMITED;
1289 
1290 	if (type == CC_ACK) {
1291 #ifdef NETFLIX_STATS
1292 		stats_voi_update_abs_s32(tp->t_stats, VOI_TCP_CALCFRWINDIFF,
1293 		    ((int32_t) tp->snd_cwnd) - tp->snd_wnd);
1294 		if ((tp->t_flags & TF_GPUTINPROG) &&
1295 		    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
1296 			gput = (((int64_t) (th->th_ack - tp->gput_seq)) << 3) /
1297 			    max(1, tcp_ts_getticks() - tp->gput_ts);
1298 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
1299 			    gput);
1300 			/*
1301 			 * XXXLAS: This is a temporary hack, and should be
1302 			 * chained off VOI_TCP_GPUT when stats(9) grows an
1303 			 * API to deal with chained VOIs.
1304 			 */
1305 			if (tp->t_stats_gput_prev > 0)
1306 				stats_voi_update_abs_s32(tp->t_stats,
1307 				    VOI_TCP_GPUT_ND,
1308 				    ((gput - tp->t_stats_gput_prev) * 100) /
1309 				    tp->t_stats_gput_prev);
1310 			tp->t_flags &= ~TF_GPUTINPROG;
1311 			tp->t_stats_gput_prev = gput;
1312 			if (tp->t_maxpeakrate) {
1313 				/*
1314 				 * We update t_peakrate_thr. This gives us roughly
1315 				 * one update per round trip time.
1316 				 */
1317 				tcp_update_peakrate_thr(tp);
1318 			}
1319 		}
1320 #endif
1321 		if (tp->snd_cwnd > tp->snd_ssthresh) {
1322 			tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
1323 			    nsegs * V_tcp_abc_l_var * tp->t_maxseg);
1324 			if (tp->t_bytes_acked >= tp->snd_cwnd) {
1325 				tp->t_bytes_acked -= tp->snd_cwnd;
1326 				tp->ccv->flags |= CCF_ABC_SENTAWND;
1327 			}
1328 		} else {
1329 			tp->ccv->flags &= ~CCF_ABC_SENTAWND;
1330 			tp->t_bytes_acked = 0;
1331 		}
1332 	}
1333 	if (CC_ALGO(tp)->ack_received != NULL) {
1334 		/* XXXLAS: Find a way to live without this */
1335 		tp->ccv->curack = th->th_ack;
1336 		CC_ALGO(tp)->ack_received(tp->ccv, type);
1337 	}
1338 #ifdef NETFLIX_STATS
1339 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_LCWIN, tp->snd_cwnd);
1340 #endif
1341 	if (rack->r_ctl.rc_rack_largest_cwnd < tp->snd_cwnd) {
1342 		rack->r_ctl.rc_rack_largest_cwnd = tp->snd_cwnd;
1343 	}
1344 	/* we enforce max peak rate if it is set. */
1345 	if (tp->t_peakrate_thr && tp->snd_cwnd > tp->t_peakrate_thr) {
1346 		tp->snd_cwnd = tp->t_peakrate_thr;
1347 	}
1348 }
1349 
1350 static void
1351 tcp_rack_partialack(struct tcpcb *tp, struct tcphdr *th)
1352 {
1353 	struct tcp_rack *rack;
1354 
1355 	rack = (struct tcp_rack *)tp->t_fb_ptr;
1356 	INP_WLOCK_ASSERT(tp->t_inpcb);
1357 	if (rack->r_ctl.rc_prr_sndcnt > 0)
1358 		rack->r_wanted_output++;
1359 }
1360 
1361 static void
1362 rack_post_recovery(struct tcpcb *tp, struct tcphdr *th)
1363 {
1364 	struct tcp_rack *rack;
1365 
1366 	INP_WLOCK_ASSERT(tp->t_inpcb);
1367 	rack = (struct tcp_rack *)tp->t_fb_ptr;
1368 	if (CC_ALGO(tp)->post_recovery != NULL) {
1369 		tp->ccv->curack = th->th_ack;
1370 		CC_ALGO(tp)->post_recovery(tp->ccv);
1371 	}
1372 	/*
1373 	 * Here we can in theory adjust cwnd to be based on the number of
1374 	 * losses in the window (rack->r_ctl.rc_loss_count). This is done
1375 	 * based on the rack_use_proportional flag.
1376 	 */
1377 	if (rack->r_ctl.rc_prop_reduce && rack->r_ctl.rc_prop_rate) {
1378 		int32_t reduce;
1379 
1380 		reduce = (rack->r_ctl.rc_loss_count * rack->r_ctl.rc_prop_rate);
1381 		if (reduce > 50) {
1382 			reduce = 50;
1383 		}
1384 		tp->snd_cwnd -= ((reduce * tp->snd_cwnd) / 100);
1385 	} else {
1386 		if (tp->snd_cwnd > tp->snd_ssthresh) {
1387 			/* Drop us down to the ssthresh (1/2 cwnd at loss) */
1388 			tp->snd_cwnd = tp->snd_ssthresh;
1389 		}
1390 	}
1391 	if (rack->r_ctl.rc_prr_sndcnt > 0) {
1392 		/* Suck the next prr cnt back into cwnd */
1393 		tp->snd_cwnd += rack->r_ctl.rc_prr_sndcnt;
1394 		rack->r_ctl.rc_prr_sndcnt = 0;
1395 	}
1396 	tp->snd_recover = tp->snd_una;
1397 	EXIT_RECOVERY(tp->t_flags);
1398 }
1399 
1400 static void
1401 rack_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
1402 {
1403 	struct tcp_rack *rack;
1404 
1405 	INP_WLOCK_ASSERT(tp->t_inpcb);
1406 
1407 	rack = (struct tcp_rack *)tp->t_fb_ptr;
1408 	switch (type) {
1409 	case CC_NDUPACK:
1410 /*		rack->r_ctl.rc_ssthresh_set = 1;*/
1411 		if (!IN_FASTRECOVERY(tp->t_flags)) {
1412 			rack->r_ctl.rc_tlp_rtx_out = 0;
1413 			rack->r_ctl.rc_prr_delivered = 0;
1414 			rack->r_ctl.rc_prr_out = 0;
1415 			rack->r_ctl.rc_loss_count = 0;
1416 			rack->r_ctl.rc_prr_sndcnt = tp->t_maxseg;
1417 			rack->r_ctl.rc_prr_recovery_fs = tp->snd_max - tp->snd_una;
1418 			tp->snd_recover = tp->snd_max;
1419 			if (tp->t_flags & TF_ECN_PERMIT)
1420 				tp->t_flags |= TF_ECN_SND_CWR;
1421 		}
1422 		break;
1423 	case CC_ECN:
1424 		if (!IN_CONGRECOVERY(tp->t_flags)) {
1425 			TCPSTAT_INC(tcps_ecn_rcwnd);
1426 			tp->snd_recover = tp->snd_max;
1427 			if (tp->t_flags & TF_ECN_PERMIT)
1428 				tp->t_flags |= TF_ECN_SND_CWR;
1429 		}
1430 		break;
1431 	case CC_RTO:
1432 		tp->t_dupacks = 0;
1433 		tp->t_bytes_acked = 0;
1434 		EXIT_RECOVERY(tp->t_flags);
1435 		tp->snd_ssthresh = max(2, min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1436 		    tp->t_maxseg) * tp->t_maxseg;
1437 		tp->snd_cwnd = tp->t_maxseg;
1438 		break;
1439 	case CC_RTO_ERR:
1440 		TCPSTAT_INC(tcps_sndrexmitbad);
1441 		/* RTO was unnecessary, so reset everything. */
1442 		tp->snd_cwnd = tp->snd_cwnd_prev;
1443 		tp->snd_ssthresh = tp->snd_ssthresh_prev;
1444 		tp->snd_recover = tp->snd_recover_prev;
1445 		if (tp->t_flags & TF_WASFRECOVERY)
1446 			ENTER_FASTRECOVERY(tp->t_flags);
1447 		if (tp->t_flags & TF_WASCRECOVERY)
1448 			ENTER_CONGRECOVERY(tp->t_flags);
1449 		tp->snd_nxt = tp->snd_max;
1450 		tp->t_badrxtwin = 0;
1451 		break;
1452 	}
1453 
1454 	if (CC_ALGO(tp)->cong_signal != NULL) {
1455 		if (th != NULL)
1456 			tp->ccv->curack = th->th_ack;
1457 		CC_ALGO(tp)->cong_signal(tp->ccv, type);
1458 	}
1459 }
1460 
1461 
1462 
1463 static inline void
1464 rack_cc_after_idle(struct tcpcb *tp, int reduce_largest)
1465 {
1466 	uint32_t i_cwnd;
1467 
1468 	INP_WLOCK_ASSERT(tp->t_inpcb);
1469 
1470 #ifdef NETFLIX_STATS
1471 	TCPSTAT_INC(tcps_idle_restarts);
1472 	if (tp->t_state == TCPS_ESTABLISHED)
1473 		TCPSTAT_INC(tcps_idle_estrestarts);
1474 #endif
1475 	if (CC_ALGO(tp)->after_idle != NULL)
1476 		CC_ALGO(tp)->after_idle(tp->ccv);
1477 
1478 	if (V_tcp_initcwnd_segments)
1479 		i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
1480 		    max(2 * tp->t_maxseg, 14600));
1481 	else if (V_tcp_do_rfc3390)
1482 		i_cwnd = min(4 * tp->t_maxseg,
1483 		    max(2 * tp->t_maxseg, 4380));
1484 	else {
1485 		/* Per RFC5681 Section 3.1 */
1486 		if (tp->t_maxseg > 2190)
1487 			i_cwnd = 2 * tp->t_maxseg;
1488 		else if (tp->t_maxseg > 1095)
1489 			i_cwnd = 3 * tp->t_maxseg;
1490 		else
1491 			i_cwnd = 4 * tp->t_maxseg;
1492 	}
1493 	if (reduce_largest) {
1494 		/*
1495 		 * Do we reduce the largest cwnd to make
1496 		 * rack play nice on restart hptsi wise?
1497 		 */
1498 		if (((struct tcp_rack *)tp->t_fb_ptr)->r_ctl.rc_rack_largest_cwnd  > i_cwnd)
1499 			((struct tcp_rack *)tp->t_fb_ptr)->r_ctl.rc_rack_largest_cwnd = i_cwnd;
1500 	}
1501 	/*
1502 	 * Being idle is no differnt than the initial window. If the cc
1503 	 * clamps it down below the initial window raise it to the initial
1504 	 * window.
1505 	 */
1506 	if (tp->snd_cwnd < i_cwnd) {
1507 		tp->snd_cwnd = i_cwnd;
1508 	}
1509 }
1510 
1511 
1512 /*
1513  * Indicate whether this ack should be delayed.  We can delay the ack if
1514  * following conditions are met:
1515  *	- There is no delayed ack timer in progress.
1516  *	- Our last ack wasn't a 0-sized window. We never want to delay
1517  *	  the ack that opens up a 0-sized window.
1518  *	- LRO wasn't used for this segment. We make sure by checking that the
1519  *	  segment size is not larger than the MSS.
1520  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
1521  *	  connection.
1522  */
1523 #define DELAY_ACK(tp, tlen)			 \
1524 	(((tp->t_flags & TF_RXWIN0SENT) == 0) && \
1525 	((tp->t_flags & TF_DELACK) == 0) && 	 \
1526 	(tlen <= tp->t_maxseg) &&		 \
1527 	(tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
1528 
1529 static inline void
1530 rack_calc_rwin(struct socket *so, struct tcpcb *tp)
1531 {
1532 	int32_t win;
1533 
1534 	/*
1535 	 * Calculate amount of space in receive window, and then do TCP
1536 	 * input processing. Receive window is amount of space in rcv queue,
1537 	 * but not less than advertised window.
1538 	 */
1539 	win = sbspace(&so->so_rcv);
1540 	if (win < 0)
1541 		win = 0;
1542 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1543 }
1544 
1545 static void
1546 rack_do_drop(struct mbuf *m, struct tcpcb *tp)
1547 {
1548 	/*
1549 	 * Drop space held by incoming segment and return.
1550 	 */
1551 	if (tp != NULL)
1552 		INP_WUNLOCK(tp->t_inpcb);
1553 	if (m)
1554 		m_freem(m);
1555 }
1556 
1557 static void
1558 rack_do_dropwithreset(struct mbuf *m, struct tcpcb *tp, struct tcphdr *th, int32_t rstreason, int32_t tlen)
1559 {
1560 	if (tp != NULL) {
1561 		tcp_dropwithreset(m, th, tp, tlen, rstreason);
1562 		INP_WUNLOCK(tp->t_inpcb);
1563 	} else
1564 		tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1565 }
1566 
1567 /*
1568  * The value in ret_val informs the caller
1569  * if we dropped the tcb (and lock) or not.
1570  * 1 = we dropped it, 0 = the TCB is still locked
1571  * and valid.
1572  */
1573 static void
1574 rack_do_dropafterack(struct mbuf *m, struct tcpcb *tp, struct tcphdr *th, int32_t thflags, int32_t tlen, int32_t * ret_val)
1575 {
1576 	/*
1577 	 * Generate an ACK dropping incoming segment if it occupies sequence
1578 	 * space, where the ACK reflects our state.
1579 	 *
1580 	 * We can now skip the test for the RST flag since all paths to this
1581 	 * code happen after packets containing RST have been dropped.
1582 	 *
1583 	 * In the SYN-RECEIVED state, don't send an ACK unless the segment
1584 	 * we received passes the SYN-RECEIVED ACK test. If it fails send a
1585 	 * RST.  This breaks the loop in the "LAND" DoS attack, and also
1586 	 * prevents an ACK storm between two listening ports that have been
1587 	 * sent forged SYN segments, each with the source address of the
1588 	 * other.
1589 	 */
1590 	struct tcp_rack *rack;
1591 
1592 	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
1593 	    (SEQ_GT(tp->snd_una, th->th_ack) ||
1594 	    SEQ_GT(th->th_ack, tp->snd_max))) {
1595 		*ret_val = 1;
1596 		rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
1597 		return;
1598 	} else
1599 		*ret_val = 0;
1600 	rack = (struct tcp_rack *)tp->t_fb_ptr;
1601 	rack->r_wanted_output++;
1602 	tp->t_flags |= TF_ACKNOW;
1603 	if (m)
1604 		m_freem(m);
1605 }
1606 
1607 
1608 static int
1609 rack_process_rst(struct mbuf *m, struct tcphdr *th, struct socket *so, struct tcpcb *tp)
1610 {
1611 	/*
1612 	 * RFC5961 Section 3.2
1613 	 *
1614 	 * - RST drops connection only if SEG.SEQ == RCV.NXT. - If RST is in
1615 	 * window, we send challenge ACK.
1616 	 *
1617 	 * Note: to take into account delayed ACKs, we should test against
1618 	 * last_ack_sent instead of rcv_nxt. Note 2: we handle special case
1619 	 * of closed window, not covered by the RFC.
1620 	 */
1621 	int dropped = 0;
1622 
1623 	if ((SEQ_GEQ(th->th_seq, (tp->last_ack_sent - 1)) &&
1624 	    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
1625 	    (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
1626 
1627 		INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1628 		KASSERT(tp->t_state != TCPS_SYN_SENT,
1629 		    ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
1630 		    __func__, th, tp));
1631 
1632 		if (V_tcp_insecure_rst ||
1633 		    (tp->last_ack_sent == th->th_seq) ||
1634 		    (tp->rcv_nxt == th->th_seq) ||
1635 		    ((tp->last_ack_sent - 1) == th->th_seq)) {
1636 			TCPSTAT_INC(tcps_drops);
1637 			/* Drop the connection. */
1638 			switch (tp->t_state) {
1639 			case TCPS_SYN_RECEIVED:
1640 				so->so_error = ECONNREFUSED;
1641 				goto close;
1642 			case TCPS_ESTABLISHED:
1643 			case TCPS_FIN_WAIT_1:
1644 			case TCPS_FIN_WAIT_2:
1645 			case TCPS_CLOSE_WAIT:
1646 			case TCPS_CLOSING:
1647 			case TCPS_LAST_ACK:
1648 				so->so_error = ECONNRESET;
1649 		close:
1650 				tcp_state_change(tp, TCPS_CLOSED);
1651 				/* FALLTHROUGH */
1652 			default:
1653 				tp = tcp_close(tp);
1654 			}
1655 			dropped = 1;
1656 			rack_do_drop(m, tp);
1657 		} else {
1658 			TCPSTAT_INC(tcps_badrst);
1659 			/* Send challenge ACK. */
1660 			tcp_respond(tp, mtod(m, void *), th, m,
1661 			    tp->rcv_nxt, tp->snd_nxt, TH_ACK);
1662 			tp->last_ack_sent = tp->rcv_nxt;
1663 		}
1664 	} else {
1665 		m_freem(m);
1666 	}
1667 	return (dropped);
1668 }
1669 
1670 /*
1671  * The value in ret_val informs the caller
1672  * if we dropped the tcb (and lock) or not.
1673  * 1 = we dropped it, 0 = the TCB is still locked
1674  * and valid.
1675  */
1676 static void
1677 rack_challenge_ack(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp, int32_t * ret_val)
1678 {
1679 	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1680 
1681 	TCPSTAT_INC(tcps_badsyn);
1682 	if (V_tcp_insecure_syn &&
1683 	    SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1684 	    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1685 		tp = tcp_drop(tp, ECONNRESET);
1686 		*ret_val = 1;
1687 		rack_do_drop(m, tp);
1688 	} else {
1689 		/* Send challenge ACK. */
1690 		tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
1691 		    tp->snd_nxt, TH_ACK);
1692 		tp->last_ack_sent = tp->rcv_nxt;
1693 		m = NULL;
1694 		*ret_val = 0;
1695 		rack_do_drop(m, NULL);
1696 	}
1697 }
1698 
1699 /*
1700  * rack_ts_check returns 1 for you should not proceed. It places
1701  * in ret_val what should be returned 1/0 by the caller. The 1 indicates
1702  * that the TCB is unlocked and probably dropped. The 0 indicates the
1703  * TCB is still valid and locked.
1704  */
1705 static int
1706 rack_ts_check(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp, int32_t tlen, int32_t thflags, int32_t * ret_val)
1707 {
1708 
1709 	/* Check to see if ts_recent is over 24 days old.  */
1710 	if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
1711 		/*
1712 		 * Invalidate ts_recent.  If this segment updates ts_recent,
1713 		 * the age will be reset later and ts_recent will get a
1714 		 * valid value.  If it does not, setting ts_recent to zero
1715 		 * will at least satisfy the requirement that zero be placed
1716 		 * in the timestamp echo reply when ts_recent isn't valid.
1717 		 * The age isn't reset until we get a valid ts_recent
1718 		 * because we don't want out-of-order segments to be dropped
1719 		 * when ts_recent is old.
1720 		 */
1721 		tp->ts_recent = 0;
1722 	} else {
1723 		TCPSTAT_INC(tcps_rcvduppack);
1724 		TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
1725 		TCPSTAT_INC(tcps_pawsdrop);
1726 		*ret_val = 0;
1727 		if (tlen) {
1728 			rack_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
1729 		} else {
1730 			rack_do_drop(m, NULL);
1731 		}
1732 		return (1);
1733 	}
1734 	return (0);
1735 }
1736 
1737 /*
1738  * rack_drop_checks returns 1 for you should not proceed. It places
1739  * in ret_val what should be returned 1/0 by the caller. The 1 indicates
1740  * that the TCB is unlocked and probably dropped. The 0 indicates the
1741  * TCB is still valid and locked.
1742  */
1743 static int
1744 rack_drop_checks(struct tcpopt *to, struct mbuf *m, struct tcphdr *th, struct tcpcb *tp, int32_t * tlenp, int32_t * thf, int32_t * drop_hdrlen, int32_t * ret_val)
1745 {
1746 	int32_t todrop;
1747 	int32_t thflags;
1748 	int32_t tlen;
1749 
1750 	thflags = *thf;
1751 	tlen = *tlenp;
1752 	todrop = tp->rcv_nxt - th->th_seq;
1753 	if (todrop > 0) {
1754 		if (thflags & TH_SYN) {
1755 			thflags &= ~TH_SYN;
1756 			th->th_seq++;
1757 			if (th->th_urp > 1)
1758 				th->th_urp--;
1759 			else
1760 				thflags &= ~TH_URG;
1761 			todrop--;
1762 		}
1763 		/*
1764 		 * Following if statement from Stevens, vol. 2, p. 960.
1765 		 */
1766 		if (todrop > tlen
1767 		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1768 			/*
1769 			 * Any valid FIN must be to the left of the window.
1770 			 * At this point the FIN must be a duplicate or out
1771 			 * of sequence; drop it.
1772 			 */
1773 			thflags &= ~TH_FIN;
1774 			/*
1775 			 * Send an ACK to resynchronize and drop any data.
1776 			 * But keep on processing for RST or ACK.
1777 			 */
1778 			tp->t_flags |= TF_ACKNOW;
1779 			todrop = tlen;
1780 			TCPSTAT_INC(tcps_rcvduppack);
1781 			TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
1782 		} else {
1783 			TCPSTAT_INC(tcps_rcvpartduppack);
1784 			TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
1785 		}
1786 		if (tp->t_flags & TF_SACK_PERMIT) {
1787 			/*
1788 			 * record the left, to-be-dropped edge of data
1789 			 * here, for use as dsack block further down
1790 			 */
1791 			tcp_update_sack_list(tp, th->th_seq,
1792 			    th->th_seq + todrop);
1793 		}
1794 		*drop_hdrlen += todrop;	/* drop from the top afterwards */
1795 		th->th_seq += todrop;
1796 		tlen -= todrop;
1797 		if (th->th_urp > todrop)
1798 			th->th_urp -= todrop;
1799 		else {
1800 			thflags &= ~TH_URG;
1801 			th->th_urp = 0;
1802 		}
1803 	}
1804 	/*
1805 	 * If segment ends after window, drop trailing data (and PUSH and
1806 	 * FIN); if nothing left, just ACK.
1807 	 */
1808 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1809 	if (todrop > 0) {
1810 		TCPSTAT_INC(tcps_rcvpackafterwin);
1811 		if (todrop >= tlen) {
1812 			TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
1813 			/*
1814 			 * If window is closed can only take segments at
1815 			 * window edge, and have to drop data and PUSH from
1816 			 * incoming segments.  Continue processing, but
1817 			 * remember to ack.  Otherwise, drop segment and
1818 			 * ack.
1819 			 */
1820 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1821 				tp->t_flags |= TF_ACKNOW;
1822 				TCPSTAT_INC(tcps_rcvwinprobe);
1823 			} else {
1824 				rack_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
1825 				return (1);
1826 			}
1827 		} else
1828 			TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
1829 		m_adj(m, -todrop);
1830 		tlen -= todrop;
1831 		thflags &= ~(TH_PUSH | TH_FIN);
1832 	}
1833 	*thf = thflags;
1834 	*tlenp = tlen;
1835 	return (0);
1836 }
1837 
1838 static struct rack_sendmap *
1839 rack_find_lowest_rsm(struct tcp_rack *rack)
1840 {
1841 	struct rack_sendmap *rsm;
1842 
1843 	/*
1844 	 * Walk the time-order transmitted list looking for an rsm that is
1845 	 * not acked. This will be the one that was sent the longest time
1846 	 * ago that is still outstanding.
1847 	 */
1848 	TAILQ_FOREACH(rsm, &rack->r_ctl.rc_tmap, r_tnext) {
1849 		if (rsm->r_flags & RACK_ACKED) {
1850 			continue;
1851 		}
1852 		goto finish;
1853 	}
1854 finish:
1855 	return (rsm);
1856 }
1857 
1858 static struct rack_sendmap *
1859 rack_find_high_nonack(struct tcp_rack *rack, struct rack_sendmap *rsm)
1860 {
1861 	struct rack_sendmap *prsm;
1862 
1863 	/*
1864 	 * Walk the sequence order list backward until we hit and arrive at
1865 	 * the highest seq not acked. In theory when this is called it
1866 	 * should be the last segment (which it was not).
1867 	 */
1868 	counter_u64_add(rack_find_high, 1);
1869 	prsm = rsm;
1870 	TAILQ_FOREACH_REVERSE_FROM(prsm, &rack->r_ctl.rc_map, rack_head, r_next) {
1871 		if (prsm->r_flags & (RACK_ACKED | RACK_HAS_FIN)) {
1872 			continue;
1873 		}
1874 		return (prsm);
1875 	}
1876 	return (NULL);
1877 }
1878 
1879 
1880 static uint32_t
1881 rack_calc_thresh_rack(struct tcp_rack *rack, uint32_t srtt, uint32_t cts)
1882 {
1883 	int32_t lro;
1884 	uint32_t thresh;
1885 
1886 	/*
1887 	 * lro is the flag we use to determine if we have seen reordering.
1888 	 * If it gets set we have seen reordering. The reorder logic either
1889 	 * works in one of two ways:
1890 	 *
1891 	 * If reorder-fade is configured, then we track the last time we saw
1892 	 * re-ordering occur. If we reach the point where enough time as
1893 	 * passed we no longer consider reordering has occuring.
1894 	 *
1895 	 * Or if reorder-face is 0, then once we see reordering we consider
1896 	 * the connection to alway be subject to reordering and just set lro
1897 	 * to 1.
1898 	 *
1899 	 * In the end if lro is non-zero we add the extra time for
1900 	 * reordering in.
1901 	 */
1902 	if (srtt == 0)
1903 		srtt = 1;
1904 	if (rack->r_ctl.rc_reorder_ts) {
1905 		if (rack->r_ctl.rc_reorder_fade) {
1906 			if (SEQ_GEQ(cts, rack->r_ctl.rc_reorder_ts)) {
1907 				lro = cts - rack->r_ctl.rc_reorder_ts;
1908 				if (lro == 0) {
1909 					/*
1910 					 * No time as passed since the last
1911 					 * reorder, mark it as reordering.
1912 					 */
1913 					lro = 1;
1914 				}
1915 			} else {
1916 				/* Negative time? */
1917 				lro = 0;
1918 			}
1919 			if (lro > rack->r_ctl.rc_reorder_fade) {
1920 				/* Turn off reordering seen too */
1921 				rack->r_ctl.rc_reorder_ts = 0;
1922 				lro = 0;
1923 			}
1924 		} else {
1925 			/* Reodering does not fade */
1926 			lro = 1;
1927 		}
1928 	} else {
1929 		lro = 0;
1930 	}
1931 	thresh = srtt + rack->r_ctl.rc_pkt_delay;
1932 	if (lro) {
1933 		/* It must be set, if not you get 1/4 rtt */
1934 		if (rack->r_ctl.rc_reorder_shift)
1935 			thresh += (srtt >> rack->r_ctl.rc_reorder_shift);
1936 		else
1937 			thresh += (srtt >> 2);
1938 	} else {
1939 		thresh += 1;
1940 	}
1941 	/* We don't let the rack timeout be above a RTO */
1942 
1943 	if (thresh > TICKS_2_MSEC(rack->rc_tp->t_rxtcur)) {
1944 		thresh = TICKS_2_MSEC(rack->rc_tp->t_rxtcur);
1945 	}
1946 	/* And we don't want it above the RTO max either */
1947 	if (thresh > rack_rto_max) {
1948 		thresh = rack_rto_max;
1949 	}
1950 	return (thresh);
1951 }
1952 
1953 static uint32_t
1954 rack_calc_thresh_tlp(struct tcpcb *tp, struct tcp_rack *rack,
1955 		     struct rack_sendmap *rsm, uint32_t srtt)
1956 {
1957 	struct rack_sendmap *prsm;
1958 	uint32_t thresh, len;
1959 	int maxseg;
1960 
1961 	if (srtt == 0)
1962 		srtt = 1;
1963 	if (rack->r_ctl.rc_tlp_threshold)
1964 		thresh = srtt + (srtt / rack->r_ctl.rc_tlp_threshold);
1965 	else
1966 		thresh = (srtt * 2);
1967 
1968 	/* Get the previous sent packet, if any  */
1969 	maxseg = tcp_maxseg(tp);
1970 	counter_u64_add(rack_enter_tlp_calc, 1);
1971 	len = rsm->r_end - rsm->r_start;
1972 	if (rack->rack_tlp_threshold_use == TLP_USE_ID) {
1973 		/* Exactly like the ID */
1974 		if (((tp->snd_max - tp->snd_una) - rack->r_ctl.rc_sacked + rack->r_ctl.rc_holes_rxt) <= maxseg) {
1975 			uint32_t alt_thresh;
1976 			/*
1977 			 * Compensate for delayed-ack with the d-ack time.
1978 			 */
1979 			counter_u64_add(rack_used_tlpmethod, 1);
1980 			alt_thresh = srtt + (srtt / 2) + rack_delayed_ack_time;
1981 			if (alt_thresh > thresh)
1982 				thresh = alt_thresh;
1983 		}
1984 	} else if (rack->rack_tlp_threshold_use == TLP_USE_TWO_ONE) {
1985 		/* 2.1 behavior */
1986 		prsm = TAILQ_PREV(rsm, rack_head, r_tnext);
1987 		if (prsm && (len <= maxseg)) {
1988 			/*
1989 			 * Two packets outstanding, thresh should be (2*srtt) +
1990 			 * possible inter-packet delay (if any).
1991 			 */
1992 			uint32_t inter_gap = 0;
1993 			int idx, nidx;
1994 
1995 			counter_u64_add(rack_used_tlpmethod, 1);
1996 			idx = rsm->r_rtr_cnt - 1;
1997 			nidx = prsm->r_rtr_cnt - 1;
1998 			if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
1999 				/* Yes it was sent later (or at the same time) */
2000 				inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
2001 			}
2002 			thresh += inter_gap;
2003 		} else 	if (len <= maxseg) {
2004 			/*
2005 			 * Possibly compensate for delayed-ack.
2006 			 */
2007 			uint32_t alt_thresh;
2008 
2009 			counter_u64_add(rack_used_tlpmethod2, 1);
2010 			alt_thresh = srtt + (srtt / 2) + rack_delayed_ack_time;
2011 			if (alt_thresh > thresh)
2012 				thresh = alt_thresh;
2013 		}
2014 	} else if (rack->rack_tlp_threshold_use == TLP_USE_TWO_TWO) {
2015 		/* 2.2 behavior */
2016 		if (len <= maxseg) {
2017 			uint32_t alt_thresh;
2018 			/*
2019 			 * Compensate for delayed-ack with the d-ack time.
2020 			 */
2021 			counter_u64_add(rack_used_tlpmethod, 1);
2022 			alt_thresh = srtt + (srtt / 2) + rack_delayed_ack_time;
2023 			if (alt_thresh > thresh)
2024 				thresh = alt_thresh;
2025 		}
2026 	}
2027  	/* Not above an RTO */
2028 	if (thresh > TICKS_2_MSEC(tp->t_rxtcur)) {
2029 		thresh = TICKS_2_MSEC(tp->t_rxtcur);
2030 	}
2031 	/* Not above a RTO max */
2032 	if (thresh > rack_rto_max) {
2033 		thresh = rack_rto_max;
2034 	}
2035 	/* Apply user supplied min TLP */
2036 	if (thresh < rack_tlp_min) {
2037 		thresh = rack_tlp_min;
2038 	}
2039 	return (thresh);
2040 }
2041 
2042 static struct rack_sendmap *
2043 rack_check_recovery_mode(struct tcpcb *tp, uint32_t tsused)
2044 {
2045 	/*
2046 	 * Check to see that we don't need to fall into recovery. We will
2047 	 * need to do so if our oldest transmit is past the time we should
2048 	 * have had an ack.
2049 	 */
2050 	struct tcp_rack *rack;
2051 	struct rack_sendmap *rsm;
2052 	int32_t idx;
2053 	uint32_t srtt_cur, srtt, thresh;
2054 
2055 	rack = (struct tcp_rack *)tp->t_fb_ptr;
2056 	if (TAILQ_EMPTY(&rack->r_ctl.rc_map)) {
2057 		return (NULL);
2058 	}
2059 	srtt_cur = tp->t_srtt >> TCP_RTT_SHIFT;
2060 	srtt = TICKS_2_MSEC(srtt_cur);
2061 	if (rack->rc_rack_rtt && (srtt > rack->rc_rack_rtt))
2062 		srtt = rack->rc_rack_rtt;
2063 
2064 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
2065 	if (rsm == NULL)
2066 		return (NULL);
2067 
2068 	if (rsm->r_flags & RACK_ACKED) {
2069 		rsm = rack_find_lowest_rsm(rack);
2070 		if (rsm == NULL)
2071 			return (NULL);
2072 	}
2073 	idx = rsm->r_rtr_cnt - 1;
2074 	thresh = rack_calc_thresh_rack(rack, srtt, tsused);
2075 	if (tsused < rsm->r_tim_lastsent[idx]) {
2076 		return (NULL);
2077 	}
2078 	if ((tsused - rsm->r_tim_lastsent[idx]) < thresh) {
2079 		return (NULL);
2080 	}
2081 	/* Ok if we reach here we are over-due */
2082 	rack->r_ctl.rc_rsm_start = rsm->r_start;
2083 	rack->r_ctl.rc_cwnd_at = tp->snd_cwnd;
2084 	rack->r_ctl.rc_ssthresh_at = tp->snd_ssthresh;
2085 	rack_cong_signal(tp, NULL, CC_NDUPACK);
2086 	return (rsm);
2087 }
2088 
2089 static uint32_t
2090 rack_get_persists_timer_val(struct tcpcb *tp, struct tcp_rack *rack)
2091 {
2092 	int32_t t;
2093 	int32_t tt;
2094 	uint32_t ret_val;
2095 
2096 	t = TICKS_2_MSEC((tp->t_srtt >> TCP_RTT_SHIFT) + ((tp->t_rttvar * 4) >> TCP_RTT_SHIFT));
2097 	TCPT_RANGESET(tt, t * tcp_backoff[tp->t_rxtshift],
2098 	    tcp_persmin, tcp_persmax);
2099 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
2100 		tp->t_rxtshift++;
2101 	rack->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
2102 	ret_val = (uint32_t)tt;
2103 	return (ret_val);
2104 }
2105 
2106 static uint32_t
2107 rack_timer_start(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
2108 {
2109 	/*
2110 	 * Start the FR timer, we do this based on getting the first one in
2111 	 * the rc_tmap. Note that if its NULL we must stop the timer. in all
2112 	 * events we need to stop the running timer (if its running) before
2113 	 * starting the new one.
2114 	 */
2115 	uint32_t thresh, exp, to, srtt, time_since_sent;
2116 	uint32_t srtt_cur;
2117 	int32_t idx;
2118 	int32_t is_tlp_timer = 0;
2119 	struct rack_sendmap *rsm;
2120 
2121 	if (rack->t_timers_stopped) {
2122 		/* All timers have been stopped none are to run */
2123 		return (0);
2124 	}
2125 	if (rack->rc_in_persist) {
2126 		/* We can't start any timer in persists */
2127 		return (rack_get_persists_timer_val(tp, rack));
2128 	}
2129 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
2130 	if (rsm == NULL) {
2131 		/* Nothing on the send map */
2132 activate_rxt:
2133 		if (SEQ_LT(tp->snd_una, tp->snd_max) || sbavail(&(tp->t_inpcb->inp_socket->so_snd))) {
2134 			rack->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
2135 			to = TICKS_2_MSEC(tp->t_rxtcur);
2136 			if (to == 0)
2137 				to = 1;
2138 			return (to);
2139 		}
2140 		return (0);
2141 	}
2142 	if (rsm->r_flags & RACK_ACKED) {
2143 		rsm = rack_find_lowest_rsm(rack);
2144 		if (rsm == NULL) {
2145 			/* No lowest? */
2146 			goto activate_rxt;
2147 		}
2148 	}
2149 	/* Convert from ms to usecs */
2150 	if (rsm->r_flags & RACK_SACK_PASSED) {
2151 		if ((tp->t_flags & TF_SENTFIN) &&
2152 		    ((tp->snd_max - tp->snd_una) == 1) &&
2153 		    (rsm->r_flags & RACK_HAS_FIN)) {
2154 			/*
2155 			 * We don't start a rack timer if all we have is a
2156 			 * FIN outstanding.
2157 			 */
2158 			goto activate_rxt;
2159 		}
2160 		if (tp->t_srtt) {
2161 			srtt_cur = (tp->t_srtt >> TCP_RTT_SHIFT);
2162 			srtt = TICKS_2_MSEC(srtt_cur);
2163 		} else
2164 			srtt = RACK_INITIAL_RTO;
2165 
2166 		thresh = rack_calc_thresh_rack(rack, srtt, cts);
2167 		idx = rsm->r_rtr_cnt - 1;
2168 		exp = rsm->r_tim_lastsent[idx] + thresh;
2169 		if (SEQ_GEQ(exp, cts)) {
2170 			to = exp - cts;
2171 			if (to < rack->r_ctl.rc_min_to) {
2172 				to = rack->r_ctl.rc_min_to;
2173 			}
2174 		} else {
2175 			to = rack->r_ctl.rc_min_to;
2176 		}
2177 	} else {
2178 		/* Ok we need to do a TLP not RACK */
2179 		if ((rack->rc_tlp_in_progress != 0) ||
2180 		    (rack->r_ctl.rc_tlp_rtx_out != 0)) {
2181 			/*
2182 			 * The previous send was a TLP or a tlp_rtx is in
2183 			 * process.
2184 			 */
2185 			goto activate_rxt;
2186 		}
2187 		if ((tp->snd_max - tp->snd_una) > tp->snd_wnd) {
2188 			/*
2189 			 * Peer collapsed rwnd, don't do TLP.
2190 			 */
2191 			goto activate_rxt;
2192 		}
2193 		rsm = TAILQ_LAST_FAST(&rack->r_ctl.rc_tmap, rack_sendmap, r_tnext);
2194 		if (rsm == NULL) {
2195 			/* We found no rsm to TLP with. */
2196 			goto activate_rxt;
2197 		}
2198 		if (rsm->r_flags & RACK_HAS_FIN) {
2199 			/* If its a FIN we dont do TLP */
2200 			rsm = NULL;
2201 			goto activate_rxt;
2202 		}
2203 		idx = rsm->r_rtr_cnt - 1;
2204 		if (TSTMP_GT(cts,  rsm->r_tim_lastsent[idx]))
2205 			time_since_sent = cts - rsm->r_tim_lastsent[idx];
2206 		else
2207 			time_since_sent = 0;
2208 		is_tlp_timer = 1;
2209 		if (tp->t_srtt) {
2210 			srtt_cur = (tp->t_srtt >> TCP_RTT_SHIFT);
2211 			srtt = TICKS_2_MSEC(srtt_cur);
2212 		} else
2213 			srtt = RACK_INITIAL_RTO;
2214 		thresh = rack_calc_thresh_tlp(tp, rack, rsm, srtt);
2215 		if (thresh > time_since_sent)
2216 			to = thresh - time_since_sent;
2217 		else
2218 			to = rack->r_ctl.rc_min_to;
2219 		if (to > TCPTV_REXMTMAX) {
2220 			/*
2221 			 * If the TLP time works out to larger than the max
2222 			 * RTO lets not do TLP.. just RTO.
2223 			 */
2224 			goto activate_rxt;
2225 		}
2226 		if (rsm->r_start != rack->r_ctl.rc_last_tlp_seq) {
2227 			/*
2228 			 * The tail is no longer the last one I did a probe
2229 			 * on
2230 			 */
2231 			rack->r_ctl.rc_tlp_seg_send_cnt = 0;
2232 			rack->r_ctl.rc_last_tlp_seq = rsm->r_start;
2233 		}
2234 	}
2235 	if (is_tlp_timer == 0) {
2236 		rack->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
2237 	} else {
2238 		if ((rack->r_ctl.rc_tlp_send_cnt > rack_tlp_max_resend) ||
2239 		    (rack->r_ctl.rc_tlp_seg_send_cnt > rack_tlp_max_resend)) {
2240 			/*
2241 			 * We have exceeded how many times we can retran the
2242 			 * current TLP timer, switch to the RTO timer.
2243 			 */
2244 			goto activate_rxt;
2245 		} else {
2246 			rack->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
2247 		}
2248 	}
2249 	if (to == 0)
2250 		to = 1;
2251 	return (to);
2252 }
2253 
2254 static void
2255 rack_enter_persist(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
2256 {
2257 	if (rack->rc_in_persist == 0) {
2258 		if (((tp->t_flags & TF_SENTFIN) == 0) &&
2259 		    (tp->snd_max - tp->snd_una) >= sbavail(&rack->rc_inp->inp_socket->so_snd))
2260 			/* Must need to send more data to enter persist */
2261 			return;
2262 		rack->r_ctl.rc_went_idle_time = cts;
2263 		rack_timer_cancel(tp, rack, cts, __LINE__);
2264 		tp->t_rxtshift = 0;
2265 		rack->rc_in_persist = 1;
2266 	}
2267 }
2268 
2269 static void
2270 rack_exit_persist(struct tcpcb *tp, struct tcp_rack *rack)
2271 {
2272 	if (rack->rc_inp->inp_in_hpts)  {
2273 		tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
2274 		rack->r_ctl.rc_hpts_flags  = 0;
2275 	}
2276 	rack->rc_in_persist = 0;
2277 	rack->r_ctl.rc_went_idle_time = 0;
2278 	tp->t_flags &= ~TF_FORCEDATA;
2279 	tp->t_rxtshift = 0;
2280 }
2281 
2282 static void
2283 rack_start_hpts_timer(struct tcp_rack *rack, struct tcpcb *tp, uint32_t cts, int32_t line,
2284     int32_t slot, uint32_t tot_len_this_send, int32_t frm_out_sbavail)
2285 {
2286 	struct inpcb *inp;
2287 	uint32_t delayed_ack = 0;
2288 	uint32_t hpts_timeout;
2289 	uint8_t stopped;
2290 	uint32_t left = 0;
2291 
2292 	inp = tp->t_inpcb;
2293 	if (inp->inp_in_hpts) {
2294 		/* A previous call is already set up */
2295 		return;
2296 	}
2297 
2298 	if ((tp->t_state == TCPS_CLOSED) ||
2299 	    (tp->t_state == TCPS_LISTEN)) {
2300 		return;
2301 	}
2302 	stopped = rack->rc_tmr_stopped;
2303 	if (stopped && TSTMP_GT(rack->r_ctl.rc_timer_exp, cts)) {
2304 		left = rack->r_ctl.rc_timer_exp - cts;
2305 	}
2306 	rack->r_ctl.rc_timer_exp = 0;
2307 	if (rack->rc_inp->inp_in_hpts == 0) {
2308 		rack->r_ctl.rc_hpts_flags = 0;
2309 	}
2310 	if (slot) {
2311 		/* We are hptsi too */
2312 		rack->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
2313 	} else if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
2314 		/*
2315 		 * We are still left on the hpts when the to goes
2316 		 * it will be for output.
2317 		 */
2318 		if (TSTMP_GT(rack->r_ctl.rc_last_output_to, cts))
2319 			slot = rack->r_ctl.rc_last_output_to - cts;
2320 		else
2321 			slot = 1;
2322 	}
2323 	if ((tp->snd_wnd == 0) && TCPS_HAVEESTABLISHED(tp->t_state)) {
2324 		/* No send window.. we must enter persist */
2325 		rack_enter_persist(tp, rack, cts);
2326 	} else if ((frm_out_sbavail &&
2327 		    (frm_out_sbavail > (tp->snd_max - tp->snd_una)) &&
2328 		    (tp->snd_wnd < tp->t_maxseg)) &&
2329 	    TCPS_HAVEESTABLISHED(tp->t_state)) {
2330 		/*
2331 		 * If we have no window or we can't send a segment (and have
2332 		 * data to send.. we cheat here and frm_out_sbavail is
2333 		 * passed in with the sbavail(sb) only from bbr_output) and
2334 		 * we are established, then we must enter persits (if not
2335 		 * already in persits).
2336 		 */
2337 		rack_enter_persist(tp, rack, cts);
2338 	}
2339 	hpts_timeout = rack_timer_start(tp, rack, cts);
2340 	if (tp->t_flags & TF_DELACK) {
2341 		delayed_ack = tcp_delacktime;
2342 		rack->r_ctl.rc_hpts_flags |= PACE_TMR_DELACK;
2343 	}
2344 	if (delayed_ack && ((hpts_timeout == 0) ||
2345 			    (delayed_ack < hpts_timeout)))
2346 		hpts_timeout = delayed_ack;
2347 	else
2348 		rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
2349 	/*
2350 	 * If no timers are going to run and we will fall off the hptsi
2351 	 * wheel, we resort to a keep-alive timer if its configured.
2352 	 */
2353 	if ((hpts_timeout == 0) &&
2354 	    (slot == 0)) {
2355 		if ((tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
2356 		    (tp->t_state <= TCPS_CLOSING)) {
2357 			/*
2358 			 * Ok we have no timer (persists, rack, tlp, rxt  or
2359 			 * del-ack), we don't have segments being paced. So
2360 			 * all that is left is the keepalive timer.
2361 			 */
2362 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
2363 				/* Get the established keep-alive time */
2364 				hpts_timeout = TP_KEEPIDLE(tp);
2365 			} else {
2366 				/* Get the initial setup keep-alive time */
2367 				hpts_timeout = TP_KEEPINIT(tp);
2368 			}
2369 			rack->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
2370 		}
2371 	}
2372 	if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
2373 	    (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
2374 		/*
2375 		 * RACK, TLP, persists and RXT timers all are restartable
2376 		 * based on actions input .. i.e we received a packet (ack
2377 		 * or sack) and that changes things (rw, or snd_una etc).
2378 		 * Thus we can restart them with a new value. For
2379 		 * keep-alive, delayed_ack we keep track of what was left
2380 		 * and restart the timer with a smaller value.
2381 		 */
2382 		if (left < hpts_timeout)
2383 			hpts_timeout = left;
2384 	}
2385 	if (hpts_timeout) {
2386 		/*
2387 		 * Hack alert for now we can't time-out over 2,147,483
2388 		 * seconds (a bit more than 596 hours), which is probably ok
2389 		 * :).
2390 		 */
2391 		if (hpts_timeout > 0x7ffffffe)
2392 			hpts_timeout = 0x7ffffffe;
2393 		rack->r_ctl.rc_timer_exp = cts + hpts_timeout;
2394 	}
2395 	if (slot) {
2396 		rack->r_ctl.rc_last_output_to = cts + slot;
2397 		if ((hpts_timeout == 0) || (hpts_timeout > slot)) {
2398 			if (rack->rc_inp->inp_in_hpts == 0)
2399 				tcp_hpts_insert(tp->t_inpcb, HPTS_MS_TO_SLOTS(slot));
2400 			rack_log_to_start(rack, cts, hpts_timeout, slot, 1);
2401 		} else {
2402 			/*
2403 			 * Arrange for the hpts to kick back in after the
2404 			 * t-o if the t-o does not cause a send.
2405 			 */
2406 			if (rack->rc_inp->inp_in_hpts == 0)
2407 				tcp_hpts_insert(tp->t_inpcb, HPTS_MS_TO_SLOTS(hpts_timeout));
2408 			rack_log_to_start(rack, cts, hpts_timeout, slot, 0);
2409 		}
2410 	} else if (hpts_timeout) {
2411 		if (rack->rc_inp->inp_in_hpts == 0)
2412 			tcp_hpts_insert(tp->t_inpcb, HPTS_MS_TO_SLOTS(hpts_timeout));
2413 		rack_log_to_start(rack, cts, hpts_timeout, slot, 0);
2414 	} else {
2415 		/* No timer starting */
2416 #ifdef INVARIANTS
2417 		if (SEQ_GT(tp->snd_max, tp->snd_una)) {
2418 			panic("tp:%p rack:%p tlts:%d cts:%u slot:%u pto:%u -- no timer started?",
2419 			    tp, rack, tot_len_this_send, cts, slot, hpts_timeout);
2420 		}
2421 #endif
2422 	}
2423 	rack->rc_tmr_stopped = 0;
2424 	if (slot)
2425 		rack_log_type_bbrsnd(rack, tot_len_this_send, slot, cts);
2426 }
2427 
2428 /*
2429  * RACK Timer, here we simply do logging and house keeping.
2430  * the normal rack_output() function will call the
2431  * appropriate thing to check if we need to do a RACK retransmit.
2432  * We return 1, saying don't proceed with rack_output only
2433  * when all timers have been stopped (destroyed PCB?).
2434  */
2435 static int
2436 rack_timeout_rack(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
2437 {
2438 	/*
2439 	 * This timer simply provides an internal trigger to send out data.
2440 	 * The check_recovery_mode call will see if there are needed
2441 	 * retransmissions, if so we will enter fast-recovery. The output
2442 	 * call may or may not do the same thing depending on sysctl
2443 	 * settings.
2444 	 */
2445 	struct rack_sendmap *rsm;
2446 	int32_t recovery;
2447 
2448 	if (tp->t_timers->tt_flags & TT_STOPPED) {
2449 		return (1);
2450 	}
2451 	if (TSTMP_LT(cts, rack->r_ctl.rc_timer_exp)) {
2452 		/* Its not time yet */
2453 		return (0);
2454 	}
2455 	rack_log_to_event(rack, RACK_TO_FRM_RACK);
2456 	recovery = IN_RECOVERY(tp->t_flags);
2457 	counter_u64_add(rack_to_tot, 1);
2458 	if (rack->r_state && (rack->r_state != tp->t_state))
2459 		rack_set_state(tp, rack);
2460 	rsm = rack_check_recovery_mode(tp, cts);
2461 	if (rsm) {
2462 		uint32_t rtt;
2463 
2464 		rtt = rack->rc_rack_rtt;
2465 		if (rtt == 0)
2466 			rtt = 1;
2467 		if ((recovery == 0) &&
2468 		    (rack->r_ctl.rc_prr_sndcnt < tp->t_maxseg)) {
2469 			/*
2470 			 * The rack-timeout that enter's us into recovery
2471 			 * will force out one MSS and set us up so that we
2472 			 * can do one more send in 2*rtt (transitioning the
2473 			 * rack timeout into a rack-tlp).
2474 			 */
2475 			rack->r_ctl.rc_prr_sndcnt = tp->t_maxseg;
2476 		} else if ((rack->r_ctl.rc_prr_sndcnt < tp->t_maxseg) &&
2477 		    ((rsm->r_end - rsm->r_start) > rack->r_ctl.rc_prr_sndcnt)) {
2478 			/*
2479 			 * When a rack timer goes, we have to send at
2480 			 * least one segment. They will be paced a min of 1ms
2481 			 * apart via the next rack timer (or further
2482 			 * if the rack timer dictates it).
2483 			 */
2484 			rack->r_ctl.rc_prr_sndcnt = tp->t_maxseg;
2485 		}
2486 	} else {
2487 		/* This is a case that should happen rarely if ever */
2488 		counter_u64_add(rack_tlp_does_nada, 1);
2489 #ifdef TCP_BLACKBOX
2490 		tcp_log_dump_tp_logbuf(tp, "nada counter trips", M_NOWAIT, true);
2491 #endif
2492 		rack->r_ctl.rc_resend = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
2493 	}
2494 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
2495 	return (0);
2496 }
2497 
2498 static struct rack_sendmap *
2499 rack_merge_rsm(struct tcp_rack *rack,
2500 	       struct rack_sendmap *l_rsm,
2501 	       struct rack_sendmap *r_rsm)
2502 {
2503 	/*
2504 	 * We are merging two ack'd RSM's,
2505 	 * the l_rsm is on the left (lower seq
2506 	 * values) and the r_rsm is on the right
2507 	 * (higher seq value). The simplest way
2508 	 * to merge these is to move the right
2509 	 * one into the left. I don't think there
2510 	 * is any reason we need to try to find
2511 	 * the oldest (or last oldest retransmitted).
2512 	 */
2513 	l_rsm->r_end = r_rsm->r_end;
2514 	if (r_rsm->r_rtr_bytes)
2515 		l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
2516 	if (r_rsm->r_in_tmap) {
2517 		/* This really should not happen */
2518 		TAILQ_REMOVE(&rack->r_ctl.rc_tmap, r_rsm, r_tnext);
2519 	}
2520 	/* Now the flags */
2521 	if (r_rsm->r_flags & RACK_HAS_FIN)
2522 		l_rsm->r_flags |= RACK_HAS_FIN;
2523 	if (r_rsm->r_flags & RACK_TLP)
2524 		l_rsm->r_flags |= RACK_TLP;
2525 	TAILQ_REMOVE(&rack->r_ctl.rc_map, r_rsm, r_next);
2526 	if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
2527 		/* Transfer the split limit to the map we free */
2528 		r_rsm->r_limit_type = l_rsm->r_limit_type;
2529 		l_rsm->r_limit_type = 0;
2530 	}
2531 	rack_free(rack, r_rsm);
2532 	return(l_rsm);
2533 }
2534 
2535 /*
2536  * TLP Timer, here we simply setup what segment we want to
2537  * have the TLP expire on, the normal rack_output() will then
2538  * send it out.
2539  *
2540  * We return 1, saying don't proceed with rack_output only
2541  * when all timers have been stopped (destroyed PCB?).
2542  */
2543 static int
2544 rack_timeout_tlp(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
2545 {
2546 	/*
2547 	 * Tail Loss Probe.
2548 	 */
2549 	struct rack_sendmap *rsm = NULL;
2550 	struct socket *so;
2551 	uint32_t amm, old_prr_snd = 0;
2552 	uint32_t out, avail;
2553 
2554 	if (tp->t_timers->tt_flags & TT_STOPPED) {
2555 		return (1);
2556 	}
2557 	if (TSTMP_LT(cts, rack->r_ctl.rc_timer_exp)) {
2558 		/* Its not time yet */
2559 		return (0);
2560 	}
2561 	if (rack_progress_timeout_check(tp)) {
2562 		tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
2563 		return (1);
2564 	}
2565 	/*
2566 	 * A TLP timer has expired. We have been idle for 2 rtts. So we now
2567 	 * need to figure out how to force a full MSS segment out.
2568 	 */
2569 	rack_log_to_event(rack, RACK_TO_FRM_TLP);
2570 	counter_u64_add(rack_tlp_tot, 1);
2571 	if (rack->r_state && (rack->r_state != tp->t_state))
2572 		rack_set_state(tp, rack);
2573 	so = tp->t_inpcb->inp_socket;
2574 	avail = sbavail(&so->so_snd);
2575 	out = tp->snd_max - tp->snd_una;
2576 	rack->rc_timer_up = 1;
2577 	/*
2578 	 * If we are in recovery we can jazz out a segment if new data is
2579 	 * present simply by setting rc_prr_sndcnt to a segment.
2580 	 */
2581 	if ((avail > out) &&
2582 	    ((rack_always_send_oldest == 0) || (TAILQ_EMPTY(&rack->r_ctl.rc_tmap)))) {
2583 		/* New data is available */
2584 		amm = avail - out;
2585 		if (amm > tp->t_maxseg) {
2586 			amm = tp->t_maxseg;
2587 		} else if ((amm < tp->t_maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
2588 			/* not enough to fill a MTU and no-delay is off */
2589 			goto need_retran;
2590 		}
2591 		if (IN_RECOVERY(tp->t_flags)) {
2592 			/* Unlikely */
2593 			old_prr_snd = rack->r_ctl.rc_prr_sndcnt;
2594 			if (out + amm <= tp->snd_wnd)
2595 				rack->r_ctl.rc_prr_sndcnt = amm;
2596 			else
2597 				goto need_retran;
2598 		} else {
2599 			/* Set the send-new override */
2600 			if (out + amm <= tp->snd_wnd)
2601 				rack->r_ctl.rc_tlp_new_data = amm;
2602 			else
2603 				goto need_retran;
2604 		}
2605 		rack->r_ctl.rc_tlp_seg_send_cnt = 0;
2606 		rack->r_ctl.rc_last_tlp_seq = tp->snd_max;
2607 		rack->r_ctl.rc_tlpsend = NULL;
2608 		counter_u64_add(rack_tlp_newdata, 1);
2609 		goto send;
2610 	}
2611 need_retran:
2612 	/*
2613 	 * Ok we need to arrange the last un-acked segment to be re-sent, or
2614 	 * optionally the first un-acked segment.
2615 	 */
2616 	if (rack_always_send_oldest)
2617 		rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
2618 	else {
2619 		rsm = TAILQ_LAST_FAST(&rack->r_ctl.rc_map, rack_sendmap, r_next);
2620 		if (rsm && (rsm->r_flags & (RACK_ACKED | RACK_HAS_FIN))) {
2621 			rsm = rack_find_high_nonack(rack, rsm);
2622 		}
2623 	}
2624 	if (rsm == NULL) {
2625 		counter_u64_add(rack_tlp_does_nada, 1);
2626 #ifdef TCP_BLACKBOX
2627 		tcp_log_dump_tp_logbuf(tp, "nada counter trips", M_NOWAIT, true);
2628 #endif
2629 		goto out;
2630 	}
2631 	if ((rsm->r_end - rsm->r_start) > tp->t_maxseg) {
2632 		/*
2633 		 * We need to split this the last segment in two.
2634 		 */
2635 		int32_t idx;
2636 		struct rack_sendmap *nrsm;
2637 
2638 		nrsm = rack_alloc_full_limit(rack);
2639 		if (nrsm == NULL) {
2640 			/*
2641 			 * No memory to split, we will just exit and punt
2642 			 * off to the RXT timer.
2643 			 */
2644 			counter_u64_add(rack_tlp_does_nada, 1);
2645 			goto out;
2646 		}
2647 		nrsm->r_start = (rsm->r_end - tp->t_maxseg);
2648 		nrsm->r_end = rsm->r_end;
2649 		nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
2650 		nrsm->r_flags = rsm->r_flags;
2651 		nrsm->r_sndcnt = rsm->r_sndcnt;
2652 		nrsm->r_rtr_bytes = 0;
2653 		rsm->r_end = nrsm->r_start;
2654 		for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
2655 			nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
2656 		}
2657 		TAILQ_INSERT_AFTER(&rack->r_ctl.rc_map, rsm, nrsm, r_next);
2658 		if (rsm->r_in_tmap) {
2659 			TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
2660 			nrsm->r_in_tmap = 1;
2661 		}
2662 		rsm->r_flags &= (~RACK_HAS_FIN);
2663 		rsm = nrsm;
2664 	}
2665 	rack->r_ctl.rc_tlpsend = rsm;
2666 	rack->r_ctl.rc_tlp_rtx_out = 1;
2667 	if (rsm->r_start == rack->r_ctl.rc_last_tlp_seq) {
2668 		rack->r_ctl.rc_tlp_seg_send_cnt++;
2669 		tp->t_rxtshift++;
2670 	} else {
2671 		rack->r_ctl.rc_last_tlp_seq = rsm->r_start;
2672 		rack->r_ctl.rc_tlp_seg_send_cnt = 1;
2673 	}
2674 send:
2675 	rack->r_ctl.rc_tlp_send_cnt++;
2676 	if (rack->r_ctl.rc_tlp_send_cnt > rack_tlp_max_resend) {
2677 		/*
2678 		 * Can't [re]/transmit a segment we have not heard from the
2679 		 * peer in max times. We need the retransmit timer to take
2680 		 * over.
2681 		 */
2682 restore:
2683 		rack->r_ctl.rc_tlpsend = NULL;
2684 		if (rsm)
2685 			rsm->r_flags &= ~RACK_TLP;
2686 		rack->r_ctl.rc_prr_sndcnt = old_prr_snd;
2687 		counter_u64_add(rack_tlp_retran_fail, 1);
2688 		goto out;
2689 	} else if (rsm) {
2690 		rsm->r_flags |= RACK_TLP;
2691 	}
2692 	if (rsm && (rsm->r_start == rack->r_ctl.rc_last_tlp_seq) &&
2693 	    (rack->r_ctl.rc_tlp_seg_send_cnt > rack_tlp_max_resend)) {
2694 		/*
2695 		 * We don't want to send a single segment more than the max
2696 		 * either.
2697 		 */
2698 		goto restore;
2699 	}
2700 	rack->r_timer_override = 1;
2701 	rack->r_tlp_running = 1;
2702 	rack->rc_tlp_in_progress = 1;
2703 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
2704 	return (0);
2705 out:
2706 	rack->rc_timer_up = 0;
2707 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
2708 	return (0);
2709 }
2710 
2711 /*
2712  * Delayed ack Timer, here we simply need to setup the
2713  * ACK_NOW flag and remove the DELACK flag. From there
2714  * the output routine will send the ack out.
2715  *
2716  * We only return 1, saying don't proceed, if all timers
2717  * are stopped (destroyed PCB?).
2718  */
2719 static int
2720 rack_timeout_delack(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
2721 {
2722 	if (tp->t_timers->tt_flags & TT_STOPPED) {
2723 		return (1);
2724 	}
2725 	rack_log_to_event(rack, RACK_TO_FRM_DELACK);
2726 	tp->t_flags &= ~TF_DELACK;
2727 	tp->t_flags |= TF_ACKNOW;
2728 	TCPSTAT_INC(tcps_delack);
2729 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
2730 	return (0);
2731 }
2732 
2733 /*
2734  * Persists timer, here we simply need to setup the
2735  * FORCE-DATA flag the output routine will send
2736  * the one byte send.
2737  *
2738  * We only return 1, saying don't proceed, if all timers
2739  * are stopped (destroyed PCB?).
2740  */
2741 static int
2742 rack_timeout_persist(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
2743 {
2744 	struct inpcb *inp;
2745 	int32_t retval = 0;
2746 
2747 	inp = tp->t_inpcb;
2748 
2749 	if (tp->t_timers->tt_flags & TT_STOPPED) {
2750 		return (1);
2751 	}
2752 	if (rack->rc_in_persist == 0)
2753 		return (0);
2754 	if (rack_progress_timeout_check(tp)) {
2755 		tcp_set_inp_to_drop(inp, ETIMEDOUT);
2756 		return (1);
2757 	}
2758 	KASSERT(inp != NULL, ("%s: tp %p tp->t_inpcb == NULL", __func__, tp));
2759 	/*
2760 	 * Persistence timer into zero window. Force a byte to be output, if
2761 	 * possible.
2762 	 */
2763 	TCPSTAT_INC(tcps_persisttimeo);
2764 	/*
2765 	 * Hack: if the peer is dead/unreachable, we do not time out if the
2766 	 * window is closed.  After a full backoff, drop the connection if
2767 	 * the idle time (no responses to probes) reaches the maximum
2768 	 * backoff that we would use if retransmitting.
2769 	 */
2770 	if (tp->t_rxtshift == TCP_MAXRXTSHIFT &&
2771 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
2772 	    ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
2773 		TCPSTAT_INC(tcps_persistdrop);
2774 		retval = 1;
2775 		tcp_set_inp_to_drop(rack->rc_inp, ETIMEDOUT);
2776 		goto out;
2777 	}
2778 	if ((sbavail(&rack->rc_inp->inp_socket->so_snd) == 0) &&
2779 	    tp->snd_una == tp->snd_max)
2780 		rack_exit_persist(tp, rack);
2781 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
2782 	/*
2783 	 * If the user has closed the socket then drop a persisting
2784 	 * connection after a much reduced timeout.
2785 	 */
2786 	if (tp->t_state > TCPS_CLOSE_WAIT &&
2787 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
2788 		retval = 1;
2789 		TCPSTAT_INC(tcps_persistdrop);
2790 		tcp_set_inp_to_drop(rack->rc_inp, ETIMEDOUT);
2791 		goto out;
2792 	}
2793 	tp->t_flags |= TF_FORCEDATA;
2794 out:
2795 	rack_log_to_event(rack, RACK_TO_FRM_PERSIST);
2796 	return (retval);
2797 }
2798 
2799 /*
2800  * If a keepalive goes off, we had no other timers
2801  * happening. We always return 1 here since this
2802  * routine either drops the connection or sends
2803  * out a segment with respond.
2804  */
2805 static int
2806 rack_timeout_keepalive(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
2807 {
2808 	struct tcptemp *t_template;
2809 	struct inpcb *inp;
2810 
2811 	if (tp->t_timers->tt_flags & TT_STOPPED) {
2812 		return (1);
2813 	}
2814 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
2815 	inp = tp->t_inpcb;
2816 	rack_log_to_event(rack, RACK_TO_FRM_KEEP);
2817 	/*
2818 	 * Keep-alive timer went off; send something or drop connection if
2819 	 * idle for too long.
2820 	 */
2821 	TCPSTAT_INC(tcps_keeptimeo);
2822 	if (tp->t_state < TCPS_ESTABLISHED)
2823 		goto dropit;
2824 	if ((tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
2825 	    tp->t_state <= TCPS_CLOSING) {
2826 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
2827 			goto dropit;
2828 		/*
2829 		 * Send a packet designed to force a response if the peer is
2830 		 * up and reachable: either an ACK if the connection is
2831 		 * still alive, or an RST if the peer has closed the
2832 		 * connection due to timeout or reboot. Using sequence
2833 		 * number tp->snd_una-1 causes the transmitted zero-length
2834 		 * segment to lie outside the receive window; by the
2835 		 * protocol spec, this requires the correspondent TCP to
2836 		 * respond.
2837 		 */
2838 		TCPSTAT_INC(tcps_keepprobe);
2839 		t_template = tcpip_maketemplate(inp);
2840 		if (t_template) {
2841 			tcp_respond(tp, t_template->tt_ipgen,
2842 			    &t_template->tt_t, (struct mbuf *)NULL,
2843 			    tp->rcv_nxt, tp->snd_una - 1, 0);
2844 			free(t_template, M_TEMP);
2845 		}
2846 	}
2847 	rack_start_hpts_timer(rack, tp, cts, __LINE__, 0, 0, 0);
2848 	return (1);
2849 dropit:
2850 	TCPSTAT_INC(tcps_keepdrops);
2851 	tcp_set_inp_to_drop(rack->rc_inp, ETIMEDOUT);
2852 	return (1);
2853 }
2854 
2855 /*
2856  * Retransmit helper function, clear up all the ack
2857  * flags and take care of important book keeping.
2858  */
2859 static void
2860 rack_remxt_tmr(struct tcpcb *tp)
2861 {
2862 	/*
2863 	 * The retransmit timer went off, all sack'd blocks must be
2864 	 * un-acked.
2865 	 */
2866 	struct rack_sendmap *rsm, *trsm = NULL;
2867 	struct tcp_rack *rack;
2868 	int32_t cnt = 0;
2869 
2870 	rack = (struct tcp_rack *)tp->t_fb_ptr;
2871 	rack_timer_cancel(tp, rack, tcp_ts_getticks(), __LINE__);
2872 	rack_log_to_event(rack, RACK_TO_FRM_TMR);
2873 	if (rack->r_state && (rack->r_state != tp->t_state))
2874 		rack_set_state(tp, rack);
2875 	/*
2876 	 * Ideally we would like to be able to
2877 	 * mark SACK-PASS on anything not acked here.
2878 	 * However, if we do that we would burst out
2879 	 * all that data 1ms apart. This would be unwise,
2880 	 * so for now we will just let the normal rxt timer
2881 	 * and tlp timer take care of it.
2882 	 */
2883 	TAILQ_FOREACH(rsm, &rack->r_ctl.rc_map, r_next) {
2884 		if (rsm->r_flags & RACK_ACKED) {
2885 			cnt++;
2886 			rsm->r_sndcnt = 0;
2887 			if (rsm->r_in_tmap == 0) {
2888 				/* We must re-add it back to the tlist */
2889 				if (trsm == NULL) {
2890 					TAILQ_INSERT_HEAD(&rack->r_ctl.rc_tmap, rsm, r_tnext);
2891 				} else {
2892 					TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, trsm, rsm, r_tnext);
2893 				}
2894 				rsm->r_in_tmap = 1;
2895 				trsm = rsm;
2896 			}
2897 		}
2898 		rsm->r_flags &= ~(RACK_ACKED | RACK_SACK_PASSED | RACK_WAS_SACKPASS);
2899 	}
2900 	/* Clear the count (we just un-acked them) */
2901 	rack->r_ctl.rc_sacked = 0;
2902 	/* Clear the tlp rtx mark */
2903 	rack->r_ctl.rc_tlp_rtx_out = 0;
2904 	rack->r_ctl.rc_tlp_seg_send_cnt = 0;
2905 	rack->r_ctl.rc_resend = TAILQ_FIRST(&rack->r_ctl.rc_map);
2906 	/* Setup so we send one segment */
2907 	if (rack->r_ctl.rc_prr_sndcnt < tp->t_maxseg)
2908 		rack->r_ctl.rc_prr_sndcnt = tp->t_maxseg;
2909 	rack->r_timer_override = 1;
2910 }
2911 
2912 /*
2913  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
2914  * we will setup to retransmit the lowest seq number outstanding.
2915  */
2916 static int
2917 rack_timeout_rxt(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
2918 {
2919 	int32_t rexmt;
2920 	struct inpcb *inp;
2921 	int32_t retval = 0;
2922 
2923 	inp = tp->t_inpcb;
2924 	if (tp->t_timers->tt_flags & TT_STOPPED) {
2925 		return (1);
2926 	}
2927 	if (rack_progress_timeout_check(tp)) {
2928 		tcp_set_inp_to_drop(inp, ETIMEDOUT);
2929 		return (1);
2930 	}
2931 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
2932 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
2933 	    (tp->snd_una == tp->snd_max)) {
2934 		/* Nothing outstanding .. nothing to do */
2935 		return (0);
2936 	}
2937 	/*
2938 	 * Retransmission timer went off.  Message has not been acked within
2939 	 * retransmit interval.  Back off to a longer retransmit interval
2940 	 * and retransmit one segment.
2941 	 */
2942 	if (++tp->t_rxtshift > TCP_MAXRXTSHIFT) {
2943 		tp->t_rxtshift = TCP_MAXRXTSHIFT;
2944 		TCPSTAT_INC(tcps_timeoutdrop);
2945 		retval = 1;
2946 		tcp_set_inp_to_drop(rack->rc_inp,
2947 		    (tp->t_softerror ? (uint16_t) tp->t_softerror : ETIMEDOUT));
2948 		goto out;
2949 	}
2950 	rack_remxt_tmr(tp);
2951 	if (tp->t_state == TCPS_SYN_SENT) {
2952 		/*
2953 		 * If the SYN was retransmitted, indicate CWND to be limited
2954 		 * to 1 segment in cc_conn_init().
2955 		 */
2956 		tp->snd_cwnd = 1;
2957 	} else if (tp->t_rxtshift == 1) {
2958 		/*
2959 		 * first retransmit; record ssthresh and cwnd so they can be
2960 		 * recovered if this turns out to be a "bad" retransmit. A
2961 		 * retransmit is considered "bad" if an ACK for this segment
2962 		 * is received within RTT/2 interval; the assumption here is
2963 		 * that the ACK was already in flight.  See "On Estimating
2964 		 * End-to-End Network Path Properties" by Allman and Paxson
2965 		 * for more details.
2966 		 */
2967 		tp->snd_cwnd_prev = tp->snd_cwnd;
2968 		tp->snd_ssthresh_prev = tp->snd_ssthresh;
2969 		tp->snd_recover_prev = tp->snd_recover;
2970 		if (IN_FASTRECOVERY(tp->t_flags))
2971 			tp->t_flags |= TF_WASFRECOVERY;
2972 		else
2973 			tp->t_flags &= ~TF_WASFRECOVERY;
2974 		if (IN_CONGRECOVERY(tp->t_flags))
2975 			tp->t_flags |= TF_WASCRECOVERY;
2976 		else
2977 			tp->t_flags &= ~TF_WASCRECOVERY;
2978 		tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
2979 		tp->t_flags |= TF_PREVVALID;
2980 	} else
2981 		tp->t_flags &= ~TF_PREVVALID;
2982 	TCPSTAT_INC(tcps_rexmttimeo);
2983 	if ((tp->t_state == TCPS_SYN_SENT) ||
2984 	    (tp->t_state == TCPS_SYN_RECEIVED))
2985 		rexmt = MSEC_2_TICKS(RACK_INITIAL_RTO * tcp_syn_backoff[tp->t_rxtshift]);
2986 	else
2987 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
2988 	TCPT_RANGESET(tp->t_rxtcur, rexmt,
2989 	   max(MSEC_2_TICKS(rack_rto_min), rexmt),
2990 	   MSEC_2_TICKS(rack_rto_max));
2991 	/*
2992 	 * We enter the path for PLMTUD if connection is established or, if
2993 	 * connection is FIN_WAIT_1 status, reason for the last is that if
2994 	 * amount of data we send is very small, we could send it in couple
2995 	 * of packets and process straight to FIN. In that case we won't
2996 	 * catch ESTABLISHED state.
2997 	 */
2998 	if (V_tcp_pmtud_blackhole_detect && (((tp->t_state == TCPS_ESTABLISHED))
2999 	    || (tp->t_state == TCPS_FIN_WAIT_1))) {
3000 #ifdef INET6
3001 		int32_t isipv6;
3002 #endif
3003 
3004 		/*
3005 		 * Idea here is that at each stage of mtu probe (usually,
3006 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
3007 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
3008 		 * should take care of that.
3009 		 */
3010 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
3011 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
3012 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
3013 		    tp->t_rxtshift % 2 == 0)) {
3014 			/*
3015 			 * Enter Path MTU Black-hole Detection mechanism: -
3016 			 * Disable Path MTU Discovery (IP "DF" bit). -
3017 			 * Reduce MTU to lower value than what we negotiated
3018 			 * with peer.
3019 			 */
3020 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
3021 				/* Record that we may have found a black hole. */
3022 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
3023 				/* Keep track of previous MSS. */
3024 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
3025 			}
3026 
3027 			/*
3028 			 * Reduce the MSS to blackhole value or to the
3029 			 * default in an attempt to retransmit.
3030 			 */
3031 #ifdef INET6
3032 			isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) ? 1 : 0;
3033 			if (isipv6 &&
3034 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
3035 				/* Use the sysctl tuneable blackhole MSS. */
3036 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
3037 				TCPSTAT_INC(tcps_pmtud_blackhole_activated);
3038 			} else if (isipv6) {
3039 				/* Use the default MSS. */
3040 				tp->t_maxseg = V_tcp_v6mssdflt;
3041 				/*
3042 				 * Disable Path MTU Discovery when we switch
3043 				 * to minmss.
3044 				 */
3045 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
3046 				TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
3047 			}
3048 #endif
3049 #if defined(INET6) && defined(INET)
3050 			else
3051 #endif
3052 #ifdef INET
3053 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
3054 				/* Use the sysctl tuneable blackhole MSS. */
3055 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
3056 				TCPSTAT_INC(tcps_pmtud_blackhole_activated);
3057 			} else {
3058 				/* Use the default MSS. */
3059 				tp->t_maxseg = V_tcp_mssdflt;
3060 				/*
3061 				 * Disable Path MTU Discovery when we switch
3062 				 * to minmss.
3063 				 */
3064 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
3065 				TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
3066 			}
3067 #endif
3068 		} else {
3069 			/*
3070 			 * If further retransmissions are still unsuccessful
3071 			 * with a lowered MTU, maybe this isn't a blackhole
3072 			 * and we restore the previous MSS and blackhole
3073 			 * detection flags. The limit '6' is determined by
3074 			 * giving each probe stage (1448, 1188, 524) 2
3075 			 * chances to recover.
3076 			 */
3077 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
3078 			    (tp->t_rxtshift >= 6)) {
3079 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
3080 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
3081 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
3082 				TCPSTAT_INC(tcps_pmtud_blackhole_failed);
3083 			}
3084 		}
3085 	}
3086 	/*
3087 	 * Disable RFC1323 and SACK if we haven't got any response to our
3088 	 * third SYN to work-around some broken terminal servers (most of
3089 	 * which have hopefully been retired) that have bad VJ header
3090 	 * compression code which trashes TCP segments containing
3091 	 * unknown-to-them TCP options.
3092 	 */
3093 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
3094 	    (tp->t_rxtshift == 3))
3095 		tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
3096 	/*
3097 	 * If we backed off this far, our srtt estimate is probably bogus.
3098 	 * Clobber it so we'll take the next rtt measurement as our srtt;
3099 	 * move the current srtt into rttvar to keep the current retransmit
3100 	 * times until then.
3101 	 */
3102 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
3103 #ifdef INET6
3104 		if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
3105 			in6_losing(tp->t_inpcb);
3106 		else
3107 #endif
3108 			in_losing(tp->t_inpcb);
3109 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
3110 		tp->t_srtt = 0;
3111 	}
3112 	if (rack_use_sack_filter)
3113 		sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
3114 	tp->snd_recover = tp->snd_max;
3115 	tp->t_flags |= TF_ACKNOW;
3116 	tp->t_rtttime = 0;
3117 	rack_cong_signal(tp, NULL, CC_RTO);
3118 out:
3119 	return (retval);
3120 }
3121 
3122 static int
3123 rack_process_timers(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, uint8_t hpts_calling)
3124 {
3125 	int32_t ret = 0;
3126 	int32_t timers = (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
3127 
3128 	if (timers == 0) {
3129 		return (0);
3130 	}
3131 	if (tp->t_state == TCPS_LISTEN) {
3132 		/* no timers on listen sockets */
3133 		if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
3134 			return (0);
3135 		return (1);
3136 	}
3137 	if (TSTMP_LT(cts, rack->r_ctl.rc_timer_exp)) {
3138 		uint32_t left;
3139 
3140 		if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
3141 			ret = -1;
3142 			rack_log_to_processing(rack, cts, ret, 0);
3143 			return (0);
3144 		}
3145 		if (hpts_calling == 0) {
3146 			ret = -2;
3147 			rack_log_to_processing(rack, cts, ret, 0);
3148 			return (0);
3149 		}
3150 		/*
3151 		 * Ok our timer went off early and we are not paced false
3152 		 * alarm, go back to sleep.
3153 		 */
3154 		ret = -3;
3155 		left = rack->r_ctl.rc_timer_exp - cts;
3156 		tcp_hpts_insert(tp->t_inpcb, HPTS_MS_TO_SLOTS(left));
3157 		rack_log_to_processing(rack, cts, ret, left);
3158 		rack->rc_last_pto_set = 0;
3159 		return (1);
3160 	}
3161 	rack->rc_tmr_stopped = 0;
3162 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
3163 	if (timers & PACE_TMR_DELACK) {
3164 		ret = rack_timeout_delack(tp, rack, cts);
3165 	} else if (timers & PACE_TMR_RACK) {
3166 		ret = rack_timeout_rack(tp, rack, cts);
3167 	} else if (timers & PACE_TMR_TLP) {
3168 		ret = rack_timeout_tlp(tp, rack, cts);
3169 	} else if (timers & PACE_TMR_RXT) {
3170 		ret = rack_timeout_rxt(tp, rack, cts);
3171 	} else if (timers & PACE_TMR_PERSIT) {
3172 		ret = rack_timeout_persist(tp, rack, cts);
3173 	} else if (timers & PACE_TMR_KEEP) {
3174 		ret = rack_timeout_keepalive(tp, rack, cts);
3175 	}
3176 	rack_log_to_processing(rack, cts, ret, timers);
3177 	return (ret);
3178 }
3179 
3180 static void
3181 rack_timer_cancel(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, int line)
3182 {
3183 	uint8_t hpts_removed = 0;
3184 
3185 	if ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
3186 	    TSTMP_GEQ(cts, rack->r_ctl.rc_last_output_to)) {
3187 		tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
3188 		hpts_removed = 1;
3189 	}
3190 	if (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
3191 		rack->rc_tmr_stopped = rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
3192 		if (rack->rc_inp->inp_in_hpts &&
3193 		    ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0)) {
3194 			/*
3195 			 * Canceling timer's when we have no output being
3196 			 * paced. We also must remove ourselves from the
3197 			 * hpts.
3198 			 */
3199 			tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
3200 			hpts_removed = 1;
3201 		}
3202 		rack_log_to_cancel(rack, hpts_removed, line);
3203 		rack->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
3204 	}
3205 }
3206 
3207 static void
3208 rack_timer_stop(struct tcpcb *tp, uint32_t timer_type)
3209 {
3210 	return;
3211 }
3212 
3213 static int
3214 rack_stopall(struct tcpcb *tp)
3215 {
3216 	struct tcp_rack *rack;
3217 	rack = (struct tcp_rack *)tp->t_fb_ptr;
3218 	rack->t_timers_stopped = 1;
3219 	return (0);
3220 }
3221 
3222 static void
3223 rack_timer_activate(struct tcpcb *tp, uint32_t timer_type, uint32_t delta)
3224 {
3225 	return;
3226 }
3227 
3228 static int
3229 rack_timer_active(struct tcpcb *tp, uint32_t timer_type)
3230 {
3231 	return (0);
3232 }
3233 
3234 static void
3235 rack_stop_all_timers(struct tcpcb *tp)
3236 {
3237 	struct tcp_rack *rack;
3238 
3239 	/*
3240 	 * Assure no timers are running.
3241 	 */
3242 	if (tcp_timer_active(tp, TT_PERSIST)) {
3243 		/* We enter in persists, set the flag appropriately */
3244 		rack = (struct tcp_rack *)tp->t_fb_ptr;
3245 		rack->rc_in_persist = 1;
3246 	}
3247 	tcp_timer_suspend(tp, TT_PERSIST);
3248 	tcp_timer_suspend(tp, TT_REXMT);
3249 	tcp_timer_suspend(tp, TT_KEEP);
3250 	tcp_timer_suspend(tp, TT_DELACK);
3251 }
3252 
3253 static void
3254 rack_update_rsm(struct tcpcb *tp, struct tcp_rack *rack,
3255     struct rack_sendmap *rsm, uint32_t ts)
3256 {
3257 	int32_t idx;
3258 
3259 	rsm->r_rtr_cnt++;
3260 	rsm->r_sndcnt++;
3261 	if (rsm->r_rtr_cnt > RACK_NUM_OF_RETRANS) {
3262 		rsm->r_rtr_cnt = RACK_NUM_OF_RETRANS;
3263 		rsm->r_flags |= RACK_OVERMAX;
3264 	}
3265 	if ((rsm->r_rtr_cnt > 1) && (rack->r_tlp_running == 0)) {
3266 		rack->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
3267 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
3268 	}
3269 	idx = rsm->r_rtr_cnt - 1;
3270 	rsm->r_tim_lastsent[idx] = ts;
3271 	if (rsm->r_flags & RACK_ACKED) {
3272 		/* Problably MTU discovery messing with us */
3273 		rsm->r_flags &= ~RACK_ACKED;
3274 		rack->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
3275 	}
3276 	if (rsm->r_in_tmap) {
3277 		TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
3278 	}
3279 	TAILQ_INSERT_TAIL(&rack->r_ctl.rc_tmap, rsm, r_tnext);
3280 	rsm->r_in_tmap = 1;
3281 	if (rsm->r_flags & RACK_SACK_PASSED) {
3282 		/* We have retransmitted due to the SACK pass */
3283 		rsm->r_flags &= ~RACK_SACK_PASSED;
3284 		rsm->r_flags |= RACK_WAS_SACKPASS;
3285 	}
3286 	/* Update memory for next rtr */
3287 	rack->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
3288 }
3289 
3290 
3291 static uint32_t
3292 rack_update_entry(struct tcpcb *tp, struct tcp_rack *rack,
3293     struct rack_sendmap *rsm, uint32_t ts, int32_t * lenp)
3294 {
3295 	/*
3296 	 * We (re-)transmitted starting at rsm->r_start for some length
3297 	 * (possibly less than r_end.
3298 	 */
3299 	struct rack_sendmap *nrsm;
3300 	uint32_t c_end;
3301 	int32_t len;
3302 	int32_t idx;
3303 
3304 	len = *lenp;
3305 	c_end = rsm->r_start + len;
3306 	if (SEQ_GEQ(c_end, rsm->r_end)) {
3307 		/*
3308 		 * We retransmitted the whole piece or more than the whole
3309 		 * slopping into the next rsm.
3310 		 */
3311 		rack_update_rsm(tp, rack, rsm, ts);
3312 		if (c_end == rsm->r_end) {
3313 			*lenp = 0;
3314 			return (0);
3315 		} else {
3316 			int32_t act_len;
3317 
3318 			/* Hangs over the end return whats left */
3319 			act_len = rsm->r_end - rsm->r_start;
3320 			*lenp = (len - act_len);
3321 			return (rsm->r_end);
3322 		}
3323 		/* We don't get out of this block. */
3324 	}
3325 	/*
3326 	 * Here we retransmitted less than the whole thing which means we
3327 	 * have to split this into what was transmitted and what was not.
3328 	 */
3329 	nrsm = rack_alloc_full_limit(rack);
3330 	if (nrsm == NULL) {
3331 		/*
3332 		 * We can't get memory, so lets not proceed.
3333 		 */
3334 		*lenp = 0;
3335 		return (0);
3336 	}
3337 	/*
3338 	 * So here we are going to take the original rsm and make it what we
3339 	 * retransmitted. nrsm will be the tail portion we did not
3340 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
3341 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
3342 	 * 1, 6 and the new piece will be 6, 11.
3343 	 */
3344 	nrsm->r_start = c_end;
3345 	nrsm->r_end = rsm->r_end;
3346 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
3347 	nrsm->r_flags = rsm->r_flags;
3348 	nrsm->r_sndcnt = rsm->r_sndcnt;
3349 	nrsm->r_rtr_bytes = 0;
3350 	rsm->r_end = c_end;
3351 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
3352 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
3353 	}
3354 	TAILQ_INSERT_AFTER(&rack->r_ctl.rc_map, rsm, nrsm, r_next);
3355 	if (rsm->r_in_tmap) {
3356 		TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
3357 		nrsm->r_in_tmap = 1;
3358 	}
3359 	rsm->r_flags &= (~RACK_HAS_FIN);
3360 	rack_update_rsm(tp, rack, rsm, ts);
3361 	*lenp = 0;
3362 	return (0);
3363 }
3364 
3365 
3366 static void
3367 rack_log_output(struct tcpcb *tp, struct tcpopt *to, int32_t len,
3368     uint32_t seq_out, uint8_t th_flags, int32_t err, uint32_t ts,
3369     uint8_t pass, struct rack_sendmap *hintrsm)
3370 {
3371 	struct tcp_rack *rack;
3372 	struct rack_sendmap *rsm, *nrsm;
3373 	register uint32_t snd_max, snd_una;
3374 	int32_t idx;
3375 
3376 	/*
3377 	 * Add to the RACK log of packets in flight or retransmitted. If
3378 	 * there is a TS option we will use the TS echoed, if not we will
3379 	 * grab a TS.
3380 	 *
3381 	 * Retransmissions will increment the count and move the ts to its
3382 	 * proper place. Note that if options do not include TS's then we
3383 	 * won't be able to effectively use the ACK for an RTT on a retran.
3384 	 *
3385 	 * Notes about r_start and r_end. Lets consider a send starting at
3386 	 * sequence 1 for 10 bytes. In such an example the r_start would be
3387 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
3388 	 * This means that r_end is actually the first sequence for the next
3389 	 * slot (11).
3390 	 *
3391 	 */
3392 	/*
3393 	 * If err is set what do we do XXXrrs? should we not add the thing?
3394 	 * -- i.e. return if err != 0 or should we pretend we sent it? --
3395 	 * i.e. proceed with add ** do this for now.
3396 	 */
3397 	INP_WLOCK_ASSERT(tp->t_inpcb);
3398 	if (err)
3399 		/*
3400 		 * We don't log errors -- we could but snd_max does not
3401 		 * advance in this case either.
3402 		 */
3403 		return;
3404 
3405 	if (th_flags & TH_RST) {
3406 		/*
3407 		 * We don't log resets and we return immediately from
3408 		 * sending
3409 		 */
3410 		return;
3411 	}
3412 	rack = (struct tcp_rack *)tp->t_fb_ptr;
3413 	snd_una = tp->snd_una;
3414 	if (SEQ_LEQ((seq_out + len), snd_una)) {
3415 		/* Are sending an old segment to induce an ack (keep-alive)? */
3416 		return;
3417 	}
3418 	if (SEQ_LT(seq_out, snd_una)) {
3419 		/* huh? should we panic? */
3420 		uint32_t end;
3421 
3422 		end = seq_out + len;
3423 		seq_out = snd_una;
3424 		len = end - seq_out;
3425 	}
3426 	snd_max = tp->snd_max;
3427 	if (th_flags & (TH_SYN | TH_FIN)) {
3428 		/*
3429 		 * The call to rack_log_output is made before bumping
3430 		 * snd_max. This means we can record one extra byte on a SYN
3431 		 * or FIN if seq_out is adding more on and a FIN is present
3432 		 * (and we are not resending).
3433 		 */
3434 		if (th_flags & TH_SYN)
3435 			len++;
3436 		if (th_flags & TH_FIN)
3437 			len++;
3438 		if (SEQ_LT(snd_max, tp->snd_nxt)) {
3439 			/*
3440 			 * The add/update as not been done for the FIN/SYN
3441 			 * yet.
3442 			 */
3443 			snd_max = tp->snd_nxt;
3444 		}
3445 	}
3446 	if (len == 0) {
3447 		/* We don't log zero window probes */
3448 		return;
3449 	}
3450 	rack->r_ctl.rc_time_last_sent = ts;
3451 	if (IN_RECOVERY(tp->t_flags)) {
3452 		rack->r_ctl.rc_prr_out += len;
3453 	}
3454 	/* First question is it a retransmission? */
3455 	if (seq_out == snd_max) {
3456 again:
3457 		rsm = rack_alloc(rack);
3458 		if (rsm == NULL) {
3459 			/*
3460 			 * Hmm out of memory and the tcb got destroyed while
3461 			 * we tried to wait.
3462 			 */
3463 			return;
3464 		}
3465 		if (th_flags & TH_FIN) {
3466 			rsm->r_flags = RACK_HAS_FIN;
3467 		} else {
3468 			rsm->r_flags = 0;
3469 		}
3470 		rsm->r_tim_lastsent[0] = ts;
3471 		rsm->r_rtr_cnt = 1;
3472 		rsm->r_rtr_bytes = 0;
3473 		rsm->r_start = seq_out;
3474 		rsm->r_end = rsm->r_start + len;
3475 		rsm->r_sndcnt = 0;
3476 		TAILQ_INSERT_TAIL(&rack->r_ctl.rc_map, rsm, r_next);
3477 		TAILQ_INSERT_TAIL(&rack->r_ctl.rc_tmap, rsm, r_tnext);
3478 		rsm->r_in_tmap = 1;
3479 		return;
3480 	}
3481 	/*
3482 	 * If we reach here its a retransmission and we need to find it.
3483 	 */
3484 more:
3485 	if (hintrsm && (hintrsm->r_start == seq_out)) {
3486 		rsm = hintrsm;
3487 		hintrsm = NULL;
3488 	} else if (rack->r_ctl.rc_next) {
3489 		/* We have a hint from a previous run */
3490 		rsm = rack->r_ctl.rc_next;
3491 	} else {
3492 		/* No hints sorry */
3493 		rsm = NULL;
3494 	}
3495 	if ((rsm) && (rsm->r_start == seq_out)) {
3496 		/*
3497 		 * We used rc_next or hintrsm  to retransmit, hopefully the
3498 		 * likely case.
3499 		 */
3500 		seq_out = rack_update_entry(tp, rack, rsm, ts, &len);
3501 		if (len == 0) {
3502 			return;
3503 		} else {
3504 			goto more;
3505 		}
3506 	}
3507 	/* Ok it was not the last pointer go through it the hard way. */
3508 	TAILQ_FOREACH(rsm, &rack->r_ctl.rc_map, r_next) {
3509 		if (rsm->r_start == seq_out) {
3510 			seq_out = rack_update_entry(tp, rack, rsm, ts, &len);
3511 			rack->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
3512 			if (len == 0) {
3513 				return;
3514 			} else {
3515 				continue;
3516 			}
3517 		}
3518 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
3519 			/* Transmitted within this piece */
3520 			/*
3521 			 * Ok we must split off the front and then let the
3522 			 * update do the rest
3523 			 */
3524 			nrsm = rack_alloc_full_limit(rack);
3525 			if (nrsm == NULL) {
3526 				rack_update_rsm(tp, rack, rsm, ts);
3527 				return;
3528 			}
3529 			/*
3530 			 * copy rsm to nrsm and then trim the front of rsm
3531 			 * to not include this part.
3532 			 */
3533 			nrsm->r_start = seq_out;
3534 			nrsm->r_end = rsm->r_end;
3535 			nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
3536 			nrsm->r_flags = rsm->r_flags;
3537 			nrsm->r_sndcnt = rsm->r_sndcnt;
3538 			nrsm->r_rtr_bytes = 0;
3539 			for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
3540 				nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
3541 			}
3542 			rsm->r_end = nrsm->r_start;
3543 			TAILQ_INSERT_AFTER(&rack->r_ctl.rc_map, rsm, nrsm, r_next);
3544 			if (rsm->r_in_tmap) {
3545 				TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
3546 				nrsm->r_in_tmap = 1;
3547 			}
3548 			rsm->r_flags &= (~RACK_HAS_FIN);
3549 			seq_out = rack_update_entry(tp, rack, nrsm, ts, &len);
3550 			if (len == 0) {
3551 				return;
3552 			}
3553 		}
3554 	}
3555 	/*
3556 	 * Hmm not found in map did they retransmit both old and on into the
3557 	 * new?
3558 	 */
3559 	if (seq_out == tp->snd_max) {
3560 		goto again;
3561 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
3562 #ifdef INVARIANTS
3563 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
3564 		    seq_out, len, tp->snd_una, tp->snd_max);
3565 		printf("Starting Dump of all rack entries\n");
3566 		TAILQ_FOREACH(rsm, &rack->r_ctl.rc_map, r_next) {
3567 			printf("rsm:%p start:%u end:%u\n",
3568 			    rsm, rsm->r_start, rsm->r_end);
3569 		}
3570 		printf("Dump complete\n");
3571 		panic("seq_out not found rack:%p tp:%p",
3572 		    rack, tp);
3573 #endif
3574 	} else {
3575 #ifdef INVARIANTS
3576 		/*
3577 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
3578 		 * flag)
3579 		 */
3580 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
3581 		    seq_out, len, tp->snd_max, tp);
3582 #endif
3583 	}
3584 }
3585 
3586 /*
3587  * Record one of the RTT updates from an ack into
3588  * our sample structure.
3589  */
3590 static void
3591 tcp_rack_xmit_timer(struct tcp_rack *rack, int32_t rtt)
3592 {
3593 	if ((rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY) ||
3594 	    (rack->r_ctl.rack_rs.rs_rtt_lowest > rtt)) {
3595 		rack->r_ctl.rack_rs.rs_rtt_lowest = rtt;
3596 	}
3597 	if ((rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY) ||
3598 	    (rack->r_ctl.rack_rs.rs_rtt_highest < rtt)) {
3599 		rack->r_ctl.rack_rs.rs_rtt_highest = rtt;
3600 	}
3601 	rack->r_ctl.rack_rs.rs_flags = RACK_RTT_VALID;
3602 	rack->r_ctl.rack_rs.rs_rtt_tot += rtt;
3603 	rack->r_ctl.rack_rs.rs_rtt_cnt++;
3604 }
3605 
3606 /*
3607  * Collect new round-trip time estimate
3608  * and update averages and current timeout.
3609  */
3610 static void
3611 tcp_rack_xmit_timer_commit(struct tcp_rack *rack, struct tcpcb *tp)
3612 {
3613 	int32_t delta;
3614 	uint32_t o_srtt, o_var;
3615 	int32_t rtt;
3616 
3617 	if (rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY)
3618 		/* No valid sample */
3619 		return;
3620 	if (rack->r_ctl.rc_rate_sample_method == USE_RTT_LOW) {
3621 		/* We are to use the lowest RTT seen in a single ack */
3622 		rtt = rack->r_ctl.rack_rs.rs_rtt_lowest;
3623 	} else if (rack->r_ctl.rc_rate_sample_method == USE_RTT_HIGH) {
3624 		/* We are to use the highest RTT seen in a single ack */
3625 		rtt = rack->r_ctl.rack_rs.rs_rtt_highest;
3626 	} else if (rack->r_ctl.rc_rate_sample_method == USE_RTT_AVG) {
3627 		/* We are to use the average RTT seen in a single ack */
3628 		rtt = (int32_t)(rack->r_ctl.rack_rs.rs_rtt_tot /
3629 				(uint64_t)rack->r_ctl.rack_rs.rs_rtt_cnt);
3630 	} else {
3631 #ifdef INVARIANTS
3632 		panic("Unknown rtt variant %d", rack->r_ctl.rc_rate_sample_method);
3633 #endif
3634 		return;
3635 	}
3636 	if (rtt == 0)
3637 		rtt = 1;
3638 	rack_log_rtt_sample(rack, rtt);
3639 	o_srtt = tp->t_srtt;
3640 	o_var = tp->t_rttvar;
3641 	rack = (struct tcp_rack *)tp->t_fb_ptr;
3642 	if (tp->t_srtt != 0) {
3643 		/*
3644 		 * srtt is stored as fixed point with 5 bits after the
3645 		 * binary point (i.e., scaled by 8).  The following magic is
3646 		 * equivalent to the smoothing algorithm in rfc793 with an
3647 		 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
3648 		 * Adjust rtt to origin 0.
3649 		 */
3650 		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3651 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3652 
3653 		tp->t_srtt += delta;
3654 		if (tp->t_srtt <= 0)
3655 			tp->t_srtt = 1;
3656 
3657 		/*
3658 		 * We accumulate a smoothed rtt variance (actually, a
3659 		 * smoothed mean difference), then set the retransmit timer
3660 		 * to smoothed rtt + 4 times the smoothed variance. rttvar
3661 		 * is stored as fixed point with 4 bits after the binary
3662 		 * point (scaled by 16).  The following is equivalent to
3663 		 * rfc793 smoothing with an alpha of .75 (rttvar =
3664 		 * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
3665 		 * wired-in beta.
3666 		 */
3667 		if (delta < 0)
3668 			delta = -delta;
3669 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3670 		tp->t_rttvar += delta;
3671 		if (tp->t_rttvar <= 0)
3672 			tp->t_rttvar = 1;
3673 		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3674 			tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3675 	} else {
3676 		/*
3677 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
3678 		 * variance to half the rtt (so our first retransmit happens
3679 		 * at 3*rtt).
3680 		 */
3681 		tp->t_srtt = rtt << TCP_RTT_SHIFT;
3682 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3683 		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3684 	}
3685 	TCPSTAT_INC(tcps_rttupdated);
3686 	rack_log_rtt_upd(tp, rack, rtt, o_srtt, o_var);
3687 	tp->t_rttupdated++;
3688 #ifdef NETFLIX_STATS
3689 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt));
3690 #endif
3691 	tp->t_rxtshift = 0;
3692 
3693 	/*
3694 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
3695 	 * way we do the smoothing, srtt and rttvar will each average +1/2
3696 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
3697 	 * tick of rounding and 1 extra tick because of +-1/2 tick
3698 	 * uncertainty in the firing of the timer.  The bias will give us
3699 	 * exactly the 1.5 tick we need.  But, because the bias is
3700 	 * statistical, we have to test that we don't drop below the minimum
3701 	 * feasible timer (which is 2 ticks).
3702 	 */
3703 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3704 	   max(MSEC_2_TICKS(rack_rto_min), rtt + 2), MSEC_2_TICKS(rack_rto_max));
3705 	tp->t_softerror = 0;
3706 }
3707 
3708 static void
3709 rack_earlier_retran(struct tcpcb *tp, struct rack_sendmap *rsm,
3710     uint32_t t, uint32_t cts)
3711 {
3712 	/*
3713 	 * For this RSM, we acknowledged the data from a previous
3714 	 * transmission, not the last one we made. This means we did a false
3715 	 * retransmit.
3716 	 */
3717 	struct tcp_rack *rack;
3718 
3719 	if (rsm->r_flags & RACK_HAS_FIN) {
3720 		/*
3721 		 * The sending of the FIN often is multiple sent when we
3722 		 * have everything outstanding ack'd. We ignore this case
3723 		 * since its over now.
3724 		 */
3725 		return;
3726 	}
3727 	if (rsm->r_flags & RACK_TLP) {
3728 		/*
3729 		 * We expect TLP's to have this occur.
3730 		 */
3731 		return;
3732 	}
3733 	rack = (struct tcp_rack *)tp->t_fb_ptr;
3734 	/* should we undo cc changes and exit recovery? */
3735 	if (IN_RECOVERY(tp->t_flags)) {
3736 		if (rack->r_ctl.rc_rsm_start == rsm->r_start) {
3737 			/*
3738 			 * Undo what we ratched down and exit recovery if
3739 			 * possible
3740 			 */
3741 			EXIT_RECOVERY(tp->t_flags);
3742 			tp->snd_recover = tp->snd_una;
3743 			if (rack->r_ctl.rc_cwnd_at > tp->snd_cwnd)
3744 				tp->snd_cwnd = rack->r_ctl.rc_cwnd_at;
3745 			if (rack->r_ctl.rc_ssthresh_at > tp->snd_ssthresh)
3746 				tp->snd_ssthresh = rack->r_ctl.rc_ssthresh_at;
3747 		}
3748 	}
3749 	if (rsm->r_flags & RACK_WAS_SACKPASS) {
3750 		/*
3751 		 * We retransmitted based on a sack and the earlier
3752 		 * retransmission ack'd it - re-ordering is occuring.
3753 		 */
3754 		counter_u64_add(rack_reorder_seen, 1);
3755 		rack->r_ctl.rc_reorder_ts = cts;
3756 	}
3757 	counter_u64_add(rack_badfr, 1);
3758 	counter_u64_add(rack_badfr_bytes, (rsm->r_end - rsm->r_start));
3759 }
3760 
3761 
3762 static int
3763 rack_update_rtt(struct tcpcb *tp, struct tcp_rack *rack,
3764     struct rack_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type)
3765 {
3766 	int32_t i;
3767 	uint32_t t;
3768 
3769 	if (rsm->r_flags & RACK_ACKED)
3770 		/* Already done */
3771 		return (0);
3772 
3773 
3774 	if ((rsm->r_rtr_cnt == 1) ||
3775 	    ((ack_type == CUM_ACKED) &&
3776 	    (to->to_flags & TOF_TS) &&
3777 	    (to->to_tsecr) &&
3778 	    (rsm->r_tim_lastsent[rsm->r_rtr_cnt - 1] == to->to_tsecr))
3779 	    ) {
3780 		/*
3781 		 * We will only find a matching timestamp if its cum-acked.
3782 		 * But if its only one retransmission its for-sure matching
3783 		 * :-)
3784 		 */
3785 		t = cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
3786 		if ((int)t <= 0)
3787 			t = 1;
3788 		if (!tp->t_rttlow || tp->t_rttlow > t)
3789 			tp->t_rttlow = t;
3790 		if (!rack->r_ctl.rc_rack_min_rtt ||
3791 		    SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
3792 			rack->r_ctl.rc_rack_min_rtt = t;
3793 			if (rack->r_ctl.rc_rack_min_rtt == 0) {
3794 				rack->r_ctl.rc_rack_min_rtt = 1;
3795 			}
3796 		}
3797 		tcp_rack_xmit_timer(rack, TCP_TS_TO_TICKS(t) + 1);
3798 		if ((rsm->r_flags & RACK_TLP) &&
3799 		    (!IN_RECOVERY(tp->t_flags))) {
3800 			/* Segment was a TLP and our retrans matched */
3801 			if (rack->r_ctl.rc_tlp_cwnd_reduce) {
3802 				rack->r_ctl.rc_rsm_start = tp->snd_max;
3803 				rack->r_ctl.rc_cwnd_at = tp->snd_cwnd;
3804 				rack->r_ctl.rc_ssthresh_at = tp->snd_ssthresh;
3805 				rack_cong_signal(tp, NULL, CC_NDUPACK);
3806 				/*
3807 				 * When we enter recovery we need to assure
3808 				 * we send one packet.
3809 				 */
3810 				rack->r_ctl.rc_prr_sndcnt = tp->t_maxseg;
3811 			} else
3812 				rack->r_ctl.rc_tlp_rtx_out = 0;
3813 		}
3814 		if (SEQ_LT(rack->r_ctl.rc_rack_tmit_time, rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)])) {
3815 			/* New more recent rack_tmit_time */
3816 			rack->r_ctl.rc_rack_tmit_time = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
3817 			rack->rc_rack_rtt = t;
3818 		}
3819 		return (1);
3820 	}
3821 	/*
3822 	 * We clear the soft/rxtshift since we got an ack.
3823 	 * There is no assurance we will call the commit() function
3824 	 * so we need to clear these to avoid incorrect handling.
3825 	 */
3826 	tp->t_rxtshift = 0;
3827 	tp->t_softerror = 0;
3828 	if ((to->to_flags & TOF_TS) &&
3829 	    (ack_type == CUM_ACKED) &&
3830 	    (to->to_tsecr) &&
3831 	    ((rsm->r_flags & (RACK_DEFERRED | RACK_OVERMAX)) == 0)) {
3832 		/*
3833 		 * Now which timestamp does it match? In this block the ACK
3834 		 * must be coming from a previous transmission.
3835 		 */
3836 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
3837 			if (rsm->r_tim_lastsent[i] == to->to_tsecr) {
3838 				t = cts - rsm->r_tim_lastsent[i];
3839 				if ((int)t <= 0)
3840 					t = 1;
3841 				if ((i + 1) < rsm->r_rtr_cnt) {
3842 					/* Likely */
3843 					rack_earlier_retran(tp, rsm, t, cts);
3844 				}
3845 				if (!tp->t_rttlow || tp->t_rttlow > t)
3846 					tp->t_rttlow = t;
3847 				if (!rack->r_ctl.rc_rack_min_rtt || SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
3848 					rack->r_ctl.rc_rack_min_rtt = t;
3849 					if (rack->r_ctl.rc_rack_min_rtt == 0) {
3850 						rack->r_ctl.rc_rack_min_rtt = 1;
3851 					}
3852 				}
3853                                 /*
3854 				 * Note the following calls to
3855 				 * tcp_rack_xmit_timer() are being commented
3856 				 * out for now. They give us no more accuracy
3857 				 * and often lead to a wrong choice. We have
3858 				 * enough samples that have not been
3859 				 * retransmitted. I leave the commented out
3860 				 * code in here in case in the future we
3861 				 * decide to add it back (though I can't forsee
3862 				 * doing that). That way we will easily see
3863 				 * where they need to be placed.
3864 				 */
3865 				if (SEQ_LT(rack->r_ctl.rc_rack_tmit_time,
3866 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)])) {
3867 					/* New more recent rack_tmit_time */
3868 					rack->r_ctl.rc_rack_tmit_time = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
3869 					rack->rc_rack_rtt = t;
3870 				}
3871 				return (1);
3872 			}
3873 		}
3874 		goto ts_not_found;
3875 	} else {
3876 		/*
3877 		 * Ok its a SACK block that we retransmitted. or a windows
3878 		 * machine without timestamps. We can tell nothing from the
3879 		 * time-stamp since its not there or the time the peer last
3880 		 * recieved a segment that moved forward its cum-ack point.
3881 		 */
3882 ts_not_found:
3883 		i = rsm->r_rtr_cnt - 1;
3884 		t = cts - rsm->r_tim_lastsent[i];
3885 		if ((int)t <= 0)
3886 			t = 1;
3887 		if (rack->r_ctl.rc_rack_min_rtt && SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
3888 			/*
3889 			 * We retransmitted and the ack came back in less
3890 			 * than the smallest rtt we have observed. We most
3891 			 * likey did an improper retransmit as outlined in
3892 			 * 4.2 Step 3 point 2 in the rack-draft.
3893 			 */
3894 			i = rsm->r_rtr_cnt - 2;
3895 			t = cts - rsm->r_tim_lastsent[i];
3896 			rack_earlier_retran(tp, rsm, t, cts);
3897 		} else if (rack->r_ctl.rc_rack_min_rtt) {
3898 			/*
3899 			 * We retransmitted it and the retransmit did the
3900 			 * job.
3901 			 */
3902 			if (!rack->r_ctl.rc_rack_min_rtt ||
3903 			    SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
3904 				rack->r_ctl.rc_rack_min_rtt = t;
3905 				if (rack->r_ctl.rc_rack_min_rtt == 0) {
3906 					rack->r_ctl.rc_rack_min_rtt = 1;
3907 				}
3908 			}
3909 			if (SEQ_LT(rack->r_ctl.rc_rack_tmit_time, rsm->r_tim_lastsent[i])) {
3910 				/* New more recent rack_tmit_time */
3911 				rack->r_ctl.rc_rack_tmit_time = rsm->r_tim_lastsent[i];
3912 				rack->rc_rack_rtt = t;
3913 			}
3914 			return (1);
3915 		}
3916 	}
3917 	return (0);
3918 }
3919 
3920 /*
3921  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
3922  */
3923 static void
3924 rack_log_sack_passed(struct tcpcb *tp,
3925     struct tcp_rack *rack, struct rack_sendmap *rsm)
3926 {
3927 	struct rack_sendmap *nrsm;
3928 	uint32_t ts;
3929 	int32_t idx;
3930 
3931 	idx = rsm->r_rtr_cnt - 1;
3932 	ts = rsm->r_tim_lastsent[idx];
3933 	nrsm = rsm;
3934 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &rack->r_ctl.rc_tmap,
3935 	    rack_head, r_tnext) {
3936 		if (nrsm == rsm) {
3937 			/* Skip orginal segment he is acked */
3938 			continue;
3939 		}
3940 		if (nrsm->r_flags & RACK_ACKED) {
3941 			/* Skip ack'd segments */
3942 			continue;
3943 		}
3944 		if (nrsm->r_flags & RACK_SACK_PASSED) {
3945 			/*
3946 			 * We found one that is already marked
3947 			 * passed, we have been here before and
3948 			 * so all others below this are marked.
3949 			 */
3950 			break;
3951 		}
3952 		idx = nrsm->r_rtr_cnt - 1;
3953 		if (ts == nrsm->r_tim_lastsent[idx]) {
3954 			/*
3955 			 * For this case lets use seq no, if we sent in a
3956 			 * big block (TSO) we would have a bunch of segments
3957 			 * sent at the same time.
3958 			 *
3959 			 * We would only get a report if its SEQ is earlier.
3960 			 * If we have done multiple retransmits the times
3961 			 * would not be equal.
3962 			 */
3963 			if (SEQ_LT(nrsm->r_start, rsm->r_start)) {
3964 				nrsm->r_flags |= RACK_SACK_PASSED;
3965 				nrsm->r_flags &= ~RACK_WAS_SACKPASS;
3966 			}
3967 		} else {
3968 			/*
3969 			 * Here they were sent at different times, not a big
3970 			 * block. Since we transmitted this one later and
3971 			 * see it sack'd then this must also be missing (or
3972 			 * we would have gotten a sack block for it)
3973 			 */
3974 			nrsm->r_flags |= RACK_SACK_PASSED;
3975 			nrsm->r_flags &= ~RACK_WAS_SACKPASS;
3976 		}
3977 	}
3978 }
3979 
3980 static uint32_t
3981 rack_proc_sack_blk(struct tcpcb *tp, struct tcp_rack *rack, struct sackblk *sack,
3982     struct tcpopt *to, struct rack_sendmap **prsm, uint32_t cts)
3983 {
3984 	int32_t idx;
3985 	int32_t times = 0;
3986 	uint32_t start, end, changed = 0;
3987 	struct rack_sendmap *rsm, *nrsm;
3988 	int32_t used_ref = 1;
3989 
3990 	start = sack->start;
3991 	end = sack->end;
3992 	rsm = *prsm;
3993 	if (rsm && SEQ_LT(start, rsm->r_start)) {
3994 		TAILQ_FOREACH_REVERSE_FROM(rsm, &rack->r_ctl.rc_map, rack_head, r_next) {
3995 			if (SEQ_GEQ(start, rsm->r_start) &&
3996 			    SEQ_LT(start, rsm->r_end)) {
3997 				goto do_rest_ofb;
3998 			}
3999 		}
4000 	}
4001 	if (rsm == NULL) {
4002 start_at_beginning:
4003 		rsm = NULL;
4004 		used_ref = 0;
4005 	}
4006 	/* First lets locate the block where this guy is */
4007 	TAILQ_FOREACH_FROM(rsm, &rack->r_ctl.rc_map, r_next) {
4008 		if (SEQ_GEQ(start, rsm->r_start) &&
4009 		    SEQ_LT(start, rsm->r_end)) {
4010 			break;
4011 		}
4012 	}
4013 do_rest_ofb:
4014 	if (rsm == NULL) {
4015 		/*
4016 		 * This happens when we get duplicate sack blocks with the
4017 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
4018 		 * will not change there location so we would just start at
4019 		 * the end of the first one and get lost.
4020 		 */
4021 		if (tp->t_flags & TF_SENTFIN) {
4022 			/*
4023 			 * Check to see if we have not logged the FIN that
4024 			 * went out.
4025 			 */
4026 			nrsm = TAILQ_LAST_FAST(&rack->r_ctl.rc_map, rack_sendmap, r_next);
4027 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
4028 				/*
4029 				 * Ok we did not get the FIN logged.
4030 				 */
4031 				nrsm->r_end++;
4032 				rsm = nrsm;
4033 				goto do_rest_ofb;
4034 			}
4035 		}
4036 		if (times == 1) {
4037 #ifdef INVARIANTS
4038 			panic("tp:%p rack:%p sack:%p to:%p prsm:%p",
4039 			    tp, rack, sack, to, prsm);
4040 #else
4041 			goto out;
4042 #endif
4043 		}
4044 		times++;
4045 		counter_u64_add(rack_sack_proc_restart, 1);
4046 		goto start_at_beginning;
4047 	}
4048 	/* Ok we have an ACK for some piece of rsm */
4049 	if (rsm->r_start != start) {
4050 		/*
4051 		 * Need to split this in two pieces the before and after.
4052 		 */
4053 		nrsm = rack_alloc_limit(rack, RACK_LIMIT_TYPE_SPLIT);
4054 		if (nrsm == NULL) {
4055 			/*
4056 			 * failed XXXrrs what can we do but loose the sack
4057 			 * info?
4058 			 */
4059 			goto out;
4060 		}
4061 		nrsm->r_start = start;
4062 		nrsm->r_rtr_bytes = 0;
4063 		nrsm->r_end = rsm->r_end;
4064 		nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4065 		nrsm->r_flags = rsm->r_flags;
4066 		nrsm->r_sndcnt = rsm->r_sndcnt;
4067 		for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4068 			nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4069 		}
4070 		rsm->r_end = nrsm->r_start;
4071 		TAILQ_INSERT_AFTER(&rack->r_ctl.rc_map, rsm, nrsm, r_next);
4072 		if (rsm->r_in_tmap) {
4073 			TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4074 			nrsm->r_in_tmap = 1;
4075 		}
4076 		rsm->r_flags &= (~RACK_HAS_FIN);
4077 		rsm = nrsm;
4078 	}
4079 	if (SEQ_GEQ(end, rsm->r_end)) {
4080 		/*
4081 		 * The end of this block is either beyond this guy or right
4082 		 * at this guy.
4083 		 */
4084 
4085 		if ((rsm->r_flags & RACK_ACKED) == 0) {
4086 			rack_update_rtt(tp, rack, rsm, to, cts, SACKED);
4087 			changed += (rsm->r_end - rsm->r_start);
4088 			rack->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
4089 			rack_log_sack_passed(tp, rack, rsm);
4090 			/* Is Reordering occuring? */
4091 			if (rsm->r_flags & RACK_SACK_PASSED) {
4092 				counter_u64_add(rack_reorder_seen, 1);
4093 				rack->r_ctl.rc_reorder_ts = cts;
4094 			}
4095 			rsm->r_flags |= RACK_ACKED;
4096 			rsm->r_flags &= ~RACK_TLP;
4097 			if (rsm->r_in_tmap) {
4098 				TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
4099 				rsm->r_in_tmap = 0;
4100 			}
4101 		}
4102 		if (end == rsm->r_end) {
4103 			/* This block only - done */
4104 			goto out;
4105 		}
4106 		/* There is more not coverend by this rsm move on */
4107 		start = rsm->r_end;
4108 		nrsm = TAILQ_NEXT(rsm, r_next);
4109 		rsm = nrsm;
4110 		times = 0;
4111 		goto do_rest_ofb;
4112 	}
4113 	/* Ok we need to split off this one at the tail */
4114 	nrsm = rack_alloc_limit(rack, RACK_LIMIT_TYPE_SPLIT);
4115 	if (nrsm == NULL) {
4116 		/* failed rrs what can we do but loose the sack info? */
4117 		goto out;
4118 	}
4119 	/* Clone it */
4120 	nrsm->r_start = end;
4121 	nrsm->r_end = rsm->r_end;
4122 	nrsm->r_rtr_bytes = 0;
4123 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4124 	nrsm->r_flags = rsm->r_flags;
4125 	nrsm->r_sndcnt = rsm->r_sndcnt;
4126 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4127 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4128 	}
4129 	/* The sack block does not cover this guy fully */
4130 	rsm->r_flags &= (~RACK_HAS_FIN);
4131 	rsm->r_end = end;
4132 	TAILQ_INSERT_AFTER(&rack->r_ctl.rc_map, rsm, nrsm, r_next);
4133 	if (rsm->r_in_tmap) {
4134 		TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4135 		nrsm->r_in_tmap = 1;
4136 	}
4137 	if (rsm->r_flags & RACK_ACKED) {
4138 		/* Been here done that */
4139 		goto out;
4140 	}
4141 	rack_update_rtt(tp, rack, rsm, to, cts, SACKED);
4142 	changed += (rsm->r_end - rsm->r_start);
4143 	rack->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
4144 	rack_log_sack_passed(tp, rack, rsm);
4145 	/* Is Reordering occuring? */
4146 	if (rsm->r_flags & RACK_SACK_PASSED) {
4147 		counter_u64_add(rack_reorder_seen, 1);
4148 		rack->r_ctl.rc_reorder_ts = cts;
4149 	}
4150 	rsm->r_flags |= RACK_ACKED;
4151 	rsm->r_flags &= ~RACK_TLP;
4152 	if (rsm->r_in_tmap) {
4153 		TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
4154 		rsm->r_in_tmap = 0;
4155 	}
4156 out:
4157 	if (rsm && (rsm->r_flags & RACK_ACKED)) {
4158 		/*
4159 		 * Now can we merge this newly acked
4160 		 * block with either the previous or
4161 		 * next block?
4162 		 */
4163 		nrsm = TAILQ_NEXT(rsm, r_next);
4164 		if (nrsm &&
4165 		    (nrsm->r_flags & RACK_ACKED)) {
4166 			/* yep this and next can be merged */
4167 			rsm = rack_merge_rsm(rack, rsm, nrsm);
4168 		}
4169 		/* Now what about the previous? */
4170 		nrsm = TAILQ_PREV(rsm, rack_head, r_next);
4171 		if (nrsm &&
4172 		    (nrsm->r_flags & RACK_ACKED)) {
4173 			/* yep the previous and this can be merged */
4174 			rsm = rack_merge_rsm(rack, nrsm, rsm);
4175 		}
4176 	}
4177 	if (used_ref == 0) {
4178 		counter_u64_add(rack_sack_proc_all, 1);
4179 	} else {
4180 		counter_u64_add(rack_sack_proc_short, 1);
4181 	}
4182 	/* Save off where we last were */
4183 	if (rsm)
4184 		rack->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
4185 	else
4186 		rack->r_ctl.rc_sacklast = NULL;
4187 	*prsm = rsm;
4188 	return (changed);
4189 }
4190 
4191 static void inline
4192 rack_peer_reneges(struct tcp_rack *rack, struct rack_sendmap *rsm, tcp_seq th_ack)
4193 {
4194 	struct rack_sendmap *tmap;
4195 
4196 	tmap = NULL;
4197 	while (rsm && (rsm->r_flags & RACK_ACKED)) {
4198 		/* Its no longer sacked, mark it so */
4199 		rack->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
4200 #ifdef INVARIANTS
4201 		if (rsm->r_in_tmap) {
4202 			panic("rack:%p rsm:%p flags:0x%x in tmap?",
4203 			      rack, rsm, rsm->r_flags);
4204 		}
4205 #endif
4206 		rsm->r_flags &= ~(RACK_ACKED|RACK_SACK_PASSED|RACK_WAS_SACKPASS);
4207 		/* Rebuild it into our tmap */
4208 		if (tmap == NULL) {
4209 			TAILQ_INSERT_HEAD(&rack->r_ctl.rc_tmap, rsm, r_tnext);
4210 			tmap = rsm;
4211 		} else {
4212 			TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, tmap, rsm, r_tnext);
4213 			tmap = rsm;
4214 		}
4215 		tmap->r_in_tmap = 1;
4216 		rsm = TAILQ_NEXT(rsm, r_next);
4217 	}
4218 	/*
4219 	 * Now lets possibly clear the sack filter so we start
4220 	 * recognizing sacks that cover this area.
4221 	 */
4222 	if (rack_use_sack_filter)
4223 		sack_filter_clear(&rack->r_ctl.rack_sf, th_ack);
4224 
4225 }
4226 
4227 static void
4228 rack_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th)
4229 {
4230 	uint32_t changed, last_seq, entered_recovery = 0;
4231 	struct tcp_rack *rack;
4232 	struct rack_sendmap *rsm;
4233 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
4234 	register uint32_t th_ack;
4235 	int32_t i, j, k, num_sack_blks = 0;
4236 	uint32_t cts, acked, ack_point, sack_changed = 0;
4237 
4238 	INP_WLOCK_ASSERT(tp->t_inpcb);
4239 	if (th->th_flags & TH_RST) {
4240 		/* We don't log resets */
4241 		return;
4242 	}
4243 	rack = (struct tcp_rack *)tp->t_fb_ptr;
4244 	cts = tcp_ts_getticks();
4245 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_map);
4246 	changed = 0;
4247 	th_ack = th->th_ack;
4248 
4249 	if (SEQ_GT(th_ack, tp->snd_una)) {
4250 		rack_log_progress_event(rack, tp, ticks, PROGRESS_UPDATE, __LINE__);
4251 		tp->t_acktime = ticks;
4252 	}
4253 	if (rsm && SEQ_GT(th_ack, rsm->r_start))
4254 		changed = th_ack - rsm->r_start;
4255 	if (changed) {
4256 		/*
4257 		 * The ACK point is advancing to th_ack, we must drop off
4258 		 * the packets in the rack log and calculate any eligble
4259 		 * RTT's.
4260 		 */
4261 		rack->r_wanted_output++;
4262 more:
4263 		rsm = TAILQ_FIRST(&rack->r_ctl.rc_map);
4264 		if (rsm == NULL) {
4265 			if ((th_ack - 1) == tp->iss) {
4266 				/*
4267 				 * For the SYN incoming case we will not
4268 				 * have called tcp_output for the sending of
4269 				 * the SYN, so there will be no map. All
4270 				 * other cases should probably be a panic.
4271 				 */
4272 				goto proc_sack;
4273 			}
4274 			if (tp->t_flags & TF_SENTFIN) {
4275 				/* if we send a FIN we will not hav a map */
4276 				goto proc_sack;
4277 			}
4278 #ifdef INVARIANTS
4279 			panic("No rack map tp:%p for th:%p state:%d rack:%p snd_una:%u snd_max:%u snd_nxt:%u chg:%d\n",
4280 			    tp,
4281 			    th, tp->t_state, rack,
4282 			    tp->snd_una, tp->snd_max, tp->snd_nxt, changed);
4283 #endif
4284 			goto proc_sack;
4285 		}
4286 		if (SEQ_LT(th_ack, rsm->r_start)) {
4287 			/* Huh map is missing this */
4288 #ifdef INVARIANTS
4289 			printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d\n",
4290 			    rsm->r_start,
4291 			    th_ack, tp->t_state, rack->r_state);
4292 #endif
4293 			goto proc_sack;
4294 		}
4295 		rack_update_rtt(tp, rack, rsm, to, cts, CUM_ACKED);
4296 		/* Now do we consume the whole thing? */
4297 		if (SEQ_GEQ(th_ack, rsm->r_end)) {
4298 			/* Its all consumed. */
4299 			uint32_t left;
4300 
4301 			rack->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
4302 			rsm->r_rtr_bytes = 0;
4303 			TAILQ_REMOVE(&rack->r_ctl.rc_map, rsm, r_next);
4304 			if (rsm->r_in_tmap) {
4305 				TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
4306 				rsm->r_in_tmap = 0;
4307 			}
4308 			if (rack->r_ctl.rc_next == rsm) {
4309 				/* scoot along the marker */
4310 				rack->r_ctl.rc_next = TAILQ_FIRST(&rack->r_ctl.rc_map);
4311 			}
4312 			if (rsm->r_flags & RACK_ACKED) {
4313 				/*
4314 				 * It was acked on the scoreboard -- remove
4315 				 * it from total
4316 				 */
4317 				rack->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
4318 			} else if (rsm->r_flags & RACK_SACK_PASSED) {
4319 				/*
4320 				 * There are acked segments ACKED on the
4321 				 * scoreboard further up. We are seeing
4322 				 * reordering.
4323 				 */
4324 				counter_u64_add(rack_reorder_seen, 1);
4325 				rsm->r_flags |= RACK_ACKED;
4326 				rack->r_ctl.rc_reorder_ts = cts;
4327 			}
4328 			left = th_ack - rsm->r_end;
4329 			if (rsm->r_rtr_cnt > 1) {
4330 				/*
4331 				 * Technically we should make r_rtr_cnt be
4332 				 * monotonicly increasing and just mod it to
4333 				 * the timestamp it is replacing.. that way
4334 				 * we would have the last 3 retransmits. Now
4335 				 * rc_loss_count will be wrong if we
4336 				 * retransmit something more than 2 times in
4337 				 * recovery :(
4338 				 */
4339 				rack->r_ctl.rc_loss_count += (rsm->r_rtr_cnt - 1);
4340 			}
4341 			/* Free back to zone */
4342 			rack_free(rack, rsm);
4343 			if (left) {
4344 				goto more;
4345 			}
4346 			goto proc_sack;
4347 		}
4348 		if (rsm->r_flags & RACK_ACKED) {
4349 			/*
4350 			 * It was acked on the scoreboard -- remove it from
4351 			 * total for the part being cum-acked.
4352 			 */
4353 			rack->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
4354 		}
4355 		rack->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
4356 		rsm->r_rtr_bytes = 0;
4357 		rsm->r_start = th_ack;
4358 	}
4359 proc_sack:
4360 	/* Check for reneging */
4361 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_map);
4362 	if (rsm && (rsm->r_flags & RACK_ACKED) && (th_ack == rsm->r_start)) {
4363 		/*
4364 		 * The peer has moved snd_una up to
4365 		 * the edge of this send, i.e. one
4366 		 * that it had previously acked. The only
4367 		 * way that can be true if the peer threw
4368 		 * away data (space issues) that it had
4369 		 * previously sacked (else it would have
4370 		 * given us snd_una up to (rsm->r_end).
4371 		 * We need to undo the acked markings here.
4372 		 *
4373 		 * Note we have to look to make sure th_ack is
4374 		 * our rsm->r_start in case we get an old ack
4375 		 * where th_ack is behind snd_una.
4376 		 */
4377 		rack_peer_reneges(rack, rsm, th->th_ack);
4378 	}
4379 	if ((to->to_flags & TOF_SACK) == 0) {
4380 		/* We are done nothing left to log */
4381 		goto out;
4382 	}
4383 	rsm = TAILQ_LAST_FAST(&rack->r_ctl.rc_map, rack_sendmap, r_next);
4384 	if (rsm) {
4385 		last_seq = rsm->r_end;
4386 	} else {
4387 		last_seq = tp->snd_max;
4388 	}
4389 	/* Sack block processing */
4390 	if (SEQ_GT(th_ack, tp->snd_una))
4391 		ack_point = th_ack;
4392 	else
4393 		ack_point = tp->snd_una;
4394 	for (i = 0; i < to->to_nsacks; i++) {
4395 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
4396 		    &sack, sizeof(sack));
4397 		sack.start = ntohl(sack.start);
4398 		sack.end = ntohl(sack.end);
4399 		if (SEQ_GT(sack.end, sack.start) &&
4400 		    SEQ_GT(sack.start, ack_point) &&
4401 		    SEQ_LT(sack.start, tp->snd_max) &&
4402 		    SEQ_GT(sack.end, ack_point) &&
4403 		    SEQ_LEQ(sack.end, tp->snd_max)) {
4404 			if ((rack->r_ctl.rc_num_maps_alloced > rack_sack_block_limit) &&
4405 			    (SEQ_LT(sack.end, last_seq)) &&
4406 			    ((sack.end - sack.start) < (tp->t_maxseg / 8))) {
4407 				/*
4408 				 * Not the last piece and its smaller than
4409 				 * 1/8th of a MSS. We ignore this.
4410 				 */
4411 				counter_u64_add(rack_runt_sacks, 1);
4412 				continue;
4413 			}
4414 			sack_blocks[num_sack_blks] = sack;
4415 			num_sack_blks++;
4416 		} else if (SEQ_LEQ(sack.start, th_ack) &&
4417 			   SEQ_LEQ(sack.end, th_ack)) {
4418 			/*
4419 			 * Its a D-SACK block.
4420 			 */
4421 /*			tcp_record_dsack(sack.start, sack.end); */
4422 		}
4423 	}
4424 	if (num_sack_blks == 0)
4425 		goto out;
4426 	/*
4427 	 * Sort the SACK blocks so we can update the rack scoreboard with
4428 	 * just one pass.
4429 	 */
4430 	if (rack_use_sack_filter) {
4431 		num_sack_blks = sack_filter_blks(&rack->r_ctl.rack_sf, sack_blocks,
4432 						 num_sack_blks, th->th_ack);
4433 		ctf_log_sack_filter(rack->rc_tp, num_sack_blks, sack_blocks);
4434 	}
4435 	if (num_sack_blks < 2) {
4436 		goto do_sack_work;
4437 	}
4438 	/* Sort the sacks */
4439 	for (i = 0; i < num_sack_blks; i++) {
4440 		for (j = i + 1; j < num_sack_blks; j++) {
4441 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
4442 				sack = sack_blocks[i];
4443 				sack_blocks[i] = sack_blocks[j];
4444 				sack_blocks[j] = sack;
4445 			}
4446 		}
4447 	}
4448 	/*
4449 	 * Now are any of the sack block ends the same (yes some
4450 	 * implememtations send these)?
4451 	 */
4452 again:
4453 	if (num_sack_blks > 1) {
4454 		for (i = 0; i < num_sack_blks; i++) {
4455 			for (j = i + 1; j < num_sack_blks; j++) {
4456 				if (sack_blocks[i].end == sack_blocks[j].end) {
4457 					/*
4458 					 * Ok these two have the same end we
4459 					 * want the smallest end and then
4460 					 * throw away the larger and start
4461 					 * again.
4462 					 */
4463 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
4464 						/*
4465 						 * The second block covers
4466 						 * more area use that
4467 						 */
4468 						sack_blocks[i].start = sack_blocks[j].start;
4469 					}
4470 					/*
4471 					 * Now collapse out the dup-sack and
4472 					 * lower the count
4473 					 */
4474 					for (k = (j + 1); k < num_sack_blks; k++) {
4475 						sack_blocks[j].start = sack_blocks[k].start;
4476 						sack_blocks[j].end = sack_blocks[k].end;
4477 						j++;
4478 					}
4479 					num_sack_blks--;
4480 					goto again;
4481 				}
4482 			}
4483 		}
4484 	}
4485 do_sack_work:
4486 	rsm = rack->r_ctl.rc_sacklast;
4487 	for (i = 0; i < num_sack_blks; i++) {
4488 		acked = rack_proc_sack_blk(tp, rack, &sack_blocks[i], to, &rsm, cts);
4489 		if (acked) {
4490 			rack->r_wanted_output++;
4491 			changed += acked;
4492 			sack_changed += acked;
4493 		}
4494 	}
4495 out:
4496 	if (changed) {
4497 		/* Something changed cancel the rack timer */
4498 		rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
4499 	}
4500 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
4501 		/*
4502 		 * Ok we have a high probability that we need to go in to
4503 		 * recovery since we have data sack'd
4504 		 */
4505 		struct rack_sendmap *rsm;
4506 		uint32_t tsused;
4507 
4508 		tsused = tcp_ts_getticks();
4509 		rsm = tcp_rack_output(tp, rack, tsused);
4510 		if (rsm) {
4511 			/* Enter recovery */
4512 			rack->r_ctl.rc_rsm_start = rsm->r_start;
4513 			rack->r_ctl.rc_cwnd_at = tp->snd_cwnd;
4514 			rack->r_ctl.rc_ssthresh_at = tp->snd_ssthresh;
4515 			entered_recovery = 1;
4516 			rack_cong_signal(tp, NULL, CC_NDUPACK);
4517 			/*
4518 			 * When we enter recovery we need to assure we send
4519 			 * one packet.
4520 			 */
4521 			rack->r_ctl.rc_prr_sndcnt = tp->t_maxseg;
4522 			rack->r_timer_override = 1;
4523 		}
4524 	}
4525 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
4526 		/* Deal with changed an PRR here (in recovery only) */
4527 		uint32_t pipe, snd_una;
4528 
4529 		rack->r_ctl.rc_prr_delivered += changed;
4530 		/* Compute prr_sndcnt */
4531 		if (SEQ_GT(tp->snd_una, th_ack)) {
4532 			snd_una = tp->snd_una;
4533 		} else {
4534 			snd_una = th_ack;
4535 		}
4536 		pipe = ((tp->snd_max - snd_una) - rack->r_ctl.rc_sacked) + rack->r_ctl.rc_holes_rxt;
4537 		if (pipe > tp->snd_ssthresh) {
4538 			long sndcnt;
4539 
4540 			sndcnt = rack->r_ctl.rc_prr_delivered * tp->snd_ssthresh;
4541 			if (rack->r_ctl.rc_prr_recovery_fs > 0)
4542 				sndcnt /= (long)rack->r_ctl.rc_prr_recovery_fs;
4543 			else {
4544 				rack->r_ctl.rc_prr_sndcnt = 0;
4545 				sndcnt = 0;
4546 			}
4547 			sndcnt++;
4548 			if (sndcnt > (long)rack->r_ctl.rc_prr_out)
4549 				sndcnt -= rack->r_ctl.rc_prr_out;
4550 			else
4551 				sndcnt = 0;
4552 			rack->r_ctl.rc_prr_sndcnt = sndcnt;
4553 		} else {
4554 			uint32_t limit;
4555 
4556 			if (rack->r_ctl.rc_prr_delivered > rack->r_ctl.rc_prr_out)
4557 				limit = (rack->r_ctl.rc_prr_delivered - rack->r_ctl.rc_prr_out);
4558 			else
4559 				limit = 0;
4560 			if (changed > limit)
4561 				limit = changed;
4562 			limit += tp->t_maxseg;
4563 			if (tp->snd_ssthresh > pipe) {
4564 				rack->r_ctl.rc_prr_sndcnt = min((tp->snd_ssthresh - pipe), limit);
4565 			} else {
4566 				rack->r_ctl.rc_prr_sndcnt = min(0, limit);
4567 			}
4568 		}
4569 		if (rack->r_ctl.rc_prr_sndcnt >= tp->t_maxseg) {
4570 			rack->r_timer_override = 1;
4571 		}
4572 	}
4573 }
4574 
4575 /*
4576  * Return value of 1, we do not need to call rack_process_data().
4577  * return value of 0, rack_process_data can be called.
4578  * For ret_val if its 0 the TCP is locked, if its non-zero
4579  * its unlocked and probably unsafe to touch the TCB.
4580  */
4581 static int
4582 rack_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
4583     struct tcpcb *tp, struct tcpopt *to,
4584     uint32_t tiwin, int32_t tlen,
4585     int32_t * ofia, int32_t thflags, int32_t * ret_val)
4586 {
4587 	int32_t ourfinisacked = 0;
4588 	int32_t nsegs, acked_amount;
4589 	int32_t acked;
4590 	struct mbuf *mfree;
4591 	struct tcp_rack *rack;
4592 	int32_t recovery = 0;
4593 
4594 	rack = (struct tcp_rack *)tp->t_fb_ptr;
4595 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
4596 		rack_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
4597 		return (1);
4598 	}
4599 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
4600 		rack_log_ack(tp, to, th);
4601 	}
4602 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
4603 		/*
4604 		 * Old ack, behind (or duplicate to) the last one rcv'd
4605 		 * Note: Should mark reordering is occuring! We should also
4606 		 * look for sack blocks arriving e.g. ack 1, 4-4 then ack 1,
4607 		 * 3-3, 4-4 would be reording. As well as ack 1, 3-3 <no
4608 		 * retran and> ack 3
4609 		 */
4610 		return (0);
4611 	}
4612 	/*
4613 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
4614 	 * something we sent.
4615 	 */
4616 	if (tp->t_flags & TF_NEEDSYN) {
4617 		/*
4618 		 * T/TCP: Connection was half-synchronized, and our SYN has
4619 		 * been ACK'd (so connection is now fully synchronized).  Go
4620 		 * to non-starred state, increment snd_una for ACK of SYN,
4621 		 * and check if we can do window scaling.
4622 		 */
4623 		tp->t_flags &= ~TF_NEEDSYN;
4624 		tp->snd_una++;
4625 		/* Do window scaling? */
4626 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
4627 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
4628 			tp->rcv_scale = tp->request_r_scale;
4629 			/* Send window already scaled. */
4630 		}
4631 	}
4632 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
4633 	INP_WLOCK_ASSERT(tp->t_inpcb);
4634 
4635 	acked = BYTES_THIS_ACK(tp, th);
4636 	TCPSTAT_ADD(tcps_rcvackpack, nsegs);
4637 	TCPSTAT_ADD(tcps_rcvackbyte, acked);
4638 
4639 	/*
4640 	 * If we just performed our first retransmit, and the ACK arrives
4641 	 * within our recovery window, then it was a mistake to do the
4642 	 * retransmit in the first place.  Recover our original cwnd and
4643 	 * ssthresh, and proceed to transmit where we left off.
4644 	 */
4645 	if (tp->t_flags & TF_PREVVALID) {
4646 		tp->t_flags &= ~TF_PREVVALID;
4647 		if (tp->t_rxtshift == 1 &&
4648 		    (int)(ticks - tp->t_badrxtwin) < 0)
4649 			rack_cong_signal(tp, th, CC_RTO_ERR);
4650 	}
4651 	/*
4652 	 * If we have a timestamp reply, update smoothed round trip time. If
4653 	 * no timestamp is present but transmit timer is running and timed
4654 	 * sequence number was acked, update smoothed round trip time. Since
4655 	 * we now have an rtt measurement, cancel the timer backoff (cf.,
4656 	 * Phil Karn's retransmit alg.). Recompute the initial retransmit
4657 	 * timer.
4658 	 *
4659 	 * Some boxes send broken timestamp replies during the SYN+ACK
4660 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
4661 	 * and blow up the retransmit timer.
4662 	 */
4663 	/*
4664 	 * If all outstanding data is acked, stop retransmit timer and
4665 	 * remember to restart (more output or persist). If there is more
4666 	 * data to be acked, restart retransmit timer, using current
4667 	 * (possibly backed-off) value.
4668 	 */
4669 	if (th->th_ack == tp->snd_max) {
4670 		rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
4671 		rack->r_wanted_output++;
4672 	}
4673 	/*
4674 	 * If no data (only SYN) was ACK'd, skip rest of ACK processing.
4675 	 */
4676 	if (acked == 0) {
4677 		if (ofia)
4678 			*ofia = ourfinisacked;
4679 		return (0);
4680 	}
4681 	if (rack->r_ctl.rc_early_recovery) {
4682 		if (IN_RECOVERY(tp->t_flags)) {
4683 			if (SEQ_LT(th->th_ack, tp->snd_recover) &&
4684 			    (SEQ_LT(th->th_ack, tp->snd_max))) {
4685 				tcp_rack_partialack(tp, th);
4686 			} else {
4687 				rack_post_recovery(tp, th);
4688 				recovery = 1;
4689 			}
4690 		}
4691 	}
4692 	/*
4693 	 * Let the congestion control algorithm update congestion control
4694 	 * related information. This typically means increasing the
4695 	 * congestion window.
4696 	 */
4697 	rack_ack_received(tp, rack, th, nsegs, CC_ACK, recovery);
4698 	SOCKBUF_LOCK(&so->so_snd);
4699 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
4700 	tp->snd_wnd -= acked_amount;
4701 	mfree = sbcut_locked(&so->so_snd, acked_amount);
4702 	if ((sbused(&so->so_snd) == 0) &&
4703 	    (acked > acked_amount) &&
4704 	    (tp->t_state >= TCPS_FIN_WAIT_1)) {
4705 		ourfinisacked = 1;
4706 	}
4707 	/* NB: sowwakeup_locked() does an implicit unlock. */
4708 	sowwakeup_locked(so);
4709 	m_freem(mfree);
4710 	if (rack->r_ctl.rc_early_recovery == 0) {
4711 		if (IN_RECOVERY(tp->t_flags)) {
4712 			if (SEQ_LT(th->th_ack, tp->snd_recover) &&
4713 			    (SEQ_LT(th->th_ack, tp->snd_max))) {
4714 				tcp_rack_partialack(tp, th);
4715 			} else {
4716 				rack_post_recovery(tp, th);
4717 			}
4718 		}
4719 	}
4720 	tp->snd_una = th->th_ack;
4721 	if (SEQ_GT(tp->snd_una, tp->snd_recover))
4722 		tp->snd_recover = tp->snd_una;
4723 
4724 	if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
4725 		tp->snd_nxt = tp->snd_una;
4726 	}
4727 	if (tp->snd_una == tp->snd_max) {
4728 		/* Nothing left outstanding */
4729 		rack_log_progress_event(rack, tp, 0, PROGRESS_CLEAR, __LINE__);
4730 		tp->t_acktime = 0;
4731 		rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
4732 		/* Set need output so persist might get set */
4733 		rack->r_wanted_output++;
4734 		if (rack_use_sack_filter)
4735 			sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
4736 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
4737 		    (sbavail(&so->so_snd) == 0) &&
4738 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
4739 			/*
4740 			 * The socket was gone and the
4741 			 * peer sent data, time to
4742 			 * reset him.
4743 			 */
4744 			*ret_val = 1;
4745 			tp = tcp_close(tp);
4746 			rack_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
4747 			return (1);
4748 		}
4749 	}
4750 	if (ofia)
4751 		*ofia = ourfinisacked;
4752 	return (0);
4753 }
4754 
4755 
4756 /*
4757  * Return value of 1, the TCB is unlocked and most
4758  * likely gone, return value of 0, the TCP is still
4759  * locked.
4760  */
4761 static int
4762 rack_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
4763     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
4764     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
4765 {
4766 	/*
4767 	 * Update window information. Don't look at window if no ACK: TAC's
4768 	 * send garbage on first SYN.
4769 	 */
4770 	int32_t nsegs;
4771 #ifdef TCP_RFC7413
4772 	int32_t tfo_syn;
4773 #else
4774 #define	tfo_syn	(FALSE)
4775 #endif
4776 	struct tcp_rack *rack;
4777 
4778 	rack = (struct tcp_rack *)tp->t_fb_ptr;
4779 	INP_WLOCK_ASSERT(tp->t_inpcb);
4780 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
4781 	if ((thflags & TH_ACK) &&
4782 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
4783 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
4784 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
4785 		/* keep track of pure window updates */
4786 		if (tlen == 0 &&
4787 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
4788 			TCPSTAT_INC(tcps_rcvwinupd);
4789 		tp->snd_wnd = tiwin;
4790 		tp->snd_wl1 = th->th_seq;
4791 		tp->snd_wl2 = th->th_ack;
4792 		if (tp->snd_wnd > tp->max_sndwnd)
4793 			tp->max_sndwnd = tp->snd_wnd;
4794 		rack->r_wanted_output++;
4795 	} else if (thflags & TH_ACK) {
4796 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
4797 			tp->snd_wnd = tiwin;
4798 			tp->snd_wl1 = th->th_seq;
4799 			tp->snd_wl2 = th->th_ack;
4800 		}
4801 	}
4802 	/* Was persist timer active and now we have window space? */
4803 	if ((rack->rc_in_persist != 0) && tp->snd_wnd) {
4804 		rack_exit_persist(tp, rack);
4805 		tp->snd_nxt = tp->snd_max;
4806 		/* Make sure we output to start the timer */
4807 		rack->r_wanted_output++;
4808 	}
4809 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
4810 		m_freem(m);
4811 		return (0);
4812 	}
4813 	/*
4814 	 * Process segments with URG.
4815 	 */
4816 	if ((thflags & TH_URG) && th->th_urp &&
4817 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
4818 		/*
4819 		 * This is a kludge, but if we receive and accept random
4820 		 * urgent pointers, we'll crash in soreceive.  It's hard to
4821 		 * imagine someone actually wanting to send this much urgent
4822 		 * data.
4823 		 */
4824 		SOCKBUF_LOCK(&so->so_rcv);
4825 		if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
4826 			th->th_urp = 0;	/* XXX */
4827 			thflags &= ~TH_URG;	/* XXX */
4828 			SOCKBUF_UNLOCK(&so->so_rcv);	/* XXX */
4829 			goto dodata;	/* XXX */
4830 		}
4831 		/*
4832 		 * If this segment advances the known urgent pointer, then
4833 		 * mark the data stream.  This should not happen in
4834 		 * CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since a
4835 		 * FIN has been received from the remote side. In these
4836 		 * states we ignore the URG.
4837 		 *
4838 		 * According to RFC961 (Assigned Protocols), the urgent
4839 		 * pointer points to the last octet of urgent data.  We
4840 		 * continue, however, to consider it to indicate the first
4841 		 * octet of data past the urgent section as the original
4842 		 * spec states (in one of two places).
4843 		 */
4844 		if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
4845 			tp->rcv_up = th->th_seq + th->th_urp;
4846 			so->so_oobmark = sbavail(&so->so_rcv) +
4847 			    (tp->rcv_up - tp->rcv_nxt) - 1;
4848 			if (so->so_oobmark == 0)
4849 				so->so_rcv.sb_state |= SBS_RCVATMARK;
4850 			sohasoutofband(so);
4851 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
4852 		}
4853 		SOCKBUF_UNLOCK(&so->so_rcv);
4854 		/*
4855 		 * Remove out of band data so doesn't get presented to user.
4856 		 * This can happen independent of advancing the URG pointer,
4857 		 * but if two URG's are pending at once, some out-of-band
4858 		 * data may creep in... ick.
4859 		 */
4860 		if (th->th_urp <= (uint32_t) tlen &&
4861 		    !(so->so_options & SO_OOBINLINE)) {
4862 			/* hdr drop is delayed */
4863 			tcp_pulloutofband(so, th, m, drop_hdrlen);
4864 		}
4865 	} else {
4866 		/*
4867 		 * If no out of band data is expected, pull receive urgent
4868 		 * pointer along with the receive window.
4869 		 */
4870 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
4871 			tp->rcv_up = tp->rcv_nxt;
4872 	}
4873 dodata:				/* XXX */
4874 	INP_WLOCK_ASSERT(tp->t_inpcb);
4875 
4876 	/*
4877 	 * Process the segment text, merging it into the TCP sequencing
4878 	 * queue, and arranging for acknowledgment of receipt if necessary.
4879 	 * This process logically involves adjusting tp->rcv_wnd as data is
4880 	 * presented to the user (this happens in tcp_usrreq.c, case
4881 	 * PRU_RCVD).  If a FIN has already been received on this connection
4882 	 * then we just ignore the text.
4883 	 */
4884 #ifdef TCP_RFC7413
4885 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
4886 	    (tp->t_flags & TF_FASTOPEN));
4887 #endif
4888 	if ((tlen || (thflags & TH_FIN) || tfo_syn) &&
4889 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
4890 		tcp_seq save_start = th->th_seq;
4891 		tcp_seq save_rnxt  = tp->rcv_nxt;
4892 		int     save_tlen  = tlen;
4893 
4894 		m_adj(m, drop_hdrlen);	/* delayed header drop */
4895 		/*
4896 		 * Insert segment which includes th into TCP reassembly
4897 		 * queue with control block tp.  Set thflags to whether
4898 		 * reassembly now includes a segment with FIN.  This handles
4899 		 * the common case inline (segment is the next to be
4900 		 * received on an established connection, and the queue is
4901 		 * empty), avoiding linkage into and removal from the queue
4902 		 * and repetition of various conversions. Set DELACK for
4903 		 * segments received in order, but ack immediately when
4904 		 * segments are out of order (so fast retransmit can work).
4905 		 */
4906 		if (th->th_seq == tp->rcv_nxt &&
4907 		    SEGQ_EMPTY(tp) &&
4908 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
4909 		    tfo_syn)) {
4910 			if (DELAY_ACK(tp, tlen) || tfo_syn) {
4911 				rack_timer_cancel(tp, rack,
4912 				    rack->r_ctl.rc_rcvtime, __LINE__);
4913 				tp->t_flags |= TF_DELACK;
4914 			} else {
4915 				rack->r_wanted_output++;
4916 				tp->t_flags |= TF_ACKNOW;
4917 			}
4918 			tp->rcv_nxt += tlen;
4919 			thflags = th->th_flags & TH_FIN;
4920 			TCPSTAT_ADD(tcps_rcvpack, nsegs);
4921 			TCPSTAT_ADD(tcps_rcvbyte, tlen);
4922 			SOCKBUF_LOCK(&so->so_rcv);
4923 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
4924 				m_freem(m);
4925 			else
4926 				sbappendstream_locked(&so->so_rcv, m, 0);
4927 			/* NB: sorwakeup_locked() does an implicit unlock. */
4928 			sorwakeup_locked(so);
4929 		} else {
4930 			/*
4931 			 * XXX: Due to the header drop above "th" is
4932 			 * theoretically invalid by now.  Fortunately
4933 			 * m_adj() doesn't actually frees any mbufs when
4934 			 * trimming from the head.
4935 			 */
4936 			tcp_seq temp = save_start;
4937 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
4938 			tp->t_flags |= TF_ACKNOW;
4939 		}
4940 		if (((tlen == 0) && (save_tlen > 0) &&
4941 		    (SEQ_LT(save_start, save_rnxt)))) {
4942 			/*
4943 			 * DSACK actually handled in the fastpath
4944 			 * above.
4945 			 */
4946 			tcp_update_sack_list(tp, save_start,
4947 			    save_start + save_tlen);
4948 		} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
4949 			/*
4950 			 * Cleaning sackblks by using zero length
4951 			 * update.
4952 			 */
4953 			if ((tp->rcv_numsacks >= 1) &&
4954 			    (tp->sackblks[0].end == save_start)) {
4955 				/* partial overlap, recorded at todrop above */
4956 				tcp_update_sack_list(tp, tp->sackblks[0].start,
4957 				    tp->sackblks[0].end);
4958 			} else {
4959 				tcp_update_dsack_list(tp, save_start,
4960 				    save_start + save_tlen);
4961 			}
4962 		} else if ((tlen > 0) && (tlen >= save_tlen)) {
4963 			/* Update of sackblks. */
4964 			tcp_update_dsack_list(tp, save_start,
4965 			    save_start + save_tlen);
4966 		} else if (tlen > 0) {
4967 			tcp_update_dsack_list(tp, save_start,
4968 			    save_start + tlen);
4969 		}
4970 	} else {
4971 		m_freem(m);
4972 		thflags &= ~TH_FIN;
4973 	}
4974 
4975 	/*
4976 	 * If FIN is received ACK the FIN and let the user know that the
4977 	 * connection is closing.
4978 	 */
4979 	if (thflags & TH_FIN) {
4980 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
4981 			socantrcvmore(so);
4982 			/*
4983 			 * If connection is half-synchronized (ie NEEDSYN
4984 			 * flag on) then delay ACK, so it may be piggybacked
4985 			 * when SYN is sent. Otherwise, since we received a
4986 			 * FIN then no more input can be expected, send ACK
4987 			 * now.
4988 			 */
4989 			if (tp->t_flags & TF_NEEDSYN) {
4990 				rack_timer_cancel(tp, rack,
4991 				    rack->r_ctl.rc_rcvtime, __LINE__);
4992 				tp->t_flags |= TF_DELACK;
4993 			} else {
4994 				tp->t_flags |= TF_ACKNOW;
4995 			}
4996 			tp->rcv_nxt++;
4997 		}
4998 		switch (tp->t_state) {
4999 
5000 			/*
5001 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
5002 			 * CLOSE_WAIT state.
5003 			 */
5004 		case TCPS_SYN_RECEIVED:
5005 			tp->t_starttime = ticks;
5006 			/* FALLTHROUGH */
5007 		case TCPS_ESTABLISHED:
5008 			rack_timer_cancel(tp, rack,
5009 			    rack->r_ctl.rc_rcvtime, __LINE__);
5010 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
5011 			break;
5012 
5013 			/*
5014 			 * If still in FIN_WAIT_1 STATE FIN has not been
5015 			 * acked so enter the CLOSING state.
5016 			 */
5017 		case TCPS_FIN_WAIT_1:
5018 			rack_timer_cancel(tp, rack,
5019 			    rack->r_ctl.rc_rcvtime, __LINE__);
5020 			tcp_state_change(tp, TCPS_CLOSING);
5021 			break;
5022 
5023 			/*
5024 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
5025 			 * starting the time-wait timer, turning off the
5026 			 * other standard timers.
5027 			 */
5028 		case TCPS_FIN_WAIT_2:
5029 			rack_timer_cancel(tp, rack,
5030 			    rack->r_ctl.rc_rcvtime, __LINE__);
5031 			INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
5032 			tcp_twstart(tp);
5033 			return (1);
5034 		}
5035 	}
5036 	/*
5037 	 * Return any desired output.
5038 	 */
5039 	if ((tp->t_flags & TF_ACKNOW) ||
5040 	    (sbavail(&so->so_snd) > (tp->snd_max - tp->snd_una))) {
5041 		rack->r_wanted_output++;
5042 	}
5043 	INP_WLOCK_ASSERT(tp->t_inpcb);
5044 	return (0);
5045 }
5046 
5047 /*
5048  * Here nothing is really faster, its just that we
5049  * have broken out the fast-data path also just like
5050  * the fast-ack.
5051  */
5052 static int
5053 rack_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
5054     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
5055     uint32_t tiwin, int32_t nxt_pkt)
5056 {
5057 	int32_t nsegs;
5058 	int32_t newsize = 0;	/* automatic sockbuf scaling */
5059 	struct tcp_rack *rack;
5060 #ifdef TCPDEBUG
5061 	/*
5062 	 * The size of tcp_saveipgen must be the size of the max ip header,
5063 	 * now IPv6.
5064 	 */
5065 	u_char tcp_saveipgen[IP6_HDR_LEN];
5066 	struct tcphdr tcp_savetcp;
5067 	short ostate = 0;
5068 
5069 #endif
5070 	/*
5071 	 * If last ACK falls within this segment's sequence numbers, record
5072 	 * the timestamp. NOTE that the test is modified according to the
5073 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
5074 	 */
5075 	if (__predict_false(th->th_seq != tp->rcv_nxt)) {
5076 		return (0);
5077 	}
5078 	if (__predict_false(tp->snd_nxt != tp->snd_max)) {
5079 		return (0);
5080 	}
5081 	if (tiwin && tiwin != tp->snd_wnd) {
5082 		return (0);
5083 	}
5084 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
5085 		return (0);
5086 	}
5087 	if (__predict_false((to->to_flags & TOF_TS) &&
5088 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
5089 		return (0);
5090 	}
5091 	if (__predict_false((th->th_ack != tp->snd_una))) {
5092 		return (0);
5093 	}
5094 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
5095 		return (0);
5096 	}
5097 	if ((to->to_flags & TOF_TS) != 0 &&
5098 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
5099 		tp->ts_recent_age = tcp_ts_getticks();
5100 		tp->ts_recent = to->to_tsval;
5101 	}
5102 	rack = (struct tcp_rack *)tp->t_fb_ptr;
5103 	/*
5104 	 * This is a pure, in-sequence data packet with nothing on the
5105 	 * reassembly queue and we have enough buffer space to take it.
5106 	 */
5107 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
5108 
5109 
5110 	/* Clean receiver SACK report if present */
5111 	if (tp->rcv_numsacks)
5112 	        tcp_clean_sackreport(tp);
5113 	TCPSTAT_INC(tcps_preddat);
5114 	tp->rcv_nxt += tlen;
5115 	/*
5116 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
5117 	 */
5118 	tp->snd_wl1 = th->th_seq;
5119 	/*
5120 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
5121 	 */
5122 	tp->rcv_up = tp->rcv_nxt;
5123 	TCPSTAT_ADD(tcps_rcvpack, nsegs);
5124 	TCPSTAT_ADD(tcps_rcvbyte, tlen);
5125 #ifdef TCPDEBUG
5126 	if (so->so_options & SO_DEBUG)
5127 		tcp_trace(TA_INPUT, ostate, tp,
5128 		    (void *)tcp_saveipgen, &tcp_savetcp, 0);
5129 #endif
5130 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
5131 
5132 	/* Add data to socket buffer. */
5133 	SOCKBUF_LOCK(&so->so_rcv);
5134 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
5135 		m_freem(m);
5136 	} else {
5137 		/*
5138 		 * Set new socket buffer size. Give up when limit is
5139 		 * reached.
5140 		 */
5141 		if (newsize)
5142 			if (!sbreserve_locked(&so->so_rcv,
5143 			    newsize, so, NULL))
5144 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
5145 		m_adj(m, drop_hdrlen);	/* delayed header drop */
5146 		sbappendstream_locked(&so->so_rcv, m, 0);
5147 		rack_calc_rwin(so, tp);
5148 	}
5149 	/* NB: sorwakeup_locked() does an implicit unlock. */
5150 	sorwakeup_locked(so);
5151 	if (DELAY_ACK(tp, tlen)) {
5152 		rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
5153 		tp->t_flags |= TF_DELACK;
5154 	} else {
5155 		tp->t_flags |= TF_ACKNOW;
5156 		rack->r_wanted_output++;
5157 	}
5158 	if ((tp->snd_una == tp->snd_max) && rack_use_sack_filter)
5159 		sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
5160 	return (1);
5161 }
5162 
5163 /*
5164  * This subfunction is used to try to highly optimize the
5165  * fast path. We again allow window updates that are
5166  * in sequence to remain in the fast-path. We also add
5167  * in the __predict's to attempt to help the compiler.
5168  * Note that if we return a 0, then we can *not* process
5169  * it and the caller should push the packet into the
5170  * slow-path.
5171  */
5172 static int
5173 rack_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
5174     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
5175     uint32_t tiwin, int32_t nxt_pkt, uint32_t cts)
5176 {
5177 	int32_t acked;
5178 	int32_t nsegs;
5179 
5180 #ifdef TCPDEBUG
5181 	/*
5182 	 * The size of tcp_saveipgen must be the size of the max ip header,
5183 	 * now IPv6.
5184 	 */
5185 	u_char tcp_saveipgen[IP6_HDR_LEN];
5186 	struct tcphdr tcp_savetcp;
5187 	short ostate = 0;
5188 
5189 #endif
5190 	struct tcp_rack *rack;
5191 
5192 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
5193 		/* Old ack, behind (or duplicate to) the last one rcv'd */
5194 		return (0);
5195 	}
5196 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
5197 		/* Above what we have sent? */
5198 		return (0);
5199 	}
5200 	if (__predict_false(tp->snd_nxt != tp->snd_max)) {
5201 		/* We are retransmitting */
5202 		return (0);
5203 	}
5204 	if (__predict_false(tiwin == 0)) {
5205 		/* zero window */
5206 		return (0);
5207 	}
5208 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
5209 		/* We need a SYN or a FIN, unlikely.. */
5210 		return (0);
5211 	}
5212 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
5213 		/* Timestamp is behind .. old ack with seq wrap? */
5214 		return (0);
5215 	}
5216 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
5217 		/* Still recovering */
5218 		return (0);
5219 	}
5220 	rack = (struct tcp_rack *)tp->t_fb_ptr;
5221 	if (rack->r_ctl.rc_sacked) {
5222 		/* We have sack holes on our scoreboard */
5223 		return (0);
5224 	}
5225 	/* Ok if we reach here, we can process a fast-ack */
5226 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
5227 	rack_log_ack(tp, to, th);
5228 	/* Did the window get updated? */
5229 	if (tiwin != tp->snd_wnd) {
5230 		tp->snd_wnd = tiwin;
5231 		tp->snd_wl1 = th->th_seq;
5232 		if (tp->snd_wnd > tp->max_sndwnd)
5233 			tp->max_sndwnd = tp->snd_wnd;
5234 	}
5235 	if ((rack->rc_in_persist != 0) && (tp->snd_wnd >= tp->t_maxseg)) {
5236 		rack_exit_persist(tp, rack);
5237 	}
5238 	/*
5239 	 * If last ACK falls within this segment's sequence numbers, record
5240 	 * the timestamp. NOTE that the test is modified according to the
5241 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
5242 	 */
5243 	if ((to->to_flags & TOF_TS) != 0 &&
5244 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
5245 		tp->ts_recent_age = tcp_ts_getticks();
5246 		tp->ts_recent = to->to_tsval;
5247 	}
5248 	/*
5249 	 * This is a pure ack for outstanding data.
5250 	 */
5251 	TCPSTAT_INC(tcps_predack);
5252 
5253 	/*
5254 	 * "bad retransmit" recovery.
5255 	 */
5256 	if (tp->t_flags & TF_PREVVALID) {
5257 		tp->t_flags &= ~TF_PREVVALID;
5258 		if (tp->t_rxtshift == 1 &&
5259 		    (int)(ticks - tp->t_badrxtwin) < 0)
5260 			rack_cong_signal(tp, th, CC_RTO_ERR);
5261 	}
5262 	/*
5263 	 * Recalculate the transmit timer / rtt.
5264 	 *
5265 	 * Some boxes send broken timestamp replies during the SYN+ACK
5266 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
5267 	 * and blow up the retransmit timer.
5268 	 */
5269 	acked = BYTES_THIS_ACK(tp, th);
5270 
5271 #ifdef TCP_HHOOK
5272 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
5273 	hhook_run_tcp_est_in(tp, th, to);
5274 #endif
5275 
5276 	TCPSTAT_ADD(tcps_rcvackpack, nsegs);
5277 	TCPSTAT_ADD(tcps_rcvackbyte, acked);
5278 	sbdrop(&so->so_snd, acked);
5279 	/*
5280 	 * Let the congestion control algorithm update congestion control
5281 	 * related information. This typically means increasing the
5282 	 * congestion window.
5283 	 */
5284 	rack_ack_received(tp, rack, th, nsegs, CC_ACK, 0);
5285 
5286 	tp->snd_una = th->th_ack;
5287 	/*
5288 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
5289 	 */
5290 	tp->snd_wl2 = th->th_ack;
5291 	tp->t_dupacks = 0;
5292 	m_freem(m);
5293 	/* ND6_HINT(tp);	 *//* Some progress has been made. */
5294 
5295 	/*
5296 	 * If all outstanding data are acked, stop retransmit timer,
5297 	 * otherwise restart timer using current (possibly backed-off)
5298 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
5299 	 * If data are ready to send, let tcp_output decide between more
5300 	 * output or persist.
5301 	 */
5302 #ifdef TCPDEBUG
5303 	if (so->so_options & SO_DEBUG)
5304 		tcp_trace(TA_INPUT, ostate, tp,
5305 		    (void *)tcp_saveipgen,
5306 		    &tcp_savetcp, 0);
5307 #endif
5308 	if (tp->snd_una == tp->snd_max) {
5309 		rack_log_progress_event(rack, tp, 0, PROGRESS_CLEAR, __LINE__);
5310 		tp->t_acktime = 0;
5311 		rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
5312 	}
5313 	/* Wake up the socket if we have room to write more */
5314 	sowwakeup(so);
5315 	if (sbavail(&so->so_snd)) {
5316 		rack->r_wanted_output++;
5317 	}
5318 	return (1);
5319 }
5320 
5321 /*
5322  * Return value of 1, the TCB is unlocked and most
5323  * likely gone, return value of 0, the TCP is still
5324  * locked.
5325  */
5326 static int
5327 rack_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
5328     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
5329     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
5330 {
5331 	int32_t ret_val = 0;
5332 	int32_t todrop;
5333 	int32_t ourfinisacked = 0;
5334 
5335 	rack_calc_rwin(so, tp);
5336 	/*
5337 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
5338 	 * SYN, drop the input. if seg contains a RST, then drop the
5339 	 * connection. if seg does not contain SYN, then drop it. Otherwise
5340 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
5341 	 * tp->irs if seg contains ack then advance tp->snd_una if seg
5342 	 * contains an ECE and ECN support is enabled, the stream is ECN
5343 	 * capable. if SYN has been acked change to ESTABLISHED else
5344 	 * SYN_RCVD state arrange for segment to be acked (eventually)
5345 	 * continue processing rest of data/controls, beginning with URG
5346 	 */
5347 	if ((thflags & TH_ACK) &&
5348 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
5349 	    SEQ_GT(th->th_ack, tp->snd_max))) {
5350 		rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
5351 		return (1);
5352 	}
5353 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
5354 		TCP_PROBE5(connect__refused, NULL, tp,
5355 		    mtod(m, const char *), tp, th);
5356 		tp = tcp_drop(tp, ECONNREFUSED);
5357 		rack_do_drop(m, tp);
5358 		return (1);
5359 	}
5360 	if (thflags & TH_RST) {
5361 		rack_do_drop(m, tp);
5362 		return (1);
5363 	}
5364 	if (!(thflags & TH_SYN)) {
5365 		rack_do_drop(m, tp);
5366 		return (1);
5367 	}
5368 	tp->irs = th->th_seq;
5369 	tcp_rcvseqinit(tp);
5370 	if (thflags & TH_ACK) {
5371 		TCPSTAT_INC(tcps_connects);
5372 		soisconnected(so);
5373 #ifdef MAC
5374 		mac_socketpeer_set_from_mbuf(m, so);
5375 #endif
5376 		/* Do window scaling on this connection? */
5377 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
5378 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
5379 			tp->rcv_scale = tp->request_r_scale;
5380 		}
5381 		tp->rcv_adv += min(tp->rcv_wnd,
5382 		    TCP_MAXWIN << tp->rcv_scale);
5383 		/*
5384 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
5385 		 * will be turned on later.
5386 		 */
5387 		if (DELAY_ACK(tp, tlen) && tlen != 0) {
5388 			rack_timer_cancel(tp, (struct tcp_rack *)tp->t_fb_ptr,
5389 					  ((struct tcp_rack *)tp->t_fb_ptr)->r_ctl.rc_rcvtime, __LINE__);
5390 			tp->t_flags |= TF_DELACK;
5391 		} else {
5392 			((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output++;
5393 			tp->t_flags |= TF_ACKNOW;
5394 		}
5395 
5396 		if ((thflags & TH_ECE) && V_tcp_do_ecn) {
5397 			tp->t_flags |= TF_ECN_PERMIT;
5398 			TCPSTAT_INC(tcps_ecn_shs);
5399 		}
5400 		/*
5401 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
5402 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
5403 		 */
5404 		tp->t_starttime = ticks;
5405 		if (tp->t_flags & TF_NEEDFIN) {
5406 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
5407 			tp->t_flags &= ~TF_NEEDFIN;
5408 			thflags &= ~TH_SYN;
5409 		} else {
5410 			tcp_state_change(tp, TCPS_ESTABLISHED);
5411 			TCP_PROBE5(connect__established, NULL, tp,
5412 			    mtod(m, const char *), tp, th);
5413 			cc_conn_init(tp);
5414 		}
5415 	} else {
5416 		/*
5417 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
5418 		 * open.  If segment contains CC option and there is a
5419 		 * cached CC, apply TAO test. If it succeeds, connection is *
5420 		 * half-synchronized. Otherwise, do 3-way handshake:
5421 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
5422 		 * there was no CC option, clear cached CC value.
5423 		 */
5424 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
5425 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
5426 	}
5427 	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
5428 	INP_WLOCK_ASSERT(tp->t_inpcb);
5429 	/*
5430 	 * Advance th->th_seq to correspond to first data byte. If data,
5431 	 * trim to stay within window, dropping FIN if necessary.
5432 	 */
5433 	th->th_seq++;
5434 	if (tlen > tp->rcv_wnd) {
5435 		todrop = tlen - tp->rcv_wnd;
5436 		m_adj(m, -todrop);
5437 		tlen = tp->rcv_wnd;
5438 		thflags &= ~TH_FIN;
5439 		TCPSTAT_INC(tcps_rcvpackafterwin);
5440 		TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
5441 	}
5442 	tp->snd_wl1 = th->th_seq - 1;
5443 	tp->rcv_up = th->th_seq;
5444 	/*
5445 	 * Client side of transaction: already sent SYN and data. If the
5446 	 * remote host used T/TCP to validate the SYN, our data will be
5447 	 * ACK'd; if so, enter normal data segment processing in the middle
5448 	 * of step 5, ack processing. Otherwise, goto step 6.
5449 	 */
5450 	if (thflags & TH_ACK) {
5451 		if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
5452 			return (ret_val);
5453 		/* We may have changed to FIN_WAIT_1 above */
5454 		if (tp->t_state == TCPS_FIN_WAIT_1) {
5455 			/*
5456 			 * In FIN_WAIT_1 STATE in addition to the processing
5457 			 * for the ESTABLISHED state if our FIN is now
5458 			 * acknowledged then enter FIN_WAIT_2.
5459 			 */
5460 			if (ourfinisacked) {
5461 				/*
5462 				 * If we can't receive any more data, then
5463 				 * closing user can proceed. Starting the
5464 				 * timer is contrary to the specification,
5465 				 * but if we don't get a FIN we'll hang
5466 				 * forever.
5467 				 *
5468 				 * XXXjl: we should release the tp also, and
5469 				 * use a compressed state.
5470 				 */
5471 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
5472 					soisdisconnected(so);
5473 					tcp_timer_activate(tp, TT_2MSL,
5474 					    (tcp_fast_finwait2_recycle ?
5475 					    tcp_finwait2_timeout :
5476 					    TP_MAXIDLE(tp)));
5477 				}
5478 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
5479 			}
5480 		}
5481 	}
5482 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5483 	    tiwin, thflags, nxt_pkt));
5484 }
5485 
5486 /*
5487  * Return value of 1, the TCB is unlocked and most
5488  * likely gone, return value of 0, the TCP is still
5489  * locked.
5490  */
5491 static int
5492 rack_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
5493     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
5494     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
5495 {
5496 	int32_t ret_val = 0;
5497 	int32_t ourfinisacked = 0;
5498 
5499 	rack_calc_rwin(so, tp);
5500 
5501 	if ((thflags & TH_ACK) &&
5502 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
5503 	    SEQ_GT(th->th_ack, tp->snd_max))) {
5504 		rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
5505 		return (1);
5506 	}
5507 #ifdef TCP_RFC7413
5508 	if (tp->t_flags & TF_FASTOPEN) {
5509 		/*
5510 		 * When a TFO connection is in SYN_RECEIVED, the only valid
5511 		 * packets are the initial SYN, a retransmit/copy of the
5512 		 * initial SYN (possibly with a subset of the original
5513 		 * data), a valid ACK, a FIN, or a RST.
5514 		 */
5515 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
5516 			rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
5517 			return (1);
5518 		} else if (thflags & TH_SYN) {
5519 			/* non-initial SYN is ignored */
5520 			struct tcp_rack *rack;
5521 
5522 			rack = (struct tcp_rack *)tp->t_fb_ptr;
5523 			if ((rack->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
5524 			    (rack->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
5525 			    (rack->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
5526 				rack_do_drop(m, NULL);
5527 				return (0);
5528 			}
5529 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
5530 			rack_do_drop(m, NULL);
5531 			return (0);
5532 		}
5533 	}
5534 #endif
5535 	if (thflags & TH_RST)
5536 		return (rack_process_rst(m, th, so, tp));
5537 	/*
5538 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
5539 	 * synchronized state.
5540 	 */
5541 	if (thflags & TH_SYN) {
5542 		rack_challenge_ack(m, th, tp, &ret_val);
5543 		return (ret_val);
5544 	}
5545 	/*
5546 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
5547 	 * it's less than ts_recent, drop it.
5548 	 */
5549 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
5550 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
5551 		if (rack_ts_check(m, th, tp, tlen, thflags, &ret_val))
5552 			return (ret_val);
5553 	}
5554 	/*
5555 	 * In the SYN-RECEIVED state, validate that the packet belongs to
5556 	 * this connection before trimming the data to fit the receive
5557 	 * window.  Check the sequence number versus IRS since we know the
5558 	 * sequence numbers haven't wrapped.  This is a partial fix for the
5559 	 * "LAND" DoS attack.
5560 	 */
5561 	if (SEQ_LT(th->th_seq, tp->irs)) {
5562 		rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
5563 		return (1);
5564 	}
5565 	if (rack_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
5566 		return (ret_val);
5567 	}
5568 	/*
5569 	 * If last ACK falls within this segment's sequence numbers, record
5570 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
5571 	 * from the latest proposal of the tcplw@cray.com list (Braden
5572 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
5573 	 * with our earlier PAWS tests, so this check should be solely
5574 	 * predicated on the sequence space of this segment. 3) That we
5575 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
5576 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
5577 	 * SEG.Len, This modified check allows us to overcome RFC1323's
5578 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
5579 	 * p.869. In such cases, we can still calculate the RTT correctly
5580 	 * when RCV.NXT == Last.ACK.Sent.
5581 	 */
5582 	if ((to->to_flags & TOF_TS) != 0 &&
5583 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
5584 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
5585 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
5586 		tp->ts_recent_age = tcp_ts_getticks();
5587 		tp->ts_recent = to->to_tsval;
5588 	}
5589 	/*
5590 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
5591 	 * is on (half-synchronized state), then queue data for later
5592 	 * processing; else drop segment and return.
5593 	 */
5594 	if ((thflags & TH_ACK) == 0) {
5595 #ifdef TCP_RFC7413
5596 		if (tp->t_flags & TF_FASTOPEN) {
5597 			tp->snd_wnd = tiwin;
5598 			cc_conn_init(tp);
5599 		}
5600 #endif
5601 		return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5602 		    tiwin, thflags, nxt_pkt));
5603 	}
5604 	TCPSTAT_INC(tcps_connects);
5605 	soisconnected(so);
5606 	/* Do window scaling? */
5607 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
5608 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
5609 		tp->rcv_scale = tp->request_r_scale;
5610 		tp->snd_wnd = tiwin;
5611 	}
5612 	/*
5613 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
5614 	 * FIN-WAIT-1
5615 	 */
5616 	tp->t_starttime = ticks;
5617 	if (tp->t_flags & TF_NEEDFIN) {
5618 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
5619 		tp->t_flags &= ~TF_NEEDFIN;
5620 	} else {
5621 		tcp_state_change(tp, TCPS_ESTABLISHED);
5622 		TCP_PROBE5(accept__established, NULL, tp,
5623 		    mtod(m, const char *), tp, th);
5624 #ifdef TCP_RFC7413
5625 		if (tp->t_tfo_pending) {
5626 			tcp_fastopen_decrement_counter(tp->t_tfo_pending);
5627 			tp->t_tfo_pending = NULL;
5628 
5629 			/*
5630 			 * Account for the ACK of our SYN prior to regular
5631 			 * ACK processing below.
5632 			 */
5633 			tp->snd_una++;
5634 		}
5635 		/*
5636 		 * TFO connections call cc_conn_init() during SYN
5637 		 * processing.  Calling it again here for such connections
5638 		 * is not harmless as it would undo the snd_cwnd reduction
5639 		 * that occurs when a TFO SYN|ACK is retransmitted.
5640 		 */
5641 		if (!(tp->t_flags & TF_FASTOPEN))
5642 #endif
5643 			cc_conn_init(tp);
5644 	}
5645 	/*
5646 	 * If segment contains data or ACK, will call tcp_reass() later; if
5647 	 * not, do so now to pass queued data to user.
5648 	 */
5649 	if (tlen == 0 && (thflags & TH_FIN) == 0)
5650 		(void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
5651 		    (struct mbuf *)0);
5652 	tp->snd_wl1 = th->th_seq - 1;
5653 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
5654 		return (ret_val);
5655 	}
5656 	if (tp->t_state == TCPS_FIN_WAIT_1) {
5657 		/* We could have went to FIN_WAIT_1 (or EST) above */
5658 		/*
5659 		 * In FIN_WAIT_1 STATE in addition to the processing for the
5660 		 * ESTABLISHED state if our FIN is now acknowledged then
5661 		 * enter FIN_WAIT_2.
5662 		 */
5663 		if (ourfinisacked) {
5664 			/*
5665 			 * If we can't receive any more data, then closing
5666 			 * user can proceed. Starting the timer is contrary
5667 			 * to the specification, but if we don't get a FIN
5668 			 * we'll hang forever.
5669 			 *
5670 			 * XXXjl: we should release the tp also, and use a
5671 			 * compressed state.
5672 			 */
5673 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
5674 				soisdisconnected(so);
5675 				tcp_timer_activate(tp, TT_2MSL,
5676 				    (tcp_fast_finwait2_recycle ?
5677 				    tcp_finwait2_timeout :
5678 				    TP_MAXIDLE(tp)));
5679 			}
5680 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
5681 		}
5682 	}
5683 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5684 	    tiwin, thflags, nxt_pkt));
5685 }
5686 
5687 /*
5688  * Return value of 1, the TCB is unlocked and most
5689  * likely gone, return value of 0, the TCP is still
5690  * locked.
5691  */
5692 static int
5693 rack_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
5694     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
5695     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
5696 {
5697 	int32_t ret_val = 0;
5698 
5699 	/*
5700 	 * Header prediction: check for the two common cases of a
5701 	 * uni-directional data xfer.  If the packet has no control flags,
5702 	 * is in-sequence, the window didn't change and we're not
5703 	 * retransmitting, it's a candidate.  If the length is zero and the
5704 	 * ack moved forward, we're the sender side of the xfer.  Just free
5705 	 * the data acked & wake any higher level process that was blocked
5706 	 * waiting for space.  If the length is non-zero and the ack didn't
5707 	 * move, we're the receiver side.  If we're getting packets in-order
5708 	 * (the reassembly queue is empty), add the data toc The socket
5709 	 * buffer and note that we need a delayed ack. Make sure that the
5710 	 * hidden state-flags are also off. Since we check for
5711 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
5712 	 */
5713 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
5714 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
5715 	    __predict_true(SEGQ_EMPTY(tp)) &&
5716 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
5717 		struct tcp_rack *rack;
5718 
5719 		rack = (struct tcp_rack *)tp->t_fb_ptr;
5720 		if (tlen == 0) {
5721 			if (rack_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
5722 			    tiwin, nxt_pkt, rack->r_ctl.rc_rcvtime)) {
5723 				return (0);
5724 			}
5725 		} else {
5726 			if (rack_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
5727 			    tiwin, nxt_pkt)) {
5728 				return (0);
5729 			}
5730 		}
5731 	}
5732 	rack_calc_rwin(so, tp);
5733 
5734 	if (thflags & TH_RST)
5735 		return (rack_process_rst(m, th, so, tp));
5736 
5737 	/*
5738 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
5739 	 * synchronized state.
5740 	 */
5741 	if (thflags & TH_SYN) {
5742 		rack_challenge_ack(m, th, tp, &ret_val);
5743 		return (ret_val);
5744 	}
5745 	/*
5746 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
5747 	 * it's less than ts_recent, drop it.
5748 	 */
5749 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
5750 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
5751 		if (rack_ts_check(m, th, tp, tlen, thflags, &ret_val))
5752 			return (ret_val);
5753 	}
5754 	if (rack_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
5755 		return (ret_val);
5756 	}
5757 	/*
5758 	 * If last ACK falls within this segment's sequence numbers, record
5759 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
5760 	 * from the latest proposal of the tcplw@cray.com list (Braden
5761 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
5762 	 * with our earlier PAWS tests, so this check should be solely
5763 	 * predicated on the sequence space of this segment. 3) That we
5764 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
5765 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
5766 	 * SEG.Len, This modified check allows us to overcome RFC1323's
5767 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
5768 	 * p.869. In such cases, we can still calculate the RTT correctly
5769 	 * when RCV.NXT == Last.ACK.Sent.
5770 	 */
5771 	if ((to->to_flags & TOF_TS) != 0 &&
5772 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
5773 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
5774 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
5775 		tp->ts_recent_age = tcp_ts_getticks();
5776 		tp->ts_recent = to->to_tsval;
5777 	}
5778 	/*
5779 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
5780 	 * is on (half-synchronized state), then queue data for later
5781 	 * processing; else drop segment and return.
5782 	 */
5783 	if ((thflags & TH_ACK) == 0) {
5784 		if (tp->t_flags & TF_NEEDSYN) {
5785 
5786 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5787 			    tiwin, thflags, nxt_pkt));
5788 
5789 		} else if (tp->t_flags & TF_ACKNOW) {
5790 			rack_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
5791 			return (ret_val);
5792 		} else {
5793 			rack_do_drop(m, NULL);
5794 			return (0);
5795 		}
5796 	}
5797 	/*
5798 	 * Ack processing.
5799 	 */
5800 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
5801 		return (ret_val);
5802 	}
5803 	if (sbavail(&so->so_snd)) {
5804 		if (rack_progress_timeout_check(tp)) {
5805 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
5806 			rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
5807 			return (1);
5808 		}
5809 	}
5810 	/* State changes only happen in rack_process_data() */
5811 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5812 	    tiwin, thflags, nxt_pkt));
5813 }
5814 
5815 /*
5816  * Return value of 1, the TCB is unlocked and most
5817  * likely gone, return value of 0, the TCP is still
5818  * locked.
5819  */
5820 static int
5821 rack_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
5822     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
5823     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
5824 {
5825 	int32_t ret_val = 0;
5826 
5827 	rack_calc_rwin(so, tp);
5828 	if (thflags & TH_RST)
5829 		return (rack_process_rst(m, th, so, tp));
5830 	/*
5831 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
5832 	 * synchronized state.
5833 	 */
5834 	if (thflags & TH_SYN) {
5835 		rack_challenge_ack(m, th, tp, &ret_val);
5836 		return (ret_val);
5837 	}
5838 	/*
5839 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
5840 	 * it's less than ts_recent, drop it.
5841 	 */
5842 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
5843 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
5844 		if (rack_ts_check(m, th, tp, tlen, thflags, &ret_val))
5845 			return (ret_val);
5846 	}
5847 	if (rack_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
5848 		return (ret_val);
5849 	}
5850 	/*
5851 	 * If last ACK falls within this segment's sequence numbers, record
5852 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
5853 	 * from the latest proposal of the tcplw@cray.com list (Braden
5854 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
5855 	 * with our earlier PAWS tests, so this check should be solely
5856 	 * predicated on the sequence space of this segment. 3) That we
5857 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
5858 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
5859 	 * SEG.Len, This modified check allows us to overcome RFC1323's
5860 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
5861 	 * p.869. In such cases, we can still calculate the RTT correctly
5862 	 * when RCV.NXT == Last.ACK.Sent.
5863 	 */
5864 	if ((to->to_flags & TOF_TS) != 0 &&
5865 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
5866 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
5867 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
5868 		tp->ts_recent_age = tcp_ts_getticks();
5869 		tp->ts_recent = to->to_tsval;
5870 	}
5871 	/*
5872 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
5873 	 * is on (half-synchronized state), then queue data for later
5874 	 * processing; else drop segment and return.
5875 	 */
5876 	if ((thflags & TH_ACK) == 0) {
5877 		if (tp->t_flags & TF_NEEDSYN) {
5878 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5879 			    tiwin, thflags, nxt_pkt));
5880 
5881 		} else if (tp->t_flags & TF_ACKNOW) {
5882 			rack_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
5883 			return (ret_val);
5884 		} else {
5885 			rack_do_drop(m, NULL);
5886 			return (0);
5887 		}
5888 	}
5889 	/*
5890 	 * Ack processing.
5891 	 */
5892 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
5893 		return (ret_val);
5894 	}
5895 	if (sbavail(&so->so_snd)) {
5896 		if (rack_progress_timeout_check(tp)) {
5897 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
5898 			rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
5899 			return (1);
5900 		}
5901 	}
5902 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5903 	    tiwin, thflags, nxt_pkt));
5904 }
5905 
5906 static int
5907 rack_check_data_after_close(struct mbuf *m,
5908     struct tcpcb *tp, int32_t *tlen, struct tcphdr *th, struct socket *so)
5909 {
5910 	struct tcp_rack *rack;
5911 
5912 	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
5913 	rack = (struct tcp_rack *)tp->t_fb_ptr;
5914 	if (rack->rc_allow_data_af_clo == 0) {
5915 	close_now:
5916 		tp = tcp_close(tp);
5917 		TCPSTAT_INC(tcps_rcvafterclose);
5918 		rack_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
5919 		return (1);
5920 	}
5921 	if (sbavail(&so->so_snd) == 0)
5922 		goto close_now;
5923 	/* Ok we allow data that is ignored and a followup reset */
5924 	tp->rcv_nxt = th->th_seq + *tlen;
5925 	tp->t_flags2 |= TF2_DROP_AF_DATA;
5926 	rack->r_wanted_output = 1;
5927 	*tlen = 0;
5928 	return (0);
5929 }
5930 
5931 /*
5932  * Return value of 1, the TCB is unlocked and most
5933  * likely gone, return value of 0, the TCP is still
5934  * locked.
5935  */
5936 static int
5937 rack_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
5938     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
5939     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
5940 {
5941 	int32_t ret_val = 0;
5942 	int32_t ourfinisacked = 0;
5943 
5944 	rack_calc_rwin(so, tp);
5945 
5946 	if (thflags & TH_RST)
5947 		return (rack_process_rst(m, th, so, tp));
5948 	/*
5949 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
5950 	 * synchronized state.
5951 	 */
5952 	if (thflags & TH_SYN) {
5953 		rack_challenge_ack(m, th, tp, &ret_val);
5954 		return (ret_val);
5955 	}
5956 	/*
5957 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
5958 	 * it's less than ts_recent, drop it.
5959 	 */
5960 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
5961 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
5962 		if (rack_ts_check(m, th, tp, tlen, thflags, &ret_val))
5963 			return (ret_val);
5964 	}
5965 	if (rack_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
5966 		return (ret_val);
5967 	}
5968 	/*
5969 	 * If new data are received on a connection after the user processes
5970 	 * are gone, then RST the other end.
5971 	 */
5972 	if ((so->so_state & SS_NOFDREF) && tlen) {
5973 		if (rack_check_data_after_close(m, tp, &tlen, th, so))
5974 			return (1);
5975 	}
5976 	/*
5977 	 * If last ACK falls within this segment's sequence numbers, record
5978 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
5979 	 * from the latest proposal of the tcplw@cray.com list (Braden
5980 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
5981 	 * with our earlier PAWS tests, so this check should be solely
5982 	 * predicated on the sequence space of this segment. 3) That we
5983 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
5984 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
5985 	 * SEG.Len, This modified check allows us to overcome RFC1323's
5986 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
5987 	 * p.869. In such cases, we can still calculate the RTT correctly
5988 	 * when RCV.NXT == Last.ACK.Sent.
5989 	 */
5990 	if ((to->to_flags & TOF_TS) != 0 &&
5991 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
5992 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
5993 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
5994 		tp->ts_recent_age = tcp_ts_getticks();
5995 		tp->ts_recent = to->to_tsval;
5996 	}
5997 	/*
5998 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
5999 	 * is on (half-synchronized state), then queue data for later
6000 	 * processing; else drop segment and return.
6001 	 */
6002 	if ((thflags & TH_ACK) == 0) {
6003 		if (tp->t_flags & TF_NEEDSYN) {
6004 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
6005 			    tiwin, thflags, nxt_pkt));
6006 		} else if (tp->t_flags & TF_ACKNOW) {
6007 			rack_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
6008 			return (ret_val);
6009 		} else {
6010 			rack_do_drop(m, NULL);
6011 			return (0);
6012 		}
6013 	}
6014 	/*
6015 	 * Ack processing.
6016 	 */
6017 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
6018 		return (ret_val);
6019 	}
6020 	if (ourfinisacked) {
6021 		/*
6022 		 * If we can't receive any more data, then closing user can
6023 		 * proceed. Starting the timer is contrary to the
6024 		 * specification, but if we don't get a FIN we'll hang
6025 		 * forever.
6026 		 *
6027 		 * XXXjl: we should release the tp also, and use a
6028 		 * compressed state.
6029 		 */
6030 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
6031 			soisdisconnected(so);
6032 			tcp_timer_activate(tp, TT_2MSL,
6033 			    (tcp_fast_finwait2_recycle ?
6034 			    tcp_finwait2_timeout :
6035 			    TP_MAXIDLE(tp)));
6036 		}
6037 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
6038 	}
6039 	if (sbavail(&so->so_snd)) {
6040 		if (rack_progress_timeout_check(tp)) {
6041 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
6042 			rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
6043 			return (1);
6044 		}
6045 	}
6046 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
6047 	    tiwin, thflags, nxt_pkt));
6048 }
6049 
6050 /*
6051  * Return value of 1, the TCB is unlocked and most
6052  * likely gone, return value of 0, the TCP is still
6053  * locked.
6054  */
6055 static int
6056 rack_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
6057     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
6058     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
6059 {
6060 	int32_t ret_val = 0;
6061 	int32_t ourfinisacked = 0;
6062 
6063 	rack_calc_rwin(so, tp);
6064 
6065 	if (thflags & TH_RST)
6066 		return (rack_process_rst(m, th, so, tp));
6067 	/*
6068 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
6069 	 * synchronized state.
6070 	 */
6071 	if (thflags & TH_SYN) {
6072 		rack_challenge_ack(m, th, tp, &ret_val);
6073 		return (ret_val);
6074 	}
6075 	/*
6076 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
6077 	 * it's less than ts_recent, drop it.
6078 	 */
6079 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
6080 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
6081 		if (rack_ts_check(m, th, tp, tlen, thflags, &ret_val))
6082 			return (ret_val);
6083 	}
6084 	if (rack_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
6085 		return (ret_val);
6086 	}
6087 	/*
6088 	 * If new data are received on a connection after the user processes
6089 	 * are gone, then RST the other end.
6090 	 */
6091 	if ((so->so_state & SS_NOFDREF) && tlen) {
6092 		if (rack_check_data_after_close(m, tp, &tlen, th, so))
6093 			return (1);
6094 	}
6095 	/*
6096 	 * If last ACK falls within this segment's sequence numbers, record
6097 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
6098 	 * from the latest proposal of the tcplw@cray.com list (Braden
6099 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
6100 	 * with our earlier PAWS tests, so this check should be solely
6101 	 * predicated on the sequence space of this segment. 3) That we
6102 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
6103 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
6104 	 * SEG.Len, This modified check allows us to overcome RFC1323's
6105 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
6106 	 * p.869. In such cases, we can still calculate the RTT correctly
6107 	 * when RCV.NXT == Last.ACK.Sent.
6108 	 */
6109 	if ((to->to_flags & TOF_TS) != 0 &&
6110 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
6111 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
6112 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
6113 		tp->ts_recent_age = tcp_ts_getticks();
6114 		tp->ts_recent = to->to_tsval;
6115 	}
6116 	/*
6117 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
6118 	 * is on (half-synchronized state), then queue data for later
6119 	 * processing; else drop segment and return.
6120 	 */
6121 	if ((thflags & TH_ACK) == 0) {
6122 		if (tp->t_flags & TF_NEEDSYN) {
6123 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
6124 			    tiwin, thflags, nxt_pkt));
6125 		} else if (tp->t_flags & TF_ACKNOW) {
6126 			rack_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
6127 			return (ret_val);
6128 		} else {
6129 			rack_do_drop(m, NULL);
6130 			return (0);
6131 		}
6132 	}
6133 	/*
6134 	 * Ack processing.
6135 	 */
6136 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
6137 		return (ret_val);
6138 	}
6139 	if (ourfinisacked) {
6140 		INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
6141 		tcp_twstart(tp);
6142 		m_freem(m);
6143 		return (1);
6144 	}
6145 	if (sbavail(&so->so_snd)) {
6146 		if (rack_progress_timeout_check(tp)) {
6147 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
6148 			rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
6149 			return (1);
6150 		}
6151 	}
6152 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
6153 	    tiwin, thflags, nxt_pkt));
6154 }
6155 
6156 /*
6157  * Return value of 1, the TCB is unlocked and most
6158  * likely gone, return value of 0, the TCP is still
6159  * locked.
6160  */
6161 static int
6162 rack_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
6163     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
6164     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
6165 {
6166 	int32_t ret_val = 0;
6167 	int32_t ourfinisacked = 0;
6168 
6169 	rack_calc_rwin(so, tp);
6170 
6171 	if (thflags & TH_RST)
6172 		return (rack_process_rst(m, th, so, tp));
6173 	/*
6174 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
6175 	 * synchronized state.
6176 	 */
6177 	if (thflags & TH_SYN) {
6178 		rack_challenge_ack(m, th, tp, &ret_val);
6179 		return (ret_val);
6180 	}
6181 	/*
6182 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
6183 	 * it's less than ts_recent, drop it.
6184 	 */
6185 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
6186 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
6187 		if (rack_ts_check(m, th, tp, tlen, thflags, &ret_val))
6188 			return (ret_val);
6189 	}
6190 	if (rack_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
6191 		return (ret_val);
6192 	}
6193 	/*
6194 	 * If new data are received on a connection after the user processes
6195 	 * are gone, then RST the other end.
6196 	 */
6197 	if ((so->so_state & SS_NOFDREF) && tlen) {
6198 		if (rack_check_data_after_close(m, tp, &tlen, th, so))
6199 			return (1);
6200 	}
6201 	/*
6202 	 * If last ACK falls within this segment's sequence numbers, record
6203 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
6204 	 * from the latest proposal of the tcplw@cray.com list (Braden
6205 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
6206 	 * with our earlier PAWS tests, so this check should be solely
6207 	 * predicated on the sequence space of this segment. 3) That we
6208 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
6209 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
6210 	 * SEG.Len, This modified check allows us to overcome RFC1323's
6211 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
6212 	 * p.869. In such cases, we can still calculate the RTT correctly
6213 	 * when RCV.NXT == Last.ACK.Sent.
6214 	 */
6215 	if ((to->to_flags & TOF_TS) != 0 &&
6216 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
6217 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
6218 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
6219 		tp->ts_recent_age = tcp_ts_getticks();
6220 		tp->ts_recent = to->to_tsval;
6221 	}
6222 	/*
6223 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
6224 	 * is on (half-synchronized state), then queue data for later
6225 	 * processing; else drop segment and return.
6226 	 */
6227 	if ((thflags & TH_ACK) == 0) {
6228 		if (tp->t_flags & TF_NEEDSYN) {
6229 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
6230 			    tiwin, thflags, nxt_pkt));
6231 		} else if (tp->t_flags & TF_ACKNOW) {
6232 			rack_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
6233 			return (ret_val);
6234 		} else {
6235 			rack_do_drop(m, NULL);
6236 			return (0);
6237 		}
6238 	}
6239 	/*
6240 	 * case TCPS_LAST_ACK: Ack processing.
6241 	 */
6242 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
6243 		return (ret_val);
6244 	}
6245 	if (ourfinisacked) {
6246 		INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
6247 		tp = tcp_close(tp);
6248 		rack_do_drop(m, tp);
6249 		return (1);
6250 	}
6251 	if (sbavail(&so->so_snd)) {
6252 		if (rack_progress_timeout_check(tp)) {
6253 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
6254 			rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
6255 			return (1);
6256 		}
6257 	}
6258 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
6259 	    tiwin, thflags, nxt_pkt));
6260 }
6261 
6262 
6263 /*
6264  * Return value of 1, the TCB is unlocked and most
6265  * likely gone, return value of 0, the TCP is still
6266  * locked.
6267  */
6268 static int
6269 rack_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
6270     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
6271     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
6272 {
6273 	int32_t ret_val = 0;
6274 	int32_t ourfinisacked = 0;
6275 
6276 	rack_calc_rwin(so, tp);
6277 
6278 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
6279 	if (thflags & TH_RST)
6280 		return (rack_process_rst(m, th, so, tp));
6281 	/*
6282 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
6283 	 * synchronized state.
6284 	 */
6285 	if (thflags & TH_SYN) {
6286 		rack_challenge_ack(m, th, tp, &ret_val);
6287 		return (ret_val);
6288 	}
6289 	/*
6290 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
6291 	 * it's less than ts_recent, drop it.
6292 	 */
6293 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
6294 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
6295 		if (rack_ts_check(m, th, tp, tlen, thflags, &ret_val))
6296 			return (ret_val);
6297 	}
6298 	if (rack_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
6299 		return (ret_val);
6300 	}
6301 	/*
6302 	 * If new data are received on a connection after the user processes
6303 	 * are gone, then RST the other end.
6304 	 */
6305 	if ((so->so_state & SS_NOFDREF) &&
6306 	    tlen) {
6307 		if (rack_check_data_after_close(m, tp, &tlen, th, so))
6308 			return (1);
6309 	}
6310 	/*
6311 	 * If last ACK falls within this segment's sequence numbers, record
6312 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
6313 	 * from the latest proposal of the tcplw@cray.com list (Braden
6314 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
6315 	 * with our earlier PAWS tests, so this check should be solely
6316 	 * predicated on the sequence space of this segment. 3) That we
6317 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
6318 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
6319 	 * SEG.Len, This modified check allows us to overcome RFC1323's
6320 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
6321 	 * p.869. In such cases, we can still calculate the RTT correctly
6322 	 * when RCV.NXT == Last.ACK.Sent.
6323 	 */
6324 	if ((to->to_flags & TOF_TS) != 0 &&
6325 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
6326 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
6327 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
6328 		tp->ts_recent_age = tcp_ts_getticks();
6329 		tp->ts_recent = to->to_tsval;
6330 	}
6331 	/*
6332 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
6333 	 * is on (half-synchronized state), then queue data for later
6334 	 * processing; else drop segment and return.
6335 	 */
6336 	if ((thflags & TH_ACK) == 0) {
6337 		if (tp->t_flags & TF_NEEDSYN) {
6338 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
6339 			    tiwin, thflags, nxt_pkt));
6340 		} else if (tp->t_flags & TF_ACKNOW) {
6341 			rack_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
6342 			return (ret_val);
6343 		} else {
6344 			rack_do_drop(m, NULL);
6345 			return (0);
6346 		}
6347 	}
6348 	/*
6349 	 * Ack processing.
6350 	 */
6351 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
6352 		return (ret_val);
6353 	}
6354 	if (sbavail(&so->so_snd)) {
6355 		if (rack_progress_timeout_check(tp)) {
6356 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
6357 			rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
6358 			return (1);
6359 		}
6360 	}
6361 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
6362 	    tiwin, thflags, nxt_pkt));
6363 }
6364 
6365 
6366 static void inline
6367 rack_clear_rate_sample(struct tcp_rack *rack)
6368 {
6369 	rack->r_ctl.rack_rs.rs_flags = RACK_RTT_EMPTY;
6370 	rack->r_ctl.rack_rs.rs_rtt_cnt = 0;
6371 	rack->r_ctl.rack_rs.rs_rtt_tot = 0;
6372 }
6373 
6374 static int
6375 rack_init(struct tcpcb *tp)
6376 {
6377 	struct tcp_rack *rack = NULL;
6378 
6379 	tp->t_fb_ptr = uma_zalloc(rack_pcb_zone, M_NOWAIT);
6380 	if (tp->t_fb_ptr == NULL) {
6381 		/*
6382 		 * We need to allocate memory but cant. The INP and INP_INFO
6383 		 * locks and they are recusive (happens during setup. So a
6384 		 * scheme to drop the locks fails :(
6385 		 *
6386 		 */
6387 		return (ENOMEM);
6388 	}
6389 	memset(tp->t_fb_ptr, 0, sizeof(struct tcp_rack));
6390 
6391 	rack = (struct tcp_rack *)tp->t_fb_ptr;
6392 	TAILQ_INIT(&rack->r_ctl.rc_map);
6393 	TAILQ_INIT(&rack->r_ctl.rc_free);
6394 	TAILQ_INIT(&rack->r_ctl.rc_tmap);
6395 	rack->rc_tp = tp;
6396 	if (tp->t_inpcb) {
6397 		rack->rc_inp = tp->t_inpcb;
6398 	}
6399 	/* Probably not needed but lets be sure */
6400 	rack_clear_rate_sample(rack);
6401 	rack->r_cpu = 0;
6402 	rack->r_ctl.rc_reorder_fade = rack_reorder_fade;
6403 	rack->rc_allow_data_af_clo = rack_ignore_data_after_close;
6404 	rack->r_ctl.rc_tlp_threshold = rack_tlp_thresh;
6405 	rack->rc_pace_reduce = rack_slot_reduction;
6406 	if (V_tcp_delack_enabled)
6407 		tp->t_delayed_ack = 1;
6408 	else
6409 		tp->t_delayed_ack = 0;
6410 	rack->rc_pace_max_segs = rack_hptsi_segments;
6411 	rack->r_ctl.rc_early_recovery_segs = rack_early_recovery_max_seg;
6412 	rack->r_ctl.rc_reorder_shift = rack_reorder_thresh;
6413 	rack->r_ctl.rc_pkt_delay = rack_pkt_delay;
6414 	rack->r_ctl.rc_prop_reduce = rack_use_proportional_reduce;
6415 	rack->r_idle_reduce_largest  = rack_reduce_largest_on_idle;
6416 	rack->r_enforce_min_pace = rack_min_pace_time;
6417 	rack->r_min_pace_seg_thresh = rack_min_pace_time_seg_req;
6418 	rack->r_ctl.rc_prop_rate = rack_proportional_rate;
6419 	rack->r_ctl.rc_tlp_cwnd_reduce = rack_lower_cwnd_at_tlp;
6420 	rack->r_ctl.rc_early_recovery = rack_early_recovery;
6421 	rack->rc_always_pace = rack_pace_every_seg;
6422 	rack->r_ctl.rc_rate_sample_method = rack_rate_sample_method;
6423 	rack->rack_tlp_threshold_use = rack_tlp_threshold_use;
6424 	rack->r_ctl.rc_prr_sendalot = rack_send_a_lot_in_prr;
6425 	rack->r_ctl.rc_min_to = rack_min_to;
6426 	rack->r_ctl.rc_prr_inc_var = rack_inc_var;
6427 	if (tp->snd_una != tp->snd_max) {
6428 		/* Create a send map for the current outstanding data */
6429 		struct rack_sendmap *rsm;
6430 
6431 		rsm = rack_alloc(rack);
6432 		if (rsm == NULL) {
6433 			uma_zfree(rack_pcb_zone, tp->t_fb_ptr);
6434 			tp->t_fb_ptr = NULL;
6435 			return (ENOMEM);
6436 		}
6437 		rsm->r_flags = RACK_OVERMAX;
6438 		rsm->r_tim_lastsent[0] = tcp_ts_getticks();
6439 		rsm->r_rtr_cnt = 1;
6440 		rsm->r_rtr_bytes = 0;
6441 		rsm->r_start = tp->snd_una;
6442 		rsm->r_end = tp->snd_max;
6443 		rsm->r_sndcnt = 0;
6444 		TAILQ_INSERT_TAIL(&rack->r_ctl.rc_map, rsm, r_next);
6445 		TAILQ_INSERT_TAIL(&rack->r_ctl.rc_tmap, rsm, r_tnext);
6446 		rsm->r_in_tmap = 1;
6447 	}
6448 	rack_stop_all_timers(tp);
6449 	rack_start_hpts_timer(rack, tp, tcp_ts_getticks(), __LINE__, 0, 0, 0);
6450 	return (0);
6451 }
6452 
6453 static int
6454 rack_handoff_ok(struct tcpcb *tp)
6455 {
6456 	if ((tp->t_state == TCPS_CLOSED) ||
6457 	    (tp->t_state == TCPS_LISTEN)) {
6458 		/* Sure no problem though it may not stick */
6459 		return (0);
6460 	}
6461 	if ((tp->t_state == TCPS_SYN_SENT) ||
6462 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
6463 		/*
6464 		 * We really don't know you have to get to ESTAB or beyond
6465 		 * to tell.
6466 		 */
6467 		return (EAGAIN);
6468 	}
6469 	if (tp->t_flags & TF_SACK_PERMIT) {
6470 		return (0);
6471 	}
6472 	/*
6473 	 * If we reach here we don't do SACK on this connection so we can
6474 	 * never do rack.
6475 	 */
6476 	return (EINVAL);
6477 }
6478 
6479 static void
6480 rack_fini(struct tcpcb *tp, int32_t tcb_is_purged)
6481 {
6482 	if (tp->t_fb_ptr) {
6483 		struct tcp_rack *rack;
6484 		struct rack_sendmap *rsm;
6485 
6486 		rack = (struct tcp_rack *)tp->t_fb_ptr;
6487 #ifdef TCP_BLACKBOX
6488 		tcp_log_flowend(tp);
6489 #endif
6490 		rsm = TAILQ_FIRST(&rack->r_ctl.rc_map);
6491 		while (rsm) {
6492 			TAILQ_REMOVE(&rack->r_ctl.rc_map, rsm, r_next);
6493 			uma_zfree(rack_zone, rsm);
6494 			rsm = TAILQ_FIRST(&rack->r_ctl.rc_map);
6495 		}
6496 		rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
6497 		while (rsm) {
6498 			TAILQ_REMOVE(&rack->r_ctl.rc_free, rsm, r_next);
6499 			uma_zfree(rack_zone, rsm);
6500 			rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
6501 		}
6502 		rack->rc_free_cnt = 0;
6503 		uma_zfree(rack_pcb_zone, tp->t_fb_ptr);
6504 		tp->t_fb_ptr = NULL;
6505 	}
6506 	/* Make sure snd_nxt is correctly set */
6507 	tp->snd_nxt = tp->snd_max;
6508 }
6509 
6510 static void
6511 rack_set_state(struct tcpcb *tp, struct tcp_rack *rack)
6512 {
6513 	switch (tp->t_state) {
6514 	case TCPS_SYN_SENT:
6515 		rack->r_state = TCPS_SYN_SENT;
6516 		rack->r_substate = rack_do_syn_sent;
6517 		break;
6518 	case TCPS_SYN_RECEIVED:
6519 		rack->r_state = TCPS_SYN_RECEIVED;
6520 		rack->r_substate = rack_do_syn_recv;
6521 		break;
6522 	case TCPS_ESTABLISHED:
6523 		rack->r_state = TCPS_ESTABLISHED;
6524 		rack->r_substate = rack_do_established;
6525 		break;
6526 	case TCPS_CLOSE_WAIT:
6527 		rack->r_state = TCPS_CLOSE_WAIT;
6528 		rack->r_substate = rack_do_close_wait;
6529 		break;
6530 	case TCPS_FIN_WAIT_1:
6531 		rack->r_state = TCPS_FIN_WAIT_1;
6532 		rack->r_substate = rack_do_fin_wait_1;
6533 		break;
6534 	case TCPS_CLOSING:
6535 		rack->r_state = TCPS_CLOSING;
6536 		rack->r_substate = rack_do_closing;
6537 		break;
6538 	case TCPS_LAST_ACK:
6539 		rack->r_state = TCPS_LAST_ACK;
6540 		rack->r_substate = rack_do_lastack;
6541 		break;
6542 	case TCPS_FIN_WAIT_2:
6543 		rack->r_state = TCPS_FIN_WAIT_2;
6544 		rack->r_substate = rack_do_fin_wait_2;
6545 		break;
6546 	case TCPS_LISTEN:
6547 	case TCPS_CLOSED:
6548 	case TCPS_TIME_WAIT:
6549 	default:
6550 		break;
6551 	};
6552 }
6553 
6554 
6555 static void
6556 rack_timer_audit(struct tcpcb *tp, struct tcp_rack *rack, struct sockbuf *sb)
6557 {
6558 	/*
6559 	 * We received an ack, and then did not
6560 	 * call send or were bounced out due to the
6561 	 * hpts was running. Now a timer is up as well, is
6562 	 * it the right timer?
6563 	 */
6564 	struct rack_sendmap *rsm;
6565 	int tmr_up;
6566 
6567 	tmr_up = rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
6568 	if (rack->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
6569 		return;
6570 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
6571 	if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
6572 	    (tmr_up == PACE_TMR_RXT)) {
6573 		/* Should be an RXT */
6574 		return;
6575 	}
6576 	if (rsm == NULL) {
6577 		/* Nothing outstanding? */
6578 		if (tp->t_flags & TF_DELACK) {
6579 			if (tmr_up == PACE_TMR_DELACK)
6580 				/* We are supposed to have delayed ack up and we do */
6581 				return;
6582 		} else if (sbavail(&tp->t_inpcb->inp_socket->so_snd) && (tmr_up == PACE_TMR_RXT)) {
6583 			/*
6584 			 * if we hit enobufs then we would expect the possiblity
6585 			 * of nothing outstanding and the RXT up (and the hptsi timer).
6586 			 */
6587 			return;
6588 		} else if (((tcp_always_keepalive ||
6589 			     rack->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
6590 			    (tp->t_state <= TCPS_CLOSING)) &&
6591 			   (tmr_up == PACE_TMR_KEEP) &&
6592 			   (tp->snd_max == tp->snd_una)) {
6593 			/* We should have keep alive up and we do */
6594 			return;
6595 		}
6596 	}
6597 	if (rsm && (rsm->r_flags & RACK_SACK_PASSED)) {
6598 		if ((tp->t_flags & TF_SENTFIN) &&
6599 		    ((tp->snd_max - tp->snd_una) == 1) &&
6600 		    (rsm->r_flags & RACK_HAS_FIN)) {
6601 			/* needs to be a RXT */
6602 			if (tmr_up == PACE_TMR_RXT)
6603 				return;
6604 		} else if (tmr_up == PACE_TMR_RACK)
6605 			return;
6606 	} else if (SEQ_GT(tp->snd_max,tp->snd_una) &&
6607 		   ((tmr_up == PACE_TMR_TLP) ||
6608 		    (tmr_up == PACE_TMR_RXT))) {
6609 		/*
6610 		 * Either a TLP or RXT is fine if no sack-passed
6611 		 * is in place and data is outstanding.
6612 		 */
6613 		return;
6614 	} else if (tmr_up == PACE_TMR_DELACK) {
6615 		/*
6616 		 * If the delayed ack was going to go off
6617 		 * before the rtx/tlp/rack timer were going to
6618 		 * expire, then that would be the timer in control.
6619 		 * Note we don't check the time here trusting the
6620 		 * code is correct.
6621 		 */
6622 		return;
6623 	}
6624 	/*
6625 	 * Ok the timer originally started is not what we want now.
6626 	 * We will force the hpts to be stopped if any, and restart
6627 	 * with the slot set to what was in the saved slot.
6628 	 */
6629 	rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
6630 	rack_start_hpts_timer(rack, tp, tcp_ts_getticks(), __LINE__, 0, 0, 0);
6631 }
6632 
6633 static void
6634 rack_hpts_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
6635     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos,
6636     int32_t nxt_pkt, struct timeval *tv)
6637 {
6638 	int32_t thflags, retval, did_out = 0;
6639 	int32_t way_out = 0;
6640 	uint32_t cts;
6641 	uint32_t tiwin;
6642 	struct tcpopt to;
6643 	struct tcp_rack *rack;
6644 	struct rack_sendmap *rsm;
6645 	int32_t prev_state = 0;
6646 
6647 	cts = tcp_tv_to_mssectick(tv);
6648 	rack = (struct tcp_rack *)tp->t_fb_ptr;
6649 
6650 	kern_prefetch(rack, &prev_state);
6651 	prev_state = 0;
6652 	thflags = th->th_flags;
6653 	/*
6654 	 * If this is either a state-changing packet or current state isn't
6655 	 * established, we require a read lock on tcbinfo.  Otherwise, we
6656 	 * allow the tcbinfo to be in either locked or unlocked, as the
6657 	 * caller may have unnecessarily acquired a lock due to a race.
6658 	 */
6659 	INP_WLOCK_ASSERT(tp->t_inpcb);
6660 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
6661 	    __func__));
6662 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
6663 	    __func__));
6664 	{
6665 		union tcp_log_stackspecific log;
6666 
6667 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
6668 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
6669 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
6670 		log.u_bbr.flex2 = rack->r_ctl.rc_num_maps_alloced;
6671 		TCP_LOG_EVENT(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_IN, 0,
6672 		    tlen, &log, true);
6673 	}
6674 	/*
6675 	 * Segment received on connection. Reset idle time and keep-alive
6676 	 * timer. XXX: This should be done after segment validation to
6677 	 * ignore broken/spoofed segs.
6678 	 */
6679 	if  (tp->t_idle_reduce && (tp->snd_max == tp->snd_una)) {
6680 		if ((ticks - tp->t_rcvtime) >= tp->t_rxtcur) {
6681 			counter_u64_add(rack_input_idle_reduces, 1);
6682 			rack_cc_after_idle(tp,
6683 			    (rack->r_idle_reduce_largest ? 1 :0));
6684 		}
6685 	}
6686 	rack->r_ctl.rc_rcvtime = cts;
6687 	tp->t_rcvtime = ticks;
6688 
6689 	/*
6690 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
6691 	 * the scale is zero.
6692 	 */
6693 	tiwin = th->th_win << tp->snd_scale;
6694 #ifdef NETFLIX_STATS
6695 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
6696 #endif
6697 	/*
6698 	 * TCP ECN processing. XXXJTL: If we ever use ECN, we need to move
6699 	 * this to occur after we've validated the segment.
6700 	 */
6701 	if (tp->t_flags & TF_ECN_PERMIT) {
6702 		if (thflags & TH_CWR)
6703 			tp->t_flags &= ~TF_ECN_SND_ECE;
6704 		switch (iptos & IPTOS_ECN_MASK) {
6705 		case IPTOS_ECN_CE:
6706 			tp->t_flags |= TF_ECN_SND_ECE;
6707 			TCPSTAT_INC(tcps_ecn_ce);
6708 			break;
6709 		case IPTOS_ECN_ECT0:
6710 			TCPSTAT_INC(tcps_ecn_ect0);
6711 			break;
6712 		case IPTOS_ECN_ECT1:
6713 			TCPSTAT_INC(tcps_ecn_ect1);
6714 			break;
6715 		}
6716 		/* Congestion experienced. */
6717 		if (thflags & TH_ECE) {
6718 			rack_cong_signal(tp, th, CC_ECN);
6719 		}
6720 	}
6721 	/*
6722 	 * Parse options on any incoming segment.
6723 	 */
6724 	tcp_dooptions(&to, (u_char *)(th + 1),
6725 	    (th->th_off << 2) - sizeof(struct tcphdr),
6726 	    (thflags & TH_SYN) ? TO_SYN : 0);
6727 
6728 	/*
6729 	 * If echoed timestamp is later than the current time, fall back to
6730 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
6731 	 * were used when this connection was established.
6732 	 */
6733 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
6734 		to.to_tsecr -= tp->ts_offset;
6735 		if (TSTMP_GT(to.to_tsecr, cts))
6736 			to.to_tsecr = 0;
6737 	}
6738 	/*
6739 	 * If its the first time in we need to take care of options and
6740 	 * verify we can do SACK for rack!
6741 	 */
6742 	if (rack->r_state == 0) {
6743 		/* Should be init'd by rack_init() */
6744 		KASSERT(rack->rc_inp != NULL,
6745 		    ("%s: rack->rc_inp unexpectedly NULL", __func__));
6746 		if (rack->rc_inp == NULL) {
6747 			rack->rc_inp = tp->t_inpcb;
6748 		}
6749 
6750 		/*
6751 		 * Process options only when we get SYN/ACK back. The SYN
6752 		 * case for incoming connections is handled in tcp_syncache.
6753 		 * According to RFC1323 the window field in a SYN (i.e., a
6754 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
6755 		 * this is traditional behavior, may need to be cleaned up.
6756 		 */
6757 		rack->r_cpu = inp_to_cpuid(tp->t_inpcb);
6758 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
6759 			if ((to.to_flags & TOF_SCALE) &&
6760 			    (tp->t_flags & TF_REQ_SCALE)) {
6761 				tp->t_flags |= TF_RCVD_SCALE;
6762 				tp->snd_scale = to.to_wscale;
6763 			}
6764 			/*
6765 			 * Initial send window.  It will be updated with the
6766 			 * next incoming segment to the scaled value.
6767 			 */
6768 			tp->snd_wnd = th->th_win;
6769 			if (to.to_flags & TOF_TS) {
6770 				tp->t_flags |= TF_RCVD_TSTMP;
6771 				tp->ts_recent = to.to_tsval;
6772 				tp->ts_recent_age = cts;
6773 			}
6774 			if (to.to_flags & TOF_MSS)
6775 				tcp_mss(tp, to.to_mss);
6776 			if ((tp->t_flags & TF_SACK_PERMIT) &&
6777 			    (to.to_flags & TOF_SACKPERM) == 0)
6778 				tp->t_flags &= ~TF_SACK_PERMIT;
6779 		}
6780 		/*
6781 		 * At this point we are at the initial call. Here we decide
6782 		 * if we are doing RACK or not. We do this by seeing if
6783 		 * TF_SACK_PERMIT is set, if not rack is *not* possible and
6784 		 * we switch to the default code.
6785 		 */
6786 		if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
6787 			tcp_switch_back_to_default(tp);
6788 			(*tp->t_fb->tfb_tcp_do_segment) (m, th, so, tp, drop_hdrlen,
6789 			    tlen, iptos);
6790 			return;
6791 		}
6792 		/* Set the flag */
6793 		rack->r_is_v6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
6794 		tcp_set_hpts(tp->t_inpcb);
6795 		sack_filter_clear(&rack->r_ctl.rack_sf, th->th_ack);
6796 	}
6797 	/*
6798 	 * This is the one exception case where we set the rack state
6799 	 * always. All other times (timers etc) we must have a rack-state
6800 	 * set (so we assure we have done the checks above for SACK).
6801 	 */
6802 	if (rack->r_state != tp->t_state)
6803 		rack_set_state(tp, rack);
6804 	if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&rack->r_ctl.rc_map)) != NULL)
6805 		kern_prefetch(rsm, &prev_state);
6806 	prev_state = rack->r_state;
6807 	rack->r_ctl.rc_tlp_send_cnt = 0;
6808 	rack_clear_rate_sample(rack);
6809 	retval = (*rack->r_substate) (m, th, so,
6810 	    tp, &to, drop_hdrlen,
6811 	    tlen, tiwin, thflags, nxt_pkt);
6812 #ifdef INVARIANTS
6813 	if ((retval == 0) &&
6814 	    (tp->t_inpcb == NULL)) {
6815 		panic("retval:%d tp:%p t_inpcb:NULL state:%d",
6816 		    retval, tp, prev_state);
6817 	}
6818 #endif
6819 	if (retval == 0) {
6820 		/*
6821 		 * If retval is 1 the tcb is unlocked and most likely the tp
6822 		 * is gone.
6823 		 */
6824 		INP_WLOCK_ASSERT(tp->t_inpcb);
6825 		tcp_rack_xmit_timer_commit(rack, tp);
6826 		if (nxt_pkt == 0) {
6827 			if (rack->r_wanted_output != 0) {
6828 				did_out = 1;
6829 				(void)tp->t_fb->tfb_tcp_output(tp);
6830 			}
6831 			rack_start_hpts_timer(rack, tp, cts, __LINE__, 0, 0, 0);
6832 		}
6833 		if (((rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
6834 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
6835 		     (tp->t_flags & TF_DELACK) ||
6836 		     ((tcp_always_keepalive || rack->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
6837 		      (tp->t_state <= TCPS_CLOSING)))) {
6838 			/* We could not send (probably in the hpts but stopped the timer earlier)? */
6839 			if ((tp->snd_max == tp->snd_una) &&
6840 			    ((tp->t_flags & TF_DELACK) == 0) &&
6841 			    (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
6842 				/* keep alive not needed if we are hptsi output yet */
6843 				;
6844 			} else {
6845 				if (rack->rc_inp->inp_in_hpts)
6846 					tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
6847 				rack_start_hpts_timer(rack, tp, tcp_ts_getticks(), __LINE__, 0, 0, 0);
6848 			}
6849 			way_out = 1;
6850 		} else {
6851 			/* Do we have the correct timer running? */
6852 			rack_timer_audit(tp, rack, &so->so_snd);
6853 			way_out = 2;
6854 		}
6855 		rack_log_doseg_done(rack, cts, nxt_pkt, did_out, way_out);
6856 		if (did_out)
6857 			rack->r_wanted_output = 0;
6858 #ifdef INVARIANTS
6859 		if (tp->t_inpcb == NULL) {
6860 			panic("OP:%d retval:%d tp:%p t_inpcb:NULL state:%d",
6861 			      did_out,
6862 			      retval, tp, prev_state);
6863 		}
6864 #endif
6865 		INP_WUNLOCK(tp->t_inpcb);
6866 	}
6867 }
6868 
6869 void
6870 rack_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
6871     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
6872 {
6873 	struct timeval tv;
6874 #ifdef RSS
6875 	struct tcp_function_block *tfb;
6876 	struct tcp_rack *rack;
6877 	struct inpcb *inp;
6878 
6879 	rack = (struct tcp_rack *)tp->t_fb_ptr;
6880 	if (rack->r_state == 0) {
6881 		/*
6882 		 * Initial input (ACK to SYN-ACK etc)lets go ahead and get
6883 		 * it processed
6884 		 */
6885 		tcp_get_usecs(&tv);
6886 		rack_hpts_do_segment(m, th, so, tp, drop_hdrlen,
6887 		    tlen, iptos, 0, &tv);
6888 		return;
6889 	}
6890 	tcp_queue_to_input(tp, m, th, tlen, drop_hdrlen, iptos);
6891 	INP_WUNLOCK(tp->t_inpcb);
6892 #else
6893 	tcp_get_usecs(&tv);
6894 	rack_hpts_do_segment(m, th, so, tp, drop_hdrlen,
6895 	    tlen, iptos, 0, &tv);
6896 #endif
6897 }
6898 
6899 struct rack_sendmap *
6900 tcp_rack_output(struct tcpcb *tp, struct tcp_rack *rack, uint32_t tsused)
6901 {
6902 	struct rack_sendmap *rsm = NULL;
6903 	int32_t idx;
6904 	uint32_t srtt_cur, srtt = 0, thresh = 0, ts_low = 0;
6905 
6906 	/* Return the next guy to be re-transmitted */
6907 	if (TAILQ_EMPTY(&rack->r_ctl.rc_map)) {
6908 		return (NULL);
6909 	}
6910 	if (tp->t_flags & TF_SENTFIN) {
6911 		/* retran the end FIN? */
6912 		return (NULL);
6913 	}
6914 	/* ok lets look at this one */
6915 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
6916 	if (rsm && ((rsm->r_flags & RACK_ACKED) == 0)) {
6917 		goto check_it;
6918 	}
6919 	rsm = rack_find_lowest_rsm(rack);
6920 	if (rsm == NULL) {
6921 		return (NULL);
6922 	}
6923 check_it:
6924 	srtt_cur = tp->t_srtt >> TCP_RTT_SHIFT;
6925 	srtt = TICKS_2_MSEC(srtt_cur);
6926 	if (rack->rc_rack_rtt && (srtt > rack->rc_rack_rtt))
6927 		srtt = rack->rc_rack_rtt;
6928 	if (rsm->r_flags & RACK_ACKED) {
6929 		return (NULL);
6930 	}
6931 	if ((rsm->r_flags & RACK_SACK_PASSED) == 0) {
6932 		/* Its not yet ready */
6933 		return (NULL);
6934 	}
6935 	idx = rsm->r_rtr_cnt - 1;
6936 	ts_low = rsm->r_tim_lastsent[idx];
6937 	thresh = rack_calc_thresh_rack(rack, srtt, tsused);
6938 	if (tsused <= ts_low) {
6939 		return (NULL);
6940 	}
6941 	if ((tsused - ts_low) >= thresh) {
6942 		return (rsm);
6943 	}
6944 	return (NULL);
6945 }
6946 
6947 static int
6948 rack_output(struct tcpcb *tp)
6949 {
6950 	struct socket *so;
6951 	uint32_t recwin, sendwin;
6952 	uint32_t sb_offset;
6953 	int32_t len, flags, error = 0;
6954 	struct mbuf *m;
6955 	struct mbuf *mb;
6956 	uint32_t if_hw_tsomaxsegcount = 0;
6957 	uint32_t if_hw_tsomaxsegsize;
6958 	long tot_len_this_send = 0;
6959 	struct ip *ip = NULL;
6960 #ifdef TCPDEBUG
6961 	struct ipovly *ipov = NULL;
6962 #endif
6963 #ifdef NETFLIX_TCP_O_UDP
6964 	struct udphdr *udp = NULL;
6965 #endif
6966 	struct tcp_rack *rack;
6967 	struct tcphdr *th;
6968 	uint8_t pass = 0;
6969 	u_char opt[TCP_MAXOLEN];
6970 	unsigned ipoptlen, optlen, hdrlen;
6971 #ifdef NETFLIX_TCP_O_UDP
6972 	unsigned ulen;
6973 #endif
6974 	uint32_t rack_seq;
6975 
6976 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
6977 	unsigned ipsec_optlen = 0;
6978 
6979 #endif
6980 	int32_t idle, sendalot;
6981 	int32_t sub_from_prr = 0;
6982 	volatile int32_t sack_rxmit;
6983 	struct rack_sendmap *rsm = NULL;
6984 	int32_t tso, mtu, would_have_fin = 0;
6985 	struct tcpopt to;
6986 	int32_t slot = 0;
6987 	uint32_t cts;
6988 	uint8_t hpts_calling, doing_tlp = 0;
6989 	int32_t do_a_prefetch;
6990 	int32_t prefetch_rsm = 0;
6991 	int32_t prefetch_so_done = 0;
6992 	struct tcp_log_buffer *lgb = NULL;
6993 	struct inpcb *inp;
6994 	struct sockbuf *sb;
6995 #ifdef INET6
6996 	struct ip6_hdr *ip6 = NULL;
6997 	int32_t isipv6;
6998 #endif
6999 #ifdef KERN_TLS
7000 	const bool hw_tls = (so->so_snd.sb_flags & SB_TLS_IFNET) != 0;
7001 #else
7002 	const bool hw_tls = false;
7003 #endif
7004 
7005 	/* setup and take the cache hits here */
7006 	rack = (struct tcp_rack *)tp->t_fb_ptr;
7007 	inp = rack->rc_inp;
7008 	so = inp->inp_socket;
7009 	sb = &so->so_snd;
7010 	kern_prefetch(sb, &do_a_prefetch);
7011 	do_a_prefetch = 1;
7012 
7013 	INP_WLOCK_ASSERT(inp);
7014 #ifdef TCP_OFFLOAD
7015 	if (tp->t_flags & TF_TOE)
7016 		return (tcp_offload_output(tp));
7017 #endif
7018 
7019 #ifdef TCP_RFC7413
7020 	/*
7021 	 * For TFO connections in SYN_RECEIVED, only allow the initial
7022 	 * SYN|ACK and those sent by the retransmit timer.
7023 	 */
7024 	if ((tp->t_flags & TF_FASTOPEN) &&
7025 	    (tp->t_state == TCPS_SYN_RECEIVED) &&
7026 	    SEQ_GT(tp->snd_max, tp->snd_una) &&	/* inital SYN|ACK sent */
7027 	    (tp->snd_nxt != tp->snd_una))	/* not a retransmit */
7028 		return (0);
7029 #endif
7030 #ifdef INET6
7031 	if (rack->r_state) {
7032 		/* Use the cache line loaded if possible */
7033 		isipv6 = rack->r_is_v6;
7034 	} else {
7035 		isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
7036 	}
7037 #endif
7038 	cts = tcp_ts_getticks();
7039 	if (((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
7040 	    inp->inp_in_hpts) {
7041 		/*
7042 		 * We are on the hpts for some timer but not hptsi output.
7043 		 * Remove from the hpts unconditionally.
7044 		 */
7045 		rack_timer_cancel(tp, rack, cts, __LINE__);
7046 	}
7047 	/* Mark that we have called rack_output(). */
7048 	if ((rack->r_timer_override) ||
7049 	    (tp->t_flags & TF_FORCEDATA) ||
7050 	    (tp->t_state < TCPS_ESTABLISHED)) {
7051 		if (tp->t_inpcb->inp_in_hpts)
7052 			tcp_hpts_remove(tp->t_inpcb, HPTS_REMOVE_OUTPUT);
7053 	} else if (tp->t_inpcb->inp_in_hpts) {
7054 		/*
7055 		 * On the hpts you can't pass even if ACKNOW is on, we will
7056 		 * when the hpts fires.
7057 		 */
7058 		counter_u64_add(rack_out_size[TCP_MSS_ACCT_INPACE], 1);
7059 		return (0);
7060 	}
7061 	hpts_calling = inp->inp_hpts_calls;
7062 	inp->inp_hpts_calls = 0;
7063 	if (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
7064 		if (rack_process_timers(tp, rack, cts, hpts_calling)) {
7065 			counter_u64_add(rack_out_size[TCP_MSS_ACCT_ATIMER], 1);
7066 			return (0);
7067 		}
7068 	}
7069 	rack->r_wanted_output = 0;
7070 	rack->r_timer_override = 0;
7071 	/*
7072 	 * Determine length of data that should be transmitted, and flags
7073 	 * that will be used. If there is some data or critical controls
7074 	 * (SYN, RST) to send, then transmit; otherwise, investigate
7075 	 * further.
7076 	 */
7077 	idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
7078 	if (tp->t_idle_reduce) {
7079 		if (idle && ((ticks - tp->t_rcvtime) >= tp->t_rxtcur))
7080 			rack_cc_after_idle(tp,
7081 		            (rack->r_idle_reduce_largest ? 1 :0));
7082 	}
7083 	tp->t_flags &= ~TF_LASTIDLE;
7084 	if (idle) {
7085 		if (tp->t_flags & TF_MORETOCOME) {
7086 			tp->t_flags |= TF_LASTIDLE;
7087 			idle = 0;
7088 		}
7089 	}
7090 again:
7091 	/*
7092 	 * If we've recently taken a timeout, snd_max will be greater than
7093 	 * snd_nxt.  There may be SACK information that allows us to avoid
7094 	 * resending already delivered data.  Adjust snd_nxt accordingly.
7095 	 */
7096 	sendalot = 0;
7097 	cts = tcp_ts_getticks();
7098 	tso = 0;
7099 	mtu = 0;
7100 	sb_offset = tp->snd_max - tp->snd_una;
7101 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
7102 
7103 	flags = tcp_outflags[tp->t_state];
7104 	/*
7105 	 * Send any SACK-generated retransmissions.  If we're explicitly
7106 	 * trying to send out new data (when sendalot is 1), bypass this
7107 	 * function. If we retransmit in fast recovery mode, decrement
7108 	 * snd_cwnd, since we're replacing a (future) new transmission with
7109 	 * a retransmission now, and we previously incremented snd_cwnd in
7110 	 * tcp_input().
7111 	 */
7112 	/*
7113 	 * Still in sack recovery , reset rxmit flag to zero.
7114 	 */
7115 	while (rack->rc_free_cnt < rack_free_cache) {
7116 		rsm = rack_alloc(rack);
7117 		if (rsm == NULL) {
7118 			if (inp->inp_hpts_calls)
7119 				/* Retry in a ms */
7120 				slot = 1;
7121 			goto just_return_nolock;
7122 		}
7123 		TAILQ_INSERT_TAIL(&rack->r_ctl.rc_free, rsm, r_next);
7124 		rack->rc_free_cnt++;
7125 		rsm = NULL;
7126 	}
7127 	if (inp->inp_hpts_calls)
7128 		inp->inp_hpts_calls = 0;
7129 	sack_rxmit = 0;
7130 	len = 0;
7131 	rsm = NULL;
7132 	if (flags & TH_RST) {
7133 		SOCKBUF_LOCK(sb);
7134 		goto send;
7135 	}
7136 	if (rack->r_ctl.rc_tlpsend) {
7137 		/* Tail loss probe */
7138 		long cwin;
7139 		long tlen;
7140 
7141 		doing_tlp = 1;
7142 		rsm = rack->r_ctl.rc_tlpsend;
7143 		rack->r_ctl.rc_tlpsend = NULL;
7144 		sack_rxmit = 1;
7145 		tlen = rsm->r_end - rsm->r_start;
7146 		if (tlen > tp->t_maxseg)
7147 			tlen = tp->t_maxseg;
7148 #ifdef INVARIANTS
7149 		if (SEQ_GT(tp->snd_una, rsm->r_start)) {
7150 			panic("tp:%p rack:%p snd_una:%u rsm:%p r_start:%u",
7151 			    tp, rack, tp->snd_una, rsm, rsm->r_start);
7152 		}
7153 #endif
7154 		sb_offset = rsm->r_start - tp->snd_una;
7155 		cwin = min(tp->snd_wnd, tlen);
7156 		len = cwin;
7157 	} else if (rack->r_ctl.rc_resend) {
7158 		/* Retransmit timer */
7159 		rsm = rack->r_ctl.rc_resend;
7160 		rack->r_ctl.rc_resend = NULL;
7161 		len = rsm->r_end - rsm->r_start;
7162 		sack_rxmit = 1;
7163 		sendalot = 0;
7164 		sb_offset = rsm->r_start - tp->snd_una;
7165 		if (len >= tp->t_maxseg) {
7166 			len = tp->t_maxseg;
7167 		}
7168 		KASSERT(sb_offset >= 0, ("%s: sack block to the left of una : %d",
7169 		    __func__, sb_offset));
7170 	} else if ((rack->rc_in_persist == 0) &&
7171 	    ((rsm = tcp_rack_output(tp, rack, cts)) != NULL)) {
7172 		long tlen;
7173 
7174 		if ((!IN_RECOVERY(tp->t_flags)) &&
7175 		    ((tp->t_flags & (TF_WASFRECOVERY | TF_WASCRECOVERY)) == 0)) {
7176 			/* Enter recovery if not induced by a time-out */
7177 			rack->r_ctl.rc_rsm_start = rsm->r_start;
7178 			rack->r_ctl.rc_cwnd_at = tp->snd_cwnd;
7179 			rack->r_ctl.rc_ssthresh_at = tp->snd_ssthresh;
7180 			rack_cong_signal(tp, NULL, CC_NDUPACK);
7181 			/*
7182 			 * When we enter recovery we need to assure we send
7183 			 * one packet.
7184 			 */
7185 			rack->r_ctl.rc_prr_sndcnt = tp->t_maxseg;
7186 		}
7187 #ifdef INVARIANTS
7188 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
7189 			panic("Huh, tp:%p rack:%p rsm:%p start:%u < snd_una:%u\n",
7190 			    tp, rack, rsm, rsm->r_start, tp->snd_una);
7191 		}
7192 #endif
7193 		tlen = rsm->r_end - rsm->r_start;
7194 		sb_offset = rsm->r_start - tp->snd_una;
7195 		if (tlen > rack->r_ctl.rc_prr_sndcnt) {
7196 			len = rack->r_ctl.rc_prr_sndcnt;
7197 		} else {
7198 			len = tlen;
7199 		}
7200 		if (len >= tp->t_maxseg) {
7201 			sendalot = 1;
7202 			len = tp->t_maxseg;
7203 		} else {
7204 			sendalot = 0;
7205 			if ((rack->rc_timer_up == 0) &&
7206 			    (len < tlen)) {
7207 				/*
7208 				 * If its not a timer don't send a partial
7209 				 * segment.
7210 				 */
7211 				len = 0;
7212 				goto just_return_nolock;
7213 			}
7214 		}
7215 		KASSERT(sb_offset >= 0, ("%s: sack block to the left of una : %d",
7216 		    __func__, sb_offset));
7217 		if (len > 0) {
7218 			sub_from_prr = 1;
7219 			sack_rxmit = 1;
7220 			TCPSTAT_INC(tcps_sack_rexmits);
7221 			TCPSTAT_ADD(tcps_sack_rexmit_bytes,
7222 			    min(len, tp->t_maxseg));
7223 			counter_u64_add(rack_rtm_prr_retran, 1);
7224 		}
7225 	}
7226 	if (rsm && (rsm->r_flags & RACK_HAS_FIN)) {
7227 		/* we are retransmitting the fin */
7228 		len--;
7229 		if (len) {
7230 			/*
7231 			 * When retransmitting data do *not* include the
7232 			 * FIN. This could happen from a TLP probe.
7233 			 */
7234 			flags &= ~TH_FIN;
7235 		}
7236 	}
7237 #ifdef INVARIANTS
7238 	/* For debugging */
7239 	rack->r_ctl.rc_rsm_at_retran = rsm;
7240 #endif
7241 	/*
7242 	 * Enforce a connection sendmap count limit if set
7243 	 * as long as we are not retransmiting.
7244 	 */
7245 	if ((rsm == NULL) &&
7246 	    (rack_map_entries_limit > 0) &&
7247 	    (rack->r_ctl.rc_num_maps_alloced >= rack_map_entries_limit)) {
7248 		counter_u64_add(rack_to_alloc_limited, 1);
7249 		if (!rack->alloc_limit_reported) {
7250 			rack->alloc_limit_reported = 1;
7251 			counter_u64_add(rack_alloc_limited_conns, 1);
7252 		}
7253 		goto just_return_nolock;
7254 	}
7255 	/*
7256 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
7257 	 * state flags.
7258 	 */
7259 	if (tp->t_flags & TF_NEEDFIN)
7260 		flags |= TH_FIN;
7261 	if (tp->t_flags & TF_NEEDSYN)
7262 		flags |= TH_SYN;
7263 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
7264 		void *end_rsm;
7265 		end_rsm = TAILQ_LAST_FAST(&rack->r_ctl.rc_tmap, rack_sendmap, r_tnext);
7266 		if (end_rsm)
7267 			kern_prefetch(end_rsm, &prefetch_rsm);
7268 		prefetch_rsm = 1;
7269 	}
7270 	SOCKBUF_LOCK(sb);
7271 	/*
7272 	 * If in persist timeout with window of 0, send 1 byte. Otherwise,
7273 	 * if window is small but nonzero and time TF_SENTFIN expired, we
7274 	 * will send what we can and go to transmit state.
7275 	 */
7276 	if (tp->t_flags & TF_FORCEDATA) {
7277 		if (sendwin == 0) {
7278 			/*
7279 			 * If we still have some data to send, then clear
7280 			 * the FIN bit.  Usually this would happen below
7281 			 * when it realizes that we aren't sending all the
7282 			 * data.  However, if we have exactly 1 byte of
7283 			 * unsent data, then it won't clear the FIN bit
7284 			 * below, and if we are in persist state, we wind up
7285 			 * sending the packet without recording that we sent
7286 			 * the FIN bit.
7287 			 *
7288 			 * We can't just blindly clear the FIN bit, because
7289 			 * if we don't have any more data to send then the
7290 			 * probe will be the FIN itself.
7291 			 */
7292 			if (sb_offset < sbused(sb))
7293 				flags &= ~TH_FIN;
7294 			sendwin = 1;
7295 		} else {
7296 			if (rack->rc_in_persist)
7297 				rack_exit_persist(tp, rack);
7298 			/*
7299 			 * If we are dropping persist mode then we need to
7300 			 * correct snd_nxt/snd_max and off.
7301 			 */
7302 			tp->snd_nxt = tp->snd_max;
7303 			sb_offset = tp->snd_nxt - tp->snd_una;
7304 		}
7305 	}
7306 	/*
7307 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
7308 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
7309 	 * negative length.  This can also occur when TCP opens up its
7310 	 * congestion window while receiving additional duplicate acks after
7311 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
7312 	 * the fast-retransmit.
7313 	 *
7314 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
7315 	 * set to snd_una, the sb_offset will be 0, and the length may wind
7316 	 * up 0.
7317 	 *
7318 	 * If sack_rxmit is true we are retransmitting from the scoreboard
7319 	 * in which case len is already set.
7320 	 */
7321 	if (sack_rxmit == 0) {
7322 		uint32_t avail;
7323 
7324 		avail = sbavail(sb);
7325 		if (SEQ_GT(tp->snd_nxt, tp->snd_una))
7326 			sb_offset = tp->snd_nxt - tp->snd_una;
7327 		else
7328 			sb_offset = 0;
7329 		if (IN_RECOVERY(tp->t_flags) == 0) {
7330 			if (rack->r_ctl.rc_tlp_new_data) {
7331 				/* TLP is forcing out new data */
7332 				if (rack->r_ctl.rc_tlp_new_data > (uint32_t) (avail - sb_offset)) {
7333 					rack->r_ctl.rc_tlp_new_data = (uint32_t) (avail - sb_offset);
7334 				}
7335 				if (rack->r_ctl.rc_tlp_new_data > tp->snd_wnd)
7336 					len = tp->snd_wnd;
7337 				else
7338 					len = rack->r_ctl.rc_tlp_new_data;
7339 				rack->r_ctl.rc_tlp_new_data = 0;
7340 				doing_tlp = 1;
7341 			} else {
7342 				if (sendwin > avail) {
7343 					/* use the available */
7344 					if (avail > sb_offset) {
7345 						len = (int32_t)(avail - sb_offset);
7346 					} else {
7347 						len = 0;
7348 					}
7349 				} else {
7350 					if (sendwin > sb_offset) {
7351 						len = (int32_t)(sendwin - sb_offset);
7352 					} else {
7353 						len = 0;
7354 					}
7355 				}
7356 			}
7357 		} else {
7358 			uint32_t outstanding;
7359 
7360 			/*
7361 			 * We are inside of a SACK recovery episode and are
7362 			 * sending new data, having retransmitted all the
7363 			 * data possible so far in the scoreboard.
7364 			 */
7365 			outstanding = tp->snd_max - tp->snd_una;
7366 			if ((rack->r_ctl.rc_prr_sndcnt + outstanding) > tp->snd_wnd) {
7367 				if (tp->snd_wnd > outstanding) {
7368 					len = tp->snd_wnd - outstanding;
7369 					/* Check to see if we have the data */
7370 					if (((sb_offset + len) > avail) &&
7371 					    (avail > sb_offset))
7372 						len = avail - sb_offset;
7373 					else
7374 						len = 0;
7375 				} else
7376 					len = 0;
7377 			} else if (avail > sb_offset)
7378 				len = avail - sb_offset;
7379 			else
7380 				len = 0;
7381 			if (len > 0) {
7382 				if (len > rack->r_ctl.rc_prr_sndcnt)
7383 					len = rack->r_ctl.rc_prr_sndcnt;
7384 
7385 				if (len > 0) {
7386 					sub_from_prr = 1;
7387 					counter_u64_add(rack_rtm_prr_newdata, 1);
7388 				}
7389 			}
7390 			if (len > tp->t_maxseg) {
7391 				/*
7392 				 * We should never send more than a MSS when
7393 				 * retransmitting or sending new data in prr
7394 				 * mode unless the override flag is on. Most
7395 				 * likely the PRR algorithm is not going to
7396 				 * let us send a lot as well :-)
7397 				 */
7398 				if (rack->r_ctl.rc_prr_sendalot == 0)
7399 					len = tp->t_maxseg;
7400 			} else if (len < tp->t_maxseg) {
7401 				/*
7402 				 * Do we send any? The idea here is if the
7403 				 * send empty's the socket buffer we want to
7404 				 * do it. However if not then lets just wait
7405 				 * for our prr_sndcnt to get bigger.
7406 				 */
7407 				long leftinsb;
7408 
7409 				leftinsb = sbavail(sb) - sb_offset;
7410 				if (leftinsb > len) {
7411 					/* This send does not empty the sb */
7412 					len = 0;
7413 				}
7414 			}
7415 		}
7416 	}
7417 	if (prefetch_so_done == 0) {
7418 		kern_prefetch(so, &prefetch_so_done);
7419 		prefetch_so_done = 1;
7420 	}
7421 	/*
7422 	 * Lop off SYN bit if it has already been sent.  However, if this is
7423 	 * SYN-SENT state and if segment contains data and if we don't know
7424 	 * that foreign host supports TAO, suppress sending segment.
7425 	 */
7426 	if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una)) {
7427 		if ((tp->t_state != TCPS_SYN_RECEIVED) &&
7428 		    (tp->t_state != TCPS_SYN_SENT))
7429 			flags &= ~TH_SYN;
7430 #ifdef TCP_RFC7413
7431 		/*
7432 		 * When sending additional segments following a TFO SYN|ACK,
7433 		 * do not include the SYN bit.
7434 		 */
7435 		if ((tp->t_flags & TF_FASTOPEN) &&
7436 		    (tp->t_state == TCPS_SYN_RECEIVED))
7437 			flags &= ~TH_SYN;
7438 #endif
7439 	}
7440 	/*
7441 	 * Be careful not to send data and/or FIN on SYN segments. This
7442 	 * measure is needed to prevent interoperability problems with not
7443 	 * fully conformant TCP implementations.
7444 	 */
7445 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
7446 		len = 0;
7447 		flags &= ~TH_FIN;
7448 	}
7449 #ifdef TCP_RFC7413
7450 	/*
7451 	 * When retransmitting SYN|ACK on a passively-created TFO socket,
7452 	 * don't include data, as the presence of data may have caused the
7453 	 * original SYN|ACK to have been dropped by a middlebox.
7454 	 */
7455 	if ((tp->t_flags & TF_FASTOPEN) &&
7456 	    ((tp->t_state == TCPS_SYN_RECEIVED) && (tp->t_rxtshift > 0)))
7457 		len = 0;
7458 #endif
7459 	if (len <= 0) {
7460 		/*
7461 		 * If FIN has been sent but not acked, but we haven't been
7462 		 * called to retransmit, len will be < 0.  Otherwise, window
7463 		 * shrank after we sent into it.  If window shrank to 0,
7464 		 * cancel pending retransmit, pull snd_nxt back to (closed)
7465 		 * window, and set the persist timer if it isn't already
7466 		 * going.  If the window didn't close completely, just wait
7467 		 * for an ACK.
7468 		 *
7469 		 * We also do a general check here to ensure that we will
7470 		 * set the persist timer when we have data to send, but a
7471 		 * 0-byte window. This makes sure the persist timer is set
7472 		 * even if the packet hits one of the "goto send" lines
7473 		 * below.
7474 		 */
7475 		len = 0;
7476 		if ((tp->snd_wnd == 0) &&
7477 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
7478 		    (sb_offset < (int)sbavail(sb))) {
7479 			tp->snd_nxt = tp->snd_una;
7480 			rack_enter_persist(tp, rack, cts);
7481 		}
7482 	}
7483 	/* len will be >= 0 after this point. */
7484 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
7485 	tcp_sndbuf_autoscale(tp, so, sendwin);
7486 	/*
7487 	 * Decide if we can use TCP Segmentation Offloading (if supported by
7488 	 * hardware).
7489 	 *
7490 	 * TSO may only be used if we are in a pure bulk sending state.  The
7491 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
7492 	 * options prevent using TSO.  With TSO the TCP header is the same
7493 	 * (except for the sequence number) for all generated packets.  This
7494 	 * makes it impossible to transmit any options which vary per
7495 	 * generated segment or packet.
7496 	 *
7497 	 * IPv4 handling has a clear separation of ip options and ip header
7498 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen() does
7499 	 * the right thing below to provide length of just ip options and thus
7500 	 * checking for ipoptlen is enough to decide if ip options are present.
7501 	 */
7502 
7503 #ifdef INET6
7504 	if (isipv6)
7505 		ipoptlen = ip6_optlen(tp->t_inpcb);
7506 	else
7507 #endif
7508 		if (tp->t_inpcb->inp_options)
7509 			ipoptlen = tp->t_inpcb->inp_options->m_len -
7510 			    offsetof(struct ipoption, ipopt_list);
7511 		else
7512 			ipoptlen = 0;
7513 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
7514 	/*
7515 	 * Pre-calculate here as we save another lookup into the darknesses
7516 	 * of IPsec that way and can actually decide if TSO is ok.
7517 	 */
7518 #ifdef INET6
7519 	if (isipv6 && IPSEC_ENABLED(ipv6))
7520 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, tp->t_inpcb);
7521 #ifdef INET
7522 	else
7523 #endif
7524 #endif				/* INET6 */
7525 #ifdef INET
7526 	if (IPSEC_ENABLED(ipv4))
7527 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, tp->t_inpcb);
7528 #endif				/* INET */
7529 #endif
7530 
7531 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
7532 	ipoptlen += ipsec_optlen;
7533 #endif
7534 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso && len > tp->t_maxseg &&
7535 #ifdef NETFLIX_TCP_O_UDP
7536 	    (tp->t_port == 0) &&
7537 #endif
7538 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
7539 	    tp->rcv_numsacks == 0 && sack_rxmit == 0 &&
7540 	    ipoptlen == 0)
7541 		tso = 1;
7542 	{
7543 		uint32_t outstanding;
7544 
7545 		outstanding = tp->snd_max - tp->snd_una;
7546 		if (tp->t_flags & TF_SENTFIN) {
7547 			/*
7548 			 * If we sent a fin, snd_max is 1 higher than
7549 			 * snd_una
7550 			 */
7551 			outstanding--;
7552 		}
7553 		if (outstanding > 0) {
7554 			/*
7555 			 * This is sub-optimal. We only send a stand alone
7556 			 * FIN on its own segment.
7557 			 */
7558 			if (flags & TH_FIN) {
7559 				flags &= ~TH_FIN;
7560 				would_have_fin = 1;
7561 			}
7562 		} else if (sack_rxmit) {
7563 			if ((rsm->r_flags & RACK_HAS_FIN) == 0)
7564 				flags &= ~TH_FIN;
7565 		} else {
7566 			if (SEQ_LT(tp->snd_nxt + len, tp->snd_una +
7567 			    sbused(sb)))
7568 				flags &= ~TH_FIN;
7569 		}
7570 	}
7571 	recwin = sbspace(&so->so_rcv);
7572 
7573 	/*
7574 	 * Sender silly window avoidance.   We transmit under the following
7575 	 * conditions when len is non-zero:
7576 	 *
7577 	 * - We have a full segment (or more with TSO) - This is the last
7578 	 * buffer in a write()/send() and we are either idle or running
7579 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
7580 	 * then 1/2 the maximum send window's worth of data (receiver may be
7581 	 * limited the window size) - we need to retransmit
7582 	 */
7583 	if (len) {
7584 		if (len >= tp->t_maxseg) {
7585 			pass = 1;
7586 			goto send;
7587 		}
7588 		/*
7589 		 * NOTE! on localhost connections an 'ack' from the remote
7590 		 * end may occur synchronously with the output and cause us
7591 		 * to flush a buffer queued with moretocome.  XXX
7592 		 *
7593 		 */
7594 		if (!(tp->t_flags & TF_MORETOCOME) &&	/* normal case */
7595 		    (idle || (tp->t_flags & TF_NODELAY)) &&
7596 		    ((uint32_t)len + (uint32_t)sb_offset >= sbavail(&so->so_snd)) &&
7597 		    (tp->t_flags & TF_NOPUSH) == 0) {
7598 			pass = 2;
7599 			goto send;
7600 		}
7601 		if (tp->t_flags & TF_FORCEDATA) {	/* typ. timeout case */
7602 			pass = 3;
7603 			goto send;
7604 		}
7605 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
7606 			goto send;
7607 		}
7608 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
7609 			pass = 4;
7610 			goto send;
7611 		}
7612 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {	/* retransmit case */
7613 			pass = 5;
7614 			goto send;
7615 		}
7616 		if (sack_rxmit) {
7617 			pass = 6;
7618 			goto send;
7619 		}
7620 	}
7621 	/*
7622 	 * Sending of standalone window updates.
7623 	 *
7624 	 * Window updates are important when we close our window due to a
7625 	 * full socket buffer and are opening it again after the application
7626 	 * reads data from it.  Once the window has opened again and the
7627 	 * remote end starts to send again the ACK clock takes over and
7628 	 * provides the most current window information.
7629 	 *
7630 	 * We must avoid the silly window syndrome whereas every read from
7631 	 * the receive buffer, no matter how small, causes a window update
7632 	 * to be sent.  We also should avoid sending a flurry of window
7633 	 * updates when the socket buffer had queued a lot of data and the
7634 	 * application is doing small reads.
7635 	 *
7636 	 * Prevent a flurry of pointless window updates by only sending an
7637 	 * update when we can increase the advertized window by more than
7638 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
7639 	 * full or is very small be more aggressive and send an update
7640 	 * whenever we can increase by two mss sized segments. In all other
7641 	 * situations the ACK's to new incoming data will carry further
7642 	 * window increases.
7643 	 *
7644 	 * Don't send an independent window update if a delayed ACK is
7645 	 * pending (it will get piggy-backed on it) or the remote side
7646 	 * already has done a half-close and won't send more data.  Skip
7647 	 * this if the connection is in T/TCP half-open state.
7648 	 */
7649 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
7650 	    !(tp->t_flags & TF_DELACK) &&
7651 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
7652 		/*
7653 		 * "adv" is the amount we could increase the window, taking
7654 		 * into account that we are limited by TCP_MAXWIN <<
7655 		 * tp->rcv_scale.
7656 		 */
7657 		int32_t adv;
7658 		int oldwin;
7659 
7660 		adv = min(recwin, (long)TCP_MAXWIN << tp->rcv_scale);
7661 		if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
7662 			oldwin = (tp->rcv_adv - tp->rcv_nxt);
7663 			adv -= oldwin;
7664 		} else
7665 			oldwin = 0;
7666 
7667 		/*
7668 		 * If the new window size ends up being the same as the old
7669 		 * size when it is scaled, then don't force a window update.
7670 		 */
7671 		if (oldwin >> tp->rcv_scale == (adv + oldwin) >> tp->rcv_scale)
7672 			goto dontupdate;
7673 
7674 		if (adv >= (int32_t)(2 * tp->t_maxseg) &&
7675 		    (adv >= (int32_t)(so->so_rcv.sb_hiwat / 4) ||
7676 		    recwin <= (int32_t)(so->so_rcv.sb_hiwat / 8) ||
7677 		    so->so_rcv.sb_hiwat <= 8 * tp->t_maxseg)) {
7678 			pass = 7;
7679 			goto send;
7680 		}
7681 		if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
7682 			goto send;
7683 	}
7684 dontupdate:
7685 
7686 	/*
7687 	 * Send if we owe the peer an ACK, RST, SYN, or urgent data.  ACKNOW
7688 	 * is also a catch-all for the retransmit timer timeout case.
7689 	 */
7690 	if (tp->t_flags & TF_ACKNOW) {
7691 		pass = 8;
7692 		goto send;
7693 	}
7694 	if (((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0)) {
7695 		pass = 9;
7696 		goto send;
7697 	}
7698 	if (SEQ_GT(tp->snd_up, tp->snd_una)) {
7699 		pass = 10;
7700 		goto send;
7701 	}
7702 	/*
7703 	 * If our state indicates that FIN should be sent and we have not
7704 	 * yet done so, then we need to send.
7705 	 */
7706 	if (flags & TH_FIN) {
7707 		if ((tp->t_flags & TF_SENTFIN) ||
7708 		    (((tp->t_flags & TF_SENTFIN) == 0) &&
7709 		     (tp->snd_nxt == tp->snd_una))) {
7710 			pass = 11;
7711 			goto send;
7712 		}
7713 	}
7714 	/*
7715 	 * No reason to send a segment, just return.
7716 	 */
7717 just_return:
7718 	SOCKBUF_UNLOCK(sb);
7719 just_return_nolock:
7720 	if (tot_len_this_send == 0)
7721 		counter_u64_add(rack_out_size[TCP_MSS_ACCT_JUSTRET], 1);
7722 	rack_start_hpts_timer(rack, tp, cts, __LINE__, slot, tot_len_this_send, 1);
7723 	rack_log_type_just_return(rack, cts, tot_len_this_send, slot, hpts_calling);
7724 	tp->t_flags &= ~TF_FORCEDATA;
7725 	return (0);
7726 
7727 send:
7728 	if (doing_tlp == 0) {
7729 		/*
7730 		 * Data not a TLP, and its not the rxt firing. If it is the
7731 		 * rxt firing, we want to leave the tlp_in_progress flag on
7732 		 * so we don't send another TLP. It has to be a rack timer
7733 		 * or normal send (response to acked data) to clear the tlp
7734 		 * in progress flag.
7735 		 */
7736 		rack->rc_tlp_in_progress = 0;
7737 	}
7738 	SOCKBUF_LOCK_ASSERT(sb);
7739 	if (len > 0) {
7740 		if (len >= tp->t_maxseg)
7741 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
7742 		else
7743 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
7744 	}
7745 	/*
7746 	 * Before ESTABLISHED, force sending of initial options unless TCP
7747 	 * set not to do any options. NOTE: we assume that the IP/TCP header
7748 	 * plus TCP options always fit in a single mbuf, leaving room for a
7749 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
7750 	 * + optlen <= MCLBYTES
7751 	 */
7752 	optlen = 0;
7753 #ifdef INET6
7754 	if (isipv6)
7755 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
7756 	else
7757 #endif
7758 		hdrlen = sizeof(struct tcpiphdr);
7759 
7760 	/*
7761 	 * Compute options for segment. We only have to care about SYN and
7762 	 * established connection segments.  Options for SYN-ACK segments
7763 	 * are handled in TCP syncache.
7764 	 */
7765 	to.to_flags = 0;
7766 	if ((tp->t_flags & TF_NOOPT) == 0) {
7767 		/* Maximum segment size. */
7768 		if (flags & TH_SYN) {
7769 			tp->snd_nxt = tp->iss;
7770 			to.to_mss = tcp_mssopt(&inp->inp_inc);
7771 #ifdef NETFLIX_TCP_O_UDP
7772 			if (tp->t_port)
7773 				to.to_mss -= V_tcp_udp_tunneling_overhead;
7774 #endif
7775 			to.to_flags |= TOF_MSS;
7776 #ifdef TCP_RFC7413
7777 			/*
7778 			 * Only include the TFO option on the first
7779 			 * transmission of the SYN|ACK on a
7780 			 * passively-created TFO socket, as the presence of
7781 			 * the TFO option may have caused the original
7782 			 * SYN|ACK to have been dropped by a middlebox.
7783 			 */
7784 			if ((tp->t_flags & TF_FASTOPEN) &&
7785 			    (tp->t_state == TCPS_SYN_RECEIVED) &&
7786 			    (tp->t_rxtshift == 0)) {
7787 				to.to_tfo_len = TCP_FASTOPEN_MAX_COOKIE_LEN;
7788 				to.to_tfo_cookie = (u_char *)&tp->t_tfo_cookie;
7789 				to.to_flags |= TOF_FASTOPEN;
7790 			}
7791 #endif
7792 		}
7793 		/* Window scaling. */
7794 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
7795 			to.to_wscale = tp->request_r_scale;
7796 			to.to_flags |= TOF_SCALE;
7797 		}
7798 		/* Timestamps. */
7799 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
7800 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
7801 			to.to_tsval = cts + tp->ts_offset;
7802 			to.to_tsecr = tp->ts_recent;
7803 			to.to_flags |= TOF_TS;
7804 		}
7805 		/* Set receive buffer autosizing timestamp. */
7806 		if (tp->rfbuf_ts == 0 &&
7807 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
7808 			tp->rfbuf_ts = tcp_ts_getticks();
7809 		/* Selective ACK's. */
7810 		if (flags & TH_SYN)
7811 			to.to_flags |= TOF_SACKPERM;
7812 		else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
7813 		    tp->rcv_numsacks > 0) {
7814 			to.to_flags |= TOF_SACK;
7815 			to.to_nsacks = tp->rcv_numsacks;
7816 			to.to_sacks = (u_char *)tp->sackblks;
7817 		}
7818 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
7819 		/* TCP-MD5 (RFC2385). */
7820 		if (tp->t_flags & TF_SIGNATURE)
7821 			to.to_flags |= TOF_SIGNATURE;
7822 #endif				/* TCP_SIGNATURE */
7823 
7824 		/* Processing the options. */
7825 		hdrlen += optlen = tcp_addoptions(&to, opt);
7826 	}
7827 #ifdef NETFLIX_TCP_O_UDP
7828 	if (tp->t_port) {
7829 		if (V_tcp_udp_tunneling_port == 0) {
7830 			/* The port was removed?? */
7831 			SOCKBUF_UNLOCK(&so->so_snd);
7832 			return (EHOSTUNREACH);
7833 		}
7834 		hdrlen += sizeof(struct udphdr);
7835 	}
7836 #endif
7837 	ipoptlen = 0;
7838 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
7839 	ipoptlen += ipsec_optlen;
7840 #endif
7841 
7842 	/*
7843 	 * Adjust data length if insertion of options will bump the packet
7844 	 * length beyond the t_maxseg length. Clear the FIN bit because we
7845 	 * cut off the tail of the segment.
7846 	 */
7847 	if (len + optlen + ipoptlen > tp->t_maxseg) {
7848 		if (flags & TH_FIN) {
7849 			would_have_fin = 1;
7850 			flags &= ~TH_FIN;
7851 		}
7852 		if (tso) {
7853 			uint32_t if_hw_tsomax;
7854 			uint32_t moff;
7855 			int32_t max_len;
7856 
7857 			/* extract TSO information */
7858 			if_hw_tsomax = tp->t_tsomax;
7859 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
7860 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
7861 			KASSERT(ipoptlen == 0,
7862 			    ("%s: TSO can't do IP options", __func__));
7863 
7864 			/*
7865 			 * Check if we should limit by maximum payload
7866 			 * length:
7867 			 */
7868 			if (if_hw_tsomax != 0) {
7869 				/* compute maximum TSO length */
7870 				max_len = (if_hw_tsomax - hdrlen -
7871 				    max_linkhdr);
7872 				if (max_len <= 0) {
7873 					len = 0;
7874 				} else if (len > max_len) {
7875 					sendalot = 1;
7876 					len = max_len;
7877 				}
7878 			}
7879 			/*
7880 			 * Prevent the last segment from being fractional
7881 			 * unless the send sockbuf can be emptied:
7882 			 */
7883 			max_len = (tp->t_maxseg - optlen);
7884 			if ((sb_offset + len) < sbavail(sb)) {
7885 				moff = len % (u_int)max_len;
7886 				if (moff != 0) {
7887 					len -= moff;
7888 					sendalot = 1;
7889 				}
7890 			}
7891 			/*
7892 			 * In case there are too many small fragments don't
7893 			 * use TSO:
7894 			 */
7895 			if (len <= max_len) {
7896 				len = max_len;
7897 				sendalot = 1;
7898 				tso = 0;
7899 			}
7900 			/*
7901 			 * Send the FIN in a separate segment after the bulk
7902 			 * sending is done. We don't trust the TSO
7903 			 * implementations to clear the FIN flag on all but
7904 			 * the last segment.
7905 			 */
7906 			if (tp->t_flags & TF_NEEDFIN)
7907 				sendalot = 1;
7908 
7909 		} else {
7910 			len = tp->t_maxseg - optlen - ipoptlen;
7911 			sendalot = 1;
7912 		}
7913 	} else
7914 		tso = 0;
7915 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
7916 	    ("%s: len > IP_MAXPACKET", __func__));
7917 #ifdef DIAGNOSTIC
7918 #ifdef INET6
7919 	if (max_linkhdr + hdrlen > MCLBYTES)
7920 #else
7921 	if (max_linkhdr + hdrlen > MHLEN)
7922 #endif
7923 		panic("tcphdr too big");
7924 #endif
7925 
7926 	/*
7927 	 * This KASSERT is here to catch edge cases at a well defined place.
7928 	 * Before, those had triggered (random) panic conditions further
7929 	 * down.
7930 	 */
7931 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
7932 	if ((len == 0) &&
7933 	    (flags & TH_FIN) &&
7934 	    (sbused(sb))) {
7935 		/*
7936 		 * We have outstanding data, don't send a fin by itself!.
7937 		 */
7938 		goto just_return;
7939 	}
7940 	/*
7941 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
7942 	 * and initialize the header from the template for sends on this
7943 	 * connection.
7944 	 */
7945 	if (len) {
7946 		uint32_t max_val;
7947 		uint32_t moff;
7948 
7949 		if (rack->rc_pace_max_segs)
7950 			max_val = rack->rc_pace_max_segs * tp->t_maxseg;
7951 		else
7952 			max_val = len;
7953 		/*
7954 		 * We allow a limit on sending with hptsi.
7955 		 */
7956 		if (len > max_val) {
7957 			len = max_val;
7958 		}
7959 #ifdef INET6
7960 		if (MHLEN < hdrlen + max_linkhdr)
7961 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
7962 		else
7963 #endif
7964 			m = m_gethdr(M_NOWAIT, MT_DATA);
7965 
7966 		if (m == NULL) {
7967 			SOCKBUF_UNLOCK(sb);
7968 			error = ENOBUFS;
7969 			sack_rxmit = 0;
7970 			goto out;
7971 		}
7972 		m->m_data += max_linkhdr;
7973 		m->m_len = hdrlen;
7974 
7975 		/*
7976 		 * Start the m_copy functions from the closest mbuf to the
7977 		 * sb_offset in the socket buffer chain.
7978 		 */
7979 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
7980 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
7981 			m_copydata(mb, moff, (int)len,
7982 			    mtod(m, caddr_t)+hdrlen);
7983 			if (SEQ_LT(tp->snd_nxt, tp->snd_max))
7984 				sbsndptr_adv(sb, mb, len);
7985 			m->m_len += len;
7986 		} else {
7987 			struct sockbuf *msb;
7988 
7989 			if (SEQ_LT(tp->snd_nxt, tp->snd_max))
7990 				msb = NULL;
7991 			else
7992 				msb = sb;
7993 			m->m_next = tcp_m_copym(/*tp, */ mb, moff, &len,
7994 			    if_hw_tsomaxsegcount, if_hw_tsomaxsegsize, msb,
7995 			    hw_tls /*, NULL */);
7996 			if (len <= (tp->t_maxseg - optlen)) {
7997 				/*
7998 				 * Must have ran out of mbufs for the copy
7999 				 * shorten it to no longer need tso. Lets
8000 				 * not put on sendalot since we are low on
8001 				 * mbufs.
8002 				 */
8003 				tso = 0;
8004 			}
8005 			if (m->m_next == NULL) {
8006 				SOCKBUF_UNLOCK(sb);
8007 				(void)m_free(m);
8008 				error = ENOBUFS;
8009 				sack_rxmit = 0;
8010 				goto out;
8011 			}
8012 		}
8013 		if ((tp->t_flags & TF_FORCEDATA) && len == 1) {
8014 			TCPSTAT_INC(tcps_sndprobe);
8015 #ifdef NETFLIX_STATS
8016 			if (SEQ_LT(tp->snd_nxt, tp->snd_max))
8017 				stats_voi_update_abs_u32(tp->t_stats,
8018 				    VOI_TCP_RETXPB, len);
8019 			else
8020 				stats_voi_update_abs_u64(tp->t_stats,
8021 				    VOI_TCP_TXPB, len);
8022 #endif
8023 		} else if (SEQ_LT(tp->snd_nxt, tp->snd_max) || sack_rxmit) {
8024 			if (rsm && (rsm->r_flags & RACK_TLP)) {
8025 				/*
8026 				 * TLP should not count in retran count, but
8027 				 * in its own bin
8028 				 */
8029 /*				tp->t_sndtlppack++;*/
8030 /*				tp->t_sndtlpbyte += len;*/
8031 				counter_u64_add(rack_tlp_retran, 1);
8032 				counter_u64_add(rack_tlp_retran_bytes, len);
8033 			} else {
8034 				tp->t_sndrexmitpack++;
8035 				TCPSTAT_INC(tcps_sndrexmitpack);
8036 				TCPSTAT_ADD(tcps_sndrexmitbyte, len);
8037 			}
8038 #ifdef NETFLIX_STATS
8039 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
8040 			    len);
8041 #endif
8042 		} else {
8043 			TCPSTAT_INC(tcps_sndpack);
8044 			TCPSTAT_ADD(tcps_sndbyte, len);
8045 #ifdef NETFLIX_STATS
8046 			stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
8047 			    len);
8048 #endif
8049 		}
8050 		/*
8051 		 * If we're sending everything we've got, set PUSH. (This
8052 		 * will keep happy those implementations which only give
8053 		 * data to the user when a buffer fills or a PUSH comes in.)
8054 		 */
8055 		if (sb_offset + len == sbused(sb) &&
8056 		    sbused(sb) &&
8057 		    !(flags & TH_SYN))
8058 			flags |= TH_PUSH;
8059 
8060 		/*
8061 		 * Are we doing hptsi, if so we must calculate the slot. We
8062 		 * only do hptsi in ESTABLISHED and with no RESET being
8063 		 * sent where we have data to send.
8064 		 */
8065 		if (((tp->t_state == TCPS_ESTABLISHED) ||
8066 		    (tp->t_state == TCPS_CLOSE_WAIT) ||
8067 		    ((tp->t_state == TCPS_FIN_WAIT_1) &&
8068 		    ((tp->t_flags & TF_SENTFIN) == 0) &&
8069 		    ((flags & TH_FIN) == 0))) &&
8070 		    ((flags & TH_RST) == 0) &&
8071 		    (rack->rc_always_pace)) {
8072 			/*
8073 			 * We use the most optimistic possible cwnd/srtt for
8074 			 * sending calculations. This will make our
8075 			 * calculation anticipate getting more through
8076 			 * quicker then possible. But thats ok we don't want
8077 			 * the peer to have a gap in data sending.
8078 			 */
8079 			uint32_t srtt, cwnd, tr_perms = 0;
8080 
8081 			if (rack->r_ctl.rc_rack_min_rtt)
8082 				srtt = rack->r_ctl.rc_rack_min_rtt;
8083 			else
8084 				srtt = TICKS_2_MSEC((tp->t_srtt >> TCP_RTT_SHIFT));
8085 			if (rack->r_ctl.rc_rack_largest_cwnd)
8086 				cwnd = rack->r_ctl.rc_rack_largest_cwnd;
8087 			else
8088 				cwnd = tp->snd_cwnd;
8089 			tr_perms = cwnd / srtt;
8090 			if (tr_perms == 0) {
8091 				tr_perms = tp->t_maxseg;
8092 			}
8093 			tot_len_this_send += len;
8094 			/*
8095 			 * Calculate how long this will take to drain, if
8096 			 * the calculation comes out to zero, thats ok we
8097 			 * will use send_a_lot to possibly spin around for
8098 			 * more increasing tot_len_this_send to the point
8099 			 * that its going to require a pace, or we hit the
8100 			 * cwnd. Which in that case we are just waiting for
8101 			 * a ACK.
8102 			 */
8103 			slot = tot_len_this_send / tr_perms;
8104 			/* Now do we reduce the time so we don't run dry? */
8105 			if (slot && rack->rc_pace_reduce) {
8106 				int32_t reduce;
8107 
8108 				reduce = (slot / rack->rc_pace_reduce);
8109 				if (reduce < slot) {
8110 					slot -= reduce;
8111 				} else
8112 					slot = 0;
8113 			}
8114 			if (rack->r_enforce_min_pace &&
8115 			    (slot == 0) &&
8116 			    (tot_len_this_send >= (rack->r_min_pace_seg_thresh * tp->t_maxseg))) {
8117 				/* We are enforcing a minimum pace time of 1ms */
8118 				slot = rack->r_enforce_min_pace;
8119 			}
8120 		}
8121 		SOCKBUF_UNLOCK(sb);
8122 	} else {
8123 		SOCKBUF_UNLOCK(sb);
8124 		if (tp->t_flags & TF_ACKNOW)
8125 			TCPSTAT_INC(tcps_sndacks);
8126 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
8127 			TCPSTAT_INC(tcps_sndctrl);
8128 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
8129 			TCPSTAT_INC(tcps_sndurg);
8130 		else
8131 			TCPSTAT_INC(tcps_sndwinup);
8132 
8133 		m = m_gethdr(M_NOWAIT, MT_DATA);
8134 		if (m == NULL) {
8135 			error = ENOBUFS;
8136 			sack_rxmit = 0;
8137 			goto out;
8138 		}
8139 #ifdef INET6
8140 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
8141 		    MHLEN >= hdrlen) {
8142 			M_ALIGN(m, hdrlen);
8143 		} else
8144 #endif
8145 			m->m_data += max_linkhdr;
8146 		m->m_len = hdrlen;
8147 	}
8148 	SOCKBUF_UNLOCK_ASSERT(sb);
8149 	m->m_pkthdr.rcvif = (struct ifnet *)0;
8150 #ifdef MAC
8151 	mac_inpcb_create_mbuf(inp, m);
8152 #endif
8153 #ifdef INET6
8154 	if (isipv6) {
8155 		ip6 = mtod(m, struct ip6_hdr *);
8156 #ifdef NETFLIX_TCP_O_UDP
8157 		if (tp->t_port) {
8158 			udp = (struct udphdr *)((caddr_t)ip6 + ipoptlen + sizeof(struct ip6_hdr));
8159 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
8160 			udp->uh_dport = tp->t_port;
8161 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
8162 			udp->uh_ulen = htons(ulen);
8163 			th = (struct tcphdr *)(udp + 1);
8164 		} else
8165 #endif
8166 			th = (struct tcphdr *)(ip6 + 1);
8167 		tcpip_fillheaders(inp, /*tp->t_port, */ ip6, th);
8168 	} else
8169 #endif				/* INET6 */
8170 	{
8171 		ip = mtod(m, struct ip *);
8172 #ifdef TCPDEBUG
8173 		ipov = (struct ipovly *)ip;
8174 #endif
8175 #ifdef NETFLIX_TCP_O_UDP
8176 		if (tp->t_port) {
8177 			udp = (struct udphdr *)((caddr_t)ip + ipoptlen + sizeof(struct ip));
8178 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
8179 			udp->uh_dport = tp->t_port;
8180 			ulen = hdrlen + len - sizeof(struct ip);
8181 			udp->uh_ulen = htons(ulen);
8182 			th = (struct tcphdr *)(udp + 1);
8183 		} else
8184 #endif
8185 			th = (struct tcphdr *)(ip + 1);
8186 		tcpip_fillheaders(inp,/*tp->t_port, */ ip, th);
8187 	}
8188 	/*
8189 	 * Fill in fields, remembering maximum advertised window for use in
8190 	 * delaying messages about window sizes. If resending a FIN, be sure
8191 	 * not to use a new sequence number.
8192 	 */
8193 	if (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&
8194 	    tp->snd_nxt == tp->snd_max)
8195 		tp->snd_nxt--;
8196 	/*
8197 	 * If we are starting a connection, send ECN setup SYN packet. If we
8198 	 * are on a retransmit, we may resend those bits a number of times
8199 	 * as per RFC 3168.
8200 	 */
8201 	if (tp->t_state == TCPS_SYN_SENT && V_tcp_do_ecn == 1) {
8202 		if (tp->t_rxtshift >= 1) {
8203 			if (tp->t_rxtshift <= V_tcp_ecn_maxretries)
8204 				flags |= TH_ECE | TH_CWR;
8205 		} else
8206 			flags |= TH_ECE | TH_CWR;
8207 	}
8208 	if (tp->t_state == TCPS_ESTABLISHED &&
8209 	    (tp->t_flags & TF_ECN_PERMIT)) {
8210 		/*
8211 		 * If the peer has ECN, mark data packets with ECN capable
8212 		 * transmission (ECT). Ignore pure ack packets,
8213 		 * retransmissions and window probes.
8214 		 */
8215 		if (len > 0 && SEQ_GEQ(tp->snd_nxt, tp->snd_max) &&
8216 		    !((tp->t_flags & TF_FORCEDATA) && len == 1)) {
8217 #ifdef INET6
8218 			if (isipv6)
8219 				ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
8220 			else
8221 #endif
8222 				ip->ip_tos |= IPTOS_ECN_ECT0;
8223 			TCPSTAT_INC(tcps_ecn_ect0);
8224 		}
8225 		/*
8226 		 * Reply with proper ECN notifications.
8227 		 */
8228 		if (tp->t_flags & TF_ECN_SND_CWR) {
8229 			flags |= TH_CWR;
8230 			tp->t_flags &= ~TF_ECN_SND_CWR;
8231 		}
8232 		if (tp->t_flags & TF_ECN_SND_ECE)
8233 			flags |= TH_ECE;
8234 	}
8235 	/*
8236 	 * If we are doing retransmissions, then snd_nxt will not reflect
8237 	 * the first unsent octet.  For ACK only packets, we do not want the
8238 	 * sequence number of the retransmitted packet, we want the sequence
8239 	 * number of the next unsent octet.  So, if there is no data (and no
8240 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
8241 	 * ti_seq.  But if we are in persist state, snd_max might reflect
8242 	 * one byte beyond the right edge of the window, so use snd_nxt in
8243 	 * that case, since we know we aren't doing a retransmission.
8244 	 * (retransmit and persist are mutually exclusive...)
8245 	 */
8246 	if (sack_rxmit == 0) {
8247 		if (len || (flags & (TH_SYN | TH_FIN)) ||
8248 		    rack->rc_in_persist) {
8249 			th->th_seq = htonl(tp->snd_nxt);
8250 			rack_seq = tp->snd_nxt;
8251 		} else if (flags & TH_RST) {
8252 			/*
8253 			 * For a Reset send the last cum ack in sequence
8254 			 * (this like any other choice may still generate a
8255 			 * challenge ack, if a ack-update packet is in
8256 			 * flight).
8257 			 */
8258 			th->th_seq = htonl(tp->snd_una);
8259 			rack_seq = tp->snd_una;
8260 		} else {
8261 			th->th_seq = htonl(tp->snd_max);
8262 			rack_seq = tp->snd_max;
8263 		}
8264 	} else {
8265 		th->th_seq = htonl(rsm->r_start);
8266 		rack_seq = rsm->r_start;
8267 	}
8268 	th->th_ack = htonl(tp->rcv_nxt);
8269 	if (optlen) {
8270 		bcopy(opt, th + 1, optlen);
8271 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
8272 	}
8273 	th->th_flags = flags;
8274 	/*
8275 	 * Calculate receive window.  Don't shrink window, but avoid silly
8276 	 * window syndrome.
8277 	 */
8278 	if (recwin < (long)(so->so_rcv.sb_hiwat / 4) &&
8279 	    recwin < (long)tp->t_maxseg)
8280 		recwin = 0;
8281 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
8282 	    recwin < (long)(tp->rcv_adv - tp->rcv_nxt))
8283 		recwin = (long)(tp->rcv_adv - tp->rcv_nxt);
8284 	if (recwin > (long)TCP_MAXWIN << tp->rcv_scale)
8285 		recwin = (long)TCP_MAXWIN << tp->rcv_scale;
8286 
8287 	/*
8288 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
8289 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
8290 	 * handled in syncache.
8291 	 */
8292 	if (flags & TH_SYN)
8293 		th->th_win = htons((u_short)
8294 		    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
8295 	else
8296 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
8297 	/*
8298 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
8299 	 * window.  This may cause the remote transmitter to stall.  This
8300 	 * flag tells soreceive() to disable delayed acknowledgements when
8301 	 * draining the buffer.  This can occur if the receiver is
8302 	 * attempting to read more data than can be buffered prior to
8303 	 * transmitting on the connection.
8304 	 */
8305 	if (th->th_win == 0) {
8306 		tp->t_sndzerowin++;
8307 		tp->t_flags |= TF_RXWIN0SENT;
8308 	} else
8309 		tp->t_flags &= ~TF_RXWIN0SENT;
8310 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
8311 		th->th_urp = htons((u_short)(tp->snd_up - tp->snd_nxt));
8312 		th->th_flags |= TH_URG;
8313 	} else
8314 		/*
8315 		 * If no urgent pointer to send, then we pull the urgent
8316 		 * pointer to the left edge of the send window so that it
8317 		 * doesn't drift into the send window on sequence number
8318 		 * wraparound.
8319 		 */
8320 		tp->snd_up = tp->snd_una;	/* drag it along */
8321 
8322 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
8323 	if (to.to_flags & TOF_SIGNATURE) {
8324 		/*
8325 		 * Calculate MD5 signature and put it into the place
8326 		 * determined before.
8327 		 * NOTE: since TCP options buffer doesn't point into
8328 		 * mbuf's data, calculate offset and use it.
8329 		 */
8330 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
8331 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
8332 			/*
8333 			 * Do not send segment if the calculation of MD5
8334 			 * digest has failed.
8335 			 */
8336 			goto out;
8337 		}
8338 	}
8339 #endif
8340 
8341 	/*
8342 	 * Put TCP length in extended header, and then checksum extended
8343 	 * header and data.
8344 	 */
8345 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
8346 #ifdef INET6
8347 	if (isipv6) {
8348 		/*
8349 		 * ip6_plen is not need to be filled now, and will be filled
8350 		 * in ip6_output.
8351 		 */
8352 #ifdef NETFLIX_TCP_O_UDP
8353 		if (tp->t_port) {
8354 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
8355 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
8356 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
8357 			th->th_sum = htons(0);
8358 			UDPSTAT_INC(udps_opackets);
8359 		} else {
8360 #endif
8361 			m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
8362 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
8363 			th->th_sum = in6_cksum_pseudo(ip6,
8364 			    sizeof(struct tcphdr) + optlen + len, IPPROTO_TCP,
8365 			    0);
8366 #ifdef NETFLIX_TCP_O_UDP
8367 		}
8368 #endif
8369 	}
8370 #endif
8371 #if defined(INET6) && defined(INET)
8372 	else
8373 #endif
8374 #ifdef INET
8375 	{
8376 #ifdef NETFLIX_TCP_O_UDP
8377 		if (tp->t_port) {
8378 			m->m_pkthdr.csum_flags = CSUM_UDP;
8379 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
8380 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
8381 			   ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
8382 			th->th_sum = htons(0);
8383 			UDPSTAT_INC(udps_opackets);
8384 		} else {
8385 #endif
8386 			m->m_pkthdr.csum_flags = CSUM_TCP;
8387 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
8388 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
8389 			    ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
8390 			    IPPROTO_TCP + len + optlen));
8391 #ifdef NETFLIX_TCP_O_UDP
8392 		}
8393 #endif
8394 		/* IP version must be set here for ipv4/ipv6 checking later */
8395 		KASSERT(ip->ip_v == IPVERSION,
8396 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
8397 	}
8398 #endif
8399 
8400 	/*
8401 	 * Enable TSO and specify the size of the segments. The TCP pseudo
8402 	 * header checksum is always provided. XXX: Fixme: This is currently
8403 	 * not the case for IPv6.
8404 	 */
8405 	if (tso) {
8406 		KASSERT(len > tp->t_maxseg - optlen,
8407 		    ("%s: len <= tso_segsz", __func__));
8408 		m->m_pkthdr.csum_flags |= CSUM_TSO;
8409 		m->m_pkthdr.tso_segsz = tp->t_maxseg - optlen;
8410 	}
8411 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
8412 	KASSERT(len + hdrlen + ipoptlen - ipsec_optlen == m_length(m, NULL),
8413 	    ("%s: mbuf chain shorter than expected: %d + %u + %u - %u != %u",
8414 	    __func__, len, hdrlen, ipoptlen, ipsec_optlen, m_length(m, NULL)));
8415 #else
8416 	KASSERT(len + hdrlen + ipoptlen == m_length(m, NULL),
8417 	    ("%s: mbuf chain shorter than expected: %d + %u + %u != %u",
8418 	    __func__, len, hdrlen, ipoptlen, m_length(m, NULL)));
8419 #endif
8420 
8421 #ifdef TCP_HHOOK
8422 	/* Run HHOOK_TCP_ESTABLISHED_OUT helper hooks. */
8423 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
8424 #endif
8425 
8426 #ifdef TCPDEBUG
8427 	/*
8428 	 * Trace.
8429 	 */
8430 	if (so->so_options & SO_DEBUG) {
8431 		u_short save = 0;
8432 
8433 #ifdef INET6
8434 		if (!isipv6)
8435 #endif
8436 		{
8437 			save = ipov->ih_len;
8438 			ipov->ih_len = htons(m->m_pkthdr.len	/* - hdrlen +
8439 			      * (th->th_off << 2) */ );
8440 		}
8441 		tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
8442 #ifdef INET6
8443 		if (!isipv6)
8444 #endif
8445 			ipov->ih_len = save;
8446 	}
8447 #endif				/* TCPDEBUG */
8448 
8449 	/* We're getting ready to send; log now. */
8450 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
8451 		union tcp_log_stackspecific log;
8452 
8453 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
8454 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
8455 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
8456 		log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
8457 		if (rsm || sack_rxmit) {
8458 			log.u_bbr.flex8 = 1;
8459 		} else {
8460 			log.u_bbr.flex8 = 0;
8461 		}
8462 		lgb = tcp_log_event_(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
8463 		    len, &log, false, NULL, NULL, 0, NULL);
8464 	} else
8465 		lgb = NULL;
8466 
8467 	/*
8468 	 * Fill in IP length and desired time to live and send to IP level.
8469 	 * There should be a better way to handle ttl and tos; we could keep
8470 	 * them in the template, but need a way to checksum without them.
8471 	 */
8472 	/*
8473 	 * m->m_pkthdr.len should have been set before cksum calcuration,
8474 	 * because in6_cksum() need it.
8475 	 */
8476 #ifdef INET6
8477 	if (isipv6) {
8478 		/*
8479 		 * we separately set hoplimit for every segment, since the
8480 		 * user might want to change the value via setsockopt. Also,
8481 		 * desired default hop limit might be changed via Neighbor
8482 		 * Discovery.
8483 		 */
8484 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
8485 
8486 		/*
8487 		 * Set the packet size here for the benefit of DTrace
8488 		 * probes. ip6_output() will set it properly; it's supposed
8489 		 * to include the option header lengths as well.
8490 		 */
8491 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
8492 
8493 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss)
8494 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
8495 		else
8496 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
8497 
8498 		if (tp->t_state == TCPS_SYN_SENT)
8499 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
8500 
8501 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
8502 		/* TODO: IPv6 IP6TOS_ECT bit on */
8503 		error = ip6_output(m, tp->t_inpcb->in6p_outputopts,
8504 		    &inp->inp_route6,
8505 		    ((so->so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0),
8506 		    NULL, NULL, inp);
8507 
8508 		if (error == EMSGSIZE && inp->inp_route6.ro_rt != NULL)
8509 			mtu = inp->inp_route6.ro_rt->rt_mtu;
8510 	}
8511 #endif				/* INET6 */
8512 #if defined(INET) && defined(INET6)
8513 	else
8514 #endif
8515 #ifdef INET
8516 	{
8517 		ip->ip_len = htons(m->m_pkthdr.len);
8518 #ifdef INET6
8519 		if (inp->inp_vflag & INP_IPV6PROTO)
8520 			ip->ip_ttl = in6_selecthlim(inp, NULL);
8521 #endif				/* INET6 */
8522 		/*
8523 		 * If we do path MTU discovery, then we set DF on every
8524 		 * packet. This might not be the best thing to do according
8525 		 * to RFC3390 Section 2. However the tcp hostcache migitates
8526 		 * the problem so it affects only the first tcp connection
8527 		 * with a host.
8528 		 *
8529 		 * NB: Don't set DF on small MTU/MSS to have a safe
8530 		 * fallback.
8531 		 */
8532 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
8533 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
8534 			if (tp->t_port == 0 || len < V_tcp_minmss) {
8535 				ip->ip_off |= htons(IP_DF);
8536 			}
8537 		} else {
8538 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
8539 		}
8540 
8541 		if (tp->t_state == TCPS_SYN_SENT)
8542 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
8543 
8544 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
8545 
8546 		error = ip_output(m, tp->t_inpcb->inp_options, &inp->inp_route,
8547 		    ((so->so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0), 0,
8548 		    inp);
8549 		if (error == EMSGSIZE && inp->inp_route.ro_rt != NULL)
8550 			mtu = inp->inp_route.ro_rt->rt_mtu;
8551 	}
8552 #endif				/* INET */
8553 
8554 out:
8555 	if (lgb) {
8556 		lgb->tlb_errno = error;
8557 		lgb = NULL;
8558 	}
8559 	/*
8560 	 * In transmit state, time the transmission and arrange for the
8561 	 * retransmit.  In persist state, just set snd_max.
8562 	 */
8563 	if (error == 0) {
8564 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
8565 		    (tp->t_flags & TF_SACK_PERMIT) &&
8566 		    tp->rcv_numsacks > 0)
8567 		    tcp_clean_dsack_blocks(tp);
8568 		if (len == 0)
8569 			counter_u64_add(rack_out_size[TCP_MSS_ACCT_SNDACK], 1);
8570 		else if (len == 1) {
8571 			counter_u64_add(rack_out_size[TCP_MSS_ACCT_PERSIST], 1);
8572 		} else if (len > 1) {
8573 			int idx;
8574 
8575 			idx = (len / tp->t_maxseg) + 3;
8576 			if (idx >= TCP_MSS_ACCT_ATIMER)
8577 				counter_u64_add(rack_out_size[(TCP_MSS_ACCT_ATIMER-1)], 1);
8578 			else
8579 				counter_u64_add(rack_out_size[idx], 1);
8580 		}
8581 	}
8582 	if (sub_from_prr && (error == 0)) {
8583 		if (rack->r_ctl.rc_prr_sndcnt >= len)
8584 			rack->r_ctl.rc_prr_sndcnt -= len;
8585 		else
8586 			rack->r_ctl.rc_prr_sndcnt = 0;
8587 	}
8588 	sub_from_prr = 0;
8589 	rack_log_output(tp, &to, len, rack_seq, (uint8_t) flags, error, cts,
8590 	    pass, rsm);
8591 	if ((tp->t_flags & TF_FORCEDATA) == 0 ||
8592 	    (rack->rc_in_persist == 0)) {
8593 #ifdef NETFLIX_STATS
8594 		tcp_seq startseq = tp->snd_nxt;
8595 #endif
8596 		/*
8597 		 * Advance snd_nxt over sequence space of this segment.
8598 		 */
8599 		if (error)
8600 			/* We don't log or do anything with errors */
8601 			goto timer;
8602 
8603 		if (flags & (TH_SYN | TH_FIN)) {
8604 			if (flags & TH_SYN)
8605 				tp->snd_nxt++;
8606 			if (flags & TH_FIN) {
8607 				tp->snd_nxt++;
8608 				tp->t_flags |= TF_SENTFIN;
8609 			}
8610 		}
8611 		/* In the ENOBUFS case we do *not* update snd_max */
8612 		if (sack_rxmit)
8613 			goto timer;
8614 
8615 		tp->snd_nxt += len;
8616 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
8617 			if (tp->snd_una == tp->snd_max) {
8618 				/*
8619 				 * Update the time we just added data since
8620 				 * none was outstanding.
8621 				 */
8622 				rack_log_progress_event(rack, tp, ticks, PROGRESS_START, __LINE__);
8623 				tp->t_acktime = ticks;
8624 			}
8625 			tp->snd_max = tp->snd_nxt;
8626 #ifdef NETFLIX_STATS
8627 			if (!(tp->t_flags & TF_GPUTINPROG) && len) {
8628 				tp->t_flags |= TF_GPUTINPROG;
8629 				tp->gput_seq = startseq;
8630 				tp->gput_ack = startseq +
8631 				    ulmin(sbavail(sb) - sb_offset, sendwin);
8632 				tp->gput_ts = tcp_ts_getticks();
8633 			}
8634 #endif
8635 		}
8636 		/*
8637 		 * Set retransmit timer if not currently set, and not doing
8638 		 * a pure ack or a keep-alive probe. Initial value for
8639 		 * retransmit timer is smoothed round-trip time + 2 *
8640 		 * round-trip time variance. Initialize shift counter which
8641 		 * is used for backoff of retransmit time.
8642 		 */
8643 timer:
8644 		if ((tp->snd_wnd == 0) &&
8645 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
8646 			/*
8647 			 * If the persists timer was set above (right before
8648 			 * the goto send), and still needs to be on. Lets
8649 			 * make sure all is canceled. If the persist timer
8650 			 * is not running, we want to get it up.
8651 			 */
8652 			if (rack->rc_in_persist == 0) {
8653 				rack_enter_persist(tp, rack, cts);
8654 			}
8655 		}
8656 	} else {
8657 		/*
8658 		 * Persist case, update snd_max but since we are in persist
8659 		 * mode (no window) we do not update snd_nxt.
8660 		 */
8661 		int32_t xlen = len;
8662 
8663 		if (error)
8664 			goto nomore;
8665 
8666 		if (flags & TH_SYN)
8667 			++xlen;
8668 		if (flags & TH_FIN) {
8669 			++xlen;
8670 			tp->t_flags |= TF_SENTFIN;
8671 		}
8672 		/* In the ENOBUFS case we do *not* update snd_max */
8673 		if (SEQ_GT(tp->snd_nxt + xlen, tp->snd_max)) {
8674 			if (tp->snd_una == tp->snd_max) {
8675 				/*
8676 				 * Update the time we just added data since
8677 				 * none was outstanding.
8678 				 */
8679 				rack_log_progress_event(rack, tp, ticks, PROGRESS_START, __LINE__);
8680 				tp->t_acktime = ticks;
8681 			}
8682 			tp->snd_max = tp->snd_nxt + len;
8683 		}
8684 	}
8685 nomore:
8686 	if (error) {
8687 		SOCKBUF_UNLOCK_ASSERT(sb);	/* Check gotos. */
8688 		/*
8689 		 * Failures do not advance the seq counter above. For the
8690 		 * case of ENOBUFS we will fall out and retry in 1ms with
8691 		 * the hpts. Everything else will just have to retransmit
8692 		 * with the timer.
8693 		 *
8694 		 * In any case, we do not want to loop around for another
8695 		 * send without a good reason.
8696 		 */
8697 		sendalot = 0;
8698 		switch (error) {
8699 		case EPERM:
8700 			tp->t_flags &= ~TF_FORCEDATA;
8701 			tp->t_softerror = error;
8702 			return (error);
8703 		case ENOBUFS:
8704 			if (slot == 0) {
8705 				/*
8706 				 * Pace us right away to retry in a some
8707 				 * time
8708 				 */
8709 				slot = 1 + rack->rc_enobuf;
8710 				if (rack->rc_enobuf < 255)
8711 					rack->rc_enobuf++;
8712 				if (slot > (rack->rc_rack_rtt / 2)) {
8713 					slot = rack->rc_rack_rtt / 2;
8714 				}
8715 				if (slot < 10)
8716 					slot = 10;
8717 			}
8718 			counter_u64_add(rack_saw_enobuf, 1);
8719 			error = 0;
8720 			goto enobufs;
8721 		case EMSGSIZE:
8722 			/*
8723 			 * For some reason the interface we used initially
8724 			 * to send segments changed to another or lowered
8725 			 * its MTU. If TSO was active we either got an
8726 			 * interface without TSO capabilits or TSO was
8727 			 * turned off. If we obtained mtu from ip_output()
8728 			 * then update it and try again.
8729 			 */
8730 			if (tso)
8731 				tp->t_flags &= ~TF_TSO;
8732 			if (mtu != 0) {
8733 				tcp_mss_update(tp, -1, mtu, NULL, NULL);
8734 				goto again;
8735 			}
8736 			slot = 10;
8737 			rack_start_hpts_timer(rack, tp, cts, __LINE__, slot, 0, 1);
8738 			tp->t_flags &= ~TF_FORCEDATA;
8739 			return (error);
8740 		case ENETUNREACH:
8741 			counter_u64_add(rack_saw_enetunreach, 1);
8742 		case EHOSTDOWN:
8743 		case EHOSTUNREACH:
8744 		case ENETDOWN:
8745 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
8746 				tp->t_softerror = error;
8747 			}
8748 			/* FALLTHROUGH */
8749 		default:
8750 			slot = 10;
8751 			rack_start_hpts_timer(rack, tp, cts, __LINE__, slot, 0, 1);
8752 			tp->t_flags &= ~TF_FORCEDATA;
8753 			return (error);
8754 		}
8755 	} else {
8756 		rack->rc_enobuf = 0;
8757 	}
8758 	TCPSTAT_INC(tcps_sndtotal);
8759 
8760 	/*
8761 	 * Data sent (as far as we can tell). If this advertises a larger
8762 	 * window than any other segment, then remember the size of the
8763 	 * advertised window. Any pending ACK has now been sent.
8764 	 */
8765 	if (recwin > 0 && SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
8766 		tp->rcv_adv = tp->rcv_nxt + recwin;
8767 	tp->last_ack_sent = tp->rcv_nxt;
8768 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
8769 enobufs:
8770 	rack->r_tlp_running = 0;
8771 	if ((flags & TH_RST) || (would_have_fin == 1)) {
8772 		/*
8773 		 * We don't send again after a RST. We also do *not* send
8774 		 * again if we would have had a find, but now have
8775 		 * outstanding data.
8776 		 */
8777 		slot = 0;
8778 		sendalot = 0;
8779 	}
8780 	if (slot) {
8781 		/* set the rack tcb into the slot N */
8782 		counter_u64_add(rack_paced_segments, 1);
8783 	} else if (sendalot) {
8784 		if (len)
8785 			counter_u64_add(rack_unpaced_segments, 1);
8786 		sack_rxmit = 0;
8787 		tp->t_flags &= ~TF_FORCEDATA;
8788 		goto again;
8789 	} else if (len) {
8790 		counter_u64_add(rack_unpaced_segments, 1);
8791 	}
8792 	tp->t_flags &= ~TF_FORCEDATA;
8793 	rack_start_hpts_timer(rack, tp, cts, __LINE__, slot, tot_len_this_send, 1);
8794 	return (error);
8795 }
8796 
8797 /*
8798  * rack_ctloutput() must drop the inpcb lock before performing copyin on
8799  * socket option arguments.  When it re-acquires the lock after the copy, it
8800  * has to revalidate that the connection is still valid for the socket
8801  * option.
8802  */
8803 static int
8804 rack_set_sockopt(struct socket *so, struct sockopt *sopt,
8805     struct inpcb *inp, struct tcpcb *tp, struct tcp_rack *rack)
8806 {
8807 	int32_t error = 0, optval;
8808 
8809 	switch (sopt->sopt_name) {
8810 	case TCP_RACK_PROP_RATE:
8811 	case TCP_RACK_PROP:
8812 	case TCP_RACK_TLP_REDUCE:
8813 	case TCP_RACK_EARLY_RECOV:
8814 	case TCP_RACK_PACE_ALWAYS:
8815 	case TCP_DELACK:
8816 	case TCP_RACK_PACE_REDUCE:
8817 	case TCP_RACK_PACE_MAX_SEG:
8818 	case TCP_RACK_PRR_SENDALOT:
8819 	case TCP_RACK_MIN_TO:
8820 	case TCP_RACK_EARLY_SEG:
8821 	case TCP_RACK_REORD_THRESH:
8822 	case TCP_RACK_REORD_FADE:
8823 	case TCP_RACK_TLP_THRESH:
8824 	case TCP_RACK_PKT_DELAY:
8825 	case TCP_RACK_TLP_USE:
8826 	case TCP_RACK_TLP_INC_VAR:
8827 	case TCP_RACK_IDLE_REDUCE_HIGH:
8828 	case TCP_RACK_MIN_PACE:
8829 	case TCP_RACK_MIN_PACE_SEG:
8830 	case TCP_BBR_RACK_RTT_USE:
8831 	case TCP_DATA_AFTER_CLOSE:
8832 		break;
8833 	default:
8834 		return (tcp_default_ctloutput(so, sopt, inp, tp));
8835 		break;
8836 	}
8837 	INP_WUNLOCK(inp);
8838 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
8839 	if (error)
8840 		return (error);
8841 	INP_WLOCK(inp);
8842 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
8843 		INP_WUNLOCK(inp);
8844 		return (ECONNRESET);
8845 	}
8846 	tp = intotcpcb(inp);
8847 	rack = (struct tcp_rack *)tp->t_fb_ptr;
8848 	switch (sopt->sopt_name) {
8849 	case TCP_RACK_PROP_RATE:
8850 		if ((optval <= 0) || (optval >= 100)) {
8851 			error = EINVAL;
8852 			break;
8853 		}
8854 		RACK_OPTS_INC(tcp_rack_prop_rate);
8855 		rack->r_ctl.rc_prop_rate = optval;
8856 		break;
8857 	case TCP_RACK_TLP_USE:
8858 		if ((optval < TLP_USE_ID) || (optval > TLP_USE_TWO_TWO)) {
8859 			error = EINVAL;
8860 			break;
8861 		}
8862 		RACK_OPTS_INC(tcp_tlp_use);
8863 		rack->rack_tlp_threshold_use = optval;
8864 		break;
8865 	case TCP_RACK_PROP:
8866 		/* RACK proportional rate reduction (bool) */
8867 		RACK_OPTS_INC(tcp_rack_prop);
8868 		rack->r_ctl.rc_prop_reduce = optval;
8869 		break;
8870 	case TCP_RACK_TLP_REDUCE:
8871 		/* RACK TLP cwnd reduction (bool) */
8872 		RACK_OPTS_INC(tcp_rack_tlp_reduce);
8873 		rack->r_ctl.rc_tlp_cwnd_reduce = optval;
8874 		break;
8875 	case TCP_RACK_EARLY_RECOV:
8876 		/* Should recovery happen early (bool) */
8877 		RACK_OPTS_INC(tcp_rack_early_recov);
8878 		rack->r_ctl.rc_early_recovery = optval;
8879 		break;
8880 	case TCP_RACK_PACE_ALWAYS:
8881 		/* Use the always pace method (bool)  */
8882 		RACK_OPTS_INC(tcp_rack_pace_always);
8883 		if (optval > 0)
8884 			rack->rc_always_pace = 1;
8885 		else
8886 			rack->rc_always_pace = 0;
8887 		break;
8888 	case TCP_RACK_PACE_REDUCE:
8889 		/* RACK Hptsi reduction factor (divisor) */
8890 		RACK_OPTS_INC(tcp_rack_pace_reduce);
8891 		if (optval)
8892 			/* Must be non-zero */
8893 			rack->rc_pace_reduce = optval;
8894 		else
8895 			error = EINVAL;
8896 		break;
8897 	case TCP_RACK_PACE_MAX_SEG:
8898 		/* Max segments in a pace */
8899 		RACK_OPTS_INC(tcp_rack_max_seg);
8900 		rack->rc_pace_max_segs = optval;
8901 		break;
8902 	case TCP_RACK_PRR_SENDALOT:
8903 		/* Allow PRR to send more than one seg */
8904 		RACK_OPTS_INC(tcp_rack_prr_sendalot);
8905 		rack->r_ctl.rc_prr_sendalot = optval;
8906 		break;
8907 	case TCP_RACK_MIN_TO:
8908 		/* Minimum time between rack t-o's in ms */
8909 		RACK_OPTS_INC(tcp_rack_min_to);
8910 		rack->r_ctl.rc_min_to = optval;
8911 		break;
8912 	case TCP_RACK_EARLY_SEG:
8913 		/* If early recovery max segments */
8914 		RACK_OPTS_INC(tcp_rack_early_seg);
8915 		rack->r_ctl.rc_early_recovery_segs = optval;
8916 		break;
8917 	case TCP_RACK_REORD_THRESH:
8918 		/* RACK reorder threshold (shift amount) */
8919 		RACK_OPTS_INC(tcp_rack_reord_thresh);
8920 		if ((optval > 0) && (optval < 31))
8921 			rack->r_ctl.rc_reorder_shift = optval;
8922 		else
8923 			error = EINVAL;
8924 		break;
8925 	case TCP_RACK_REORD_FADE:
8926 		/* Does reordering fade after ms time */
8927 		RACK_OPTS_INC(tcp_rack_reord_fade);
8928 		rack->r_ctl.rc_reorder_fade = optval;
8929 		break;
8930 	case TCP_RACK_TLP_THRESH:
8931 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
8932 		RACK_OPTS_INC(tcp_rack_tlp_thresh);
8933 		if (optval)
8934 			rack->r_ctl.rc_tlp_threshold = optval;
8935 		else
8936 			error = EINVAL;
8937 		break;
8938 	case TCP_RACK_PKT_DELAY:
8939 		/* RACK added ms i.e. rack-rtt + reord + N */
8940 		RACK_OPTS_INC(tcp_rack_pkt_delay);
8941 		rack->r_ctl.rc_pkt_delay = optval;
8942 		break;
8943 	case TCP_RACK_TLP_INC_VAR:
8944 		/* Does TLP include rtt variance in t-o */
8945 		RACK_OPTS_INC(tcp_rack_tlp_inc_var);
8946 		rack->r_ctl.rc_prr_inc_var = optval;
8947 		break;
8948 	case TCP_RACK_IDLE_REDUCE_HIGH:
8949 		RACK_OPTS_INC(tcp_rack_idle_reduce_high);
8950 		if (optval)
8951 			rack->r_idle_reduce_largest = 1;
8952 		else
8953 			rack->r_idle_reduce_largest = 0;
8954 		break;
8955 	case TCP_DELACK:
8956 		if (optval == 0)
8957 			tp->t_delayed_ack = 0;
8958 		else
8959 			tp->t_delayed_ack = 1;
8960 		if (tp->t_flags & TF_DELACK) {
8961 			tp->t_flags &= ~TF_DELACK;
8962 			tp->t_flags |= TF_ACKNOW;
8963 			rack_output(tp);
8964 		}
8965 		break;
8966 	case TCP_RACK_MIN_PACE:
8967 		RACK_OPTS_INC(tcp_rack_min_pace);
8968 		if (optval > 3)
8969 			rack->r_enforce_min_pace = 3;
8970 		else
8971 			rack->r_enforce_min_pace = optval;
8972 		break;
8973 	case TCP_RACK_MIN_PACE_SEG:
8974 		RACK_OPTS_INC(tcp_rack_min_pace_seg);
8975 		if (optval >= 16)
8976 			rack->r_min_pace_seg_thresh = 15;
8977 		else
8978 			rack->r_min_pace_seg_thresh = optval;
8979 		break;
8980 	case TCP_BBR_RACK_RTT_USE:
8981 		if ((optval != USE_RTT_HIGH) &&
8982 		    (optval != USE_RTT_LOW) &&
8983 		    (optval != USE_RTT_AVG))
8984 			error = EINVAL;
8985 		else
8986 			rack->r_ctl.rc_rate_sample_method = optval;
8987 		break;
8988 	case TCP_DATA_AFTER_CLOSE:
8989 		if (optval)
8990 			rack->rc_allow_data_af_clo = 1;
8991 		else
8992 			rack->rc_allow_data_af_clo = 0;
8993 		break;
8994 	default:
8995 		return (tcp_default_ctloutput(so, sopt, inp, tp));
8996 		break;
8997 	}
8998 /*	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);*/
8999 	INP_WUNLOCK(inp);
9000 	return (error);
9001 }
9002 
9003 static int
9004 rack_get_sockopt(struct socket *so, struct sockopt *sopt,
9005     struct inpcb *inp, struct tcpcb *tp, struct tcp_rack *rack)
9006 {
9007 	int32_t error, optval;
9008 
9009 	/*
9010 	 * Because all our options are either boolean or an int, we can just
9011 	 * pull everything into optval and then unlock and copy. If we ever
9012 	 * add a option that is not a int, then this will have quite an
9013 	 * impact to this routine.
9014 	 */
9015 	switch (sopt->sopt_name) {
9016 	case TCP_RACK_PROP_RATE:
9017 		optval = rack->r_ctl.rc_prop_rate;
9018 		break;
9019 	case TCP_RACK_PROP:
9020 		/* RACK proportional rate reduction (bool) */
9021 		optval = rack->r_ctl.rc_prop_reduce;
9022 		break;
9023 	case TCP_RACK_TLP_REDUCE:
9024 		/* RACK TLP cwnd reduction (bool) */
9025 		optval = rack->r_ctl.rc_tlp_cwnd_reduce;
9026 		break;
9027 	case TCP_RACK_EARLY_RECOV:
9028 		/* Should recovery happen early (bool) */
9029 		optval = rack->r_ctl.rc_early_recovery;
9030 		break;
9031 	case TCP_RACK_PACE_REDUCE:
9032 		/* RACK Hptsi reduction factor (divisor) */
9033 		optval = rack->rc_pace_reduce;
9034 		break;
9035 	case TCP_RACK_PACE_MAX_SEG:
9036 		/* Max segments in a pace */
9037 		optval = rack->rc_pace_max_segs;
9038 		break;
9039 	case TCP_RACK_PACE_ALWAYS:
9040 		/* Use the always pace method */
9041 		optval = rack->rc_always_pace;
9042 		break;
9043 	case TCP_RACK_PRR_SENDALOT:
9044 		/* Allow PRR to send more than one seg */
9045 		optval = rack->r_ctl.rc_prr_sendalot;
9046 		break;
9047 	case TCP_RACK_MIN_TO:
9048 		/* Minimum time between rack t-o's in ms */
9049 		optval = rack->r_ctl.rc_min_to;
9050 		break;
9051 	case TCP_RACK_EARLY_SEG:
9052 		/* If early recovery max segments */
9053 		optval = rack->r_ctl.rc_early_recovery_segs;
9054 		break;
9055 	case TCP_RACK_REORD_THRESH:
9056 		/* RACK reorder threshold (shift amount) */
9057 		optval = rack->r_ctl.rc_reorder_shift;
9058 		break;
9059 	case TCP_RACK_REORD_FADE:
9060 		/* Does reordering fade after ms time */
9061 		optval = rack->r_ctl.rc_reorder_fade;
9062 		break;
9063 	case TCP_RACK_TLP_THRESH:
9064 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
9065 		optval = rack->r_ctl.rc_tlp_threshold;
9066 		break;
9067 	case TCP_RACK_PKT_DELAY:
9068 		/* RACK added ms i.e. rack-rtt + reord + N */
9069 		optval = rack->r_ctl.rc_pkt_delay;
9070 		break;
9071 	case TCP_RACK_TLP_USE:
9072 		optval = rack->rack_tlp_threshold_use;
9073 		break;
9074 	case TCP_RACK_TLP_INC_VAR:
9075 		/* Does TLP include rtt variance in t-o */
9076 		optval = rack->r_ctl.rc_prr_inc_var;
9077 		break;
9078 	case TCP_RACK_IDLE_REDUCE_HIGH:
9079 		optval = rack->r_idle_reduce_largest;
9080 		break;
9081 	case TCP_RACK_MIN_PACE:
9082 		optval = rack->r_enforce_min_pace;
9083 		break;
9084 	case TCP_RACK_MIN_PACE_SEG:
9085 		optval = rack->r_min_pace_seg_thresh;
9086 		break;
9087 	case TCP_BBR_RACK_RTT_USE:
9088 		optval = rack->r_ctl.rc_rate_sample_method;
9089 		break;
9090 	case TCP_DELACK:
9091 		optval = tp->t_delayed_ack;
9092 		break;
9093 	case TCP_DATA_AFTER_CLOSE:
9094 		optval = rack->rc_allow_data_af_clo;
9095 		break;
9096 	default:
9097 		return (tcp_default_ctloutput(so, sopt, inp, tp));
9098 		break;
9099 	}
9100 	INP_WUNLOCK(inp);
9101 	error = sooptcopyout(sopt, &optval, sizeof optval);
9102 	return (error);
9103 }
9104 
9105 static int
9106 rack_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp, struct tcpcb *tp)
9107 {
9108 	int32_t error = EINVAL;
9109 	struct tcp_rack *rack;
9110 
9111 	rack = (struct tcp_rack *)tp->t_fb_ptr;
9112 	if (rack == NULL) {
9113 		/* Huh? */
9114 		goto out;
9115 	}
9116 	if (sopt->sopt_dir == SOPT_SET) {
9117 		return (rack_set_sockopt(so, sopt, inp, tp, rack));
9118 	} else if (sopt->sopt_dir == SOPT_GET) {
9119 		return (rack_get_sockopt(so, sopt, inp, tp, rack));
9120 	}
9121 out:
9122 	INP_WUNLOCK(inp);
9123 	return (error);
9124 }
9125 
9126 
9127 struct tcp_function_block __tcp_rack = {
9128 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
9129 	.tfb_tcp_output = rack_output,
9130 	.tfb_tcp_do_segment = rack_do_segment,
9131 	.tfb_tcp_ctloutput = rack_ctloutput,
9132 	.tfb_tcp_fb_init = rack_init,
9133 	.tfb_tcp_fb_fini = rack_fini,
9134 	.tfb_tcp_timer_stop_all = rack_stopall,
9135 	.tfb_tcp_timer_activate = rack_timer_activate,
9136 	.tfb_tcp_timer_active = rack_timer_active,
9137 	.tfb_tcp_timer_stop = rack_timer_stop,
9138 	.tfb_tcp_rexmit_tmr = rack_remxt_tmr,
9139 	.tfb_tcp_handoff_ok = rack_handoff_ok
9140 };
9141 
9142 static const char *rack_stack_names[] = {
9143 	__XSTRING(STACKNAME),
9144 #ifdef STACKALIAS
9145 	__XSTRING(STACKALIAS),
9146 #endif
9147 };
9148 
9149 static int
9150 rack_ctor(void *mem, int32_t size, void *arg, int32_t how)
9151 {
9152 	memset(mem, 0, size);
9153 	return (0);
9154 }
9155 
9156 static void
9157 rack_dtor(void *mem, int32_t size, void *arg)
9158 {
9159 
9160 }
9161 
9162 static bool rack_mod_inited = false;
9163 
9164 static int
9165 tcp_addrack(module_t mod, int32_t type, void *data)
9166 {
9167 	int32_t err = 0;
9168 	int num_stacks;
9169 
9170 	switch (type) {
9171 	case MOD_LOAD:
9172 		rack_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
9173 		    sizeof(struct rack_sendmap),
9174 		    rack_ctor, rack_dtor, NULL, NULL, UMA_ALIGN_PTR, 0);
9175 
9176 		rack_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
9177 		    sizeof(struct tcp_rack),
9178 		    rack_ctor, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
9179 
9180 		sysctl_ctx_init(&rack_sysctl_ctx);
9181 		rack_sysctl_root = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
9182 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
9183 		    OID_AUTO,
9184 		    __XSTRING(STACKNAME),
9185 		    CTLFLAG_RW, 0,
9186 		    "");
9187 		if (rack_sysctl_root == NULL) {
9188 			printf("Failed to add sysctl node\n");
9189 			err = EFAULT;
9190 			goto free_uma;
9191 		}
9192 		rack_init_sysctls();
9193 		num_stacks = nitems(rack_stack_names);
9194 		err = register_tcp_functions_as_names(&__tcp_rack, M_WAITOK,
9195 		    rack_stack_names, &num_stacks);
9196 		if (err) {
9197 			printf("Failed to register %s stack name for "
9198 			    "%s module\n", rack_stack_names[num_stacks],
9199 			    __XSTRING(MODNAME));
9200 			sysctl_ctx_free(&rack_sysctl_ctx);
9201 free_uma:
9202 			uma_zdestroy(rack_zone);
9203 			uma_zdestroy(rack_pcb_zone);
9204 			rack_counter_destroy();
9205 			printf("Failed to register rack module -- err:%d\n", err);
9206 			return (err);
9207 		}
9208 		rack_mod_inited = true;
9209 		break;
9210 	case MOD_QUIESCE:
9211 		err = deregister_tcp_functions(&__tcp_rack, true, false);
9212 		break;
9213 	case MOD_UNLOAD:
9214 		err = deregister_tcp_functions(&__tcp_rack, false, true);
9215 		if (err == EBUSY)
9216 			break;
9217 		if (rack_mod_inited) {
9218 			uma_zdestroy(rack_zone);
9219 			uma_zdestroy(rack_pcb_zone);
9220 			sysctl_ctx_free(&rack_sysctl_ctx);
9221 			rack_counter_destroy();
9222 			rack_mod_inited = false;
9223 		}
9224 		err = 0;
9225 		break;
9226 	default:
9227 		return (EOPNOTSUPP);
9228 	}
9229 	return (err);
9230 }
9231 
9232 static moduledata_t tcp_rack = {
9233 	.name = __XSTRING(MODNAME),
9234 	.evhand = tcp_addrack,
9235 	.priv = 0
9236 };
9237 
9238 MODULE_VERSION(MODNAME, 1);
9239 DECLARE_MODULE(MODNAME, tcp_rack, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
9240 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
9241