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