xref: /freebsd/sys/netinet/tcp_var.h (revision a2b560cc69eb254c92caf2027a69cadf9865d273)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1993, 1994, 1995
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)tcp_var.h	8.4 (Berkeley) 5/24/95
32  */
33 
34 #ifndef _NETINET_TCP_VAR_H_
35 #define _NETINET_TCP_VAR_H_
36 
37 #include <netinet/tcp.h>
38 #include <netinet/tcp_fsm.h>
39 
40 #ifdef _KERNEL
41 #include "opt_kern_tls.h"
42 #include <net/vnet.h>
43 #include <sys/mbuf.h>
44 #include <sys/ktls.h>
45 #endif
46 
47 #define TCP_END_BYTE_INFO 8	/* Bytes that makeup the "end information array" */
48 /* Types of ending byte info */
49 #define TCP_EI_EMPTY_SLOT	0
50 #define TCP_EI_STATUS_CLIENT_FIN	0x1
51 #define TCP_EI_STATUS_CLIENT_RST	0x2
52 #define TCP_EI_STATUS_SERVER_FIN	0x3
53 #define TCP_EI_STATUS_SERVER_RST	0x4
54 #define TCP_EI_STATUS_RETRAN		0x5
55 #define TCP_EI_STATUS_PROGRESS		0x6
56 #define TCP_EI_STATUS_PERSIST_MAX	0x7
57 #define TCP_EI_STATUS_KEEP_MAX		0x8
58 #define TCP_EI_STATUS_DATA_A_CLOSE	0x9
59 #define TCP_EI_STATUS_RST_IN_FRONT	0xa
60 #define TCP_EI_STATUS_2MSL		0xb
61 #define TCP_EI_STATUS_MAX_VALUE		0xb
62 
63 #define TCP_TRK_REQ_LOG_NEW		0x01
64 #define TCP_TRK_REQ_LOG_COMPLETE	0x02
65 #define TCP_TRK_REQ_LOG_FREED		0x03
66 #define TCP_TRK_REQ_LOG_ALLOCFAIL	0x04
67 #define TCP_TRK_REQ_LOG_MOREYET	0x05
68 #define TCP_TRK_REQ_LOG_FORCEFREE	0x06
69 #define TCP_TRK_REQ_LOG_STALE		0x07
70 #define TCP_TRK_REQ_LOG_SEARCH		0x08
71 
72 /************************************************/
73 /* Status bits we track to assure no duplicates,
74  * the bits here are not used by the code but
75  * for human representation. To check a bit we
76  * take and shift over by 1 minus the value (1-8).
77  */
78 /************************************************/
79 #define TCP_EI_BITS_CLIENT_FIN	0x001
80 #define TCP_EI_BITS_CLIENT_RST	0x002
81 #define TCP_EI_BITS_SERVER_FIN	0x004
82 #define TCP_EI_BITS_SERVER_RST	0x008
83 #define TCP_EI_BITS_RETRAN	0x010
84 #define TCP_EI_BITS_PROGRESS	0x020
85 #define TCP_EI_BITS_PRESIST_MAX	0x040
86 #define TCP_EI_BITS_KEEP_MAX	0x080
87 #define TCP_EI_BITS_DATA_A_CLO  0x100
88 #define TCP_EI_BITS_RST_IN_FR	0x200	/* a front state reset */
89 #define TCP_EI_BITS_2MS_TIMER	0x400	/* 2 MSL timer expired */
90 
91 #if defined(_KERNEL) || defined(_WANT_TCPCB)
92 #include <netinet/cc/cc.h>
93 
94 /* TCP segment queue entry */
95 struct tseg_qent {
96 	TAILQ_ENTRY(tseg_qent) tqe_q;
97 	struct	mbuf   *tqe_m;		/* mbuf contains packet */
98 	struct  mbuf   *tqe_last;	/* last mbuf in chain */
99 	tcp_seq tqe_start;		/* TCP Sequence number start */
100 	int	tqe_len;		/* TCP segment data length */
101 	uint32_t tqe_flags;		/* The flags from tcp_get_flags() */
102 	uint32_t tqe_mbuf_cnt;		/* Count of mbuf overhead */
103 };
104 TAILQ_HEAD(tsegqe_head, tseg_qent);
105 
106 struct sackblk {
107 	tcp_seq start;		/* start seq no. of sack block */
108 	tcp_seq end;		/* end seq no. */
109 };
110 
111 struct sackhole {
112 	tcp_seq start;		/* start seq no. of hole */
113 	tcp_seq end;		/* end seq no. */
114 	tcp_seq rxmit;		/* next seq. no in hole to be retransmitted */
115 	TAILQ_ENTRY(sackhole) scblink;	/* scoreboard linkage */
116 };
117 
118 struct sackhint {
119 	struct sackhole	*nexthole;
120 	int32_t		sack_bytes_rexmit;
121 	tcp_seq		last_sack_ack;	/* Most recent/largest sacked ack */
122 
123 	int32_t		delivered_data; /* Newly acked data from last SACK */
124 
125 	int32_t		sacked_bytes;	/* Total sacked bytes reported by the
126 					 * receiver via sack option
127 					 */
128 	uint32_t	recover_fs;	/* Flight Size at the start of Loss recovery */
129 	uint32_t	prr_delivered;	/* Total bytes delivered using PRR */
130 	uint32_t	prr_out;	/* Bytes sent during IN_RECOVERY */
131 	int32_t		hole_bytes;	/* current number of bytes in scoreboard holes */
132 	int32_t		lost_bytes;	/* number of rfc6675 IsLost() bytes */
133 };
134 
135 #define SEGQ_EMPTY(tp) TAILQ_EMPTY(&(tp)->t_segq)
136 
137 STAILQ_HEAD(tcp_log_stailq, tcp_log_mem);
138 
139 #define TCP_TRK_TRACK_FLG_EMPTY 0x00	/* Available */
140 #define TCP_TRK_TRACK_FLG_USED  0x01	/* In use */
141 #define TCP_TRK_TRACK_FLG_OPEN  0x02	/* End is not valid (open range request) */
142 #define TCP_TRK_TRACK_FLG_SEQV  0x04	/* We had a sendfile that touched it  */
143 #define TCP_TRK_TRACK_FLG_COMP  0x08	/* Sendfile as placed the last bits (range req only) */
144 #define TCP_TRK_TRACK_FLG_FSND	 0x10	/* First send has been done into the seq space */
145 #define MAX_TCP_TRK_REQ 5		/* Max we will have at once */
146 
147 struct tcp_sendfile_track {
148 	uint64_t timestamp;	/* User sent timestamp */
149 	uint64_t start;		/* Start of sendfile offset */
150 	uint64_t end;		/* End if not open-range req */
151 	uint64_t localtime;	/* Time we actually got the req */
152 	uint64_t deadline;	/* If in CU mode, deadline to delivery */
153 	uint64_t first_send;	/* Time of first send in the range */
154 	uint64_t cspr;		/* Client suggested pace rate */
155 	uint64_t sent_at_fs;	/* What was t_sndbytes as we begun sending */
156 	uint64_t rxt_at_fs;	/* What was t_snd_rxt_bytes as we begun sending */
157 	tcp_seq start_seq;	/* First TCP Seq assigned */
158 	tcp_seq end_seq;	/* If range req last seq */
159 	uint32_t flags;		/* Type of request open etc */
160 	uint32_t sbcc_at_s;	/* When we allocate what is the sb_cc */
161 	uint32_t hint_maxseg;	/* Client hinted maxseg */
162 	uint32_t hybrid_flags;	/* Hybrid flags on this request */
163 };
164 
165 
166 /*
167  * Change Query responses for a stack switch we create a structure
168  * that allows query response from the new stack to the old, if
169  * supported.
170  *
171  * There are three queries currently defined.
172  *  - sendmap
173  *  - timers
174  *  - rack_times
175  *
176  * For the sendmap query the caller fills in the
177  * req and the req_param as the first seq (usually
178  * snd_una). When the response comes back indicating
179  * that there was data (return value 1), then the caller
180  * can build a sendmap entry based on the range and the
181  * times. The next query would then be done at the
182  * newly created sendmap_end. Repeated until sendmap_end == snd_max.
183  *
184  * Flags in sendmap_flags are defined below as well.
185  *
186  * For timers the standard PACE_TMR_XXXX flags are returned indicating
187  * a pacing timer (possibly) and one other timer. If pacing timer then
188  * the expiration timeout time in microseconds is in timer_pacing_to.
189  * And the value used with whatever timer (if a flag is set) is in
190  * timer_rxt. If no timers are running a 0 is returned and of
191  * course no flags are set in timer_hpts_flags.
192  *
193  * The rack_times are a misc collection of information that
194  * the old stack might possibly fill in. Of course its possible
195  * that an old stack may not have a piece of information. If so
196  * then setting that value to zero is advised. Setting any
197  * timestamp passed should only place a zero in it when it
198  * is unfilled. This may mean that a time is off by a micro-second
199  * but this is ok in the grand scheme of things.
200  *
201  * When switching stacks it is desireable to get as much information
202  * from the old stack to the new stack as possible. Though not always
203  * will the stack be compatible in the types of information. The
204  * init() function needs to take care when it begins changing
205  * things such as inp_flags2 and the timer units to position these
206  * changes at a point where it is unlikely they will fail after
207  * making such changes. A stack optionally can have an "undo"
208  * function
209  *
210  * To transfer information to the old stack from the new in
211  * respect to LRO and the inp_flags2, the new stack should set
212  * the inp_flags2 to what it supports. The old stack in its
213  * fini() function should call the tcp_handle_orphaned_packets()
214  * to clean up any packets. Note that a new stack should attempt
215  */
216 
217 /* Query types */
218 #define TCP_QUERY_SENDMAP	1
219 #define TCP_QUERY_TIMERS_UP	2
220 #define TCP_QUERY_RACK_TIMES	3
221 
222 /* Flags returned in sendmap_flags */
223 #define SNDMAP_ACKED		0x000001/* The remote endpoint acked this */
224 #define SNDMAP_OVERMAX		0x000008/* We have more retran's then we can fit */
225 #define SNDMAP_SACK_PASSED	0x000010/* A sack was done above this block */
226 #define SNDMAP_HAS_FIN		0x000040/* segment is sent with fin */
227 #define SNDMAP_TLP		0x000080/* segment sent as tail-loss-probe */
228 #define SNDMAP_HAS_SYN		0x000800/* SYN is on this guy */
229 #define SNDMAP_HAD_PUSH		0x008000/* Push was sent on original send */
230 #define SNDMAP_MASK  (SNDMAP_ACKED|SNDMAP_OVERMAX|SNDMAP_SACK_PASSED|SNDMAP_HAS_FIN\
231 		      |SNDMAP_TLP|SNDMAP_HAS_SYN|SNDMAP_HAD_PUSH)
232 #define SNDMAP_NRTX 3
233 
234 struct tcp_query_resp {
235 	int req;
236 	uint32_t req_param;
237 	union {
238 		struct {
239 			tcp_seq sendmap_start;
240 			tcp_seq sendmap_end;
241 			int sendmap_send_cnt;
242 			uint64_t sendmap_time[SNDMAP_NRTX];
243 			uint64_t sendmap_ack_arrival;
244 			int sendmap_flags;
245 			uint32_t sendmap_r_rtr_bytes;
246 			/* If FAS is available if not 0 */
247 			uint32_t sendmap_fas;
248 			uint8_t sendmap_dupacks;
249 		};
250 		struct {
251 			uint32_t timer_hpts_flags;
252 			uint32_t timer_pacing_to;
253 			uint32_t timer_timer_exp;
254 		};
255 		struct {
256 			/* Timestamps and rtt's */
257 			uint32_t rack_reorder_ts;	/* Last uscts that reordering was seen */
258 			uint32_t rack_num_dsacks;	/* Num of dsacks seen */
259 			uint32_t rack_rxt_last_time; 	/* Last time a RXT/TLP or rack tmr  went off */
260 			uint32_t rack_min_rtt;		/* never 0 smallest rtt seen */
261 			uint32_t rack_rtt;		/* Last rtt used by rack */
262 			uint32_t rack_tmit_time;	/* The time the rtt seg was tmited */
263 			uint32_t rack_time_went_idle;	/* If in persist the time we went idle */
264 			/* Prr data  */
265 			uint32_t rack_sacked;
266 			uint32_t rack_holes_rxt;
267 			uint32_t rack_prr_delivered;
268 			uint32_t rack_prr_recovery_fs;
269 			uint32_t rack_prr_out;
270 			uint32_t rack_prr_sndcnt;
271 			/* TLP data */
272 			uint16_t rack_tlp_cnt_out;	/* How many tlp's have been sent */
273 			/* Various bits */
274 			uint8_t  rack_tlp_out;		/* Is a TLP outstanding */
275 			uint8_t  rack_srtt_measured;	/* The previous stack has measured srtt */
276 			uint8_t  rack_in_persist;	/* Is the old stack in persists? */
277 			uint8_t	 rack_wanted_output;	/* Did the prevous stack have a want output set */
278 		};
279 	};
280 };
281 
282 #define TCP_TMR_GRANULARITY_TICKS	1	/* TCP timers are in ticks (msec if hz=1000)  */
283 #define TCP_TMR_GRANULARITY_USEC	2	/* TCP timers are in microseconds */
284 
285 typedef enum {
286 	TT_REXMT = 0,
287 	TT_PERSIST,
288 	TT_KEEP,
289 	TT_2MSL,
290 	TT_DELACK,
291 	TT_N,
292 } tt_which;
293 
294 typedef enum {
295 	TT_PROCESSING = 0,
296 	TT_PROCESSED,
297 	TT_STARTING,
298 	TT_STOPPING,
299 } tt_what;
300 
301 /*
302  * Tcp control block, one per tcp connection.
303  */
304 struct tcpcb {
305 	struct inpcb t_inpcb;		/* embedded protocol independent cb */
306 #define	t_start_zero	t_fb
307 #define	t_zero_size	(sizeof(struct tcpcb) - \
308 			    offsetof(struct tcpcb, t_start_zero))
309 	struct tcp_function_block *t_fb;/* TCP function call block */
310 	void	*t_fb_ptr;		/* Pointer to t_fb specific data */
311 
312 	struct callout t_callout;
313 	sbintime_t t_timers[TT_N];
314 	sbintime_t t_precisions[TT_N];
315 
316 	/* HPTS. Used by BBR and Rack stacks. See tcp_hpts.c for more info. */
317 	TAILQ_ENTRY(tcpcb)	t_hpts;		/* linkage to HPTS ring */
318 	STAILQ_HEAD(, mbuf)	t_inqueue;	/* HPTS input packets queue */
319 	uint32_t t_hpts_request;	/* Current hpts request, zero if
320 					 * fits in the pacing window. */
321 	uint32_t t_hpts_slot;		/* HPTS wheel slot this tcb is. */
322 	uint32_t t_hpts_drop_reas;	/* Reason we are dropping the pcb. */
323 	uint32_t t_hpts_gencnt;
324 	uint16_t t_hpts_cpu;		/* CPU chosen by hpts_cpuid(). */
325 	uint16_t t_lro_cpu;		/* CPU derived from LRO. */
326 #define	HPTS_CPU_NONE	((uint16_t)-1)
327 	enum {
328 		IHPTS_NONE = 0,
329 		IHPTS_ONQUEUE,
330 		IHPTS_MOVING,
331 	} t_in_hpts;			/* Is it linked into HPTS? */
332 
333 	uint32_t t_maxseg:24,		/* maximum segment size */
334 		_t_logstate:8;		/* State of "black box" logging */
335 	uint32_t t_port:16,		/* Tunneling (over udp) port */
336 		t_state:4,		/* state of this connection */
337 		t_idle_reduce : 1,
338 		t_delayed_ack: 7,	/* Delayed ack variable */
339 		t_fin_is_rst: 1,	/* Are fin's treated as resets */
340 		t_log_state_set: 1,
341 		bits_spare : 2;
342 	u_int	t_flags;
343 	tcp_seq	snd_una;		/* sent but unacknowledged */
344 	tcp_seq	snd_max;		/* highest sequence number sent;
345 					 * used to recognize retransmits
346 					 */
347 	tcp_seq snd_nxt;		/* send next */
348 	tcp_seq snd_up;			/* send urgent pointer */
349 	uint32_t snd_wnd;		/* send window */
350 	uint32_t snd_cwnd;		/* congestion-controlled window */
351 	uint32_t ts_offset;		/* our timestamp offset */
352 	uint32_t rfbuf_ts;		/* recv buffer autoscaling timestamp */
353 	int	rcv_numsacks;		/* # distinct sack blks present */
354 	u_int	t_tsomax;		/* TSO total burst length limit */
355 	u_int	t_tsomaxsegcount;	/* TSO maximum segment count */
356 	u_int	t_tsomaxsegsize;	/* TSO maximum segment size in bytes */
357 	tcp_seq	rcv_nxt;		/* receive next */
358 	tcp_seq	rcv_adv;		/* advertised window */
359 	uint32_t rcv_wnd;		/* receive window */
360 	u_int	t_flags2;		/* More tcpcb flags storage */
361 	int	t_srtt;			/* smoothed round-trip time */
362 	int	t_rttvar;		/* variance in round-trip time */
363 	uint32_t ts_recent;		/* timestamp echo data */
364 	u_char	snd_scale;		/* window scaling for send window */
365 	u_char	rcv_scale;		/* window scaling for recv window */
366 	u_char	snd_limited;		/* segments limited transmitted */
367 	u_char	request_r_scale;	/* pending window scaling */
368 	tcp_seq	last_ack_sent;
369 	u_int	t_rcvtime;		/* inactivity time */
370 	tcp_seq	rcv_up;			/* receive urgent pointer */
371 	int	t_segqlen;		/* segment reassembly queue length */
372 	uint32_t t_segqmbuflen;		/* total reassembly queue byte length */
373 	struct	tsegqe_head t_segq;	/* segment reassembly queue */
374 	uint32_t snd_ssthresh;		/* snd_cwnd size threshold for
375 					 * for slow start exponential to
376 					 * linear switch
377 					 */
378 	tcp_seq	snd_wl1;		/* window update seg seq number */
379 	tcp_seq	snd_wl2;		/* window update seg ack number */
380 
381 	tcp_seq	irs;			/* initial receive sequence number */
382 	tcp_seq	iss;			/* initial send sequence number */
383 	u_int	t_acktime;		/* RACK and BBR incoming new data was acked */
384 	u_int	t_sndtime;		/* time last data was sent */
385 	u_int	ts_recent_age;		/* when last updated */
386 	tcp_seq	snd_recover;		/* for use in NewReno Fast Recovery */
387 	char	t_oobflags;		/* have some */
388 	char	t_iobc;			/* input character */
389 	uint8_t t_nic_ktls_xmit:1,	/* active nic ktls xmit sessions */
390 		t_nic_ktls_xmit_dis:1,	/* disabled nic xmit ktls? */
391 		t_nic_ktls_spare:6;	/* spare nic ktls */
392 	int	t_rxtcur;		/* current retransmit value (ticks) */
393 
394 	int	t_rxtshift;		/* log(2) of rexmt exp. backoff */
395 	u_int	t_rtttime;		/* RTT measurement start time */
396 
397 	tcp_seq	t_rtseq;		/* sequence number being timed */
398 	u_int	t_starttime;		/* time connection was established */
399 	u_int	t_fbyte_in;		/* ticks time first byte queued in */
400 	u_int	t_fbyte_out;		/* ticks time first byte queued out */
401 
402 	u_int	t_pmtud_saved_maxseg;	/* pre-blackhole MSS */
403 	int	t_blackhole_enter;	/* when to enter blackhole detection */
404 	int	t_blackhole_exit;	/* when to exit blackhole detection */
405 	u_int	t_rttmin;		/* minimum rtt allowed */
406 
407 	int	t_softerror;		/* possible error not yet reported */
408 	uint32_t max_sndwnd;		/* largest window peer has offered */
409 	uint32_t snd_cwnd_prev;		/* cwnd prior to retransmit */
410 	uint32_t snd_ssthresh_prev;	/* ssthresh prior to retransmit */
411 	tcp_seq	snd_recover_prev;	/* snd_recover prior to retransmit */
412 	int	t_sndzerowin;		/* zero-window updates sent */
413 	int	snd_numholes;		/* number of holes seen by sender */
414 	u_int	t_badrxtwin;		/* window for retransmit recovery */
415 	TAILQ_HEAD(sackhole_head, sackhole) snd_holes;
416 					/* SACK scoreboard (sorted) */
417 	tcp_seq	snd_fack;		/* last seq number(+1) sack'd by rcv'r*/
418 	struct sackblk sackblks[MAX_SACK_BLKS]; /* seq nos. of sack blocks */
419 	struct sackhint	sackhint;	/* SACK scoreboard hint */
420 	int	t_rttlow;		/* smallest observerved RTT */
421 	int	rfbuf_cnt;		/* recv buffer autoscaling byte count */
422 	struct toedev	*tod;		/* toedev handling this connection */
423 	int	t_sndrexmitpack;	/* retransmit packets sent */
424 	int	t_rcvoopack;		/* out-of-order packets received */
425 	void	*t_toe;			/* TOE pcb pointer */
426 	struct cc_algo	*t_cc;		/* congestion control algorithm */
427 	struct cc_var	t_ccv;		/* congestion control specific vars */
428 	int	t_bytes_acked;		/* # bytes acked during current RTT */
429 	u_int	t_maxunacktime;
430 	u_int	t_keepinit;		/* time to establish connection */
431 	u_int	t_keepidle;		/* time before keepalive probes begin */
432 	u_int	t_keepintvl;		/* interval between keepalives */
433 	u_int	t_keepcnt;		/* number of keepalives before close */
434 	int	t_dupacks;		/* consecutive dup acks recd */
435 	int	t_lognum;		/* Number of log entries */
436 	int	t_loglimit;		/* Maximum number of log entries */
437 	uint32_t t_rcep;		/* Number of received CE marked pkts */
438 	uint32_t t_scep;		/* Synced number of delivered CE pkts */
439 	int64_t	t_pacing_rate;		/* bytes / sec, -1 => unlimited */
440 	struct tcp_log_stailq t_logs;	/* Log buffer */
441 	struct tcp_log_id_node *t_lin;
442 	struct tcp_log_id_bucket *t_lib;
443 	const char *t_output_caller;	/* Function that called tcp_output */
444 	struct statsblob *t_stats;	/* Per-connection stats */
445 	/* Should these be a pointer to the arrays or an array? */
446 	uint32_t t_logsn;		/* Log "serial number" */
447 	uint32_t gput_ts;		/* Time goodput measurement started */
448 	tcp_seq gput_seq;		/* Outbound measurement seq */
449 	tcp_seq gput_ack;		/* Inbound measurement ack */
450 	int32_t t_stats_gput_prev;	/* XXXLAS: Prev gput measurement */
451 	uint32_t t_maxpeakrate;		/* max peak rate set by user, bytes/s */
452 	uint32_t t_sndtlppack;		/* tail loss probe packets sent */
453 	uint64_t t_sndtlpbyte;		/* total tail loss probe bytes sent */
454 	uint64_t t_sndbytes;		/* total bytes sent */
455 	uint64_t t_snd_rxt_bytes;	/* total bytes retransmitted */
456 	uint32_t t_dsack_bytes;		/* dsack bytes received */
457 	uint32_t t_dsack_tlp_bytes;	/* dsack bytes received for TLPs sent */
458 	uint32_t t_dsack_pack;		/* dsack packets we have eceived */
459 	uint8_t t_tmr_granularity;	/* Granularity of all timers srtt etc */
460 	uint8_t t_rttupdated;		/* number of times rtt sampled */
461 	/* TCP Fast Open */
462 	uint8_t t_tfo_client_cookie_len; /* TFO client cookie length */
463 	uint32_t t_end_info_status;	/* Status flag of end info */
464 	unsigned int *t_tfo_pending;	/* TFO server pending counter */
465 	union {
466 		uint8_t client[TCP_FASTOPEN_MAX_COOKIE_LEN];
467 		uint64_t server;
468 	} t_tfo_cookie;			/* TCP Fast Open cookie to send */
469 	union {
470 		uint8_t t_end_info_bytes[TCP_END_BYTE_INFO];
471 		uint64_t t_end_info;
472 	};
473 	struct osd	t_osd;		/* storage for Khelp module data */
474 	uint8_t _t_logpoint;	/* Used when a BB log points is enabled */
475 	/*
476 	 * Keep all #ifdef'ed components at the end of the structure!
477 	 * This is important to minimize problems when compiling modules
478 	 * using this structure from within the modules' directory.
479 	 */
480 #ifdef TCP_REQUEST_TRK
481 	/* Response tracking addons. */
482 	uint8_t t_tcpreq_req;	/* Request count */
483 	uint8_t t_tcpreq_open;	/* Number of open range requests */
484 	uint8_t t_tcpreq_closed;	/* Number of closed range requests */
485 	uint32_t tcp_hybrid_start;	/* Num of times we started hybrid pacing */
486 	uint32_t tcp_hybrid_stop;	/* Num of times we stopped hybrid pacing */
487 	uint32_t tcp_hybrid_error;	/* Num of times we failed to start hybrid pacing */
488 	struct tcp_sendfile_track t_tcpreq_info[MAX_TCP_TRK_REQ];
489 #endif
490 #ifdef TCP_ACCOUNTING
491 	uint64_t tcp_cnt_counters[TCP_NUM_CNT_COUNTERS];
492 	uint64_t tcp_proc_time[TCP_NUM_CNT_COUNTERS];
493 #endif
494 #ifdef TCPPCAP
495 	struct mbufq t_inpkts;		/* List of saved input packets. */
496 	struct mbufq t_outpkts;		/* List of saved output packets. */
497 #endif
498 };
499 #endif	/* _KERNEL || _WANT_TCPCB */
500 
501 #ifdef _KERNEL
502 struct tcptemp {
503 	u_char	tt_ipgen[40]; /* the size must be of max ip header, now IPv6 */
504 	struct	tcphdr tt_t;
505 };
506 
507 /* SACK scoreboard update status */
508 typedef enum {
509 	SACK_NOCHANGE = 0,
510 	SACK_CHANGE,
511 	SACK_NEWLOSS
512 } sackstatus_t;
513 
514 /* Enable TCP/UDP tunneling port */
515 #define TCP_TUNNELING_PORT_MIN		0
516 #define TCP_TUNNELING_PORT_MAX		65535
517 #define TCP_TUNNELING_PORT_DEFAULT	0
518 
519 /* Enable TCP/UDP tunneling port */
520 #define TCP_TUNNELING_OVERHEAD_MIN	sizeof(struct udphdr)
521 #define TCP_TUNNELING_OVERHEAD_MAX	1024
522 #define TCP_TUNNELING_OVERHEAD_DEFAULT	TCP_TUNNELING_OVERHEAD_MIN
523 
524 /* Minimum map entries limit value, if set */
525 #define TCP_MIN_MAP_ENTRIES_LIMIT	128
526 
527 /*
528  * TODO: We yet need to brave plowing in
529  * to tcp_input() and the pru_usrreq() block.
530  * Right now these go to the old standards which
531  * are somewhat ok, but in the long term may
532  * need to be changed. If we do tackle tcp_input()
533  * then we need to get rid of the tcp_do_segment()
534  * function below.
535  */
536 /* Flags for tcp functions */
537 #define	TCP_FUNC_BEING_REMOVED	0x01   	/* Can no longer be referenced */
538 #define	TCP_FUNC_OUTPUT_CANDROP	0x02   	/* tfb_tcp_output may ask tcp_drop */
539 
540 /**
541  * If defining the optional tcp_timers, in the
542  * tfb_tcp_timer_stop call you must use the
543  * callout_async_drain() function with the
544  * tcp_timer_discard callback. You should check
545  * the return of callout_async_drain() and if 0
546  * increment tt_draincnt. Since the timer sub-system
547  * does not know your callbacks you must provide a
548  * stop_all function that loops through and calls
549  * tcp_timer_stop() with each of your defined timers.
550  *
551  * Adding a tfb_tcp_handoff_ok function allows the socket
552  * option to change stacks to query you even if the
553  * connection is in a later stage. You return 0 to
554  * say you can take over and run your stack, you return
555  * non-zero (an error number) to say no you can't.
556  * If the function is undefined you can only change
557  * in the early states (before connect or listen).
558  *
559  * tfb_tcp_fb_init is used to allow the new stack to
560  * setup its control block. Among the things it must
561  * do is:
562  * a) Make sure that the inp_flags2 is setup correctly
563  *    for LRO. There are two flags that the previous
564  *    stack may have set INP_MBUF_ACKCMP and
565  *    INP_SUPPORTS_MBUFQ. If the new stack does not
566  *    support these it *should* clear the flags.
567  * b) Make sure that the timers are in the proper
568  *    granularity that the stack wants. The stack
569  *    should check the t_tmr_granularity field. Currently
570  *    there are two values that it may hold
571  *    TCP_TMR_GRANULARITY_TICKS and TCP_TMR_GRANULARITY_USEC.
572  *    Use the functions tcp_timer_convert(tp, granularity);
573  *    to move the timers to the correct format for your stack.
574  *
575  * The new stack may also optionally query the tfb_chg_query
576  * function if the old stack has one. The new stack may ask
577  * for one of three entries and can also state to the old
578  * stack its support for the INP_MBUF_ACKCMP and
579  * INP_SUPPORTS_MBUFQ. This is important since if there are
580  * queued ack's without that statement the old stack will
581  * be forced to discard the queued acks. The requests that
582  * can be made for information by the new stacks are:
583  *
584  * Note also that the tfb_tcp_fb_init() when called can
585  * determine if a query is needed by looking at the
586  * value passed in the ptr. The ptr is designed to be
587  * set in with any allocated memory, but the address
588  * of the condtion (ptr == &tp->t_fb_ptr) will be
589  * true if this is not a stack switch but the initial
590  * setup of a tcb (which means no query would be needed).
591  * If, however, the value is not t_fb_ptr, then the caller
592  * is in the middle of a stack switch and is the new stack.
593  * A query would be appropriate (if the new stack support
594  * the query mechanism).
595  *
596  * TCP_QUERY_SENDMAP - Query of outstanding data.
597  * TCP_QUERY_TIMERS_UP	- Query about running timers.
598  * TCP_SUPPORTED_LRO - Declaration in req_param of
599  *                     the inp_flags2 supported by
600  *                     the new stack.
601  * TCP_QUERY_RACK_TIMES	- Enquire about various timestamps
602  *                        and states the old stack may be in.
603  *
604  * tfb_tcp_fb_fini is changed to add a flag to tell
605  * the old stack if the tcb is being destroyed or
606  * not. A one in the flag means the TCB is being
607  * destroyed, a zero indicates its transitioning to
608  * another stack (via socket option). The
609  * tfb_tcp_fb_fini() function itself should not change timers
610  * or inp_flags2 (the tfb_tcp_fb_init() must do that). However
611  * if the old stack supports the LRO mbuf queuing, and the new
612  * stack does not communicate via chg messages that it too does,
613  * it must assume it does not and free any queued mbufs.
614  *
615  */
616 struct tcp_function_block {
617 	char tfb_tcp_block_name[TCP_FUNCTION_NAME_LEN_MAX];
618 	int	(*tfb_tcp_output)(struct tcpcb *);
619 	void	(*tfb_tcp_do_segment)(struct tcpcb *, struct mbuf *,
620 		    struct tcphdr *, int, int, uint8_t);
621 	int      (*tfb_do_segment_nounlock)(struct tcpcb *, struct mbuf *,
622 		    struct tcphdr *, int, int, uint8_t, int, struct timeval *);
623 	int     (*tfb_do_queued_segments)(struct tcpcb *, int);
624 	int     (*tfb_tcp_ctloutput)(struct tcpcb *, struct sockopt *);
625 	/* Optional memory allocation/free routine */
626 	int	(*tfb_tcp_fb_init)(struct tcpcb *, void **);
627 	void	(*tfb_tcp_fb_fini)(struct tcpcb *, int);
628 	/* Optional timers, must define all if you define one */
629 	int	(*tfb_tcp_timer_stop_all)(struct tcpcb *);
630 	void	(*tfb_tcp_rexmit_tmr)(struct tcpcb *);
631 	int	(*tfb_tcp_handoff_ok)(struct tcpcb *);
632 	void	(*tfb_tcp_mtu_chg)(struct tcpcb *tp);
633 	int	(*tfb_pru_options)(struct tcpcb *, int);
634 	void	(*tfb_hwtls_change)(struct tcpcb *, int);
635 	int	(*tfb_chg_query)(struct tcpcb *, struct tcp_query_resp *);
636 	void	(*tfb_switch_failed)(struct tcpcb *);
637 	bool	(*tfb_early_wake_check)(struct tcpcb *);
638 	int     (*tfb_compute_pipe)(struct tcpcb *tp);
639 	volatile uint32_t tfb_refcnt;
640 	uint32_t  tfb_flags;
641 	uint8_t	tfb_id;
642 };
643 
644 struct tcp_function {
645 	TAILQ_ENTRY(tcp_function)	tf_next;
646 	char				tf_name[TCP_FUNCTION_NAME_LEN_MAX];
647 	struct tcp_function_block	*tf_fb;
648 };
649 
650 TAILQ_HEAD(tcp_funchead, tcp_function);
651 
652 struct tcpcb * tcp_drop(struct tcpcb *, int);
653 
654 #ifdef _NETINET_IN_PCB_H_
655 #define	intotcpcb(inp)	__containerof((inp), struct tcpcb, t_inpcb)
656 #define	sototcpcb(so)	intotcpcb(sotoinpcb(so))
657 #define	tptoinpcb(tp)	(&(tp)->t_inpcb)
658 #define	tptosocket(tp)	(tp)->t_inpcb.inp_socket
659 
660 /*
661  * tcp_output()
662  * Handles tcp_drop request from advanced stacks and reports that inpcb is
663  * gone with negative return code.
664  * Drop in replacement for the default stack.
665  */
666 static inline int
667 tcp_output(struct tcpcb *tp)
668 {
669 	struct inpcb *inp = tptoinpcb(tp);
670 	int rv;
671 
672 	INP_WLOCK_ASSERT(inp);
673 
674 	rv = tp->t_fb->tfb_tcp_output(tp);
675 	if (rv < 0) {
676 		KASSERT(tp->t_fb->tfb_flags & TCP_FUNC_OUTPUT_CANDROP,
677 		    ("TCP stack %s requested tcp_drop(%p)",
678 		    tp->t_fb->tfb_tcp_block_name, tp));
679 		tp = tcp_drop(tp, -rv);
680 		if (tp)
681 			INP_WUNLOCK(inp);
682 	}
683 
684 	return (rv);
685 }
686 
687 /*
688  * tcp_output_unlock()
689  * Always returns unlocked, handles drop request from advanced stacks.
690  * Always returns positive error code.
691  */
692 static inline int
693 tcp_output_unlock(struct tcpcb *tp)
694 {
695 	struct inpcb *inp = tptoinpcb(tp);
696 	int rv;
697 
698 	INP_WLOCK_ASSERT(inp);
699 
700 	rv = tp->t_fb->tfb_tcp_output(tp);
701 	if (rv < 0) {
702 		KASSERT(tp->t_fb->tfb_flags & TCP_FUNC_OUTPUT_CANDROP,
703 		    ("TCP stack %s requested tcp_drop(%p)",
704 		    tp->t_fb->tfb_tcp_block_name, tp));
705 		rv = -rv;
706 		tp = tcp_drop(tp, rv);
707 		if (tp)
708 			INP_WUNLOCK(inp);
709 	} else
710 		INP_WUNLOCK(inp);
711 
712 	return (rv);
713 }
714 
715 /*
716  * tcp_output_nodrop()
717  * Always returns locked.  It is caller's responsibility to run tcp_drop()!
718  * Useful in syscall implementations, when we want to perform some logging
719  * and/or tracing with tcpcb before calling tcp_drop().  To be used with
720  * tcp_unlock_or_drop() later.
721  *
722  * XXXGL: maybe don't allow stacks to return a drop request at certain
723  * TCP states? Why would it do in connect(2)? In recv(2)?
724  */
725 static inline int
726 tcp_output_nodrop(struct tcpcb *tp)
727 {
728 	int rv;
729 
730 	INP_WLOCK_ASSERT(tptoinpcb(tp));
731 
732 	rv = tp->t_fb->tfb_tcp_output(tp);
733 	KASSERT(rv >= 0 || tp->t_fb->tfb_flags & TCP_FUNC_OUTPUT_CANDROP,
734 	    ("TCP stack %s requested tcp_drop(%p)",
735 	    tp->t_fb->tfb_tcp_block_name, tp));
736 	return (rv);
737 }
738 
739 /*
740  * tcp_unlock_or_drop()
741  * Handle return code from tfb_tcp_output() after we have logged/traced,
742  * to be used with tcp_output_nodrop().
743  */
744 static inline int
745 tcp_unlock_or_drop(struct tcpcb *tp, int tcp_output_retval)
746 {
747 	struct inpcb *inp = tptoinpcb(tp);
748 
749 	INP_WLOCK_ASSERT(inp);
750 
751         if (tcp_output_retval < 0) {
752                 tcp_output_retval = -tcp_output_retval;
753                 if (tcp_drop(tp, tcp_output_retval) != NULL)
754                         INP_WUNLOCK(inp);
755         } else
756 		INP_WUNLOCK(inp);
757 
758 	return (tcp_output_retval);
759 }
760 #endif	/* _NETINET_IN_PCB_H_ */
761 
762 static int inline
763 tcp_packets_this_ack(struct tcpcb *tp, tcp_seq ack)
764 {
765 	return ((ack - tp->snd_una) / tp->t_maxseg +
766 		((((ack - tp->snd_una) % tp->t_maxseg) != 0) ? 1 : 0));
767 }
768 #endif	/* _KERNEL */
769 
770 /*
771  * Flags and utility macros for the t_flags field.
772  */
773 #define	TF_ACKNOW	0x00000001	/* ack peer immediately */
774 #define	TF_DELACK	0x00000002	/* ack, but try to delay it */
775 #define	TF_NODELAY	0x00000004	/* don't delay packets to coalesce */
776 #define	TF_NOOPT	0x00000008	/* don't use tcp options */
777 #define	TF_SENTFIN	0x00000010	/* have sent FIN */
778 #define	TF_REQ_SCALE	0x00000020	/* have/will request window scaling */
779 #define	TF_RCVD_SCALE	0x00000040	/* other side has requested scaling */
780 #define	TF_REQ_TSTMP	0x00000080	/* have/will request timestamps */
781 #define	TF_RCVD_TSTMP	0x00000100	/* a timestamp was received in SYN */
782 #define	TF_SACK_PERMIT	0x00000200	/* other side said I could SACK */
783 #define	TF_NEEDSYN	0x00000400	/* send SYN (implicit state) */
784 #define	TF_NEEDFIN	0x00000800	/* send FIN (implicit state) */
785 #define	TF_NOPUSH	0x00001000	/* don't push */
786 #define	TF_PREVVALID	0x00002000	/* saved values for bad rxmit valid
787 					 * Note: accessing and restoring from
788 					 * these may only be done in the 1st
789 					 * RTO recovery round (t_rxtshift == 1)
790 					 */
791 #define	TF_WAKESOR	0x00004000	/* wake up receive socket */
792 #define	TF_GPUTINPROG	0x00008000	/* Goodput measurement in progress */
793 #define	TF_MORETOCOME	0x00010000	/* More data to be appended to sock */
794 #define	TF_SONOTCONN	0x00020000	/* needs soisconnected() on ESTAB */
795 #define	TF_LASTIDLE	0x00040000	/* connection was previously idle */
796 #define	TF_RXWIN0SENT	0x00080000	/* sent a receiver win 0 in response */
797 #define	TF_FASTRECOVERY	0x00100000	/* in NewReno Fast Recovery */
798 #define	TF_WASFRECOVERY	0x00200000	/* was in NewReno Fast Recovery */
799 #define	TF_SIGNATURE	0x00400000	/* require MD5 digests (RFC2385) */
800 #define	TF_FORCEDATA	0x00800000	/* force out a byte */
801 #define	TF_TSO		0x01000000	/* TSO enabled on this connection */
802 #define	TF_TOE		0x02000000	/* this connection is offloaded */
803 #define	TF_CLOSED	0x04000000	/* close(2) called on socket */
804 #define	TF_UNUSED1	0x08000000	/* unused */
805 #define	TF_LRD		0x10000000	/* Lost Retransmission Detection */
806 #define	TF_CONGRECOVERY	0x20000000	/* congestion recovery mode */
807 #define	TF_WASCRECOVERY	0x40000000	/* was in congestion recovery */
808 #define	TF_FASTOPEN	0x80000000	/* TCP Fast Open indication */
809 
810 #define	IN_FASTRECOVERY(t_flags)	(t_flags & TF_FASTRECOVERY)
811 #define	ENTER_FASTRECOVERY(t_flags)	t_flags |= TF_FASTRECOVERY
812 #define	EXIT_FASTRECOVERY(t_flags)	t_flags &= ~TF_FASTRECOVERY
813 
814 #define	IN_CONGRECOVERY(t_flags)	(t_flags & TF_CONGRECOVERY)
815 #define	ENTER_CONGRECOVERY(t_flags)	t_flags |= TF_CONGRECOVERY
816 #define	EXIT_CONGRECOVERY(t_flags)	t_flags &= ~TF_CONGRECOVERY
817 
818 #define	IN_RECOVERY(t_flags) (t_flags & (TF_CONGRECOVERY | TF_FASTRECOVERY))
819 #define	ENTER_RECOVERY(t_flags) t_flags |= (TF_CONGRECOVERY | TF_FASTRECOVERY)
820 #define	EXIT_RECOVERY(t_flags) t_flags &= ~(TF_CONGRECOVERY | TF_FASTRECOVERY)
821 
822 #if defined(_KERNEL) && !defined(TCP_RFC7413)
823 #define	IS_FASTOPEN(t_flags)		(false)
824 #else
825 #define	IS_FASTOPEN(t_flags)		(t_flags & TF_FASTOPEN)
826 #endif
827 
828 #define	BYTES_THIS_ACK(tp, th)	(th->th_ack - tp->snd_una)
829 
830 /*
831  * Flags for the t_oobflags field.
832  */
833 #define	TCPOOB_HAVEDATA	0x01
834 #define	TCPOOB_HADDATA	0x02
835 
836 /*
837  * Flags for the extended TCP flags field, t_flags2
838  */
839 #define	TF2_PLPMTU_BLACKHOLE	0x00000001 /* Possible PLPMTUD Black Hole. */
840 #define	TF2_PLPMTU_PMTUD	0x00000002 /* Allowed to attempt PLPMTUD. */
841 #define	TF2_PLPMTU_MAXSEGSNT	0x00000004 /* Last seg sent was full seg. */
842 #define	TF2_LOG_AUTO		0x00000008 /* Session is auto-logging. */
843 #define	TF2_DROP_AF_DATA	0x00000010 /* Drop after all data ack'd */
844 #define	TF2_ECN_PERMIT		0x00000020 /* connection ECN-ready */
845 #define	TF2_ECN_SND_CWR		0x00000040 /* ECN CWR in queue */
846 #define	TF2_ECN_SND_ECE		0x00000080 /* ECN ECE in queue */
847 #define	TF2_ACE_PERMIT		0x00000100 /* Accurate ECN mode */
848 #define	TF2_HPTS_CPU_SET	0x00000200 /* t_hpts_cpu is not random */
849 #define	TF2_FBYTES_COMPLETE	0x00000400 /* We have first bytes in and out */
850 #define	TF2_ECN_USE_ECT1	0x00000800 /* Use ECT(1) marking on session */
851 #define TF2_TCP_ACCOUNTING	0x00001000 /* Do TCP accounting */
852 #define	TF2_HPTS_CALLS		0x00002000 /* tcp_output() called via HPTS */
853 #define	TF2_MBUF_L_ACKS		0x00004000 /* large mbufs for ack compression */
854 #define	TF2_MBUF_ACKCMP		0x00008000 /* mbuf ack compression ok */
855 #define	TF2_SUPPORTS_MBUFQ	0x00010000 /* Supports the mbuf queue method */
856 #define	TF2_MBUF_QUEUE_READY	0x00020000 /* Inputs can be queued */
857 #define	TF2_DONT_SACK_QUEUE	0x00040000 /* Don't wake on sack */
858 #define	TF2_CANNOT_DO_ECN	0x00080000 /* The stack does not do ECN */
859 
860 /*
861  * Structure to hold TCP options that are only used during segment
862  * processing (in tcp_input), but not held in the tcpcb.
863  * It's basically used to reduce the number of parameters
864  * to tcp_dooptions and tcp_addoptions.
865  * The binary order of the to_flags is relevant for packing of the
866  * options in tcp_addoptions.
867  */
868 struct tcpopt {
869 	u_int32_t	to_flags;	/* which options are present */
870 #define	TOF_MSS		0x0001		/* maximum segment size */
871 #define	TOF_SCALE	0x0002		/* window scaling */
872 #define	TOF_SACKPERM	0x0004		/* SACK permitted */
873 #define	TOF_TS		0x0010		/* timestamp */
874 #define	TOF_SIGNATURE	0x0040		/* TCP-MD5 signature option (RFC2385) */
875 #define	TOF_SACK	0x0080		/* Peer sent SACK option */
876 #define	TOF_FASTOPEN	0x0100		/* TCP Fast Open (TFO) cookie */
877 #define	TOF_MAXOPT	0x0200
878 	u_int32_t	to_tsval;	/* new timestamp */
879 	u_int32_t	to_tsecr;	/* reflected timestamp */
880 	u_char		*to_sacks;	/* pointer to the first SACK blocks */
881 	u_char		*to_signature;	/* pointer to the TCP-MD5 signature */
882 	u_int8_t	*to_tfo_cookie; /* pointer to the TFO cookie */
883 	u_int16_t	to_mss;		/* maximum segment size */
884 	u_int8_t	to_wscale;	/* window scaling */
885 	u_int8_t	to_nsacks;	/* number of SACK blocks */
886 	u_int8_t	to_tfo_len;	/* TFO cookie length */
887 	u_int32_t	to_spare;	/* UTO */
888 };
889 
890 /*
891  * Flags for tcp_dooptions.
892  */
893 #define	TO_SYN		0x01		/* parse SYN-only options */
894 
895 struct hc_metrics_lite {	/* must stay in sync with hc_metrics */
896 	uint32_t	rmx_mtu;	/* MTU for this path */
897 	uint32_t	rmx_ssthresh;	/* outbound gateway buffer limit */
898 	uint32_t	rmx_rtt;	/* estimated round trip time */
899 	uint32_t	rmx_rttvar;	/* estimated rtt variance */
900 	uint32_t	rmx_cwnd;	/* congestion window */
901 	uint32_t	rmx_sendpipe;   /* outbound delay-bandwidth product */
902 	uint32_t	rmx_recvpipe;   /* inbound delay-bandwidth product */
903 };
904 
905 /*
906  * Used by tcp_maxmtu() to communicate interface specific features
907  * and limits at the time of connection setup.
908  */
909 struct tcp_ifcap {
910 	int	ifcap;
911 	u_int	tsomax;
912 	u_int	tsomaxsegcount;
913 	u_int	tsomaxsegsize;
914 };
915 
916 #ifndef _NETINET_IN_PCB_H_
917 struct in_conninfo;
918 #endif /* _NETINET_IN_PCB_H_ */
919 
920 /*
921  * The smoothed round-trip time and estimated variance
922  * are stored as fixed point numbers scaled by the values below.
923  * For convenience, these scales are also used in smoothing the average
924  * (smoothed = (1/scale)sample + ((scale-1)/scale)smoothed).
925  * With these scales, srtt has 3 bits to the right of the binary point,
926  * and thus an "ALPHA" of 0.875.  rttvar has 2 bits to the right of the
927  * binary point, and is smoothed with an ALPHA of 0.75.
928  */
929 #define	TCP_RTT_SCALE		32	/* multiplier for srtt; 3 bits frac. */
930 #define	TCP_RTT_SHIFT		5	/* shift for srtt; 3 bits frac. */
931 #define	TCP_RTTVAR_SCALE	16	/* multiplier for rttvar; 2 bits */
932 #define	TCP_RTTVAR_SHIFT	4	/* shift for rttvar; 2 bits */
933 #define	TCP_DELTA_SHIFT		2	/* see tcp_input.c */
934 
935 /*
936  * The initial retransmission should happen at rtt + 4 * rttvar.
937  * Because of the way we do the smoothing, srtt and rttvar
938  * will each average +1/2 tick of bias.  When we compute
939  * the retransmit timer, we want 1/2 tick of rounding and
940  * 1 extra tick because of +-1/2 tick uncertainty in the
941  * firing of the timer.  The bias will give us exactly the
942  * 1.5 tick we need.  But, because the bias is
943  * statistical, we have to test that we don't drop below
944  * the minimum feasible timer (which is 2 ticks).
945  * This version of the macro adapted from a paper by Lawrence
946  * Brakmo and Larry Peterson which outlines a problem caused
947  * by insufficient precision in the original implementation,
948  * which results in inappropriately large RTO values for very
949  * fast networks.
950  */
951 #define	TCP_REXMTVAL(tp) \
952 	max((tp)->t_rttmin, (((tp)->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT))  \
953 	  + (tp)->t_rttvar) >> TCP_DELTA_SHIFT)
954 
955 /*
956  * TCP statistics.
957  * Many of these should be kept per connection,
958  * but that's inconvenient at the moment.
959  */
960 struct	tcpstat {
961 	uint64_t tcps_connattempt;	/* connections initiated */
962 	uint64_t tcps_accepts;		/* connections accepted */
963 	uint64_t tcps_connects;		/* connections established */
964 	uint64_t tcps_drops;		/* connections dropped */
965 	uint64_t tcps_conndrops;	/* embryonic connections dropped */
966 	uint64_t tcps_minmssdrops;	/* average minmss too low drops */
967 	uint64_t tcps_closed;		/* conn. closed (includes drops) */
968 	uint64_t tcps_segstimed;	/* segs where we tried to get rtt */
969 	uint64_t tcps_rttupdated;	/* times we succeeded */
970 	uint64_t tcps_delack;		/* delayed acks sent */
971 	uint64_t tcps_timeoutdrop;	/* conn. dropped in rxmt timeout */
972 	uint64_t tcps_rexmttimeo;	/* retransmit timeouts */
973 	uint64_t tcps_persisttimeo;	/* persist timeouts */
974 	uint64_t tcps_keeptimeo;	/* keepalive timeouts */
975 	uint64_t tcps_keepprobe;	/* keepalive probes sent */
976 	uint64_t tcps_keepdrops;	/* connections dropped in keepalive */
977 	uint64_t tcps_progdrops;	/* drops due to no progress */
978 
979 	uint64_t tcps_sndtotal;		/* total packets sent */
980 	uint64_t tcps_sndpack;		/* data packets sent */
981 	uint64_t tcps_sndbyte;		/* data bytes sent */
982 	uint64_t tcps_sndrexmitpack;	/* data packets retransmitted */
983 	uint64_t tcps_sndrexmitbyte;	/* data bytes retransmitted */
984 	uint64_t tcps_sndrexmitbad;	/* unnecessary packet retransmissions */
985 	uint64_t tcps_sndacks;		/* ack-only packets sent */
986 	uint64_t tcps_sndprobe;		/* window probes sent */
987 	uint64_t tcps_sndurg;		/* packets sent with URG only */
988 	uint64_t tcps_sndwinup;		/* window update-only packets sent */
989 	uint64_t tcps_sndctrl;		/* control (SYN|FIN|RST) packets sent */
990 
991 	uint64_t tcps_rcvtotal;		/* total packets received */
992 	uint64_t tcps_rcvpack;		/* packets received in sequence */
993 	uint64_t tcps_rcvbyte;		/* bytes received in sequence */
994 	uint64_t tcps_rcvbadsum;	/* packets received with ccksum errs */
995 	uint64_t tcps_rcvbadoff;	/* packets received with bad offset */
996 	uint64_t tcps_rcvreassfull;	/* packets dropped for no reass space */
997 	uint64_t tcps_rcvshort;		/* packets received too short */
998 	uint64_t tcps_rcvduppack;	/* duplicate-only packets received */
999 	uint64_t tcps_rcvdupbyte;	/* duplicate-only bytes received */
1000 	uint64_t tcps_rcvpartduppack;	/* packets with some duplicate data */
1001 	uint64_t tcps_rcvpartdupbyte;	/* dup. bytes in part-dup. packets */
1002 	uint64_t tcps_rcvoopack;	/* out-of-order packets received */
1003 	uint64_t tcps_rcvoobyte;	/* out-of-order bytes received */
1004 	uint64_t tcps_rcvpackafterwin;	/* packets with data after window */
1005 	uint64_t tcps_rcvbyteafterwin;	/* bytes rcvd after window */
1006 	uint64_t tcps_rcvafterclose;	/* packets rcvd after "close" */
1007 	uint64_t tcps_rcvwinprobe;	/* rcvd window probe packets */
1008 	uint64_t tcps_rcvdupack;	/* rcvd duplicate acks */
1009 	uint64_t tcps_rcvacktoomuch;	/* rcvd acks for unsent data */
1010 	uint64_t tcps_rcvackpack;	/* rcvd ack packets */
1011 	uint64_t tcps_rcvackbyte;	/* bytes acked by rcvd acks */
1012 	uint64_t tcps_rcvwinupd;	/* rcvd window update packets */
1013 	uint64_t tcps_pawsdrop;		/* segments dropped due to PAWS */
1014 	uint64_t tcps_predack;		/* times hdr predict ok for acks */
1015 	uint64_t tcps_preddat;		/* times hdr predict ok for data pkts */
1016 	uint64_t tcps_pcbcachemiss;
1017 	uint64_t tcps_cachedrtt;	/* times cached RTT in route updated */
1018 	uint64_t tcps_cachedrttvar;	/* times cached rttvar updated */
1019 	uint64_t tcps_cachedssthresh;	/* times cached ssthresh updated */
1020 	uint64_t tcps_usedrtt;		/* times RTT initialized from route */
1021 	uint64_t tcps_usedrttvar;	/* times RTTVAR initialized from rt */
1022 	uint64_t tcps_usedssthresh;	/* times ssthresh initialized from rt*/
1023 	uint64_t tcps_persistdrop;	/* timeout in persist state */
1024 	uint64_t tcps_badsyn;		/* bogus SYN, e.g. premature ACK */
1025 	uint64_t tcps_mturesent;	/* resends due to MTU discovery */
1026 	uint64_t tcps_listendrop;	/* listen queue overflows */
1027 	uint64_t tcps_badrst;		/* ignored RSTs in the window */
1028 
1029 	uint64_t tcps_sc_added;		/* entry added to syncache */
1030 	uint64_t tcps_sc_retransmitted;	/* syncache entry was retransmitted */
1031 	uint64_t tcps_sc_dupsyn;	/* duplicate SYN packet */
1032 	uint64_t tcps_sc_dropped;	/* could not reply to packet */
1033 	uint64_t tcps_sc_completed;	/* successful extraction of entry */
1034 	uint64_t tcps_sc_bucketoverflow;/* syncache per-bucket limit hit */
1035 	uint64_t tcps_sc_cacheoverflow;	/* syncache cache limit hit */
1036 	uint64_t tcps_sc_reset;		/* RST removed entry from syncache */
1037 	uint64_t tcps_sc_stale;		/* timed out or listen socket gone */
1038 	uint64_t tcps_sc_aborted;	/* syncache entry aborted */
1039 	uint64_t tcps_sc_badack;	/* removed due to bad ACK */
1040 	uint64_t tcps_sc_unreach;	/* ICMP unreachable received */
1041 	uint64_t tcps_sc_zonefail;	/* zalloc() failed */
1042 	uint64_t tcps_sc_sendcookie;	/* SYN cookie sent */
1043 	uint64_t tcps_sc_recvcookie;	/* SYN cookie received */
1044 
1045 	uint64_t tcps_hc_added;		/* entry added to hostcache */
1046 	uint64_t tcps_hc_bucketoverflow;/* hostcache per bucket limit hit */
1047 
1048 	uint64_t tcps_finwait2_drops;    /* Drop FIN_WAIT_2 connection after time limit */
1049 
1050 	/* SACK related stats */
1051 	uint64_t tcps_sack_recovery_episode; /* SACK recovery episodes */
1052 	uint64_t tcps_sack_rexmits;	    /* SACK rexmit segments   */
1053 	uint64_t tcps_sack_rexmit_bytes;    /* SACK rexmit bytes      */
1054 	uint64_t tcps_sack_rcv_blocks;	    /* SACK blocks (options) received */
1055 	uint64_t tcps_sack_send_blocks;	    /* SACK blocks (options) sent     */
1056 	uint64_t tcps_sack_lostrexmt;	    /* SACK lost retransmission recovered */
1057 	uint64_t tcps_sack_sboverflow;	    /* times scoreboard overflowed */
1058 
1059 	/* ECN related stats */
1060 	uint64_t tcps_ecn_rcvce;		/* ECN Congestion Experienced */
1061 	uint64_t tcps_ecn_rcvect0;		/* ECN Capable Transport */
1062 	uint64_t tcps_ecn_rcvect1;		/* ECN Capable Transport */
1063 	uint64_t tcps_ecn_shs;		/* ECN successful handshakes */
1064 	uint64_t tcps_ecn_rcwnd;	/* # times ECN reduced the cwnd */
1065 
1066 	/* TCP_SIGNATURE related stats */
1067 	uint64_t tcps_sig_rcvgoodsig;	/* Total matching signature received */
1068 	uint64_t tcps_sig_rcvbadsig;	/* Total bad signature received */
1069 	uint64_t tcps_sig_err_buildsig;	/* Failed to make signature */
1070 	uint64_t tcps_sig_err_sigopt;	/* No signature expected by socket */
1071 	uint64_t tcps_sig_err_nosigopt;	/* No signature provided by segment */
1072 
1073 	/* Path MTU Discovery Black Hole Detection related stats */
1074 	uint64_t tcps_pmtud_blackhole_activated;	 /* Black Hole Count */
1075 	uint64_t tcps_pmtud_blackhole_activated_min_mss; /* BH at min MSS Count */
1076 	uint64_t tcps_pmtud_blackhole_failed;		 /* Black Hole Failure Count */
1077 
1078 	uint64_t tcps_tunneled_pkts;	/* Packets encap's in UDP received */
1079 	uint64_t tcps_tunneled_errs;	/* Packets that had errors that were UDP encaped */
1080 
1081 	/* Dsack related stats */
1082 	uint64_t tcps_dsack_count;	/* Number of ACKs arriving with DSACKs */
1083 	uint64_t tcps_dsack_bytes;	/* Number of bytes DSACK'ed no TLP */
1084 	uint64_t tcps_dsack_tlp_bytes;	/* Number of bytes DSACK'ed due to TLPs */
1085 
1086 	/* TCPS_TIME_WAIT usage stats */
1087 	uint64_t tcps_tw_recycles;	/* Times time-wait was recycled. */
1088 	uint64_t tcps_tw_resets;	/* Times time-wait sent a reset. */
1089 	uint64_t tcps_tw_responds;	/* Times time-wait sent a valid ack. */
1090 
1091 	/* Accurate ECN Handshake stats */
1092 	uint64_t tcps_ace_nect;		/* ACE SYN packet with Non-ECT */
1093 	uint64_t tcps_ace_ect1;		/* ACE SYN packet with ECT1 */
1094 	uint64_t tcps_ace_ect0;		/* ACE SYN packet with ECT0 */
1095 	uint64_t tcps_ace_ce;		/* ACE SYN packet with CE */
1096 
1097 	/* ECN related stats */
1098 	uint64_t tcps_ecn_sndect0;		/* ECN Capable Transport */
1099 	uint64_t tcps_ecn_sndect1;		/* ECN Capable Transport */
1100 
1101 	/*
1102 	 * BBR and Rack implement TLP's these values count TLP bytes in
1103 	 * two catagories, bytes that were retransmitted and bytes that
1104 	 * were newly transmited. Both types can serve as TLP's but they
1105 	 * are accounted differently.
1106 	 */
1107 	uint64_t tcps_tlpresends;	/* number of tlp resends */
1108 	uint64_t tcps_tlpresend_bytes;	/* number of bytes resent by tlp */
1109 
1110 
1111 	uint64_t _pad[4];		/* 4 TBD placeholder for STABLE */
1112 };
1113 
1114 #define	tcps_rcvmemdrop	tcps_rcvreassfull	/* compat */
1115 
1116 #ifdef _KERNEL
1117 #define	TI_UNLOCKED	1
1118 #define	TI_RLOCKED	2
1119 #include <sys/counter.h>
1120 
1121 VNET_PCPUSTAT_DECLARE(struct tcpstat, tcpstat);	/* tcp statistics */
1122 /*
1123  * In-kernel consumers can use these accessor macros directly to update
1124  * stats.
1125  */
1126 #define	TCPSTAT_ADD(name, val)	\
1127     VNET_PCPUSTAT_ADD(struct tcpstat, tcpstat, name, (val))
1128 #define	TCPSTAT_INC(name)	TCPSTAT_ADD(name, 1)
1129 
1130 /*
1131  * Kernel module consumers must use this accessor macro.
1132  */
1133 void	kmod_tcpstat_add(int statnum, int val);
1134 #define	KMOD_TCPSTAT_ADD(name, val)					\
1135     kmod_tcpstat_add(offsetof(struct tcpstat, name) / sizeof(uint64_t), val)
1136 #define	KMOD_TCPSTAT_INC(name)	KMOD_TCPSTAT_ADD(name, 1)
1137 
1138 /*
1139  * Running TCP connection count by state.
1140  */
1141 VNET_DECLARE(counter_u64_t, tcps_states[TCP_NSTATES]);
1142 #define	V_tcps_states	VNET(tcps_states)
1143 #define	TCPSTATES_INC(state)	counter_u64_add(V_tcps_states[state], 1)
1144 #define	TCPSTATES_DEC(state)	counter_u64_add(V_tcps_states[state], -1)
1145 
1146 /*
1147  * TCP specific helper hook point identifiers.
1148  */
1149 #define	HHOOK_TCP_EST_IN		0
1150 #define	HHOOK_TCP_EST_OUT		1
1151 #define	HHOOK_TCP_LAST			HHOOK_TCP_EST_OUT
1152 
1153 struct tcp_hhook_data {
1154 	struct tcpcb	*tp;
1155 	struct tcphdr	*th;
1156 	struct tcpopt	*to;
1157 	uint32_t	len;
1158 	int		tso;
1159 	tcp_seq		curack;
1160 };
1161 #ifdef TCP_HHOOK
1162 void hhook_run_tcp_est_out(struct tcpcb *tp,
1163 	struct tcphdr *th, struct tcpopt *to,
1164 	uint32_t len, int tso);
1165 #endif
1166 #endif
1167 
1168 /*
1169  * TCB structure exported to user-land via sysctl(3).
1170  *
1171  * Fields prefixed with "xt_" are unique to the export structure, and fields
1172  * with "t_" or other prefixes match corresponding fields of 'struct tcpcb'.
1173  *
1174  * Legend:
1175  * (s) - used by userland utilities in src
1176  * (p) - used by utilities in ports
1177  * (3) - is known to be used by third party software not in ports
1178  * (n) - no known usage
1179  *
1180  * Evil hack: declare only if in_pcb.h and sys/socketvar.h have been
1181  * included.  Not all of our clients do.
1182  */
1183 #if defined(_NETINET_IN_PCB_H_) && defined(_SYS_SOCKETVAR_H_)
1184 struct xtcpcb {
1185 	ksize_t	xt_len;		/* length of this structure */
1186 	struct xinpcb	xt_inp;
1187 	char		xt_stack[TCP_FUNCTION_NAME_LEN_MAX];	/* (s) */
1188 	char		xt_logid[TCP_LOG_ID_LEN];	/* (s) */
1189 	char		xt_cc[TCP_CA_NAME_MAX];	/* (s) */
1190 	int64_t		spare64[6];
1191 	int32_t		t_state;		/* (s,p) */
1192 	uint32_t	t_flags;		/* (s,p) */
1193 	int32_t		t_sndzerowin;		/* (s) */
1194 	int32_t		t_sndrexmitpack;	/* (s) */
1195 	int32_t		t_rcvoopack;		/* (s) */
1196 	int32_t		t_rcvtime;		/* (s) */
1197 	int32_t		tt_rexmt;		/* (s) */
1198 	int32_t		tt_persist;		/* (s) */
1199 	int32_t		tt_keep;		/* (s) */
1200 	int32_t		tt_2msl;		/* (s) */
1201 	int32_t		tt_delack;		/* (s) */
1202 	int32_t		t_logstate;		/* (3) */
1203 	uint32_t	t_snd_cwnd;		/* (s) */
1204 	uint32_t	t_snd_ssthresh;		/* (s) */
1205 	uint32_t	t_maxseg;		/* (s) */
1206 	uint32_t	t_rcv_wnd;		/* (s) */
1207 	uint32_t	t_snd_wnd;		/* (s) */
1208 	uint32_t	xt_ecn;			/* (s) */
1209 	uint32_t	t_dsack_bytes;		/* (n) */
1210 	uint32_t	t_dsack_tlp_bytes;	/* (n) */
1211 	uint32_t	t_dsack_pack;		/* (n) */
1212 	uint16_t	xt_encaps_port;		/* (s) */
1213 	int16_t		spare16;
1214 	int32_t		spare32[22];
1215 } __aligned(8);
1216 
1217 #ifdef _KERNEL
1218 void	tcp_inptoxtp(const struct inpcb *, struct xtcpcb *);
1219 #endif
1220 #endif
1221 
1222 /*
1223  * TCP function information (name-to-id mapping, aliases, and refcnt)
1224  * exported to user-land via sysctl(3).
1225  */
1226 struct tcp_function_info {
1227 	uint32_t	tfi_refcnt;
1228 	uint8_t		tfi_id;
1229 	char		tfi_name[TCP_FUNCTION_NAME_LEN_MAX];
1230 	char		tfi_alias[TCP_FUNCTION_NAME_LEN_MAX];
1231 };
1232 
1233 /*
1234  * Identifiers for TCP sysctl nodes
1235  */
1236 #define	TCPCTL_DO_RFC1323	1	/* use RFC-1323 extensions */
1237 #define	TCPCTL_MSSDFLT		3	/* MSS default */
1238 #define TCPCTL_STATS		4	/* statistics */
1239 #define	TCPCTL_RTTDFLT		5	/* default RTT estimate */
1240 #define	TCPCTL_KEEPIDLE		6	/* keepalive idle timer */
1241 #define	TCPCTL_KEEPINTVL	7	/* interval to send keepalives */
1242 #define	TCPCTL_SENDSPACE	8	/* send buffer space */
1243 #define	TCPCTL_RECVSPACE	9	/* receive buffer space */
1244 #define	TCPCTL_KEEPINIT		10	/* timeout for establishing syn */
1245 #define	TCPCTL_PCBLIST		11	/* list of all outstanding PCBs */
1246 #define	TCPCTL_DELACKTIME	12	/* time before sending delayed ACK */
1247 #define	TCPCTL_V6MSSDFLT	13	/* MSS default for IPv6 */
1248 #define	TCPCTL_SACK		14	/* Selective Acknowledgement,rfc 2018 */
1249 #define	TCPCTL_DROP		15	/* drop tcp connection */
1250 #define	TCPCTL_STATES		16	/* connection counts by TCP state */
1251 
1252 #ifdef _KERNEL
1253 #ifdef SYSCTL_DECL
1254 SYSCTL_DECL(_net_inet_tcp);
1255 SYSCTL_DECL(_net_inet_tcp_sack);
1256 MALLOC_DECLARE(M_TCPLOG);
1257 #endif
1258 
1259 VNET_DECLARE(int, tcp_log_in_vain);
1260 #define	V_tcp_log_in_vain		VNET(tcp_log_in_vain)
1261 
1262 /*
1263  * Global TCP tunables shared between different stacks.
1264  * Please keep the list sorted.
1265  */
1266 VNET_DECLARE(int, drop_synfin);
1267 VNET_DECLARE(int, path_mtu_discovery);
1268 VNET_DECLARE(int, tcp_abc_l_var);
1269 VNET_DECLARE(int, tcp_autorcvbuf_max);
1270 VNET_DECLARE(int, tcp_autosndbuf_inc);
1271 VNET_DECLARE(int, tcp_autosndbuf_max);
1272 VNET_DECLARE(int, tcp_delack_enabled);
1273 VNET_DECLARE(int, tcp_do_autorcvbuf);
1274 VNET_DECLARE(int, tcp_do_autosndbuf);
1275 VNET_DECLARE(int, tcp_do_ecn);
1276 VNET_DECLARE(int, tcp_do_lrd);
1277 VNET_DECLARE(int, tcp_do_prr);
1278 VNET_DECLARE(int, tcp_do_prr_conservative);
1279 VNET_DECLARE(int, tcp_do_newcwv);
1280 VNET_DECLARE(int, tcp_do_rfc1323);
1281 VNET_DECLARE(int, tcp_tolerate_missing_ts);
1282 VNET_DECLARE(int, tcp_do_rfc3042);
1283 VNET_DECLARE(int, tcp_do_rfc3390);
1284 VNET_DECLARE(int, tcp_do_rfc3465);
1285 VNET_DECLARE(int, tcp_do_newsack);
1286 VNET_DECLARE(int, tcp_do_sack);
1287 VNET_DECLARE(int, tcp_do_tso);
1288 VNET_DECLARE(int, tcp_ecn_maxretries);
1289 VNET_DECLARE(int, tcp_initcwnd_segments);
1290 VNET_DECLARE(int, tcp_insecure_rst);
1291 VNET_DECLARE(int, tcp_insecure_syn);
1292 VNET_DECLARE(uint32_t, tcp_map_entries_limit);
1293 VNET_DECLARE(uint32_t, tcp_map_split_limit);
1294 VNET_DECLARE(int, tcp_minmss);
1295 VNET_DECLARE(int, tcp_mssdflt);
1296 #ifdef STATS
1297 VNET_DECLARE(int, tcp_perconn_stats_dflt_tpl);
1298 VNET_DECLARE(int, tcp_perconn_stats_enable);
1299 #endif /* STATS */
1300 VNET_DECLARE(int, tcp_recvspace);
1301 VNET_DECLARE(int, tcp_retries);
1302 VNET_DECLARE(int, tcp_sack_globalholes);
1303 VNET_DECLARE(int, tcp_sack_globalmaxholes);
1304 VNET_DECLARE(int, tcp_sack_maxholes);
1305 VNET_DECLARE(int, tcp_sc_rst_sock_fail);
1306 VNET_DECLARE(int, tcp_sendspace);
1307 VNET_DECLARE(int, tcp_udp_tunneling_overhead);
1308 VNET_DECLARE(int, tcp_udp_tunneling_port);
1309 VNET_DECLARE(struct inpcbinfo, tcbinfo);
1310 
1311 #define	V_tcp_do_lrd			VNET(tcp_do_lrd)
1312 #define	V_tcp_do_prr			VNET(tcp_do_prr)
1313 #define	V_tcp_do_newcwv			VNET(tcp_do_newcwv)
1314 #define	V_drop_synfin			VNET(drop_synfin)
1315 #define	V_path_mtu_discovery		VNET(path_mtu_discovery)
1316 #define	V_tcbinfo			VNET(tcbinfo)
1317 #define	V_tcp_abc_l_var			VNET(tcp_abc_l_var)
1318 #define	V_tcp_autorcvbuf_max		VNET(tcp_autorcvbuf_max)
1319 #define	V_tcp_autosndbuf_inc		VNET(tcp_autosndbuf_inc)
1320 #define	V_tcp_autosndbuf_max		VNET(tcp_autosndbuf_max)
1321 #define	V_tcp_delack_enabled		VNET(tcp_delack_enabled)
1322 #define	V_tcp_do_autorcvbuf		VNET(tcp_do_autorcvbuf)
1323 #define	V_tcp_do_autosndbuf		VNET(tcp_do_autosndbuf)
1324 #define	V_tcp_do_ecn			VNET(tcp_do_ecn)
1325 #define	V_tcp_do_rfc1323		VNET(tcp_do_rfc1323)
1326 #define	V_tcp_tolerate_missing_ts	VNET(tcp_tolerate_missing_ts)
1327 #define V_tcp_ts_offset_per_conn	VNET(tcp_ts_offset_per_conn)
1328 #define	V_tcp_do_rfc3042		VNET(tcp_do_rfc3042)
1329 #define	V_tcp_do_rfc3390		VNET(tcp_do_rfc3390)
1330 #define	V_tcp_do_rfc3465		VNET(tcp_do_rfc3465)
1331 #define	V_tcp_do_newsack		VNET(tcp_do_newsack)
1332 #define	V_tcp_do_sack			VNET(tcp_do_sack)
1333 #define	V_tcp_do_tso			VNET(tcp_do_tso)
1334 #define	V_tcp_ecn_maxretries		VNET(tcp_ecn_maxretries)
1335 #define	V_tcp_initcwnd_segments		VNET(tcp_initcwnd_segments)
1336 #define	V_tcp_insecure_rst		VNET(tcp_insecure_rst)
1337 #define	V_tcp_insecure_syn		VNET(tcp_insecure_syn)
1338 #define	V_tcp_map_entries_limit		VNET(tcp_map_entries_limit)
1339 #define	V_tcp_map_split_limit		VNET(tcp_map_split_limit)
1340 #define	V_tcp_minmss			VNET(tcp_minmss)
1341 #define	V_tcp_mssdflt			VNET(tcp_mssdflt)
1342 #ifdef STATS
1343 #define	V_tcp_perconn_stats_dflt_tpl	VNET(tcp_perconn_stats_dflt_tpl)
1344 #define	V_tcp_perconn_stats_enable	VNET(tcp_perconn_stats_enable)
1345 #endif /* STATS */
1346 #define	V_tcp_recvspace			VNET(tcp_recvspace)
1347 #define	V_tcp_retries			VNET(tcp_retries)
1348 #define	V_tcp_sack_globalholes		VNET(tcp_sack_globalholes)
1349 #define	V_tcp_sack_globalmaxholes	VNET(tcp_sack_globalmaxholes)
1350 #define	V_tcp_sack_maxholes		VNET(tcp_sack_maxholes)
1351 #define	V_tcp_sc_rst_sock_fail		VNET(tcp_sc_rst_sock_fail)
1352 #define	V_tcp_sendspace			VNET(tcp_sendspace)
1353 #define	V_tcp_udp_tunneling_overhead	VNET(tcp_udp_tunneling_overhead)
1354 #define	V_tcp_udp_tunneling_port	VNET(tcp_udp_tunneling_port)
1355 
1356 #ifdef TCP_HHOOK
1357 VNET_DECLARE(struct hhook_head *, tcp_hhh[HHOOK_TCP_LAST + 1]);
1358 #define	V_tcp_hhh		VNET(tcp_hhh)
1359 #endif
1360 
1361 int	 tcp_addoptions(struct tcpopt *, u_char *);
1362 struct tcpcb *
1363 	 tcp_close(struct tcpcb *);
1364 void	 tcp_discardcb(struct tcpcb *);
1365 void	 tcp_twstart(struct tcpcb *);
1366 int	 tcp_ctloutput(struct socket *, struct sockopt *);
1367 void	 tcp_fini(void *);
1368 char	*tcp_log_addrs(struct in_conninfo *, struct tcphdr *, const void *,
1369 	    const void *);
1370 char	*tcp_log_vain(struct in_conninfo *, struct tcphdr *, const void *,
1371 	    const void *);
1372 int	 tcp_reass(struct tcpcb *, struct tcphdr *, tcp_seq *, int *,
1373 	    struct mbuf *);
1374 void	 tcp_reass_global_init(void);
1375 void	 tcp_reass_flush(struct tcpcb *);
1376 void	 tcp_dooptions(struct tcpopt *, u_char *, int, int);
1377 void	tcp_dropwithreset(struct mbuf *, struct tcphdr *,
1378 		     struct tcpcb *, int, int);
1379 void	tcp_pulloutofband(struct socket *,
1380 		     struct tcphdr *, struct mbuf *, int);
1381 void	tcp_xmit_timer(struct tcpcb *, int);
1382 void	tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
1383 void	cc_ack_received(struct tcpcb *tp, struct tcphdr *th,
1384 			    uint16_t nsegs, uint16_t type);
1385 void 	cc_conn_init(struct tcpcb *tp);
1386 void 	cc_post_recovery(struct tcpcb *tp, struct tcphdr *th);
1387 void    cc_ecnpkt_handler(struct tcpcb *tp, struct tcphdr *th, uint8_t iptos);
1388 void	cc_ecnpkt_handler_flags(struct tcpcb *tp, uint16_t flags, uint8_t iptos);
1389 void	cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type);
1390 #ifdef TCP_HHOOK
1391 void	hhook_run_tcp_est_in(struct tcpcb *tp,
1392 			    struct tcphdr *th, struct tcpopt *to);
1393 #endif
1394 
1395 int	 tcp_input(struct mbuf **, int *, int);
1396 int	 tcp_autorcvbuf(struct mbuf *, struct tcphdr *, struct socket *,
1397 	    struct tcpcb *, int);
1398 int	 tcp_input_with_port(struct mbuf **, int *, int, uint16_t);
1399 void	tcp_do_segment(struct tcpcb *, struct mbuf *, struct tcphdr *, int,
1400     int, uint8_t);
1401 
1402 int register_tcp_functions(struct tcp_function_block *blk, int wait);
1403 int register_tcp_functions_as_names(struct tcp_function_block *blk,
1404     int wait, const char *names[], int *num_names);
1405 int register_tcp_functions_as_name(struct tcp_function_block *blk,
1406     const char *name, int wait);
1407 int deregister_tcp_functions(struct tcp_function_block *blk, bool quiesce,
1408     bool force);
1409 struct tcp_function_block *find_and_ref_tcp_functions(struct tcp_function_set *fs);
1410 int find_tcp_function_alias(struct tcp_function_block *blk, struct tcp_function_set *fs);
1411 uint32_t tcp_get_srtt(struct tcpcb *tp, int granularity);
1412 void tcp_switch_back_to_default(struct tcpcb *tp);
1413 struct tcp_function_block *
1414 find_and_ref_tcp_fb(struct tcp_function_block *fs);
1415 int tcp_default_ctloutput(struct tcpcb *tp, struct sockopt *sopt);
1416 int tcp_ctloutput_set(struct inpcb *inp, struct sockopt *sopt);
1417 void tcp_log_socket_option(struct tcpcb *tp, uint32_t option_num,
1418     uint32_t option_val, int err);
1419 
1420 
1421 extern counter_u64_t tcp_inp_lro_direct_queue;
1422 extern counter_u64_t tcp_inp_lro_wokeup_queue;
1423 extern counter_u64_t tcp_inp_lro_compressed;
1424 extern counter_u64_t tcp_inp_lro_locks_taken;
1425 extern counter_u64_t tcp_extra_mbuf;
1426 extern counter_u64_t tcp_would_have_but;
1427 extern counter_u64_t tcp_comp_total;
1428 extern counter_u64_t tcp_uncomp_total;
1429 extern counter_u64_t tcp_bad_csums;
1430 
1431 #ifdef TCP_SAD_DETECTION
1432 /* Various SACK attack thresholds */
1433 extern int32_t tcp_force_detection;
1434 extern int32_t tcp_sad_limit;
1435 extern int32_t tcp_sack_to_ack_thresh;
1436 extern int32_t tcp_sack_to_move_thresh;
1437 extern int32_t tcp_restoral_thresh;
1438 extern int32_t tcp_sad_decay_val;
1439 extern int32_t tcp_sad_pacing_interval;
1440 extern int32_t tcp_sad_low_pps;
1441 extern int32_t tcp_map_minimum;
1442 extern int32_t tcp_attack_on_turns_on_logging;
1443 #endif
1444 extern uint32_t tcp_ack_war_time_window;
1445 extern uint32_t tcp_ack_war_cnt;
1446 
1447 uint32_t tcp_maxmtu(struct in_conninfo *, struct tcp_ifcap *);
1448 uint32_t tcp_maxmtu6(struct in_conninfo *, struct tcp_ifcap *);
1449 void	 tcp6_use_min_mtu(struct tcpcb *);
1450 u_int	 tcp_maxseg(const struct tcpcb *);
1451 u_int	 tcp_fixed_maxseg(const struct tcpcb *);
1452 void	 tcp_mss_update(struct tcpcb *, int, int, struct hc_metrics_lite *,
1453 	    struct tcp_ifcap *);
1454 void	 tcp_mss(struct tcpcb *, int);
1455 int	 tcp_mssopt(struct in_conninfo *);
1456 struct tcpcb *
1457 	 tcp_newtcpcb(struct inpcb *);
1458 int	 tcp_default_output(struct tcpcb *);
1459 void	 tcp_state_change(struct tcpcb *, int);
1460 void	 tcp_respond(struct tcpcb *, void *,
1461 	    struct tcphdr *, struct mbuf *, tcp_seq, tcp_seq, uint16_t);
1462 bool	 tcp_twcheck(struct inpcb *, struct tcpopt *, struct tcphdr *,
1463 	    struct mbuf *, int);
1464 void	 tcp_setpersist(struct tcpcb *);
1465 void	 tcp_record_dsack(struct tcpcb *tp, tcp_seq start, tcp_seq end, int tlp);
1466 struct tcptemp *
1467 	 tcpip_maketemplate(struct inpcb *);
1468 void	 tcpip_fillheaders(struct inpcb *, uint16_t, void *, void *);
1469 void	 tcp_timer_activate(struct tcpcb *, tt_which, u_int);
1470 bool	 tcp_timer_active(struct tcpcb *, tt_which);
1471 void	 tcp_timer_stop(struct tcpcb *);
1472 int	 inp_to_cpuid(struct inpcb *inp);
1473 /*
1474  * All tcp_hc_* functions are IPv4 and IPv6 (via in_conninfo)
1475  */
1476 void	 tcp_hc_init(void);
1477 #ifdef VIMAGE
1478 void	 tcp_hc_destroy(void);
1479 #endif
1480 void	 tcp_hc_get(struct in_conninfo *, struct hc_metrics_lite *);
1481 uint32_t tcp_hc_getmtu(struct in_conninfo *);
1482 void	 tcp_hc_updatemtu(struct in_conninfo *, uint32_t);
1483 void	 tcp_hc_update(struct in_conninfo *, struct hc_metrics_lite *);
1484 void 	 cc_after_idle(struct tcpcb *tp);
1485 
1486 extern	struct protosw tcp_protosw;		/* shared for TOE */
1487 extern	struct protosw tcp6_protosw;		/* shared for TOE */
1488 
1489 uint32_t tcp_new_ts_offset(struct in_conninfo *);
1490 tcp_seq	 tcp_new_isn(struct in_conninfo *);
1491 
1492 sackstatus_t
1493 	 tcp_sack_doack(struct tcpcb *, struct tcpopt *, tcp_seq);
1494 int	 tcp_dsack_block_exists(struct tcpcb *);
1495 void	 tcp_update_dsack_list(struct tcpcb *, tcp_seq, tcp_seq);
1496 void	 tcp_update_sack_list(struct tcpcb *tp, tcp_seq rcv_laststart, tcp_seq rcv_lastend);
1497 void	 tcp_clean_dsack_blocks(struct tcpcb *tp);
1498 void	 tcp_clean_sackreport(struct tcpcb *tp);
1499 void	 tcp_sack_adjust(struct tcpcb *tp);
1500 struct sackhole *tcp_sack_output(struct tcpcb *tp, int *sack_bytes_rexmt);
1501 void	 tcp_do_prr_ack(struct tcpcb *, struct tcphdr *, struct tcpopt *, sackstatus_t);
1502 void	 tcp_lost_retransmission(struct tcpcb *, struct tcphdr *);
1503 void	 tcp_sack_partialack(struct tcpcb *, struct tcphdr *);
1504 void	 tcp_free_sackholes(struct tcpcb *tp);
1505 void	 tcp_sack_lost_retransmission(struct tcpcb *, struct tcphdr *);
1506 int	 tcp_newreno(struct tcpcb *, struct tcphdr *);
1507 int	 tcp_compute_pipe(struct tcpcb *);
1508 uint32_t tcp_compute_initwnd(uint32_t);
1509 void	 tcp_sndbuf_autoscale(struct tcpcb *, struct socket *, uint32_t);
1510 int	 tcp_stats_sample_rollthedice(struct tcpcb *tp, void *seed_bytes,
1511     size_t seed_len);
1512 int tcp_can_enable_pacing(void);
1513 void tcp_decrement_paced_conn(void);
1514 void tcp_change_time_units(struct tcpcb *, int);
1515 void tcp_handle_orphaned_packets(struct tcpcb *);
1516 
1517 struct mbuf *
1518 	 tcp_m_copym(struct mbuf *m, int32_t off0, int32_t *plen,
1519 	   int32_t seglimit, int32_t segsize, struct sockbuf *sb, bool hw_tls);
1520 
1521 int	tcp_stats_init(void);
1522 void tcp_log_end_status(struct tcpcb *tp, uint8_t status);
1523 #ifdef TCP_REQUEST_TRK
1524 void tcp_req_free_a_slot(struct tcpcb *tp, struct tcp_sendfile_track *ent);
1525 struct tcp_sendfile_track *
1526 tcp_req_find_a_req_that_is_completed_by(struct tcpcb *tp, tcp_seq th_ack, int *ip);
1527 int tcp_req_check_for_comp(struct tcpcb *tp, tcp_seq ack_point);
1528 int
1529 tcp_req_is_entry_comp(struct tcpcb *tp, struct tcp_sendfile_track *ent, tcp_seq ack_point);
1530 struct tcp_sendfile_track *
1531 tcp_req_find_req_for_seq(struct tcpcb *tp, tcp_seq seq);
1532 void
1533 tcp_req_log_req_info(struct tcpcb *tp,
1534     struct tcp_sendfile_track *req, uint16_t slot,
1535     uint8_t val, uint64_t offset, uint64_t nbytes);
1536 
1537 uint32_t
1538 tcp_estimate_tls_overhead(struct socket *so, uint64_t tls_usr_bytes);
1539 void
1540 tcp_req_alloc_req(struct tcpcb *tp, union tcp_log_userdata *user,
1541     uint64_t ts);
1542 
1543 struct tcp_sendfile_track *
1544 tcp_req_alloc_req_full(struct tcpcb *tp, struct tcp_snd_req *req, uint64_t ts, int rec_dups);
1545 
1546 
1547 #endif
1548 #ifdef TCP_ACCOUNTING
1549 int tcp_do_ack_accounting(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to, uint32_t tiwin, int mss);
1550 #endif
1551 
1552 static inline void
1553 tcp_lro_features_off(struct tcpcb *tp)
1554 {
1555 	tp->t_flags2 &= ~(TF2_SUPPORTS_MBUFQ|
1556 	    TF2_MBUF_QUEUE_READY|
1557 	    TF2_DONT_SACK_QUEUE|
1558 	    TF2_MBUF_ACKCMP|
1559 	    TF2_MBUF_L_ACKS);
1560 }
1561 
1562 static inline void
1563 tcp_fields_to_host(struct tcphdr *th)
1564 {
1565 
1566 	th->th_seq = ntohl(th->th_seq);
1567 	th->th_ack = ntohl(th->th_ack);
1568 	th->th_win = ntohs(th->th_win);
1569 	th->th_urp = ntohs(th->th_urp);
1570 }
1571 
1572 static inline void
1573 tcp_fields_to_net(struct tcphdr *th)
1574 {
1575 
1576 	th->th_seq = htonl(th->th_seq);
1577 	th->th_ack = htonl(th->th_ack);
1578 	th->th_win = htons(th->th_win);
1579 	th->th_urp = htons(th->th_urp);
1580 }
1581 
1582 static inline uint16_t
1583 tcp_get_flags(const struct tcphdr *th)
1584 {
1585         return (((uint16_t)th->th_x2 << 8) | th->th_flags);
1586 }
1587 
1588 static inline void
1589 tcp_set_flags(struct tcphdr *th, uint16_t flags)
1590 {
1591         th->th_x2    = (flags >> 8) & 0x0f;
1592         th->th_flags = flags & 0xff;
1593 }
1594 
1595 static inline void
1596 tcp_account_for_send(struct tcpcb *tp, uint32_t len, uint8_t is_rxt,
1597     uint8_t is_tlp, bool hw_tls)
1598 {
1599 	if (is_tlp) {
1600 		tp->t_sndtlppack++;
1601 		tp->t_sndtlpbyte += len;
1602 	}
1603 	/* To get total bytes sent you must add t_snd_rxt_bytes to t_sndbytes */
1604 	if (is_rxt)
1605 		tp->t_snd_rxt_bytes += len;
1606 	else
1607 		tp->t_sndbytes += len;
1608 
1609 #ifdef KERN_TLS
1610 	if (hw_tls && is_rxt && len != 0) {
1611 		uint64_t rexmit_percent = (1000ULL * tp->t_snd_rxt_bytes) / (10ULL * (tp->t_snd_rxt_bytes + tp->t_sndbytes));
1612 		if (rexmit_percent > ktls_ifnet_max_rexmit_pct)
1613 			ktls_disable_ifnet(tp);
1614 	}
1615 #endif
1616 
1617 }
1618 #endif /* _KERNEL */
1619 
1620 #endif /* _NETINET_TCP_VAR_H_ */
1621