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