xref: /freebsd/sys/netinet/tcp_var.h (revision 9eb0e8326d0fe73ae947959c1df327238d3b2d53)
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  * $FreeBSD$
33  */
34 
35 #ifndef _NETINET_TCP_VAR_H_
36 #define _NETINET_TCP_VAR_H_
37 
38 #include <netinet/tcp.h>
39 #include <netinet/tcp_fsm.h>
40 
41 #ifdef _KERNEL
42 #include "opt_kern_tls.h"
43 #include <net/vnet.h>
44 #include <sys/mbuf.h>
45 #include <sys/ktls.h>
46 #endif
47 
48 #define TCP_END_BYTE_INFO 8	/* Bytes that makeup the "end information array" */
49 /* Types of ending byte info */
50 #define TCP_EI_EMPTY_SLOT	0
51 #define TCP_EI_STATUS_CLIENT_FIN	0x1
52 #define TCP_EI_STATUS_CLIENT_RST	0x2
53 #define TCP_EI_STATUS_SERVER_FIN	0x3
54 #define TCP_EI_STATUS_SERVER_RST	0x4
55 #define TCP_EI_STATUS_RETRAN		0x5
56 #define TCP_EI_STATUS_PROGRESS		0x6
57 #define TCP_EI_STATUS_PERSIST_MAX	0x7
58 #define TCP_EI_STATUS_KEEP_MAX		0x8
59 #define TCP_EI_STATUS_DATA_A_CLOSE	0x9
60 #define TCP_EI_STATUS_RST_IN_FRONT	0xa
61 #define TCP_EI_STATUS_2MSL		0xb
62 #define TCP_EI_STATUS_MAX_VALUE		0xb
63 
64 /************************************************/
65 /* Status bits we track to assure no duplicates,
66  * the bits here are not used by the code but
67  * for human representation. To check a bit we
68  * take and shift over by 1 minus the value (1-8).
69  */
70 /************************************************/
71 #define TCP_EI_BITS_CLIENT_FIN	0x001
72 #define TCP_EI_BITS_CLIENT_RST	0x002
73 #define TCP_EI_BITS_SERVER_FIN	0x004
74 #define TCP_EI_BITS_SERVER_RST	0x008
75 #define TCP_EI_BITS_RETRAN	0x010
76 #define TCP_EI_BITS_PROGRESS	0x020
77 #define TCP_EI_BITS_PRESIST_MAX	0x040
78 #define TCP_EI_BITS_KEEP_MAX	0x080
79 #define TCP_EI_BITS_DATA_A_CLO  0x100
80 #define TCP_EI_BITS_RST_IN_FR	0x200	/* a front state reset */
81 #define TCP_EI_BITS_2MS_TIMER	0x400	/* 2 MSL timer expired */
82 
83 #if defined(_KERNEL) || defined(_WANT_TCPCB)
84 /* TCP segment queue entry */
85 struct tseg_qent {
86 	TAILQ_ENTRY(tseg_qent) tqe_q;
87 	struct	mbuf   *tqe_m;		/* mbuf contains packet */
88 	struct  mbuf   *tqe_last;	/* last mbuf in chain */
89 	tcp_seq tqe_start;		/* TCP Sequence number start */
90 	int	tqe_len;		/* TCP segment data length */
91 	uint32_t tqe_flags;		/* The flags from tcp_get_flags() */
92 	uint32_t tqe_mbuf_cnt;		/* Count of mbuf overhead */
93 };
94 TAILQ_HEAD(tsegqe_head, tseg_qent);
95 
96 struct sackblk {
97 	tcp_seq start;		/* start seq no. of sack block */
98 	tcp_seq end;		/* end seq no. */
99 };
100 
101 struct sackhole {
102 	tcp_seq start;		/* start seq no. of hole */
103 	tcp_seq end;		/* end seq no. */
104 	tcp_seq rxmit;		/* next seq. no in hole to be retransmitted */
105 	TAILQ_ENTRY(sackhole) scblink;	/* scoreboard linkage */
106 };
107 
108 struct sackhint {
109 	struct sackhole	*nexthole;
110 	int32_t		sack_bytes_rexmit;
111 	tcp_seq		last_sack_ack;	/* Most recent/largest sacked ack */
112 
113 	int32_t		delivered_data; /* Newly acked data from last SACK */
114 
115 	int32_t		sacked_bytes;	/* Total sacked bytes reported by the
116 					 * receiver via sack option
117 					 */
118 	uint32_t	recover_fs;	/* Flight Size at the start of Loss recovery */
119 	uint32_t	prr_delivered;	/* Total bytes delivered using PRR */
120 	uint32_t	prr_out;	/* Bytes sent during IN_RECOVERY */
121 };
122 
123 #define SEGQ_EMPTY(tp) TAILQ_EMPTY(&(tp)->t_segq)
124 
125 STAILQ_HEAD(tcp_log_stailq, tcp_log_mem);
126 
127 /*
128  * Tcp control block, one per tcp; fields:
129  * Organized for 64 byte cacheline efficiency based
130  * on common tcp_input/tcp_output processing.
131  */
132 struct tcpcb {
133 	/* Cache line 1 */
134 	struct	inpcb *t_inpcb;		/* back pointer to internet pcb */
135 	struct tcp_function_block *t_fb;/* TCP function call block */
136 	void	*t_fb_ptr;		/* Pointer to t_fb specific data */
137 	uint32_t t_maxseg:24,		/* maximum segment size */
138 		t_logstate:8;		/* State of "black box" logging */
139 	uint32_t t_port:16,		/* Tunneling (over udp) port */
140 		t_state:4,		/* state of this connection */
141 		t_idle_reduce : 1,
142 		t_delayed_ack: 7,	/* Delayed ack variable */
143 		t_fin_is_rst: 1,	/* Are fin's treated as resets */
144 		t_log_state_set: 1,
145 		bits_spare : 2;
146 	u_int	t_flags;
147 	tcp_seq	snd_una;		/* sent but unacknowledged */
148 	tcp_seq	snd_max;		/* highest sequence number sent;
149 					 * used to recognize retransmits
150 					 */
151 	tcp_seq snd_nxt;		/* send next */
152 	tcp_seq snd_up;			/* send urgent pointer */
153 	uint32_t snd_wnd;		/* send window */
154 	uint32_t snd_cwnd;		/* congestion-controlled window */
155 	uint32_t t_peakrate_thr; 	/* pre-calculated peak rate threshold */
156 	/* Cache line 2 */
157 	uint32_t ts_offset;		/* our timestamp offset */
158 	uint32_t rfbuf_ts;		/* recv buffer autoscaling timestamp */
159 	int	rcv_numsacks;		/* # distinct sack blks present */
160 	u_int	t_tsomax;		/* TSO total burst length limit */
161 	u_int	t_tsomaxsegcount;	/* TSO maximum segment count */
162 	u_int	t_tsomaxsegsize;	/* TSO maximum segment size in bytes */
163 	tcp_seq	rcv_nxt;		/* receive next */
164 	tcp_seq	rcv_adv;		/* advertised window */
165 	uint32_t rcv_wnd;		/* receive window */
166 	u_int	t_flags2;		/* More tcpcb flags storage */
167 	int	t_srtt;			/* smoothed round-trip time */
168 	int	t_rttvar;		/* variance in round-trip time */
169 	uint32_t ts_recent;		/* timestamp echo data */
170 	u_char	snd_scale;		/* window scaling for send window */
171 	u_char	rcv_scale;		/* window scaling for recv window */
172 	u_char	snd_limited;		/* segments limited transmitted */
173 	u_char	request_r_scale;	/* pending window scaling */
174 	tcp_seq	last_ack_sent;
175 	u_int	t_rcvtime;		/* inactivity time */
176 	/* Cache line 3 */
177 	tcp_seq	rcv_up;			/* receive urgent pointer */
178 	int	t_segqlen;		/* segment reassembly queue length */
179 	uint32_t t_segqmbuflen;		/* total reassembly queue byte length */
180 	struct	tsegqe_head t_segq;	/* segment reassembly queue */
181 	struct mbuf *t_in_pkt;
182 	struct mbuf *t_tail_pkt;
183 	struct tcp_timer *t_timers;	/* All the TCP timers in one struct */
184 	struct	vnet *t_vnet;		/* back pointer to parent vnet */
185 	uint32_t snd_ssthresh;		/* snd_cwnd size threshold for
186 					 * for slow start exponential to
187 					 * linear switch
188 					 */
189 	tcp_seq	snd_wl1;		/* window update seg seq number */
190 	/* Cache line 4 */
191 	tcp_seq	snd_wl2;		/* window update seg ack number */
192 
193 	tcp_seq	irs;			/* initial receive sequence number */
194 	tcp_seq	iss;			/* initial send sequence number */
195 	u_int	t_acktime;		/* RACK and BBR incoming new data was acked */
196 	u_int	t_sndtime;		/* time last data was sent */
197 	u_int	ts_recent_age;		/* when last updated */
198 	tcp_seq	snd_recover;		/* for use in NewReno Fast Recovery */
199 	uint16_t cl4_spare;		/* Spare to adjust CL 4 */
200 	char	t_oobflags;		/* have some */
201 	char	t_iobc;			/* input character */
202 	int	t_rxtcur;		/* current retransmit value (ticks) */
203 
204 	int	t_rxtshift;		/* log(2) of rexmt exp. backoff */
205 	u_int	t_rtttime;		/* RTT measurement start time */
206 
207 	tcp_seq	t_rtseq;		/* sequence number being timed */
208 	u_int	t_starttime;		/* time connection was established */
209 	u_int	t_fbyte_in;		/* ticks time first byte queued in */
210 	u_int	t_fbyte_out;		/* ticks time first byte queued out */
211 
212 	u_int	t_pmtud_saved_maxseg;	/* pre-blackhole MSS */
213 	int	t_blackhole_enter;	/* when to enter blackhole detection */
214 	int	t_blackhole_exit;	/* when to exit blackhole detection */
215 	u_int	t_rttmin;		/* minimum rtt allowed */
216 
217 	u_int	t_rttbest;		/* best rtt we've seen */
218 
219 	int	t_softerror;		/* possible error not yet reported */
220 	uint32_t max_sndwnd;		/* largest window peer has offered */
221 	/* Cache line 5 */
222 	uint32_t snd_cwnd_prev;		/* cwnd prior to retransmit */
223 	uint32_t snd_ssthresh_prev;	/* ssthresh prior to retransmit */
224 	tcp_seq	snd_recover_prev;	/* snd_recover prior to retransmit */
225 	int	t_sndzerowin;		/* zero-window updates sent */
226 	u_long	t_rttupdated;		/* number of times rtt sampled */
227 	int	snd_numholes;		/* number of holes seen by sender */
228 	u_int	t_badrxtwin;		/* window for retransmit recovery */
229 	TAILQ_HEAD(sackhole_head, sackhole) snd_holes;
230 					/* SACK scoreboard (sorted) */
231 	tcp_seq	snd_fack;		/* last seq number(+1) sack'd by rcv'r*/
232 	struct sackblk sackblks[MAX_SACK_BLKS]; /* seq nos. of sack blocks */
233 	struct sackhint	sackhint;	/* SACK scoreboard hint */
234 	int	t_rttlow;		/* smallest observerved RTT */
235 	int	rfbuf_cnt;		/* recv buffer autoscaling byte count */
236 	struct toedev	*tod;		/* toedev handling this connection */
237 	int	t_sndrexmitpack;	/* retransmit packets sent */
238 	int	t_rcvoopack;		/* out-of-order packets received */
239 	void	*t_toe;			/* TOE pcb pointer */
240 	struct cc_algo	*cc_algo;	/* congestion control algorithm */
241 	struct cc_var	*ccv;		/* congestion control specific vars */
242 	struct osd	*osd;		/* storage for Khelp module data */
243 	int	t_bytes_acked;		/* # bytes acked during current RTT */
244 	u_int	t_maxunacktime;
245 	u_int	t_keepinit;		/* time to establish connection */
246 	u_int	t_keepidle;		/* time before keepalive probes begin */
247 	u_int	t_keepintvl;		/* interval between keepalives */
248 	u_int	t_keepcnt;		/* number of keepalives before close */
249 	int	t_dupacks;		/* consecutive dup acks recd */
250 	int	t_lognum;		/* Number of log entries */
251 	int	t_loglimit;		/* Maximum number of log entries */
252 	uint32_t t_rcep;		/* Number of received CE marked pkts */
253 	uint32_t t_scep;		/* Synced number of delivered CE pkts */
254 	int64_t	t_pacing_rate;		/* bytes / sec, -1 => unlimited */
255 	struct tcp_log_stailq t_logs;	/* Log buffer */
256 	struct tcp_log_id_node *t_lin;
257 	struct tcp_log_id_bucket *t_lib;
258 	const char *t_output_caller;	/* Function that called tcp_output */
259 	struct statsblob *t_stats;	/* Per-connection stats */
260 	uint32_t t_logsn;		/* Log "serial number" */
261 	uint32_t gput_ts;		/* Time goodput measurement started */
262 	tcp_seq gput_seq;		/* Outbound measurement seq */
263 	tcp_seq gput_ack;		/* Inbound measurement ack */
264 	int32_t t_stats_gput_prev;	/* XXXLAS: Prev gput measurement */
265 	uint32_t t_maxpeakrate;		/* max peak rate set by user, bytes/s */
266 	uint32_t t_sndtlppack;		/* tail loss probe packets sent */
267 	uint64_t t_sndtlpbyte;		/* total tail loss probe bytes sent */
268 	uint64_t t_sndbytes;		/* total bytes sent */
269 	uint64_t t_snd_rxt_bytes;	/* total bytes retransmitted */
270 	uint32_t t_dsack_bytes;		/* dsack bytes received */
271 	uint32_t t_dsack_tlp_bytes;	/* dsack bytes received for TLPs sent */
272 	uint32_t t_dsack_pack;		/* dsack packets we have eceived */
273 	/* TCP Fast Open */
274 	uint8_t t_tfo_client_cookie_len; /* TFO client cookie length */
275 	uint32_t t_end_info_status;	/* Status flag of end info */
276 	unsigned int *t_tfo_pending;	/* TFO server pending counter */
277 	union {
278 		uint8_t client[TCP_FASTOPEN_MAX_COOKIE_LEN];
279 		uint64_t server;
280 	} t_tfo_cookie;			/* TCP Fast Open cookie to send */
281 	union {
282 		uint8_t t_end_info_bytes[TCP_END_BYTE_INFO];
283 		uint64_t t_end_info;
284 	};
285 #ifdef TCPPCAP
286 	struct mbufq t_inpkts;		/* List of saved input packets. */
287 	struct mbufq t_outpkts;		/* List of saved output packets. */
288 #endif
289 };
290 #endif	/* _KERNEL || _WANT_TCPCB */
291 
292 #ifdef _KERNEL
293 struct tcptemp {
294 	u_char	tt_ipgen[40]; /* the size must be of max ip header, now IPv6 */
295 	struct	tcphdr tt_t;
296 };
297 
298 /* Enable TCP/UDP tunneling port */
299 #define TCP_TUNNELING_PORT_MIN		0
300 #define TCP_TUNNELING_PORT_MAX		65535
301 #define TCP_TUNNELING_PORT_DEFAULT	0
302 
303 /* Enable TCP/UDP tunneling port */
304 #define TCP_TUNNELING_OVERHEAD_MIN	sizeof(struct udphdr)
305 #define TCP_TUNNELING_OVERHEAD_MAX	1024
306 #define TCP_TUNNELING_OVERHEAD_DEFAULT	TCP_TUNNELING_OVERHEAD_MIN
307 
308 /* Minimum map entries limit value, if set */
309 #define TCP_MIN_MAP_ENTRIES_LIMIT	128
310 
311 /*
312  * TODO: We yet need to brave plowing in
313  * to tcp_input() and the pru_usrreq() block.
314  * Right now these go to the old standards which
315  * are somewhat ok, but in the long term may
316  * need to be changed. If we do tackle tcp_input()
317  * then we need to get rid of the tcp_do_segment()
318  * function below.
319  */
320 /* Flags for tcp functions */
321 #define	TCP_FUNC_BEING_REMOVED	0x01   	/* Can no longer be referenced */
322 #define	TCP_FUNC_OUTPUT_CANDROP	0x02   	/* tfb_tcp_output may ask tcp_drop */
323 
324 /*
325  * If defining the optional tcp_timers, in the
326  * tfb_tcp_timer_stop call you must use the
327  * callout_async_drain() function with the
328  * tcp_timer_discard callback. You should check
329  * the return of callout_async_drain() and if 0
330  * increment tt_draincnt. Since the timer sub-system
331  * does not know your callbacks you must provide a
332  * stop_all function that loops through and calls
333  * tcp_timer_stop() with each of your defined timers.
334  * Adding a tfb_tcp_handoff_ok function allows the socket
335  * option to change stacks to query you even if the
336  * connection is in a later stage. You return 0 to
337  * say you can take over and run your stack, you return
338  * non-zero (an error number) to say no you can't.
339  * If the function is undefined you can only change
340  * in the early states (before connect or listen).
341  * tfb_tcp_fb_fini is changed to add a flag to tell
342  * the old stack if the tcb is being destroyed or
343  * not. A one in the flag means the TCB is being
344  * destroyed, a zero indicates its transitioning to
345  * another stack (via socket option).
346  */
347 struct tcp_function_block {
348 	char tfb_tcp_block_name[TCP_FUNCTION_NAME_LEN_MAX];
349 	int	(*tfb_tcp_output)(struct tcpcb *);
350 	int	(*tfb_tcp_output_wtime)(struct tcpcb *, const struct timeval *);
351 	void	(*tfb_tcp_do_segment)(struct mbuf *, struct tcphdr *,
352 			    struct socket *, struct tcpcb *,
353 		        int, int, uint8_t);
354 	int     (*tfb_do_queued_segments)(struct socket *, struct tcpcb *, int);
355 	int      (*tfb_do_segment_nounlock)(struct mbuf *, struct tcphdr *,
356 			    struct socket *, struct tcpcb *,
357 			    int, int, uint8_t,
358 			    int, struct timeval *);
359 	void	(*tfb_tcp_hpts_do_segment)(struct mbuf *, struct tcphdr *,
360 			    struct socket *, struct tcpcb *,
361 			    int, int, uint8_t,
362 			    int, struct timeval *);
363 	int     (*tfb_tcp_ctloutput)(struct inpcb *inp, struct sockopt *sopt);
364 	/* Optional memory allocation/free routine */
365 	int	(*tfb_tcp_fb_init)(struct tcpcb *);
366 	void	(*tfb_tcp_fb_fini)(struct tcpcb *, int);
367 	/* Optional timers, must define all if you define one */
368 	int	(*tfb_tcp_timer_stop_all)(struct tcpcb *);
369 	void	(*tfb_tcp_timer_activate)(struct tcpcb *,
370 			    uint32_t, u_int);
371 	int	(*tfb_tcp_timer_active)(struct tcpcb *, uint32_t);
372 	void	(*tfb_tcp_timer_stop)(struct tcpcb *, uint32_t);
373 	void	(*tfb_tcp_rexmit_tmr)(struct tcpcb *);
374 	int	(*tfb_tcp_handoff_ok)(struct tcpcb *);
375 	void	(*tfb_tcp_mtu_chg)(struct tcpcb *);
376 	int	(*tfb_pru_options)(struct tcpcb *, int);
377 	void	(*tfb_hwtls_change)(struct tcpcb *, int);
378 	int     (*tfb_compute_pipe)(struct tcpcb *tp);
379 	volatile uint32_t tfb_refcnt;
380 	uint32_t  tfb_flags;
381 	uint8_t	tfb_id;
382 };
383 
384 struct tcp_function {
385 	TAILQ_ENTRY(tcp_function)	tf_next;
386 	char				tf_name[TCP_FUNCTION_NAME_LEN_MAX];
387 	struct tcp_function_block	*tf_fb;
388 };
389 
390 TAILQ_HEAD(tcp_funchead, tcp_function);
391 
392 struct tcpcb * tcp_drop(struct tcpcb *, int);
393 
394 #ifdef _NETINET_IN_PCB_H_
395 #define	intotcpcb(inp)	((struct tcpcb *)(inp)->inp_ppcb)
396 #define	sototcpcb(so)	intotcpcb(sotoinpcb(so))
397 #define	tptoinpcb(tp)	tp->t_inpcb
398 #define	tptosocket(tp)	tp->t_inpcb->inp_socket
399 
400 /*
401  * tcp_output()
402  * Handles tcp_drop request from advanced stacks and reports that inpcb is
403  * gone with negative return code.
404  * Drop in replacement for the default stack.
405  */
406 static inline int
407 tcp_output(struct tcpcb *tp)
408 {
409 	struct inpcb *inp = tptoinpcb(tp);
410 	int rv;
411 
412 	INP_WLOCK_ASSERT(inp);
413 
414 	rv = tp->t_fb->tfb_tcp_output(tp);
415 	if (rv < 0) {
416 		KASSERT(tp->t_fb->tfb_flags & TCP_FUNC_OUTPUT_CANDROP,
417 		    ("TCP stack %s requested tcp_drop(%p)",
418 		    tp->t_fb->tfb_tcp_block_name, tp));
419 		tp = tcp_drop(tp, -rv);
420 		if (tp)
421 			INP_WUNLOCK(inp);
422 	}
423 
424 	return (rv);
425 }
426 
427 /*
428  * tcp_output_unlock()
429  * Always returns unlocked, handles drop request from advanced stacks.
430  * Always returns positive error code.
431  */
432 static inline int
433 tcp_output_unlock(struct tcpcb *tp)
434 {
435 	struct inpcb *inp = tptoinpcb(tp);
436 	int rv;
437 
438 	INP_WLOCK_ASSERT(inp);
439 
440 	rv = tp->t_fb->tfb_tcp_output(tp);
441 	if (rv < 0) {
442 		KASSERT(tp->t_fb->tfb_flags & TCP_FUNC_OUTPUT_CANDROP,
443 		    ("TCP stack %s requested tcp_drop(%p)",
444 		    tp->t_fb->tfb_tcp_block_name, tp));
445 		rv = -rv;
446 		tp = tcp_drop(tp, rv);
447 		if (tp)
448 			INP_WUNLOCK(inp);
449 	} else
450 		INP_WUNLOCK(inp);
451 
452 	return (rv);
453 }
454 
455 /*
456  * tcp_output_nodrop()
457  * Always returns locked.  It is caller's responsibility to run tcp_drop()!
458  * Useful in syscall implementations, when we want to perform some logging
459  * and/or tracing with tcpcb before calling tcp_drop().  To be used with
460  * tcp_unlock_or_drop() later.
461  *
462  * XXXGL: maybe don't allow stacks to return a drop request at certain
463  * TCP states? Why would it do in connect(2)? In recv(2)?
464  */
465 static inline int
466 tcp_output_nodrop(struct tcpcb *tp)
467 {
468 	int rv;
469 
470 	INP_WLOCK_ASSERT(tptoinpcb(tp));
471 
472 	rv = tp->t_fb->tfb_tcp_output(tp);
473 	KASSERT(rv >= 0 || tp->t_fb->tfb_flags & TCP_FUNC_OUTPUT_CANDROP,
474 	    ("TCP stack %s requested tcp_drop(%p)",
475 	    tp->t_fb->tfb_tcp_block_name, tp));
476 	return (rv);
477 }
478 
479 /*
480  * tcp_unlock_or_drop()
481  * Handle return code from tfb_tcp_output() after we have logged/traced,
482  * to be used with tcp_output_nodrop().
483  */
484 static inline int
485 tcp_unlock_or_drop(struct tcpcb *tp, int tcp_output_retval)
486 {
487 	struct inpcb *inp = tptoinpcb(tp);
488 
489 	INP_WLOCK_ASSERT(inp);
490 
491         if (tcp_output_retval < 0) {
492                 tcp_output_retval = -tcp_output_retval;
493                 if (tcp_drop(tp, tcp_output_retval) != NULL)
494                         INP_WUNLOCK(inp);
495         } else
496 		INP_WUNLOCK(inp);
497 
498 	return (tcp_output_retval);
499 }
500 #endif	/* _NETINET_IN_PCB_H_ */
501 
502 static int inline
503 tcp_packets_this_ack(struct tcpcb *tp, tcp_seq ack)
504 {
505 	return ((ack - tp->snd_una) / tp->t_maxseg +
506 		((((ack - tp->snd_una) % tp->t_maxseg) != 0) ? 1 : 0));
507 }
508 #endif	/* _KERNEL */
509 
510 /*
511  * Flags and utility macros for the t_flags field.
512  */
513 #define	TF_ACKNOW	0x00000001	/* ack peer immediately */
514 #define	TF_DELACK	0x00000002	/* ack, but try to delay it */
515 #define	TF_NODELAY	0x00000004	/* don't delay packets to coalesce */
516 #define	TF_NOOPT	0x00000008	/* don't use tcp options */
517 #define	TF_SENTFIN	0x00000010	/* have sent FIN */
518 #define	TF_REQ_SCALE	0x00000020	/* have/will request window scaling */
519 #define	TF_RCVD_SCALE	0x00000040	/* other side has requested scaling */
520 #define	TF_REQ_TSTMP	0x00000080	/* have/will request timestamps */
521 #define	TF_RCVD_TSTMP	0x00000100	/* a timestamp was received in SYN */
522 #define	TF_SACK_PERMIT	0x00000200	/* other side said I could SACK */
523 #define	TF_NEEDSYN	0x00000400	/* send SYN (implicit state) */
524 #define	TF_NEEDFIN	0x00000800	/* send FIN (implicit state) */
525 #define	TF_NOPUSH	0x00001000	/* don't push */
526 #define	TF_PREVVALID	0x00002000	/* saved values for bad rxmit valid
527 					 * Note: accessing and restoring from
528 					 * these may only be done in the 1st
529 					 * RTO recovery round (t_rxtshift == 1)
530 					 */
531 #define	TF_WAKESOR	0x00004000	/* wake up receive socket */
532 #define	TF_GPUTINPROG	0x00008000	/* Goodput measurement in progress */
533 #define	TF_MORETOCOME	0x00010000	/* More data to be appended to sock */
534 #define	TF_SONOTCONN	0x00020000	/* needs soisconnected() on ESTAB */
535 #define	TF_LASTIDLE	0x00040000	/* connection was previously idle */
536 #define	TF_RXWIN0SENT	0x00080000	/* sent a receiver win 0 in response */
537 #define	TF_FASTRECOVERY	0x00100000	/* in NewReno Fast Recovery */
538 #define	TF_WASFRECOVERY	0x00200000	/* was in NewReno Fast Recovery */
539 #define	TF_SIGNATURE	0x00400000	/* require MD5 digests (RFC2385) */
540 #define	TF_FORCEDATA	0x00800000	/* force out a byte */
541 #define	TF_TSO		0x01000000	/* TSO enabled on this connection */
542 #define	TF_TOE		0x02000000	/* this connection is offloaded */
543 #define	TF_CLOSED	0x04000000	/* close(2) called on socket */
544 #define	TF_UNUSED1	0x08000000	/* unused */
545 #define	TF_LRD		0x10000000	/* Lost Retransmission Detection */
546 #define	TF_CONGRECOVERY	0x20000000	/* congestion recovery mode */
547 #define	TF_WASCRECOVERY	0x40000000	/* was in congestion recovery */
548 #define	TF_FASTOPEN	0x80000000	/* TCP Fast Open indication */
549 
550 #define	IN_FASTRECOVERY(t_flags)	(t_flags & TF_FASTRECOVERY)
551 #define	ENTER_FASTRECOVERY(t_flags)	t_flags |= TF_FASTRECOVERY
552 #define	EXIT_FASTRECOVERY(t_flags)	t_flags &= ~TF_FASTRECOVERY
553 
554 #define	IN_CONGRECOVERY(t_flags)	(t_flags & TF_CONGRECOVERY)
555 #define	ENTER_CONGRECOVERY(t_flags)	t_flags |= TF_CONGRECOVERY
556 #define	EXIT_CONGRECOVERY(t_flags)	t_flags &= ~TF_CONGRECOVERY
557 
558 #define	IN_RECOVERY(t_flags) (t_flags & (TF_CONGRECOVERY | TF_FASTRECOVERY))
559 #define	ENTER_RECOVERY(t_flags) t_flags |= (TF_CONGRECOVERY | TF_FASTRECOVERY)
560 #define	EXIT_RECOVERY(t_flags) t_flags &= ~(TF_CONGRECOVERY | TF_FASTRECOVERY)
561 
562 #if defined(_KERNEL) && !defined(TCP_RFC7413)
563 #define	IS_FASTOPEN(t_flags)		(false)
564 #else
565 #define	IS_FASTOPEN(t_flags)		(t_flags & TF_FASTOPEN)
566 #endif
567 
568 #define	BYTES_THIS_ACK(tp, th)	(th->th_ack - tp->snd_una)
569 
570 /*
571  * Flags for the t_oobflags field.
572  */
573 #define	TCPOOB_HAVEDATA	0x01
574 #define	TCPOOB_HADDATA	0x02
575 
576 /*
577  * Flags for the extended TCP flags field, t_flags2
578  */
579 #define	TF2_PLPMTU_BLACKHOLE	0x00000001 /* Possible PLPMTUD Black Hole. */
580 #define	TF2_PLPMTU_PMTUD	0x00000002 /* Allowed to attempt PLPMTUD. */
581 #define	TF2_PLPMTU_MAXSEGSNT	0x00000004 /* Last seg sent was full seg. */
582 #define	TF2_LOG_AUTO		0x00000008 /* Session is auto-logging. */
583 #define	TF2_DROP_AF_DATA	0x00000010 /* Drop after all data ack'd */
584 #define	TF2_ECN_PERMIT		0x00000020 /* connection ECN-ready */
585 #define	TF2_ECN_SND_CWR		0x00000040 /* ECN CWR in queue */
586 #define	TF2_ECN_SND_ECE		0x00000080 /* ECN ECE in queue */
587 #define	TF2_ACE_PERMIT		0x00000100 /* Accurate ECN mode */
588 #define	TF2_FBYTES_COMPLETE	0x00000400 /* We have first bytes in and out */
589 #define	TF2_ECN_USE_ECT1	0x00000800 /* Use ECT(1) marking on session */
590 
591 /*
592  * Structure to hold TCP options that are only used during segment
593  * processing (in tcp_input), but not held in the tcpcb.
594  * It's basically used to reduce the number of parameters
595  * to tcp_dooptions and tcp_addoptions.
596  * The binary order of the to_flags is relevant for packing of the
597  * options in tcp_addoptions.
598  */
599 struct tcpopt {
600 	u_int32_t	to_flags;	/* which options are present */
601 #define	TOF_MSS		0x0001		/* maximum segment size */
602 #define	TOF_SCALE	0x0002		/* window scaling */
603 #define	TOF_SACKPERM	0x0004		/* SACK permitted */
604 #define	TOF_TS		0x0010		/* timestamp */
605 #define	TOF_SIGNATURE	0x0040		/* TCP-MD5 signature option (RFC2385) */
606 #define	TOF_SACK	0x0080		/* Peer sent SACK option */
607 #define	TOF_FASTOPEN	0x0100		/* TCP Fast Open (TFO) cookie */
608 #define	TOF_MAXOPT	0x0200
609 	u_int32_t	to_tsval;	/* new timestamp */
610 	u_int32_t	to_tsecr;	/* reflected timestamp */
611 	u_char		*to_sacks;	/* pointer to the first SACK blocks */
612 	u_char		*to_signature;	/* pointer to the TCP-MD5 signature */
613 	u_int8_t	*to_tfo_cookie; /* pointer to the TFO cookie */
614 	u_int16_t	to_mss;		/* maximum segment size */
615 	u_int8_t	to_wscale;	/* window scaling */
616 	u_int8_t	to_nsacks;	/* number of SACK blocks */
617 	u_int8_t	to_tfo_len;	/* TFO cookie length */
618 	u_int32_t	to_spare;	/* UTO */
619 };
620 
621 /*
622  * Flags for tcp_dooptions.
623  */
624 #define	TO_SYN		0x01		/* parse SYN-only options */
625 
626 struct hc_metrics_lite {	/* must stay in sync with hc_metrics */
627 	uint32_t	rmx_mtu;	/* MTU for this path */
628 	uint32_t	rmx_ssthresh;	/* outbound gateway buffer limit */
629 	uint32_t	rmx_rtt;	/* estimated round trip time */
630 	uint32_t	rmx_rttvar;	/* estimated rtt variance */
631 	uint32_t	rmx_cwnd;	/* congestion window */
632 	uint32_t	rmx_sendpipe;   /* outbound delay-bandwidth product */
633 	uint32_t	rmx_recvpipe;   /* inbound delay-bandwidth product */
634 };
635 
636 /*
637  * Used by tcp_maxmtu() to communicate interface specific features
638  * and limits at the time of connection setup.
639  */
640 struct tcp_ifcap {
641 	int	ifcap;
642 	u_int	tsomax;
643 	u_int	tsomaxsegcount;
644 	u_int	tsomaxsegsize;
645 };
646 
647 #ifndef _NETINET_IN_PCB_H_
648 struct in_conninfo;
649 #endif /* _NETINET_IN_PCB_H_ */
650 
651 /*
652  * The smoothed round-trip time and estimated variance
653  * are stored as fixed point numbers scaled by the values below.
654  * For convenience, these scales are also used in smoothing the average
655  * (smoothed = (1/scale)sample + ((scale-1)/scale)smoothed).
656  * With these scales, srtt has 3 bits to the right of the binary point,
657  * and thus an "ALPHA" of 0.875.  rttvar has 2 bits to the right of the
658  * binary point, and is smoothed with an ALPHA of 0.75.
659  */
660 #define	TCP_RTT_SCALE		32	/* multiplier for srtt; 3 bits frac. */
661 #define	TCP_RTT_SHIFT		5	/* shift for srtt; 3 bits frac. */
662 #define	TCP_RTTVAR_SCALE	16	/* multiplier for rttvar; 2 bits */
663 #define	TCP_RTTVAR_SHIFT	4	/* shift for rttvar; 2 bits */
664 #define	TCP_DELTA_SHIFT		2	/* see tcp_input.c */
665 
666 /*
667  * The initial retransmission should happen at rtt + 4 * rttvar.
668  * Because of the way we do the smoothing, srtt and rttvar
669  * will each average +1/2 tick of bias.  When we compute
670  * the retransmit timer, we want 1/2 tick of rounding and
671  * 1 extra tick because of +-1/2 tick uncertainty in the
672  * firing of the timer.  The bias will give us exactly the
673  * 1.5 tick we need.  But, because the bias is
674  * statistical, we have to test that we don't drop below
675  * the minimum feasible timer (which is 2 ticks).
676  * This version of the macro adapted from a paper by Lawrence
677  * Brakmo and Larry Peterson which outlines a problem caused
678  * by insufficient precision in the original implementation,
679  * which results in inappropriately large RTO values for very
680  * fast networks.
681  */
682 #define	TCP_REXMTVAL(tp) \
683 	max((tp)->t_rttmin, (((tp)->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT))  \
684 	  + (tp)->t_rttvar) >> TCP_DELTA_SHIFT)
685 
686 /*
687  * TCP statistics.
688  * Many of these should be kept per connection,
689  * but that's inconvenient at the moment.
690  */
691 struct	tcpstat {
692 	uint64_t tcps_connattempt;	/* connections initiated */
693 	uint64_t tcps_accepts;		/* connections accepted */
694 	uint64_t tcps_connects;		/* connections established */
695 	uint64_t tcps_drops;		/* connections dropped */
696 	uint64_t tcps_conndrops;	/* embryonic connections dropped */
697 	uint64_t tcps_minmssdrops;	/* average minmss too low drops */
698 	uint64_t tcps_closed;		/* conn. closed (includes drops) */
699 	uint64_t tcps_segstimed;	/* segs where we tried to get rtt */
700 	uint64_t tcps_rttupdated;	/* times we succeeded */
701 	uint64_t tcps_delack;		/* delayed acks sent */
702 	uint64_t tcps_timeoutdrop;	/* conn. dropped in rxmt timeout */
703 	uint64_t tcps_rexmttimeo;	/* retransmit timeouts */
704 	uint64_t tcps_persisttimeo;	/* persist timeouts */
705 	uint64_t tcps_keeptimeo;	/* keepalive timeouts */
706 	uint64_t tcps_keepprobe;	/* keepalive probes sent */
707 	uint64_t tcps_keepdrops;	/* connections dropped in keepalive */
708 	uint64_t tcps_progdrops;	/* drops due to no progress */
709 
710 	uint64_t tcps_sndtotal;		/* total packets sent */
711 	uint64_t tcps_sndpack;		/* data packets sent */
712 	uint64_t tcps_sndbyte;		/* data bytes sent */
713 	uint64_t tcps_sndrexmitpack;	/* data packets retransmitted */
714 	uint64_t tcps_sndrexmitbyte;	/* data bytes retransmitted */
715 	uint64_t tcps_sndrexmitbad;	/* unnecessary packet retransmissions */
716 	uint64_t tcps_sndacks;		/* ack-only packets sent */
717 	uint64_t tcps_sndprobe;		/* window probes sent */
718 	uint64_t tcps_sndurg;		/* packets sent with URG only */
719 	uint64_t tcps_sndwinup;		/* window update-only packets sent */
720 	uint64_t tcps_sndctrl;		/* control (SYN|FIN|RST) packets sent */
721 
722 	uint64_t tcps_rcvtotal;		/* total packets received */
723 	uint64_t tcps_rcvpack;		/* packets received in sequence */
724 	uint64_t tcps_rcvbyte;		/* bytes received in sequence */
725 	uint64_t tcps_rcvbadsum;	/* packets received with ccksum errs */
726 	uint64_t tcps_rcvbadoff;	/* packets received with bad offset */
727 	uint64_t tcps_rcvreassfull;	/* packets dropped for no reass space */
728 	uint64_t tcps_rcvshort;		/* packets received too short */
729 	uint64_t tcps_rcvduppack;	/* duplicate-only packets received */
730 	uint64_t tcps_rcvdupbyte;	/* duplicate-only bytes received */
731 	uint64_t tcps_rcvpartduppack;	/* packets with some duplicate data */
732 	uint64_t tcps_rcvpartdupbyte;	/* dup. bytes in part-dup. packets */
733 	uint64_t tcps_rcvoopack;	/* out-of-order packets received */
734 	uint64_t tcps_rcvoobyte;	/* out-of-order bytes received */
735 	uint64_t tcps_rcvpackafterwin;	/* packets with data after window */
736 	uint64_t tcps_rcvbyteafterwin;	/* bytes rcvd after window */
737 	uint64_t tcps_rcvafterclose;	/* packets rcvd after "close" */
738 	uint64_t tcps_rcvwinprobe;	/* rcvd window probe packets */
739 	uint64_t tcps_rcvdupack;	/* rcvd duplicate acks */
740 	uint64_t tcps_rcvacktoomuch;	/* rcvd acks for unsent data */
741 	uint64_t tcps_rcvackpack;	/* rcvd ack packets */
742 	uint64_t tcps_rcvackbyte;	/* bytes acked by rcvd acks */
743 	uint64_t tcps_rcvwinupd;	/* rcvd window update packets */
744 	uint64_t tcps_pawsdrop;		/* segments dropped due to PAWS */
745 	uint64_t tcps_predack;		/* times hdr predict ok for acks */
746 	uint64_t tcps_preddat;		/* times hdr predict ok for data pkts */
747 	uint64_t tcps_pcbcachemiss;
748 	uint64_t tcps_cachedrtt;	/* times cached RTT in route updated */
749 	uint64_t tcps_cachedrttvar;	/* times cached rttvar updated */
750 	uint64_t tcps_cachedssthresh;	/* times cached ssthresh updated */
751 	uint64_t tcps_usedrtt;		/* times RTT initialized from route */
752 	uint64_t tcps_usedrttvar;	/* times RTTVAR initialized from rt */
753 	uint64_t tcps_usedssthresh;	/* times ssthresh initialized from rt*/
754 	uint64_t tcps_persistdrop;	/* timeout in persist state */
755 	uint64_t tcps_badsyn;		/* bogus SYN, e.g. premature ACK */
756 	uint64_t tcps_mturesent;	/* resends due to MTU discovery */
757 	uint64_t tcps_listendrop;	/* listen queue overflows */
758 	uint64_t tcps_badrst;		/* ignored RSTs in the window */
759 
760 	uint64_t tcps_sc_added;		/* entry added to syncache */
761 	uint64_t tcps_sc_retransmitted;	/* syncache entry was retransmitted */
762 	uint64_t tcps_sc_dupsyn;	/* duplicate SYN packet */
763 	uint64_t tcps_sc_dropped;	/* could not reply to packet */
764 	uint64_t tcps_sc_completed;	/* successful extraction of entry */
765 	uint64_t tcps_sc_bucketoverflow;/* syncache per-bucket limit hit */
766 	uint64_t tcps_sc_cacheoverflow;	/* syncache cache limit hit */
767 	uint64_t tcps_sc_reset;		/* RST removed entry from syncache */
768 	uint64_t tcps_sc_stale;		/* timed out or listen socket gone */
769 	uint64_t tcps_sc_aborted;	/* syncache entry aborted */
770 	uint64_t tcps_sc_badack;	/* removed due to bad ACK */
771 	uint64_t tcps_sc_unreach;	/* ICMP unreachable received */
772 	uint64_t tcps_sc_zonefail;	/* zalloc() failed */
773 	uint64_t tcps_sc_sendcookie;	/* SYN cookie sent */
774 	uint64_t tcps_sc_recvcookie;	/* SYN cookie received */
775 
776 	uint64_t tcps_hc_added;		/* entry added to hostcache */
777 	uint64_t tcps_hc_bucketoverflow;/* hostcache per bucket limit hit */
778 
779 	uint64_t tcps_finwait2_drops;    /* Drop FIN_WAIT_2 connection after time limit */
780 
781 	/* SACK related stats */
782 	uint64_t tcps_sack_recovery_episode; /* SACK recovery episodes */
783 	uint64_t tcps_sack_rexmits;	    /* SACK rexmit segments   */
784 	uint64_t tcps_sack_rexmit_bytes;    /* SACK rexmit bytes      */
785 	uint64_t tcps_sack_rcv_blocks;	    /* SACK blocks (options) received */
786 	uint64_t tcps_sack_send_blocks;	    /* SACK blocks (options) sent     */
787 	uint64_t tcps_sack_lostrexmt;	    /* SACK lost retransmission recovered */
788 	uint64_t tcps_sack_sboverflow;	    /* times scoreboard overflowed */
789 
790 	/* ECN related stats */
791 	uint64_t tcps_ecn_ce;		/* ECN Congestion Experienced */
792 	uint64_t tcps_ecn_ect0;		/* ECN Capable Transport */
793 	uint64_t tcps_ecn_ect1;		/* ECN Capable Transport */
794 	uint64_t tcps_ecn_shs;		/* ECN successful handshakes */
795 	uint64_t tcps_ecn_rcwnd;	/* # times ECN reduced the cwnd */
796 
797 	/* TCP_SIGNATURE related stats */
798 	uint64_t tcps_sig_rcvgoodsig;	/* Total matching signature received */
799 	uint64_t tcps_sig_rcvbadsig;	/* Total bad signature received */
800 	uint64_t tcps_sig_err_buildsig;	/* Failed to make signature */
801 	uint64_t tcps_sig_err_sigopt;	/* No signature expected by socket */
802 	uint64_t tcps_sig_err_nosigopt;	/* No signature provided by segment */
803 
804 	/* Path MTU Discovery Black Hole Detection related stats */
805 	uint64_t tcps_pmtud_blackhole_activated;	 /* Black Hole Count */
806 	uint64_t tcps_pmtud_blackhole_activated_min_mss; /* BH at min MSS Count */
807 	uint64_t tcps_pmtud_blackhole_failed;		 /* Black Hole Failure Count */
808 
809 	uint64_t tcps_tunneled_pkts;	/* Packets encap's in UDP received */
810 	uint64_t tcps_tunneled_errs;	/* Packets that had errors that were UDP encaped */
811 
812 	/* Dsack related stats */
813 	uint64_t tcps_dsack_count;	/* Number of ACKs arriving with DSACKs */
814 	uint64_t tcps_dsack_bytes;	/* Number of bytes DSACK'ed no TLP */
815 	uint64_t tcps_dsack_tlp_bytes;	/* Number of bytes DSACK'ed due to TLPs */
816 
817 	/* TCPS_TIME_WAIT usage stats */
818 	uint64_t tcps_tw_recycles;	/* Times time-wait was recycled. */
819 	uint64_t tcps_tw_resets;	/* Times time-wait sent a reset. */
820 	uint64_t tcps_tw_responds;	/* Times time-wait sent a valid ack. */
821 
822 	/* Accurate ECN Handshake stats */
823 	uint64_t tcps_ace_nect;		/* ACE SYN packet with Non-ECT */
824 	uint64_t tcps_ace_ect1;		/* ACE SYN packet with ECT1 */
825 	uint64_t tcps_ace_ect0;		/* ACE SYN packet with ECT0 */
826 	uint64_t tcps_ace_ce;		/* ACE SYN packet with CE */
827 
828 	uint64_t _pad[6];		/* 6 TBD placeholder for STABLE */
829 };
830 
831 #define	tcps_rcvmemdrop	tcps_rcvreassfull	/* compat */
832 
833 #ifdef _KERNEL
834 #define	TI_UNLOCKED	1
835 #define	TI_RLOCKED	2
836 #include <sys/counter.h>
837 
838 VNET_PCPUSTAT_DECLARE(struct tcpstat, tcpstat);	/* tcp statistics */
839 /*
840  * In-kernel consumers can use these accessor macros directly to update
841  * stats.
842  */
843 #define	TCPSTAT_ADD(name, val)	\
844     VNET_PCPUSTAT_ADD(struct tcpstat, tcpstat, name, (val))
845 #define	TCPSTAT_INC(name)	TCPSTAT_ADD(name, 1)
846 
847 /*
848  * Kernel module consumers must use this accessor macro.
849  */
850 void	kmod_tcpstat_add(int statnum, int val);
851 #define	KMOD_TCPSTAT_ADD(name, val)					\
852     kmod_tcpstat_add(offsetof(struct tcpstat, name) / sizeof(uint64_t), val)
853 #define	KMOD_TCPSTAT_INC(name)	KMOD_TCPSTAT_ADD(name, 1)
854 
855 /*
856  * Running TCP connection count by state.
857  */
858 VNET_DECLARE(counter_u64_t, tcps_states[TCP_NSTATES]);
859 #define	V_tcps_states	VNET(tcps_states)
860 #define	TCPSTATES_INC(state)	counter_u64_add(V_tcps_states[state], 1)
861 #define	TCPSTATES_DEC(state)	counter_u64_add(V_tcps_states[state], -1)
862 
863 /*
864  * TCP specific helper hook point identifiers.
865  */
866 #define	HHOOK_TCP_EST_IN		0
867 #define	HHOOK_TCP_EST_OUT		1
868 #define	HHOOK_TCP_LAST			HHOOK_TCP_EST_OUT
869 
870 struct tcp_hhook_data {
871 	struct tcpcb	*tp;
872 	struct tcphdr	*th;
873 	struct tcpopt	*to;
874 	uint32_t	len;
875 	int		tso;
876 	tcp_seq		curack;
877 };
878 #ifdef TCP_HHOOK
879 void hhook_run_tcp_est_out(struct tcpcb *tp,
880 	struct tcphdr *th, struct tcpopt *to,
881 	uint32_t len, int tso);
882 #endif
883 #endif
884 
885 /*
886  * TCB structure exported to user-land via sysctl(3).
887  *
888  * Fields prefixed with "xt_" are unique to the export structure, and fields
889  * with "t_" or other prefixes match corresponding fields of 'struct tcpcb'.
890  *
891  * Legend:
892  * (s) - used by userland utilities in src
893  * (p) - used by utilities in ports
894  * (3) - is known to be used by third party software not in ports
895  * (n) - no known usage
896  *
897  * Evil hack: declare only if in_pcb.h and sys/socketvar.h have been
898  * included.  Not all of our clients do.
899  */
900 #if defined(_NETINET_IN_PCB_H_) && defined(_SYS_SOCKETVAR_H_)
901 struct xtcpcb {
902 	ksize_t	xt_len;		/* length of this structure */
903 	struct xinpcb	xt_inp;
904 	char		xt_stack[TCP_FUNCTION_NAME_LEN_MAX];	/* (s) */
905 	char		xt_logid[TCP_LOG_ID_LEN];	/* (s) */
906 	char		xt_cc[TCP_CA_NAME_MAX];	/* (s) */
907 	int64_t		spare64[6];
908 	int32_t		t_state;		/* (s,p) */
909 	uint32_t	t_flags;		/* (s,p) */
910 	int32_t		t_sndzerowin;		/* (s) */
911 	int32_t		t_sndrexmitpack;	/* (s) */
912 	int32_t		t_rcvoopack;		/* (s) */
913 	int32_t		t_rcvtime;		/* (s) */
914 	int32_t		tt_rexmt;		/* (s) */
915 	int32_t		tt_persist;		/* (s) */
916 	int32_t		tt_keep;		/* (s) */
917 	int32_t		tt_2msl;		/* (s) */
918 	int32_t		tt_delack;		/* (s) */
919 	int32_t		t_logstate;		/* (3) */
920 	uint32_t	t_snd_cwnd;		/* (s) */
921 	uint32_t	t_snd_ssthresh;		/* (s) */
922 	uint32_t	t_maxseg;		/* (s) */
923 	uint32_t	t_rcv_wnd;		/* (s) */
924 	uint32_t	t_snd_wnd;		/* (s) */
925 	uint32_t	xt_ecn;			/* (s) */
926 	uint32_t	t_dsack_bytes;		/* (n) */
927 	uint32_t	t_dsack_tlp_bytes;	/* (n) */
928 	uint32_t	t_dsack_pack;		/* (n) */
929 	uint16_t	xt_encaps_port;		/* (s) */
930 	int16_t		spare16;
931 	int32_t		spare32[22];
932 } __aligned(8);
933 
934 #ifdef _KERNEL
935 void	tcp_inptoxtp(const struct inpcb *, struct xtcpcb *);
936 #endif
937 #endif
938 
939 /*
940  * TCP function information (name-to-id mapping, aliases, and refcnt)
941  * exported to user-land via sysctl(3).
942  */
943 struct tcp_function_info {
944 	uint32_t	tfi_refcnt;
945 	uint8_t		tfi_id;
946 	char		tfi_name[TCP_FUNCTION_NAME_LEN_MAX];
947 	char		tfi_alias[TCP_FUNCTION_NAME_LEN_MAX];
948 };
949 
950 /*
951  * Identifiers for TCP sysctl nodes
952  */
953 #define	TCPCTL_DO_RFC1323	1	/* use RFC-1323 extensions */
954 #define	TCPCTL_MSSDFLT		3	/* MSS default */
955 #define TCPCTL_STATS		4	/* statistics */
956 #define	TCPCTL_RTTDFLT		5	/* default RTT estimate */
957 #define	TCPCTL_KEEPIDLE		6	/* keepalive idle timer */
958 #define	TCPCTL_KEEPINTVL	7	/* interval to send keepalives */
959 #define	TCPCTL_SENDSPACE	8	/* send buffer space */
960 #define	TCPCTL_RECVSPACE	9	/* receive buffer space */
961 #define	TCPCTL_KEEPINIT		10	/* timeout for establishing syn */
962 #define	TCPCTL_PCBLIST		11	/* list of all outstanding PCBs */
963 #define	TCPCTL_DELACKTIME	12	/* time before sending delayed ACK */
964 #define	TCPCTL_V6MSSDFLT	13	/* MSS default for IPv6 */
965 #define	TCPCTL_SACK		14	/* Selective Acknowledgement,rfc 2018 */
966 #define	TCPCTL_DROP		15	/* drop tcp connection */
967 #define	TCPCTL_STATES		16	/* connection counts by TCP state */
968 
969 #ifdef _KERNEL
970 #ifdef SYSCTL_DECL
971 SYSCTL_DECL(_net_inet_tcp);
972 SYSCTL_DECL(_net_inet_tcp_sack);
973 MALLOC_DECLARE(M_TCPLOG);
974 #endif
975 
976 VNET_DECLARE(int, tcp_log_in_vain);
977 #define	V_tcp_log_in_vain		VNET(tcp_log_in_vain)
978 
979 /*
980  * Global TCP tunables shared between different stacks.
981  * Please keep the list sorted.
982  */
983 VNET_DECLARE(int, drop_synfin);
984 VNET_DECLARE(int, path_mtu_discovery);
985 VNET_DECLARE(int, tcp_abc_l_var);
986 VNET_DECLARE(int, tcp_autorcvbuf_max);
987 VNET_DECLARE(int, tcp_autosndbuf_inc);
988 VNET_DECLARE(int, tcp_autosndbuf_max);
989 VNET_DECLARE(int, tcp_delack_enabled);
990 VNET_DECLARE(int, tcp_do_autorcvbuf);
991 VNET_DECLARE(int, tcp_do_autosndbuf);
992 VNET_DECLARE(int, tcp_do_ecn);
993 VNET_DECLARE(int, tcp_do_lrd);
994 VNET_DECLARE(int, tcp_do_prr);
995 VNET_DECLARE(int, tcp_do_prr_conservative);
996 VNET_DECLARE(int, tcp_do_newcwv);
997 VNET_DECLARE(int, tcp_do_rfc1323);
998 VNET_DECLARE(int, tcp_tolerate_missing_ts);
999 VNET_DECLARE(int, tcp_do_rfc3042);
1000 VNET_DECLARE(int, tcp_do_rfc3390);
1001 VNET_DECLARE(int, tcp_do_rfc3465);
1002 VNET_DECLARE(int, tcp_do_newsack);
1003 VNET_DECLARE(int, tcp_do_sack);
1004 VNET_DECLARE(int, tcp_do_tso);
1005 VNET_DECLARE(int, tcp_ecn_maxretries);
1006 VNET_DECLARE(int, tcp_initcwnd_segments);
1007 VNET_DECLARE(int, tcp_insecure_rst);
1008 VNET_DECLARE(int, tcp_insecure_syn);
1009 VNET_DECLARE(uint32_t, tcp_map_entries_limit);
1010 VNET_DECLARE(uint32_t, tcp_map_split_limit);
1011 VNET_DECLARE(int, tcp_minmss);
1012 VNET_DECLARE(int, tcp_mssdflt);
1013 #ifdef STATS
1014 VNET_DECLARE(int, tcp_perconn_stats_dflt_tpl);
1015 VNET_DECLARE(int, tcp_perconn_stats_enable);
1016 #endif /* STATS */
1017 VNET_DECLARE(int, tcp_recvspace);
1018 VNET_DECLARE(int, tcp_sack_globalholes);
1019 VNET_DECLARE(int, tcp_sack_globalmaxholes);
1020 VNET_DECLARE(int, tcp_sack_maxholes);
1021 VNET_DECLARE(int, tcp_sc_rst_sock_fail);
1022 VNET_DECLARE(int, tcp_sendspace);
1023 VNET_DECLARE(int, tcp_udp_tunneling_overhead);
1024 VNET_DECLARE(int, tcp_udp_tunneling_port);
1025 VNET_DECLARE(struct inpcbinfo, tcbinfo);
1026 
1027 #define	V_tcp_do_lrd			VNET(tcp_do_lrd)
1028 #define	V_tcp_do_prr			VNET(tcp_do_prr)
1029 #define	V_tcp_do_prr_conservative	VNET(tcp_do_prr_conservative)
1030 #define	V_tcp_do_newcwv			VNET(tcp_do_newcwv)
1031 #define	V_drop_synfin			VNET(drop_synfin)
1032 #define	V_path_mtu_discovery		VNET(path_mtu_discovery)
1033 #define	V_tcbinfo			VNET(tcbinfo)
1034 #define	V_tcp_abc_l_var			VNET(tcp_abc_l_var)
1035 #define	V_tcp_autorcvbuf_max		VNET(tcp_autorcvbuf_max)
1036 #define	V_tcp_autosndbuf_inc		VNET(tcp_autosndbuf_inc)
1037 #define	V_tcp_autosndbuf_max		VNET(tcp_autosndbuf_max)
1038 #define	V_tcp_delack_enabled		VNET(tcp_delack_enabled)
1039 #define	V_tcp_do_autorcvbuf		VNET(tcp_do_autorcvbuf)
1040 #define	V_tcp_do_autosndbuf		VNET(tcp_do_autosndbuf)
1041 #define	V_tcp_do_ecn			VNET(tcp_do_ecn)
1042 #define	V_tcp_do_rfc1323		VNET(tcp_do_rfc1323)
1043 #define	V_tcp_tolerate_missing_ts	VNET(tcp_tolerate_missing_ts)
1044 #define V_tcp_ts_offset_per_conn	VNET(tcp_ts_offset_per_conn)
1045 #define	V_tcp_do_rfc3042		VNET(tcp_do_rfc3042)
1046 #define	V_tcp_do_rfc3390		VNET(tcp_do_rfc3390)
1047 #define	V_tcp_do_rfc3465		VNET(tcp_do_rfc3465)
1048 #define	V_tcp_do_newsack		VNET(tcp_do_newsack)
1049 #define	V_tcp_do_sack			VNET(tcp_do_sack)
1050 #define	V_tcp_do_tso			VNET(tcp_do_tso)
1051 #define	V_tcp_ecn_maxretries		VNET(tcp_ecn_maxretries)
1052 #define	V_tcp_initcwnd_segments		VNET(tcp_initcwnd_segments)
1053 #define	V_tcp_insecure_rst		VNET(tcp_insecure_rst)
1054 #define	V_tcp_insecure_syn		VNET(tcp_insecure_syn)
1055 #define	V_tcp_map_entries_limit		VNET(tcp_map_entries_limit)
1056 #define	V_tcp_map_split_limit		VNET(tcp_map_split_limit)
1057 #define	V_tcp_minmss			VNET(tcp_minmss)
1058 #define	V_tcp_mssdflt			VNET(tcp_mssdflt)
1059 #ifdef STATS
1060 #define	V_tcp_perconn_stats_dflt_tpl	VNET(tcp_perconn_stats_dflt_tpl)
1061 #define	V_tcp_perconn_stats_enable	VNET(tcp_perconn_stats_enable)
1062 #endif /* STATS */
1063 #define	V_tcp_recvspace			VNET(tcp_recvspace)
1064 #define	V_tcp_sack_globalholes		VNET(tcp_sack_globalholes)
1065 #define	V_tcp_sack_globalmaxholes	VNET(tcp_sack_globalmaxholes)
1066 #define	V_tcp_sack_maxholes		VNET(tcp_sack_maxholes)
1067 #define	V_tcp_sc_rst_sock_fail		VNET(tcp_sc_rst_sock_fail)
1068 #define	V_tcp_sendspace			VNET(tcp_sendspace)
1069 #define	V_tcp_udp_tunneling_overhead	VNET(tcp_udp_tunneling_overhead)
1070 #define	V_tcp_udp_tunneling_port	VNET(tcp_udp_tunneling_port)
1071 
1072 #ifdef TCP_HHOOK
1073 VNET_DECLARE(struct hhook_head *, tcp_hhh[HHOOK_TCP_LAST + 1]);
1074 #define	V_tcp_hhh		VNET(tcp_hhh)
1075 #endif
1076 
1077 int	 tcp_addoptions(struct tcpopt *, u_char *);
1078 struct tcpcb *
1079 	 tcp_close(struct tcpcb *);
1080 void	 tcp_discardcb(struct tcpcb *);
1081 bool	 tcp_freecb(struct tcpcb *);
1082 void	 tcp_twstart(struct tcpcb *);
1083 int	 tcp_ctloutput(struct socket *, struct sockopt *);
1084 void	 tcp_fini(void *);
1085 char	*tcp_log_addrs(struct in_conninfo *, struct tcphdr *, const void *,
1086 	    const void *);
1087 char	*tcp_log_vain(struct in_conninfo *, struct tcphdr *, const void *,
1088 	    const void *);
1089 int	 tcp_reass(struct tcpcb *, struct tcphdr *, tcp_seq *, int *,
1090 	    struct mbuf *);
1091 void	 tcp_reass_global_init(void);
1092 void	 tcp_reass_flush(struct tcpcb *);
1093 void	 tcp_dooptions(struct tcpopt *, u_char *, int, int);
1094 void	tcp_dropwithreset(struct mbuf *, struct tcphdr *,
1095 		     struct tcpcb *, int, int);
1096 void	tcp_pulloutofband(struct socket *,
1097 		     struct tcphdr *, struct mbuf *, int);
1098 void	tcp_xmit_timer(struct tcpcb *, int);
1099 void	tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
1100 void	cc_ack_received(struct tcpcb *tp, struct tcphdr *th,
1101 			    uint16_t nsegs, uint16_t type);
1102 void 	cc_conn_init(struct tcpcb *tp);
1103 void 	cc_post_recovery(struct tcpcb *tp, struct tcphdr *th);
1104 void    cc_ecnpkt_handler(struct tcpcb *tp, struct tcphdr *th, uint8_t iptos);
1105 void	cc_ecnpkt_handler_flags(struct tcpcb *tp, uint16_t flags, uint8_t iptos);
1106 void	cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type);
1107 #ifdef TCP_HHOOK
1108 void	hhook_run_tcp_est_in(struct tcpcb *tp,
1109 			    struct tcphdr *th, struct tcpopt *to);
1110 #endif
1111 
1112 int	 tcp_input(struct mbuf **, int *, int);
1113 int	 tcp_autorcvbuf(struct mbuf *, struct tcphdr *, struct socket *,
1114 	    struct tcpcb *, int);
1115 int	 tcp_input_with_port(struct mbuf **, int *, int, uint16_t);
1116 void	 tcp_do_segment(struct mbuf *, struct tcphdr *,
1117 			struct socket *, struct tcpcb *, int, int, uint8_t);
1118 
1119 int register_tcp_functions(struct tcp_function_block *blk, int wait);
1120 int register_tcp_functions_as_names(struct tcp_function_block *blk,
1121     int wait, const char *names[], int *num_names);
1122 int register_tcp_functions_as_name(struct tcp_function_block *blk,
1123     const char *name, int wait);
1124 int deregister_tcp_functions(struct tcp_function_block *blk, bool quiesce,
1125     bool force);
1126 struct tcp_function_block *find_and_ref_tcp_functions(struct tcp_function_set *fs);
1127 int find_tcp_function_alias(struct tcp_function_block *blk, struct tcp_function_set *fs);
1128 void tcp_switch_back_to_default(struct tcpcb *tp);
1129 struct tcp_function_block *
1130 find_and_ref_tcp_fb(struct tcp_function_block *fs);
1131 int tcp_default_ctloutput(struct inpcb *inp, struct sockopt *sopt);
1132 int tcp_ctloutput_set(struct inpcb *inp, struct sockopt *sopt);
1133 
1134 extern counter_u64_t tcp_inp_lro_direct_queue;
1135 extern counter_u64_t tcp_inp_lro_wokeup_queue;
1136 extern counter_u64_t tcp_inp_lro_compressed;
1137 extern counter_u64_t tcp_inp_lro_locks_taken;
1138 extern counter_u64_t tcp_extra_mbuf;
1139 extern counter_u64_t tcp_would_have_but;
1140 extern counter_u64_t tcp_comp_total;
1141 extern counter_u64_t tcp_uncomp_total;
1142 extern counter_u64_t tcp_bad_csums;
1143 
1144 #ifdef NETFLIX_EXP_DETECTION
1145 /* Various SACK attack thresholds */
1146 extern int32_t tcp_force_detection;
1147 extern int32_t tcp_sack_to_ack_thresh;
1148 extern int32_t tcp_sack_to_move_thresh;
1149 extern int32_t tcp_restoral_thresh;
1150 extern int32_t tcp_sad_decay_val;
1151 extern int32_t tcp_sad_pacing_interval;
1152 extern int32_t tcp_sad_low_pps;
1153 extern int32_t tcp_map_minimum;
1154 extern int32_t tcp_attack_on_turns_on_logging;
1155 #endif
1156 extern uint32_t tcp_ack_war_time_window;
1157 extern uint32_t tcp_ack_war_cnt;
1158 
1159 uint32_t tcp_maxmtu(struct in_conninfo *, struct tcp_ifcap *);
1160 uint32_t tcp_maxmtu6(struct in_conninfo *, struct tcp_ifcap *);
1161 void	 tcp6_use_min_mtu(struct tcpcb *);
1162 u_int	 tcp_maxseg(const struct tcpcb *);
1163 u_int	 tcp_fixed_maxseg(const struct tcpcb *);
1164 void	 tcp_mss_update(struct tcpcb *, int, int, struct hc_metrics_lite *,
1165 	    struct tcp_ifcap *);
1166 void	 tcp_mss(struct tcpcb *, int);
1167 int	 tcp_mssopt(struct in_conninfo *);
1168 struct tcpcb *
1169 	 tcp_newtcpcb(struct inpcb *);
1170 int	 tcp_default_output(struct tcpcb *);
1171 void	 tcp_state_change(struct tcpcb *, int);
1172 void	 tcp_respond(struct tcpcb *, void *,
1173 	    struct tcphdr *, struct mbuf *, tcp_seq, tcp_seq, uint16_t);
1174 bool	 tcp_twcheck(struct inpcb *, struct tcpopt *, struct tcphdr *,
1175 	    struct mbuf *, int);
1176 void	 tcp_setpersist(struct tcpcb *);
1177 void	 tcp_record_dsack(struct tcpcb *tp, tcp_seq start, tcp_seq end, int tlp);
1178 struct tcptemp *
1179 	 tcpip_maketemplate(struct inpcb *);
1180 void	 tcpip_fillheaders(struct inpcb *, uint16_t, void *, void *);
1181 void	 tcp_timer_activate(struct tcpcb *, uint32_t, u_int);
1182 int	 tcp_timer_suspend(struct tcpcb *, uint32_t);
1183 void	 tcp_timers_unsuspend(struct tcpcb *, uint32_t);
1184 int	 tcp_timer_active(struct tcpcb *, uint32_t);
1185 void	 tcp_timer_stop(struct tcpcb *, uint32_t);
1186 void	 tcp_trace(short, short, struct tcpcb *, void *, struct tcphdr *, int);
1187 int	 inp_to_cpuid(struct inpcb *inp);
1188 /*
1189  * All tcp_hc_* functions are IPv4 and IPv6 (via in_conninfo)
1190  */
1191 void	 tcp_hc_init(void);
1192 #ifdef VIMAGE
1193 void	 tcp_hc_destroy(void);
1194 #endif
1195 void	 tcp_hc_get(struct in_conninfo *, struct hc_metrics_lite *);
1196 uint32_t tcp_hc_getmtu(struct in_conninfo *);
1197 void	 tcp_hc_updatemtu(struct in_conninfo *, uint32_t);
1198 void	 tcp_hc_update(struct in_conninfo *, struct hc_metrics_lite *);
1199 void 	 cc_after_idle(struct tcpcb *tp);
1200 
1201 extern	struct protosw tcp_protosw;		/* shared for TOE */
1202 extern	struct protosw tcp6_protosw;		/* shared for TOE */
1203 
1204 uint32_t tcp_new_ts_offset(struct in_conninfo *);
1205 tcp_seq	 tcp_new_isn(struct in_conninfo *);
1206 
1207 int	 tcp_sack_doack(struct tcpcb *, struct tcpopt *, tcp_seq);
1208 int	 tcp_dsack_block_exists(struct tcpcb *);
1209 void	 tcp_update_dsack_list(struct tcpcb *, tcp_seq, tcp_seq);
1210 void	 tcp_update_sack_list(struct tcpcb *tp, tcp_seq rcv_laststart, tcp_seq rcv_lastend);
1211 void	 tcp_clean_dsack_blocks(struct tcpcb *tp);
1212 void	 tcp_clean_sackreport(struct tcpcb *tp);
1213 void	 tcp_sack_adjust(struct tcpcb *tp);
1214 struct sackhole *tcp_sack_output(struct tcpcb *tp, int *sack_bytes_rexmt);
1215 void	 tcp_do_prr_ack(struct tcpcb *, struct tcphdr *, struct tcpopt *);
1216 void	 tcp_lost_retransmission(struct tcpcb *, struct tcphdr *);
1217 void	 tcp_sack_partialack(struct tcpcb *, struct tcphdr *);
1218 void	 tcp_free_sackholes(struct tcpcb *tp);
1219 void	 tcp_sack_lost_retransmission(struct tcpcb *, struct tcphdr *);
1220 int	 tcp_newreno(struct tcpcb *, struct tcphdr *);
1221 int	 tcp_compute_pipe(struct tcpcb *);
1222 uint32_t tcp_compute_initwnd(uint32_t);
1223 void	 tcp_sndbuf_autoscale(struct tcpcb *, struct socket *, uint32_t);
1224 int	 tcp_stats_sample_rollthedice(struct tcpcb *tp, void *seed_bytes,
1225     size_t seed_len);
1226 int tcp_can_enable_pacing(void);
1227 void tcp_decrement_paced_conn(void);
1228 
1229 struct mbuf *
1230 	 tcp_m_copym(struct mbuf *m, int32_t off0, int32_t *plen,
1231 	   int32_t seglimit, int32_t segsize, struct sockbuf *sb, bool hw_tls);
1232 
1233 int	tcp_stats_init(void);
1234 void tcp_log_end_status(struct tcpcb *tp, uint8_t status);
1235 
1236 static inline void
1237 tcp_fields_to_host(struct tcphdr *th)
1238 {
1239 
1240 	th->th_seq = ntohl(th->th_seq);
1241 	th->th_ack = ntohl(th->th_ack);
1242 	th->th_win = ntohs(th->th_win);
1243 	th->th_urp = ntohs(th->th_urp);
1244 }
1245 
1246 static inline void
1247 tcp_fields_to_net(struct tcphdr *th)
1248 {
1249 
1250 	th->th_seq = htonl(th->th_seq);
1251 	th->th_ack = htonl(th->th_ack);
1252 	th->th_win = htons(th->th_win);
1253 	th->th_urp = htons(th->th_urp);
1254 }
1255 
1256 static inline uint16_t
1257 tcp_get_flags(const struct tcphdr *th)
1258 {
1259         return (((uint16_t)th->th_x2 << 8) | th->th_flags);
1260 }
1261 
1262 static inline void
1263 tcp_set_flags(struct tcphdr *th, uint16_t flags)
1264 {
1265         th->th_x2    = (flags >> 8) & 0x0f;
1266         th->th_flags = flags & 0xff;
1267 }
1268 
1269 static inline void
1270 tcp_account_for_send(struct tcpcb *tp, uint32_t len, uint8_t is_rxt,
1271     uint8_t is_tlp, int hw_tls)
1272 {
1273 	if (is_tlp) {
1274 		tp->t_sndtlppack++;
1275 		tp->t_sndtlpbyte += len;
1276 	}
1277 	/* To get total bytes sent you must add t_snd_rxt_bytes to t_sndbytes */
1278 	if (is_rxt)
1279 		tp->t_snd_rxt_bytes += len;
1280 	else
1281 		tp->t_sndbytes += len;
1282 
1283 #ifdef KERN_TLS
1284 	if (hw_tls && is_rxt && len != 0) {
1285 		uint64_t rexmit_percent = (1000ULL * tp->t_snd_rxt_bytes) / (10ULL * (tp->t_snd_rxt_bytes + tp->t_sndbytes));
1286 		if (rexmit_percent > ktls_ifnet_max_rexmit_pct)
1287 			ktls_disable_ifnet(tp);
1288 	}
1289 #endif
1290 
1291 }
1292 #endif /* _KERNEL */
1293 
1294 #endif /* _NETINET_TCP_VAR_H_ */
1295