xref: /linux/net/ipv4/tcp_output.c (revision 15b5be9389bef46884d9f970b643fedeea19105c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * INET		An implementation of the TCP/IP protocol suite for the LINUX
4  *		operating system.  INET is implemented using the  BSD Socket
5  *		interface as the means of communication with the user level.
6  *
7  *		Implementation of the Transmission Control Protocol(TCP).
8  *
9  * Authors:	Ross Biro
10  *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
11  *		Mark Evans, <evansmp@uhura.aston.ac.uk>
12  *		Corey Minyard <wf-rch!minyard@relay.EU.net>
13  *		Florian La Roche, <flla@stud.uni-sb.de>
14  *		Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
15  *		Linus Torvalds, <torvalds@cs.helsinki.fi>
16  *		Alan Cox, <gw4pts@gw4pts.ampr.org>
17  *		Matthew Dillon, <dillon@apollo.west.oic.com>
18  *		Arnt Gulbrandsen, <agulbra@nvg.unit.no>
19  *		Jorge Cwik, <jorge@laser.satlink.net>
20  */
21 
22 /*
23  * Changes:	Pedro Roque	:	Retransmit queue handled by TCP.
24  *				:	Fragmentation on mtu decrease
25  *				:	Segment collapse on retransmit
26  *				:	AF independence
27  *
28  *		Linus Torvalds	:	send_delayed_ack
29  *		David S. Miller	:	Charge memory using the right skb
30  *					during syn/ack processing.
31  *		David S. Miller :	Output engine completely rewritten.
32  *		Andrea Arcangeli:	SYNACK carry ts_recent in tsecr.
33  *		Cacophonix Gaul :	draft-minshall-nagle-01
34  *		J Hadi Salim	:	ECN support
35  *
36  */
37 
38 #define pr_fmt(fmt) "TCP: " fmt
39 
40 #include <net/tcp.h>
41 #include <net/tcp_ecn.h>
42 #include <net/mptcp.h>
43 #include <net/smc.h>
44 #include <net/proto_memory.h>
45 #include <net/psp.h>
46 
47 #include <linux/compiler.h>
48 #include <linux/gfp.h>
49 #include <linux/module.h>
50 #include <linux/static_key.h>
51 #include <linux/skbuff_ref.h>
52 
53 #include <trace/events/tcp.h>
54 
55 /* Refresh clocks of a TCP socket,
56  * ensuring monotically increasing values.
57  */
58 void tcp_mstamp_refresh(struct tcp_sock *tp)
59 {
60 	u64 val = tcp_clock_ns();
61 
62 	tp->tcp_clock_cache = val;
63 	tp->tcp_mstamp = div_u64(val, NSEC_PER_USEC);
64 }
65 
66 static bool tcp_write_xmit(struct sock *sk, unsigned int mss_now, int nonagle,
67 			   int push_one, gfp_t gfp);
68 
69 /* Insert skb into rb tree, ordered by TCP_SKB_CB(skb)->seq */
70 void tcp_rbtree_insert(struct rb_root *root, struct sk_buff *skb)
71 {
72 	struct rb_node **p = &root->rb_node;
73 	struct rb_node *parent = NULL;
74 	struct sk_buff *skb1;
75 
76 	while (*p) {
77 		parent = *p;
78 		skb1 = rb_to_skb(parent);
79 		if (before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb1)->seq))
80 			p = &parent->rb_left;
81 		else
82 			p = &parent->rb_right;
83 	}
84 	rb_link_node(&skb->rbnode, parent, p);
85 	rb_insert_color(&skb->rbnode, root);
86 }
87 
88 /* Account for new data that has been sent to the network. */
89 static void tcp_event_new_data_sent(struct sock *sk, struct sk_buff *skb)
90 {
91 	struct inet_connection_sock *icsk = inet_csk(sk);
92 	struct tcp_sock *tp = tcp_sk(sk);
93 	unsigned int prior_packets = tp->packets_out;
94 
95 	WRITE_ONCE(tp->snd_nxt, TCP_SKB_CB(skb)->end_seq);
96 
97 	__skb_unlink(skb, &sk->sk_write_queue);
98 	tcp_rbtree_insert(&sk->tcp_rtx_queue, skb);
99 
100 	if (tp->highest_sack == NULL)
101 		tp->highest_sack = skb;
102 
103 	tp->packets_out += tcp_skb_pcount(skb);
104 	if (!prior_packets || icsk->icsk_pending == ICSK_TIME_LOSS_PROBE)
105 		tcp_rearm_rto(sk);
106 
107 	NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPORIGDATASENT,
108 		      tcp_skb_pcount(skb));
109 	tcp_check_space(sk);
110 }
111 
112 /* SND.NXT, if window was not shrunk or the amount of shrunk was less than one
113  * window scaling factor due to loss of precision.
114  * If window has been shrunk, what should we make? It is not clear at all.
115  * Using SND.UNA we will fail to open window, SND.NXT is out of window. :-(
116  * Anything in between SND.UNA...SND.UNA+SND.WND also can be already
117  * invalid. OK, let's make this for now:
118  */
119 static inline __u32 tcp_acceptable_seq(const struct sock *sk)
120 {
121 	const struct tcp_sock *tp = tcp_sk(sk);
122 
123 	if (!before(tcp_wnd_end(tp), tp->snd_nxt) ||
124 	    (tp->rx_opt.wscale_ok &&
125 	     ((tp->snd_nxt - tcp_wnd_end(tp)) < (1 << tp->rx_opt.rcv_wscale))))
126 		return tp->snd_nxt;
127 	else
128 		return tcp_wnd_end(tp);
129 }
130 
131 /* Calculate mss to advertise in SYN segment.
132  * RFC1122, RFC1063, draft-ietf-tcpimpl-pmtud-01 state that:
133  *
134  * 1. It is independent of path mtu.
135  * 2. Ideally, it is maximal possible segment size i.e. 65535-40.
136  * 3. For IPv4 it is reasonable to calculate it from maximal MTU of
137  *    attached devices, because some buggy hosts are confused by
138  *    large MSS.
139  * 4. We do not make 3, we advertise MSS, calculated from first
140  *    hop device mtu, but allow to raise it to ip_rt_min_advmss.
141  *    This may be overridden via information stored in routing table.
142  * 5. Value 65535 for MSS is valid in IPv6 and means "as large as possible,
143  *    probably even Jumbo".
144  */
145 static __u16 tcp_advertise_mss(struct sock *sk)
146 {
147 	struct tcp_sock *tp = tcp_sk(sk);
148 	const struct dst_entry *dst = __sk_dst_get(sk);
149 	int mss = tp->advmss;
150 
151 	if (dst) {
152 		unsigned int metric = dst_metric_advmss(dst);
153 
154 		if (metric < mss) {
155 			mss = metric;
156 			tp->advmss = mss;
157 		}
158 	}
159 
160 	return (__u16)mss;
161 }
162 
163 /* RFC2861. Reset CWND after idle period longer RTO to "restart window".
164  * This is the first part of cwnd validation mechanism.
165  */
166 void tcp_cwnd_restart(struct sock *sk, s32 delta)
167 {
168 	struct tcp_sock *tp = tcp_sk(sk);
169 	u32 restart_cwnd = tcp_init_cwnd(tp, __sk_dst_get(sk));
170 	u32 cwnd = tcp_snd_cwnd(tp);
171 
172 	tcp_ca_event(sk, CA_EVENT_CWND_RESTART);
173 
174 	tp->snd_ssthresh = tcp_current_ssthresh(sk);
175 	restart_cwnd = min(restart_cwnd, cwnd);
176 
177 	while ((delta -= inet_csk(sk)->icsk_rto) > 0 && cwnd > restart_cwnd)
178 		cwnd >>= 1;
179 	tcp_snd_cwnd_set(tp, max(cwnd, restart_cwnd));
180 	tp->snd_cwnd_stamp = tcp_jiffies32;
181 	tp->snd_cwnd_used = 0;
182 }
183 
184 /* Congestion state accounting after a packet has been sent. */
185 static void tcp_event_data_sent(struct tcp_sock *tp,
186 				struct sock *sk)
187 {
188 	struct inet_connection_sock *icsk = inet_csk(sk);
189 	const u32 now = tcp_jiffies32;
190 
191 	if (tcp_packets_in_flight(tp) == 0)
192 		tcp_ca_event(sk, CA_EVENT_TX_START);
193 
194 	tp->lsndtime = now;
195 
196 	/* If it is a reply for ato after last received
197 	 * packet, increase pingpong count.
198 	 */
199 	if ((u32)(now - icsk->icsk_ack.lrcvtime) < icsk->icsk_ack.ato)
200 		inet_csk_inc_pingpong_cnt(sk);
201 }
202 
203 /* Account for an ACK we sent. */
204 static inline void tcp_event_ack_sent(struct sock *sk, u32 rcv_nxt)
205 {
206 	struct tcp_sock *tp = tcp_sk(sk);
207 
208 	if (unlikely(tp->compressed_ack)) {
209 		NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPACKCOMPRESSED,
210 			      tp->compressed_ack);
211 		tp->compressed_ack = 0;
212 		if (hrtimer_try_to_cancel(&tp->compressed_ack_timer) == 1)
213 			__sock_put(sk);
214 	}
215 
216 	if (unlikely(rcv_nxt != tp->rcv_nxt))
217 		return;  /* Special ACK sent by DCTCP to reflect ECN */
218 	tcp_dec_quickack_mode(sk);
219 	inet_csk_clear_xmit_timer(sk, ICSK_TIME_DACK);
220 }
221 
222 /* Determine a window scaling and initial window to offer.
223  * Based on the assumption that the given amount of space
224  * will be offered. Store the results in the tp structure.
225  * NOTE: for smooth operation initial space offering should
226  * be a multiple of mss if possible. We assume here that mss >= 1.
227  * This MUST be enforced by all callers.
228  */
229 void tcp_select_initial_window(const struct sock *sk, int __space, __u32 mss,
230 			       __u32 *rcv_wnd, __u32 *__window_clamp,
231 			       int wscale_ok, __u8 *rcv_wscale,
232 			       __u32 init_rcv_wnd)
233 {
234 	unsigned int space = (__space < 0 ? 0 : __space);
235 	u32 window_clamp = READ_ONCE(*__window_clamp);
236 
237 	/* If no clamp set the clamp to the max possible scaled window */
238 	if (window_clamp == 0)
239 		window_clamp = (U16_MAX << TCP_MAX_WSCALE);
240 	space = min(window_clamp, space);
241 
242 	/* Quantize space offering to a multiple of mss if possible. */
243 	if (space > mss)
244 		space = rounddown(space, mss);
245 
246 	/* NOTE: offering an initial window larger than 32767
247 	 * will break some buggy TCP stacks. If the admin tells us
248 	 * it is likely we could be speaking with such a buggy stack
249 	 * we will truncate our initial window offering to 32K-1
250 	 * unless the remote has sent us a window scaling option,
251 	 * which we interpret as a sign the remote TCP is not
252 	 * misinterpreting the window field as a signed quantity.
253 	 */
254 	if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_workaround_signed_windows))
255 		(*rcv_wnd) = min(space, MAX_TCP_WINDOW);
256 	else
257 		(*rcv_wnd) = space;
258 
259 	if (init_rcv_wnd)
260 		*rcv_wnd = min(*rcv_wnd, init_rcv_wnd * mss);
261 
262 	*rcv_wscale = 0;
263 	if (wscale_ok) {
264 		/* Set window scaling on max possible window */
265 		space = max_t(u32, space, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2]));
266 		space = max_t(u32, space, READ_ONCE(sysctl_rmem_max));
267 		space = min_t(u32, space, window_clamp);
268 		*rcv_wscale = clamp_t(int, ilog2(space) - 15,
269 				      0, TCP_MAX_WSCALE);
270 	}
271 	/* Set the clamp no higher than max representable value */
272 	WRITE_ONCE(*__window_clamp,
273 		   min_t(__u32, U16_MAX << (*rcv_wscale), window_clamp));
274 }
275 EXPORT_IPV6_MOD(tcp_select_initial_window);
276 
277 /* Chose a new window to advertise, update state in tcp_sock for the
278  * socket, and return result with RFC1323 scaling applied.  The return
279  * value can be stuffed directly into th->window for an outgoing
280  * frame.
281  */
282 static u16 tcp_select_window(struct sock *sk)
283 {
284 	struct tcp_sock *tp = tcp_sk(sk);
285 	struct net *net = sock_net(sk);
286 	u32 old_win = tp->rcv_wnd;
287 	u32 cur_win, new_win;
288 
289 	/* Make the window 0 if we failed to queue the data because we
290 	 * are out of memory.
291 	 */
292 	if (unlikely(inet_csk(sk)->icsk_ack.pending & ICSK_ACK_NOMEM)) {
293 		tp->pred_flags = 0;
294 		tp->rcv_wnd = 0;
295 		tp->rcv_wup = tp->rcv_nxt;
296 		return 0;
297 	}
298 
299 	cur_win = tcp_receive_window(tp);
300 	new_win = __tcp_select_window(sk);
301 	if (new_win < cur_win) {
302 		/* Danger Will Robinson!
303 		 * Don't update rcv_wup/rcv_wnd here or else
304 		 * we will not be able to advertise a zero
305 		 * window in time.  --DaveM
306 		 *
307 		 * Relax Will Robinson.
308 		 */
309 		if (!READ_ONCE(net->ipv4.sysctl_tcp_shrink_window) || !tp->rx_opt.rcv_wscale) {
310 			/* Never shrink the offered window */
311 			if (new_win == 0)
312 				NET_INC_STATS(net, LINUX_MIB_TCPWANTZEROWINDOWADV);
313 			new_win = ALIGN(cur_win, 1 << tp->rx_opt.rcv_wscale);
314 		}
315 	}
316 
317 	tp->rcv_wnd = new_win;
318 	tp->rcv_wup = tp->rcv_nxt;
319 
320 	/* Make sure we do not exceed the maximum possible
321 	 * scaled window.
322 	 */
323 	if (!tp->rx_opt.rcv_wscale &&
324 	    READ_ONCE(net->ipv4.sysctl_tcp_workaround_signed_windows))
325 		new_win = min(new_win, MAX_TCP_WINDOW);
326 	else
327 		new_win = min(new_win, (65535U << tp->rx_opt.rcv_wscale));
328 
329 	/* RFC1323 scaling applied */
330 	new_win >>= tp->rx_opt.rcv_wscale;
331 
332 	/* If we advertise zero window, disable fast path. */
333 	if (new_win == 0) {
334 		tp->pred_flags = 0;
335 		if (old_win)
336 			NET_INC_STATS(net, LINUX_MIB_TCPTOZEROWINDOWADV);
337 	} else if (old_win == 0) {
338 		NET_INC_STATS(net, LINUX_MIB_TCPFROMZEROWINDOWADV);
339 	}
340 
341 	return new_win;
342 }
343 
344 /* Set up ECN state for a packet on a ESTABLISHED socket that is about to
345  * be sent.
346  */
347 static void tcp_ecn_send(struct sock *sk, struct sk_buff *skb,
348 			 struct tcphdr *th, int tcp_header_len)
349 {
350 	struct tcp_sock *tp = tcp_sk(sk);
351 
352 	if (!tcp_ecn_mode_any(tp))
353 		return;
354 
355 	if (tcp_ecn_mode_accecn(tp)) {
356 		if (!tcp_accecn_ace_fail_recv(tp) &&
357 		    !tcp_accecn_ace_fail_send(tp))
358 			INET_ECN_xmit(sk);
359 		else
360 			INET_ECN_dontxmit(sk);
361 		tcp_accecn_set_ace(tp, skb, th);
362 		skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ACCECN;
363 	} else {
364 		/* Not-retransmitted data segment: set ECT and inject CWR. */
365 		if (skb->len != tcp_header_len &&
366 		    !before(TCP_SKB_CB(skb)->seq, tp->snd_nxt)) {
367 			INET_ECN_xmit(sk);
368 			if (tp->ecn_flags & TCP_ECN_QUEUE_CWR) {
369 				tp->ecn_flags &= ~TCP_ECN_QUEUE_CWR;
370 				th->cwr = 1;
371 				skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
372 			}
373 		} else if (!tcp_ca_needs_ecn(sk)) {
374 			/* ACK or retransmitted segment: clear ECT|CE */
375 			INET_ECN_dontxmit(sk);
376 		}
377 		if (tp->ecn_flags & TCP_ECN_DEMAND_CWR)
378 			th->ece = 1;
379 	}
380 }
381 
382 /* Constructs common control bits of non-data skb. If SYN/FIN is present,
383  * auto increment end seqno.
384  */
385 static void tcp_init_nondata_skb(struct sk_buff *skb, struct sock *sk,
386 				 u32 seq, u16 flags)
387 {
388 	skb->ip_summed = CHECKSUM_PARTIAL;
389 
390 	TCP_SKB_CB(skb)->tcp_flags = flags;
391 
392 	tcp_skb_pcount_set(skb, 1);
393 	psp_enqueue_set_decrypted(sk, skb);
394 
395 	TCP_SKB_CB(skb)->seq = seq;
396 	if (flags & (TCPHDR_SYN | TCPHDR_FIN))
397 		seq++;
398 	TCP_SKB_CB(skb)->end_seq = seq;
399 }
400 
401 static inline bool tcp_urg_mode(const struct tcp_sock *tp)
402 {
403 	return tp->snd_una != tp->snd_up;
404 }
405 
406 #define OPTION_SACK_ADVERTISE	BIT(0)
407 #define OPTION_TS		BIT(1)
408 #define OPTION_MD5		BIT(2)
409 #define OPTION_WSCALE		BIT(3)
410 #define OPTION_FAST_OPEN_COOKIE	BIT(8)
411 #define OPTION_SMC		BIT(9)
412 #define OPTION_MPTCP		BIT(10)
413 #define OPTION_AO		BIT(11)
414 #define OPTION_ACCECN		BIT(12)
415 
416 static void smc_options_write(__be32 *ptr, u16 *options)
417 {
418 #if IS_ENABLED(CONFIG_SMC)
419 	if (static_branch_unlikely(&tcp_have_smc)) {
420 		if (unlikely(OPTION_SMC & *options)) {
421 			*ptr++ = htonl((TCPOPT_NOP  << 24) |
422 				       (TCPOPT_NOP  << 16) |
423 				       (TCPOPT_EXP <<  8) |
424 				       (TCPOLEN_EXP_SMC_BASE));
425 			*ptr++ = htonl(TCPOPT_SMC_MAGIC);
426 		}
427 	}
428 #endif
429 }
430 
431 struct tcp_out_options {
432 	/* Following group is cleared in __tcp_transmit_skb() */
433 	struct_group(cleared,
434 		u16 mss;		/* 0 to disable */
435 		u8 bpf_opt_len;		/* length of BPF hdr option */
436 		u8 num_sack_blocks;	/* number of SACK blocks to include */
437 	);
438 
439 	/* Caution: following fields are not cleared in __tcp_transmit_skb() */
440 	u16 options;		/* bit field of OPTION_* */
441 	u8 ws;			/* window scale, 0 to disable */
442 	u8 num_accecn_fields:7,	/* number of AccECN fields needed */
443 	   use_synack_ecn_bytes:1; /* Use synack_ecn_bytes or not */
444 	__u8 *hash_location;	/* temporary pointer, overloaded */
445 	__u32 tsval, tsecr;	/* need to include OPTION_TS */
446 	struct tcp_fastopen_cookie *fastopen_cookie;	/* Fast open cookie */
447 	struct mptcp_out_options mptcp;
448 };
449 
450 static void mptcp_options_write(struct tcphdr *th, __be32 *ptr,
451 				struct tcp_sock *tp,
452 				struct tcp_out_options *opts)
453 {
454 #if IS_ENABLED(CONFIG_MPTCP)
455 	if (unlikely(OPTION_MPTCP & opts->options))
456 		mptcp_write_options(th, ptr, tp, &opts->mptcp);
457 #endif
458 }
459 
460 #ifdef CONFIG_CGROUP_BPF
461 static int bpf_skops_write_hdr_opt_arg0(struct sk_buff *skb,
462 					enum tcp_synack_type synack_type)
463 {
464 	if (unlikely(!skb))
465 		return BPF_WRITE_HDR_TCP_CURRENT_MSS;
466 
467 	if (unlikely(synack_type == TCP_SYNACK_COOKIE))
468 		return BPF_WRITE_HDR_TCP_SYNACK_COOKIE;
469 
470 	return 0;
471 }
472 
473 /* req, syn_skb and synack_type are used when writing synack */
474 static void bpf_skops_hdr_opt_len(struct sock *sk, struct sk_buff *skb,
475 				  struct request_sock *req,
476 				  struct sk_buff *syn_skb,
477 				  enum tcp_synack_type synack_type,
478 				  struct tcp_out_options *opts,
479 				  unsigned int *remaining)
480 {
481 	struct bpf_sock_ops_kern sock_ops;
482 	int err;
483 
484 	if (likely(!BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk),
485 					   BPF_SOCK_OPS_WRITE_HDR_OPT_CB_FLAG)) ||
486 	    !*remaining)
487 		return;
488 
489 	/* *remaining has already been aligned to 4 bytes, so *remaining >= 4 */
490 
491 	/* init sock_ops */
492 	memset(&sock_ops, 0, offsetof(struct bpf_sock_ops_kern, temp));
493 
494 	sock_ops.op = BPF_SOCK_OPS_HDR_OPT_LEN_CB;
495 
496 	if (req) {
497 		/* The listen "sk" cannot be passed here because
498 		 * it is not locked.  It would not make too much
499 		 * sense to do bpf_setsockopt(listen_sk) based
500 		 * on individual connection request also.
501 		 *
502 		 * Thus, "req" is passed here and the cgroup-bpf-progs
503 		 * of the listen "sk" will be run.
504 		 *
505 		 * "req" is also used here for fastopen even the "sk" here is
506 		 * a fullsock "child" sk.  It is to keep the behavior
507 		 * consistent between fastopen and non-fastopen on
508 		 * the bpf programming side.
509 		 */
510 		sock_ops.sk = (struct sock *)req;
511 		sock_ops.syn_skb = syn_skb;
512 	} else {
513 		sock_owned_by_me(sk);
514 
515 		sock_ops.is_fullsock = 1;
516 		sock_ops.is_locked_tcp_sock = 1;
517 		sock_ops.sk = sk;
518 	}
519 
520 	sock_ops.args[0] = bpf_skops_write_hdr_opt_arg0(skb, synack_type);
521 	sock_ops.remaining_opt_len = *remaining;
522 	/* tcp_current_mss() does not pass a skb */
523 	if (skb)
524 		bpf_skops_init_skb(&sock_ops, skb, 0);
525 
526 	err = BPF_CGROUP_RUN_PROG_SOCK_OPS_SK(&sock_ops, sk);
527 
528 	if (err || sock_ops.remaining_opt_len == *remaining)
529 		return;
530 
531 	opts->bpf_opt_len = *remaining - sock_ops.remaining_opt_len;
532 	/* round up to 4 bytes */
533 	opts->bpf_opt_len = (opts->bpf_opt_len + 3) & ~3;
534 
535 	*remaining -= opts->bpf_opt_len;
536 }
537 
538 static void bpf_skops_write_hdr_opt(struct sock *sk, struct sk_buff *skb,
539 				    struct request_sock *req,
540 				    struct sk_buff *syn_skb,
541 				    enum tcp_synack_type synack_type,
542 				    struct tcp_out_options *opts)
543 {
544 	u8 first_opt_off, nr_written, max_opt_len = opts->bpf_opt_len;
545 	struct bpf_sock_ops_kern sock_ops;
546 	int err;
547 
548 	if (likely(!max_opt_len))
549 		return;
550 
551 	memset(&sock_ops, 0, offsetof(struct bpf_sock_ops_kern, temp));
552 
553 	sock_ops.op = BPF_SOCK_OPS_WRITE_HDR_OPT_CB;
554 
555 	if (req) {
556 		sock_ops.sk = (struct sock *)req;
557 		sock_ops.syn_skb = syn_skb;
558 	} else {
559 		sock_owned_by_me(sk);
560 
561 		sock_ops.is_fullsock = 1;
562 		sock_ops.is_locked_tcp_sock = 1;
563 		sock_ops.sk = sk;
564 	}
565 
566 	sock_ops.args[0] = bpf_skops_write_hdr_opt_arg0(skb, synack_type);
567 	sock_ops.remaining_opt_len = max_opt_len;
568 	first_opt_off = tcp_hdrlen(skb) - max_opt_len;
569 	bpf_skops_init_skb(&sock_ops, skb, first_opt_off);
570 
571 	err = BPF_CGROUP_RUN_PROG_SOCK_OPS_SK(&sock_ops, sk);
572 
573 	if (err)
574 		nr_written = 0;
575 	else
576 		nr_written = max_opt_len - sock_ops.remaining_opt_len;
577 
578 	if (nr_written < max_opt_len)
579 		memset(skb->data + first_opt_off + nr_written, TCPOPT_NOP,
580 		       max_opt_len - nr_written);
581 }
582 #else
583 static void bpf_skops_hdr_opt_len(struct sock *sk, struct sk_buff *skb,
584 				  struct request_sock *req,
585 				  struct sk_buff *syn_skb,
586 				  enum tcp_synack_type synack_type,
587 				  struct tcp_out_options *opts,
588 				  unsigned int *remaining)
589 {
590 }
591 
592 static void bpf_skops_write_hdr_opt(struct sock *sk, struct sk_buff *skb,
593 				    struct request_sock *req,
594 				    struct sk_buff *syn_skb,
595 				    enum tcp_synack_type synack_type,
596 				    struct tcp_out_options *opts)
597 {
598 }
599 #endif
600 
601 static __be32 *process_tcp_ao_options(struct tcp_sock *tp,
602 				      const struct tcp_request_sock *tcprsk,
603 				      struct tcp_out_options *opts,
604 				      struct tcp_key *key, __be32 *ptr)
605 {
606 #ifdef CONFIG_TCP_AO
607 	u8 maclen = tcp_ao_maclen(key->ao_key);
608 
609 	if (tcprsk) {
610 		u8 aolen = maclen + sizeof(struct tcp_ao_hdr);
611 
612 		*ptr++ = htonl((TCPOPT_AO << 24) | (aolen << 16) |
613 			       (tcprsk->ao_keyid << 8) |
614 			       (tcprsk->ao_rcv_next));
615 	} else {
616 		struct tcp_ao_key *rnext_key;
617 		struct tcp_ao_info *ao_info;
618 
619 		ao_info = rcu_dereference_check(tp->ao_info,
620 			lockdep_sock_is_held(&tp->inet_conn.icsk_inet.sk));
621 		rnext_key = READ_ONCE(ao_info->rnext_key);
622 		if (WARN_ON_ONCE(!rnext_key))
623 			return ptr;
624 		*ptr++ = htonl((TCPOPT_AO << 24) |
625 			       (tcp_ao_len(key->ao_key) << 16) |
626 			       (key->ao_key->sndid << 8) |
627 			       (rnext_key->rcvid));
628 	}
629 	opts->hash_location = (__u8 *)ptr;
630 	ptr += maclen / sizeof(*ptr);
631 	if (unlikely(maclen % sizeof(*ptr))) {
632 		memset(ptr, TCPOPT_NOP, sizeof(*ptr));
633 		ptr++;
634 	}
635 #endif
636 	return ptr;
637 }
638 
639 /* Initial values for AccECN option, ordered is based on ECN field bits
640  * similar to received_ecn_bytes. Used for SYN/ACK AccECN option.
641  */
642 static const u32 synack_ecn_bytes[3] = { 0, 0, 0 };
643 
644 /* Write previously computed TCP options to the packet.
645  *
646  * Beware: Something in the Internet is very sensitive to the ordering of
647  * TCP options, we learned this through the hard way, so be careful here.
648  * Luckily we can at least blame others for their non-compliance but from
649  * inter-operability perspective it seems that we're somewhat stuck with
650  * the ordering which we have been using if we want to keep working with
651  * those broken things (not that it currently hurts anybody as there isn't
652  * particular reason why the ordering would need to be changed).
653  *
654  * At least SACK_PERM as the first option is known to lead to a disaster
655  * (but it may well be that other scenarios fail similarly).
656  */
657 static void tcp_options_write(struct tcphdr *th, struct tcp_sock *tp,
658 			      const struct tcp_request_sock *tcprsk,
659 			      struct tcp_out_options *opts,
660 			      struct tcp_key *key)
661 {
662 	u8 leftover_highbyte = TCPOPT_NOP; /* replace 1st NOP if avail */
663 	u8 leftover_lowbyte = TCPOPT_NOP;  /* replace 2nd NOP in succession */
664 	__be32 *ptr = (__be32 *)(th + 1);
665 	u16 options = opts->options;	/* mungable copy */
666 
667 	if (tcp_key_is_md5(key)) {
668 		*ptr++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) |
669 			       (TCPOPT_MD5SIG << 8) | TCPOLEN_MD5SIG);
670 		/* overload cookie hash location */
671 		opts->hash_location = (__u8 *)ptr;
672 		ptr += 4;
673 	} else if (tcp_key_is_ao(key)) {
674 		ptr = process_tcp_ao_options(tp, tcprsk, opts, key, ptr);
675 	}
676 	if (unlikely(opts->mss)) {
677 		*ptr++ = htonl((TCPOPT_MSS << 24) |
678 			       (TCPOLEN_MSS << 16) |
679 			       opts->mss);
680 	}
681 
682 	if (likely(OPTION_TS & options)) {
683 		if (unlikely(OPTION_SACK_ADVERTISE & options)) {
684 			*ptr++ = htonl((TCPOPT_SACK_PERM << 24) |
685 				       (TCPOLEN_SACK_PERM << 16) |
686 				       (TCPOPT_TIMESTAMP << 8) |
687 				       TCPOLEN_TIMESTAMP);
688 			options &= ~OPTION_SACK_ADVERTISE;
689 		} else {
690 			*ptr++ = htonl((TCPOPT_NOP << 24) |
691 				       (TCPOPT_NOP << 16) |
692 				       (TCPOPT_TIMESTAMP << 8) |
693 				       TCPOLEN_TIMESTAMP);
694 		}
695 		*ptr++ = htonl(opts->tsval);
696 		*ptr++ = htonl(opts->tsecr);
697 	}
698 
699 	if (OPTION_ACCECN & options) {
700 		const u32 *ecn_bytes = opts->use_synack_ecn_bytes ?
701 				       synack_ecn_bytes :
702 				       tp->received_ecn_bytes;
703 		const u8 ect0_idx = INET_ECN_ECT_0 - 1;
704 		const u8 ect1_idx = INET_ECN_ECT_1 - 1;
705 		const u8 ce_idx = INET_ECN_CE - 1;
706 		u32 e0b;
707 		u32 e1b;
708 		u32 ceb;
709 		u8 len;
710 
711 		e0b = ecn_bytes[ect0_idx] + TCP_ACCECN_E0B_INIT_OFFSET;
712 		e1b = ecn_bytes[ect1_idx] + TCP_ACCECN_E1B_INIT_OFFSET;
713 		ceb = ecn_bytes[ce_idx] + TCP_ACCECN_CEB_INIT_OFFSET;
714 		len = TCPOLEN_ACCECN_BASE +
715 		      opts->num_accecn_fields * TCPOLEN_ACCECN_PERFIELD;
716 
717 		if (opts->num_accecn_fields == 2) {
718 			*ptr++ = htonl((TCPOPT_ACCECN1 << 24) | (len << 16) |
719 				       ((e1b >> 8) & 0xffff));
720 			*ptr++ = htonl(((e1b & 0xff) << 24) |
721 				       (ceb & 0xffffff));
722 		} else if (opts->num_accecn_fields == 1) {
723 			*ptr++ = htonl((TCPOPT_ACCECN1 << 24) | (len << 16) |
724 				       ((e1b >> 8) & 0xffff));
725 			leftover_highbyte = e1b & 0xff;
726 			leftover_lowbyte = TCPOPT_NOP;
727 		} else if (opts->num_accecn_fields == 0) {
728 			leftover_highbyte = TCPOPT_ACCECN1;
729 			leftover_lowbyte = len;
730 		} else if (opts->num_accecn_fields == 3) {
731 			*ptr++ = htonl((TCPOPT_ACCECN1 << 24) | (len << 16) |
732 				       ((e1b >> 8) & 0xffff));
733 			*ptr++ = htonl(((e1b & 0xff) << 24) |
734 				       (ceb & 0xffffff));
735 			*ptr++ = htonl(((e0b & 0xffffff) << 8) |
736 				       TCPOPT_NOP);
737 		}
738 		if (tp) {
739 			tp->accecn_minlen = 0;
740 			tp->accecn_opt_tstamp = tp->tcp_mstamp;
741 			tp->accecn_opt_sent_w_dsack = tp->rx_opt.dsack;
742 			if (tp->accecn_opt_demand)
743 				tp->accecn_opt_demand--;
744 		}
745 	} else if (tp) {
746 		tp->accecn_opt_sent_w_dsack = 0;
747 	}
748 
749 	if (unlikely(OPTION_SACK_ADVERTISE & options)) {
750 		*ptr++ = htonl((leftover_highbyte << 24) |
751 			       (leftover_lowbyte << 16) |
752 			       (TCPOPT_SACK_PERM << 8) |
753 			       TCPOLEN_SACK_PERM);
754 		leftover_highbyte = TCPOPT_NOP;
755 		leftover_lowbyte = TCPOPT_NOP;
756 	}
757 
758 	if (unlikely(OPTION_WSCALE & options)) {
759 		u8 highbyte = TCPOPT_NOP;
760 
761 		/* Do not split the leftover 2-byte to fit into a single
762 		 * NOP, i.e., replace this NOP only when 1 byte is leftover
763 		 * within leftover_highbyte.
764 		 */
765 		if (unlikely(leftover_highbyte != TCPOPT_NOP &&
766 			     leftover_lowbyte == TCPOPT_NOP)) {
767 			highbyte = leftover_highbyte;
768 			leftover_highbyte = TCPOPT_NOP;
769 		}
770 		*ptr++ = htonl((highbyte << 24) |
771 			       (TCPOPT_WINDOW << 16) |
772 			       (TCPOLEN_WINDOW << 8) |
773 			       opts->ws);
774 	}
775 
776 	if (unlikely(opts->num_sack_blocks)) {
777 		struct tcp_sack_block *sp = tp->rx_opt.dsack ?
778 			tp->duplicate_sack : tp->selective_acks;
779 		int this_sack;
780 
781 		*ptr++ = htonl((leftover_highbyte << 24) |
782 			       (leftover_lowbyte << 16) |
783 			       (TCPOPT_SACK <<  8) |
784 			       (TCPOLEN_SACK_BASE + (opts->num_sack_blocks *
785 						     TCPOLEN_SACK_PERBLOCK)));
786 		leftover_highbyte = TCPOPT_NOP;
787 		leftover_lowbyte = TCPOPT_NOP;
788 
789 		for (this_sack = 0; this_sack < opts->num_sack_blocks;
790 		     ++this_sack) {
791 			*ptr++ = htonl(sp[this_sack].start_seq);
792 			*ptr++ = htonl(sp[this_sack].end_seq);
793 		}
794 
795 		tp->rx_opt.dsack = 0;
796 	} else if (unlikely(leftover_highbyte != TCPOPT_NOP ||
797 			    leftover_lowbyte != TCPOPT_NOP)) {
798 		*ptr++ = htonl((leftover_highbyte << 24) |
799 			       (leftover_lowbyte << 16) |
800 			       (TCPOPT_NOP << 8) |
801 			       TCPOPT_NOP);
802 		leftover_highbyte = TCPOPT_NOP;
803 		leftover_lowbyte = TCPOPT_NOP;
804 	}
805 
806 	if (unlikely(OPTION_FAST_OPEN_COOKIE & options)) {
807 		struct tcp_fastopen_cookie *foc = opts->fastopen_cookie;
808 		u8 *p = (u8 *)ptr;
809 		u32 len; /* Fast Open option length */
810 
811 		if (foc->exp) {
812 			len = TCPOLEN_EXP_FASTOPEN_BASE + foc->len;
813 			*ptr = htonl((TCPOPT_EXP << 24) | (len << 16) |
814 				     TCPOPT_FASTOPEN_MAGIC);
815 			p += TCPOLEN_EXP_FASTOPEN_BASE;
816 		} else {
817 			len = TCPOLEN_FASTOPEN_BASE + foc->len;
818 			*p++ = TCPOPT_FASTOPEN;
819 			*p++ = len;
820 		}
821 
822 		memcpy(p, foc->val, foc->len);
823 		if ((len & 3) == 2) {
824 			p[foc->len] = TCPOPT_NOP;
825 			p[foc->len + 1] = TCPOPT_NOP;
826 		}
827 		ptr += (len + 3) >> 2;
828 	}
829 
830 	smc_options_write(ptr, &options);
831 
832 	mptcp_options_write(th, ptr, tp, opts);
833 }
834 
835 static void smc_set_option(struct tcp_sock *tp,
836 			   struct tcp_out_options *opts,
837 			   unsigned int *remaining)
838 {
839 #if IS_ENABLED(CONFIG_SMC)
840 	if (static_branch_unlikely(&tcp_have_smc) && tp->syn_smc) {
841 		tp->syn_smc = !!smc_call_hsbpf(1, tp, syn_option);
842 		/* re-check syn_smc */
843 		if (tp->syn_smc &&
844 		    *remaining >= TCPOLEN_EXP_SMC_BASE_ALIGNED) {
845 			opts->options |= OPTION_SMC;
846 			*remaining -= TCPOLEN_EXP_SMC_BASE_ALIGNED;
847 		}
848 	}
849 #endif
850 }
851 
852 static void smc_set_option_cond(const struct tcp_sock *tp,
853 				struct inet_request_sock *ireq,
854 				struct tcp_out_options *opts,
855 				unsigned int *remaining)
856 {
857 #if IS_ENABLED(CONFIG_SMC)
858 	if (static_branch_unlikely(&tcp_have_smc) && tp->syn_smc && ireq->smc_ok) {
859 		ireq->smc_ok = !!smc_call_hsbpf(1, tp, synack_option, ireq);
860 		/* re-check smc_ok */
861 		if (ireq->smc_ok &&
862 		    *remaining >= TCPOLEN_EXP_SMC_BASE_ALIGNED) {
863 			opts->options |= OPTION_SMC;
864 			*remaining -= TCPOLEN_EXP_SMC_BASE_ALIGNED;
865 		}
866 	}
867 #endif
868 }
869 
870 static void mptcp_set_option_cond(const struct request_sock *req,
871 				  struct tcp_out_options *opts,
872 				  unsigned int *remaining)
873 {
874 	if (rsk_is_mptcp(req)) {
875 		unsigned int size;
876 
877 		if (mptcp_synack_options(req, &size, &opts->mptcp)) {
878 			if (*remaining >= size) {
879 				opts->options |= OPTION_MPTCP;
880 				*remaining -= size;
881 			}
882 		}
883 	}
884 }
885 
886 static u32 tcp_synack_options_combine_saving(struct tcp_out_options *opts)
887 {
888 	/* How much there's room for combining with the alignment padding? */
889 	if ((opts->options & (OPTION_SACK_ADVERTISE | OPTION_TS)) ==
890 	    OPTION_SACK_ADVERTISE)
891 		return 2;
892 	else if (opts->options & OPTION_WSCALE)
893 		return 1;
894 	return 0;
895 }
896 
897 /* Calculates how long AccECN option will fit to @remaining option space.
898  *
899  * AccECN option can sometimes replace NOPs used for alignment of other
900  * TCP options (up to @max_combine_saving available).
901  *
902  * Only solutions with at least @required AccECN fields are accepted.
903  *
904  * Returns: The size of the AccECN option excluding space repurposed from
905  * the alignment of the other options.
906  */
907 static int tcp_options_fit_accecn(struct tcp_out_options *opts, int required,
908 				  int remaining)
909 {
910 	int size = TCP_ACCECN_MAXSIZE;
911 	int sack_blocks_reduce = 0;
912 	int max_combine_saving;
913 	int rem = remaining;
914 	int align_size;
915 
916 	if (opts->use_synack_ecn_bytes)
917 		max_combine_saving = tcp_synack_options_combine_saving(opts);
918 	else
919 		max_combine_saving = opts->num_sack_blocks > 0 ? 2 : 0;
920 	opts->num_accecn_fields = TCP_ACCECN_NUMFIELDS;
921 	while (opts->num_accecn_fields >= required) {
922 		/* Pad to dword if cannot combine */
923 		if ((size & 0x3) > max_combine_saving)
924 			align_size = ALIGN(size, 4);
925 		else
926 			align_size = ALIGN_DOWN(size, 4);
927 
928 		if (rem >= align_size) {
929 			size = align_size;
930 			break;
931 		} else if (opts->num_accecn_fields == required &&
932 			   opts->num_sack_blocks > 2 &&
933 			   required > 0) {
934 			/* Try to fit the option by removing one SACK block */
935 			opts->num_sack_blocks--;
936 			sack_blocks_reduce++;
937 			rem = rem + TCPOLEN_SACK_PERBLOCK;
938 
939 			opts->num_accecn_fields = TCP_ACCECN_NUMFIELDS;
940 			size = TCP_ACCECN_MAXSIZE;
941 			continue;
942 		}
943 
944 		opts->num_accecn_fields--;
945 		size -= TCPOLEN_ACCECN_PERFIELD;
946 	}
947 	if (sack_blocks_reduce > 0) {
948 		if (opts->num_accecn_fields >= required)
949 			size -= sack_blocks_reduce * TCPOLEN_SACK_PERBLOCK;
950 		else
951 			opts->num_sack_blocks += sack_blocks_reduce;
952 	}
953 	if (opts->num_accecn_fields < required)
954 		return 0;
955 
956 	opts->options |= OPTION_ACCECN;
957 	return size;
958 }
959 
960 /* Compute TCP options for SYN packets. This is not the final
961  * network wire format yet.
962  */
963 static unsigned int tcp_syn_options(struct sock *sk, struct sk_buff *skb,
964 				struct tcp_out_options *opts,
965 				struct tcp_key *key)
966 {
967 	struct tcp_sock *tp = tcp_sk(sk);
968 	unsigned int remaining = MAX_TCP_OPTION_SPACE;
969 	struct tcp_fastopen_request *fastopen = tp->fastopen_req;
970 	bool timestamps;
971 
972 	opts->options = 0;
973 
974 	/* Better than switch (key.type) as it has static branches */
975 	if (tcp_key_is_md5(key)) {
976 		timestamps = false;
977 		opts->options |= OPTION_MD5;
978 		remaining -= TCPOLEN_MD5SIG_ALIGNED;
979 	} else {
980 		timestamps = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_timestamps);
981 		if (tcp_key_is_ao(key)) {
982 			opts->options |= OPTION_AO;
983 			remaining -= tcp_ao_len_aligned(key->ao_key);
984 		}
985 	}
986 
987 	/* We always get an MSS option.  The option bytes which will be seen in
988 	 * normal data packets should timestamps be used, must be in the MSS
989 	 * advertised.  But we subtract them from tp->mss_cache so that
990 	 * calculations in tcp_sendmsg are simpler etc.  So account for this
991 	 * fact here if necessary.  If we don't do this correctly, as a
992 	 * receiver we won't recognize data packets as being full sized when we
993 	 * should, and thus we won't abide by the delayed ACK rules correctly.
994 	 * SACKs don't matter, we never delay an ACK when we have any of those
995 	 * going out.  */
996 	opts->mss = tcp_advertise_mss(sk);
997 	remaining -= TCPOLEN_MSS_ALIGNED;
998 
999 	if (likely(timestamps)) {
1000 		opts->options |= OPTION_TS;
1001 		opts->tsval = tcp_skb_timestamp_ts(tp->tcp_usec_ts, skb) + tp->tsoffset;
1002 		opts->tsecr = tp->rx_opt.ts_recent;
1003 		remaining -= TCPOLEN_TSTAMP_ALIGNED;
1004 	}
1005 	if (likely(READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_window_scaling))) {
1006 		opts->ws = tp->rx_opt.rcv_wscale;
1007 		opts->options |= OPTION_WSCALE;
1008 		remaining -= TCPOLEN_WSCALE_ALIGNED;
1009 	}
1010 	if (likely(READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_sack))) {
1011 		opts->options |= OPTION_SACK_ADVERTISE;
1012 		if (unlikely(!(OPTION_TS & opts->options)))
1013 			remaining -= TCPOLEN_SACKPERM_ALIGNED;
1014 	}
1015 
1016 	if (fastopen && fastopen->cookie.len >= 0) {
1017 		u32 need = fastopen->cookie.len;
1018 
1019 		need += fastopen->cookie.exp ? TCPOLEN_EXP_FASTOPEN_BASE :
1020 					       TCPOLEN_FASTOPEN_BASE;
1021 		need = (need + 3) & ~3U;  /* Align to 32 bits */
1022 		if (remaining >= need) {
1023 			opts->options |= OPTION_FAST_OPEN_COOKIE;
1024 			opts->fastopen_cookie = &fastopen->cookie;
1025 			remaining -= need;
1026 			tp->syn_fastopen = 1;
1027 			tp->syn_fastopen_exp = fastopen->cookie.exp ? 1 : 0;
1028 		}
1029 	}
1030 
1031 	smc_set_option(tp, opts, &remaining);
1032 
1033 	if (sk_is_mptcp(sk)) {
1034 		unsigned int size;
1035 
1036 		if (mptcp_syn_options(sk, skb, &size, &opts->mptcp)) {
1037 			if (remaining >= size) {
1038 				opts->options |= OPTION_MPTCP;
1039 				remaining -= size;
1040 			}
1041 		}
1042 	}
1043 
1044 	/* Simultaneous open SYN/ACK needs AccECN option but not SYN.
1045 	 * It is attempted to negotiate the use of AccECN also on the first
1046 	 * retransmitted SYN, as mentioned in "3.1.4.1. Retransmitted SYNs"
1047 	 * of AccECN draft.
1048 	 */
1049 	if (unlikely((TCP_SKB_CB(skb)->tcp_flags & TCPHDR_ACK) &&
1050 		     tcp_ecn_mode_accecn(tp) &&
1051 		     inet_csk(sk)->icsk_retransmits < 2 &&
1052 		     READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_ecn_option) &&
1053 		     remaining >= TCPOLEN_ACCECN_BASE)) {
1054 		opts->use_synack_ecn_bytes = 1;
1055 		remaining -= tcp_options_fit_accecn(opts, 0, remaining);
1056 	}
1057 
1058 	bpf_skops_hdr_opt_len(sk, skb, NULL, NULL, 0, opts, &remaining);
1059 
1060 	return MAX_TCP_OPTION_SPACE - remaining;
1061 }
1062 
1063 /* Set up TCP options for SYN-ACKs. */
1064 static unsigned int tcp_synack_options(const struct sock *sk,
1065 				       struct request_sock *req,
1066 				       unsigned int mss, struct sk_buff *skb,
1067 				       struct tcp_out_options *opts,
1068 				       const struct tcp_key *key,
1069 				       struct tcp_fastopen_cookie *foc,
1070 				       enum tcp_synack_type synack_type,
1071 				       struct sk_buff *syn_skb)
1072 {
1073 	struct inet_request_sock *ireq = inet_rsk(req);
1074 	unsigned int remaining = MAX_TCP_OPTION_SPACE;
1075 	struct tcp_request_sock *treq = tcp_rsk(req);
1076 
1077 	if (tcp_key_is_md5(key)) {
1078 		opts->options |= OPTION_MD5;
1079 		remaining -= TCPOLEN_MD5SIG_ALIGNED;
1080 
1081 		/* We can't fit any SACK blocks in a packet with MD5 + TS
1082 		 * options. There was discussion about disabling SACK
1083 		 * rather than TS in order to fit in better with old,
1084 		 * buggy kernels, but that was deemed to be unnecessary.
1085 		 */
1086 		if (synack_type != TCP_SYNACK_COOKIE)
1087 			ireq->tstamp_ok &= !ireq->sack_ok;
1088 	} else if (tcp_key_is_ao(key)) {
1089 		opts->options |= OPTION_AO;
1090 		remaining -= tcp_ao_len_aligned(key->ao_key);
1091 		ireq->tstamp_ok &= !ireq->sack_ok;
1092 	}
1093 
1094 	/* We always send an MSS option. */
1095 	opts->mss = mss;
1096 	remaining -= TCPOLEN_MSS_ALIGNED;
1097 
1098 	if (likely(ireq->wscale_ok)) {
1099 		opts->ws = ireq->rcv_wscale;
1100 		opts->options |= OPTION_WSCALE;
1101 		remaining -= TCPOLEN_WSCALE_ALIGNED;
1102 	}
1103 	if (likely(ireq->tstamp_ok)) {
1104 		opts->options |= OPTION_TS;
1105 		opts->tsval = tcp_skb_timestamp_ts(tcp_rsk(req)->req_usec_ts, skb) +
1106 			      tcp_rsk(req)->ts_off;
1107 		if (!tcp_rsk(req)->snt_tsval_first) {
1108 			if (!opts->tsval)
1109 				opts->tsval = ~0U;
1110 			tcp_rsk(req)->snt_tsval_first = opts->tsval;
1111 		}
1112 		WRITE_ONCE(tcp_rsk(req)->snt_tsval_last, opts->tsval);
1113 		opts->tsecr = req->ts_recent;
1114 		remaining -= TCPOLEN_TSTAMP_ALIGNED;
1115 	}
1116 	if (likely(ireq->sack_ok)) {
1117 		opts->options |= OPTION_SACK_ADVERTISE;
1118 		if (unlikely(!ireq->tstamp_ok))
1119 			remaining -= TCPOLEN_SACKPERM_ALIGNED;
1120 	}
1121 	if (foc != NULL && foc->len >= 0) {
1122 		u32 need = foc->len;
1123 
1124 		need += foc->exp ? TCPOLEN_EXP_FASTOPEN_BASE :
1125 				   TCPOLEN_FASTOPEN_BASE;
1126 		need = (need + 3) & ~3U;  /* Align to 32 bits */
1127 		if (remaining >= need) {
1128 			opts->options |= OPTION_FAST_OPEN_COOKIE;
1129 			opts->fastopen_cookie = foc;
1130 			remaining -= need;
1131 		}
1132 	}
1133 
1134 	mptcp_set_option_cond(req, opts, &remaining);
1135 
1136 	smc_set_option_cond(tcp_sk(sk), ireq, opts, &remaining);
1137 
1138 	if (treq->accecn_ok &&
1139 	    READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_ecn_option) &&
1140 	    synack_type != TCP_SYNACK_RETRANS && remaining >= TCPOLEN_ACCECN_BASE) {
1141 		opts->use_synack_ecn_bytes = 1;
1142 		remaining -= tcp_options_fit_accecn(opts, 0, remaining);
1143 	}
1144 
1145 	bpf_skops_hdr_opt_len((struct sock *)sk, skb, req, syn_skb,
1146 			      synack_type, opts, &remaining);
1147 
1148 	return MAX_TCP_OPTION_SPACE - remaining;
1149 }
1150 
1151 /* Compute TCP options for ESTABLISHED sockets. This is not the
1152  * final wire format yet.
1153  */
1154 static unsigned int tcp_established_options(struct sock *sk, struct sk_buff *skb,
1155 					struct tcp_out_options *opts,
1156 					struct tcp_key *key)
1157 {
1158 	struct tcp_sock *tp = tcp_sk(sk);
1159 	unsigned int size = 0;
1160 	unsigned int eff_sacks;
1161 
1162 	opts->options = 0;
1163 
1164 	/* Better than switch (key.type) as it has static branches */
1165 	if (tcp_key_is_md5(key)) {
1166 		opts->options |= OPTION_MD5;
1167 		size += TCPOLEN_MD5SIG_ALIGNED;
1168 	} else if (tcp_key_is_ao(key)) {
1169 		opts->options |= OPTION_AO;
1170 		size += tcp_ao_len_aligned(key->ao_key);
1171 	}
1172 
1173 	if (likely(tp->rx_opt.tstamp_ok)) {
1174 		opts->options |= OPTION_TS;
1175 		opts->tsval = skb ? tcp_skb_timestamp_ts(tp->tcp_usec_ts, skb) +
1176 				tp->tsoffset : 0;
1177 		opts->tsecr = tp->rx_opt.ts_recent;
1178 		size += TCPOLEN_TSTAMP_ALIGNED;
1179 	}
1180 
1181 	/* MPTCP options have precedence over SACK for the limited TCP
1182 	 * option space because a MPTCP connection would be forced to
1183 	 * fall back to regular TCP if a required multipath option is
1184 	 * missing. SACK still gets a chance to use whatever space is
1185 	 * left.
1186 	 */
1187 	if (sk_is_mptcp(sk)) {
1188 		unsigned int remaining = MAX_TCP_OPTION_SPACE - size;
1189 		unsigned int opt_size = 0;
1190 
1191 		if (mptcp_established_options(sk, skb, &opt_size, remaining,
1192 					      &opts->mptcp)) {
1193 			opts->options |= OPTION_MPTCP;
1194 			size += opt_size;
1195 		}
1196 	}
1197 
1198 	eff_sacks = tp->rx_opt.num_sacks + tp->rx_opt.dsack;
1199 	if (unlikely(eff_sacks)) {
1200 		const unsigned int remaining = MAX_TCP_OPTION_SPACE - size;
1201 		if (likely(remaining >= TCPOLEN_SACK_BASE_ALIGNED +
1202 					TCPOLEN_SACK_PERBLOCK)) {
1203 			opts->num_sack_blocks =
1204 				min_t(unsigned int, eff_sacks,
1205 				      (remaining - TCPOLEN_SACK_BASE_ALIGNED) /
1206 				      TCPOLEN_SACK_PERBLOCK);
1207 
1208 			size += TCPOLEN_SACK_BASE_ALIGNED +
1209 				opts->num_sack_blocks * TCPOLEN_SACK_PERBLOCK;
1210 		} else {
1211 			opts->num_sack_blocks = 0;
1212 		}
1213 	} else {
1214 		opts->num_sack_blocks = 0;
1215 	}
1216 
1217 	if (tcp_ecn_mode_accecn(tp)) {
1218 		int ecn_opt = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_ecn_option);
1219 
1220 		if (ecn_opt && tp->saw_accecn_opt &&
1221 		    (ecn_opt >= TCP_ACCECN_OPTION_PERSIST ||
1222 		     !tcp_accecn_opt_fail_send(tp)) &&
1223 		    (ecn_opt >= TCP_ACCECN_OPTION_FULL || tp->accecn_opt_demand ||
1224 		     tcp_accecn_option_beacon_check(sk))) {
1225 			opts->use_synack_ecn_bytes = 0;
1226 			size += tcp_options_fit_accecn(opts, tp->accecn_minlen,
1227 						       MAX_TCP_OPTION_SPACE - size);
1228 		}
1229 	}
1230 
1231 	if (unlikely(BPF_SOCK_OPS_TEST_FLAG(tp,
1232 					    BPF_SOCK_OPS_WRITE_HDR_OPT_CB_FLAG))) {
1233 		unsigned int remaining = MAX_TCP_OPTION_SPACE - size;
1234 
1235 		bpf_skops_hdr_opt_len(sk, skb, NULL, NULL, 0, opts, &remaining);
1236 
1237 		size = MAX_TCP_OPTION_SPACE - remaining;
1238 	}
1239 
1240 	return size;
1241 }
1242 
1243 
1244 /* TCP SMALL QUEUES (TSQ)
1245  *
1246  * TSQ goal is to keep small amount of skbs per tcp flow in tx queues (qdisc+dev)
1247  * to reduce RTT and bufferbloat.
1248  * We do this using a special skb destructor (tcp_wfree).
1249  *
1250  * Its important tcp_wfree() can be replaced by sock_wfree() in the event skb
1251  * needs to be reallocated in a driver.
1252  * The invariant being skb->truesize subtracted from sk->sk_wmem_alloc
1253  *
1254  * Since transmit from skb destructor is forbidden, we use a BH work item
1255  * to process all sockets that eventually need to send more skbs.
1256  * We use one work item per cpu, with its own queue of sockets.
1257  */
1258 struct tsq_work {
1259 	struct work_struct	work;
1260 	struct list_head	head; /* queue of tcp sockets */
1261 };
1262 static DEFINE_PER_CPU(struct tsq_work, tsq_work);
1263 
1264 static void tcp_tsq_write(struct sock *sk)
1265 {
1266 	if ((1 << sk->sk_state) &
1267 	    (TCPF_ESTABLISHED | TCPF_FIN_WAIT1 | TCPF_CLOSING |
1268 	     TCPF_CLOSE_WAIT  | TCPF_LAST_ACK)) {
1269 		struct tcp_sock *tp = tcp_sk(sk);
1270 
1271 		if (tp->lost_out > tp->retrans_out &&
1272 		    tcp_snd_cwnd(tp) > tcp_packets_in_flight(tp)) {
1273 			tcp_mstamp_refresh(tp);
1274 			tcp_xmit_retransmit_queue(sk);
1275 		}
1276 
1277 		tcp_write_xmit(sk, tcp_current_mss(sk), tp->nonagle,
1278 			       0, GFP_ATOMIC);
1279 	}
1280 }
1281 
1282 static void tcp_tsq_handler(struct sock *sk)
1283 {
1284 	bh_lock_sock(sk);
1285 	if (!sock_owned_by_user(sk))
1286 		tcp_tsq_write(sk);
1287 	else if (!test_and_set_bit(TCP_TSQ_DEFERRED, &sk->sk_tsq_flags))
1288 		sock_hold(sk);
1289 	bh_unlock_sock(sk);
1290 }
1291 /*
1292  * One work item per cpu tries to send more skbs.
1293  * We run in BH context but need to disable irqs when
1294  * transferring tsq->head because tcp_wfree() might
1295  * interrupt us (non NAPI drivers)
1296  */
1297 static void tcp_tsq_workfn(struct work_struct *work)
1298 {
1299 	struct tsq_work *tsq = container_of(work, struct tsq_work, work);
1300 	LIST_HEAD(list);
1301 	unsigned long flags;
1302 	struct list_head *q, *n;
1303 	struct tcp_sock *tp;
1304 	struct sock *sk;
1305 
1306 	local_irq_save(flags);
1307 	list_splice_init(&tsq->head, &list);
1308 	local_irq_restore(flags);
1309 
1310 	list_for_each_safe(q, n, &list) {
1311 		tp = list_entry(q, struct tcp_sock, tsq_node);
1312 		list_del(&tp->tsq_node);
1313 
1314 		sk = (struct sock *)tp;
1315 		smp_mb__before_atomic();
1316 		clear_bit(TSQ_QUEUED, &sk->sk_tsq_flags);
1317 
1318 		tcp_tsq_handler(sk);
1319 		sk_free(sk);
1320 	}
1321 }
1322 
1323 #define TCP_DEFERRED_ALL (TCPF_TSQ_DEFERRED |		\
1324 			  TCPF_WRITE_TIMER_DEFERRED |	\
1325 			  TCPF_DELACK_TIMER_DEFERRED |	\
1326 			  TCPF_MTU_REDUCED_DEFERRED |	\
1327 			  TCPF_ACK_DEFERRED)
1328 /**
1329  * tcp_release_cb - tcp release_sock() callback
1330  * @sk: socket
1331  *
1332  * called from release_sock() to perform protocol dependent
1333  * actions before socket release.
1334  */
1335 void tcp_release_cb(struct sock *sk)
1336 {
1337 	unsigned long flags = smp_load_acquire(&sk->sk_tsq_flags);
1338 	unsigned long nflags;
1339 
1340 	/* perform an atomic operation only if at least one flag is set */
1341 	do {
1342 		if (!(flags & TCP_DEFERRED_ALL))
1343 			return;
1344 		nflags = flags & ~TCP_DEFERRED_ALL;
1345 	} while (!try_cmpxchg(&sk->sk_tsq_flags, &flags, nflags));
1346 
1347 	if (flags & TCPF_TSQ_DEFERRED) {
1348 		tcp_tsq_write(sk);
1349 		__sock_put(sk);
1350 	}
1351 
1352 	if (flags & TCPF_WRITE_TIMER_DEFERRED) {
1353 		tcp_write_timer_handler(sk);
1354 		__sock_put(sk);
1355 	}
1356 	if (flags & TCPF_DELACK_TIMER_DEFERRED) {
1357 		tcp_delack_timer_handler(sk);
1358 		__sock_put(sk);
1359 	}
1360 	if (flags & TCPF_MTU_REDUCED_DEFERRED) {
1361 		inet_csk(sk)->icsk_af_ops->mtu_reduced(sk);
1362 		__sock_put(sk);
1363 	}
1364 	if ((flags & TCPF_ACK_DEFERRED) && inet_csk_ack_scheduled(sk))
1365 		tcp_send_ack(sk);
1366 }
1367 EXPORT_IPV6_MOD(tcp_release_cb);
1368 
1369 void __init tcp_tsq_work_init(void)
1370 {
1371 	int i;
1372 
1373 	for_each_possible_cpu(i) {
1374 		struct tsq_work *tsq = &per_cpu(tsq_work, i);
1375 
1376 		INIT_LIST_HEAD(&tsq->head);
1377 		INIT_WORK(&tsq->work, tcp_tsq_workfn);
1378 	}
1379 }
1380 
1381 /*
1382  * Write buffer destructor automatically called from kfree_skb.
1383  * We can't xmit new skbs from this context, as we might already
1384  * hold qdisc lock.
1385  */
1386 void tcp_wfree(struct sk_buff *skb)
1387 {
1388 	struct sock *sk = skb->sk;
1389 	struct tcp_sock *tp = tcp_sk(sk);
1390 	unsigned long flags, nval, oval;
1391 	struct tsq_work *tsq;
1392 	bool empty;
1393 
1394 	/* Keep one reference on sk_wmem_alloc.
1395 	 * Will be released by sk_free() from here or tcp_tsq_workfn()
1396 	 */
1397 	WARN_ON(refcount_sub_and_test(skb->truesize - 1, &sk->sk_wmem_alloc));
1398 
1399 	/* If this softirq is serviced by ksoftirqd, we are likely under stress.
1400 	 * Wait until our queues (qdisc + devices) are drained.
1401 	 * This gives :
1402 	 * - less callbacks to tcp_write_xmit(), reducing stress (batches)
1403 	 * - chance for incoming ACK (processed by another cpu maybe)
1404 	 *   to migrate this flow (skb->ooo_okay will be eventually set)
1405 	 */
1406 	if (refcount_read(&sk->sk_wmem_alloc) >= SKB_TRUESIZE(1) && this_cpu_ksoftirqd() == current)
1407 		goto out;
1408 
1409 	oval = smp_load_acquire(&sk->sk_tsq_flags);
1410 	do {
1411 		if (!(oval & TSQF_THROTTLED) || (oval & TSQF_QUEUED))
1412 			goto out;
1413 
1414 		nval = (oval & ~TSQF_THROTTLED) | TSQF_QUEUED;
1415 	} while (!try_cmpxchg(&sk->sk_tsq_flags, &oval, nval));
1416 
1417 	/* queue this socket to BH workqueue */
1418 	local_irq_save(flags);
1419 	tsq = this_cpu_ptr(&tsq_work);
1420 	empty = list_empty(&tsq->head);
1421 	list_add(&tp->tsq_node, &tsq->head);
1422 	if (empty)
1423 		queue_work(system_bh_wq, &tsq->work);
1424 	local_irq_restore(flags);
1425 	return;
1426 out:
1427 	sk_free(sk);
1428 }
1429 
1430 /* Note: Called under soft irq.
1431  * We can call TCP stack right away, unless socket is owned by user.
1432  */
1433 enum hrtimer_restart tcp_pace_kick(struct hrtimer *timer)
1434 {
1435 	struct tcp_sock *tp = container_of(timer, struct tcp_sock, pacing_timer);
1436 	struct sock *sk = (struct sock *)tp;
1437 
1438 	tcp_tsq_handler(sk);
1439 	sock_put(sk);
1440 
1441 	return HRTIMER_NORESTART;
1442 }
1443 
1444 static void tcp_update_skb_after_send(struct sock *sk, struct sk_buff *skb,
1445 				      u64 prior_wstamp)
1446 {
1447 	struct tcp_sock *tp = tcp_sk(sk);
1448 
1449 	if (sk->sk_pacing_status != SK_PACING_NONE) {
1450 		unsigned long rate = READ_ONCE(sk->sk_pacing_rate);
1451 
1452 		/* Original sch_fq does not pace first 10 MSS
1453 		 * Note that tp->data_segs_out overflows after 2^32 packets,
1454 		 * this is a minor annoyance.
1455 		 */
1456 		if (rate != ~0UL && rate && tp->data_segs_out >= 10) {
1457 			u64 len_ns = div64_ul((u64)skb->len * NSEC_PER_SEC, rate);
1458 			u64 credit = tp->tcp_wstamp_ns - prior_wstamp;
1459 
1460 			/* take into account OS jitter */
1461 			len_ns -= min_t(u64, len_ns / 2, credit);
1462 			tp->tcp_wstamp_ns += len_ns;
1463 		}
1464 	}
1465 	list_move_tail(&skb->tcp_tsorted_anchor, &tp->tsorted_sent_queue);
1466 }
1467 
1468 /* Snapshot the current delivery information in the skb, to generate
1469  * a rate sample later when the skb is (s)acked in tcp_rate_skb_delivered().
1470  */
1471 static void tcp_rate_skb_sent(struct sock *sk, struct sk_buff *skb)
1472 {
1473 	struct tcp_sock *tp = tcp_sk(sk);
1474 
1475 	 /* In general we need to start delivery rate samples from the
1476 	  * time we received the most recent ACK, to ensure we include
1477 	  * the full time the network needs to deliver all in-flight
1478 	  * packets. If there are no packets in flight yet, then we
1479 	  * know that any ACKs after now indicate that the network was
1480 	  * able to deliver those packets completely in the sampling
1481 	  * interval between now and the next ACK.
1482 	  *
1483 	  * Note that we use packets_out instead of tcp_packets_in_flight(tp)
1484 	  * because the latter is a guess based on RTO and loss-marking
1485 	  * heuristics. We don't want spurious RTOs or loss markings to cause
1486 	  * a spuriously small time interval, causing a spuriously high
1487 	  * bandwidth estimate.
1488 	  */
1489 	if (!tp->packets_out) {
1490 		u64 tstamp_us = tcp_skb_timestamp_us(skb);
1491 
1492 		tp->first_tx_mstamp  = tstamp_us;
1493 		tp->delivered_mstamp = tstamp_us;
1494 	}
1495 
1496 	TCP_SKB_CB(skb)->tx.first_tx_mstamp	= tp->first_tx_mstamp;
1497 	TCP_SKB_CB(skb)->tx.delivered_mstamp	= tp->delivered_mstamp;
1498 	TCP_SKB_CB(skb)->tx.delivered		= tp->delivered;
1499 	TCP_SKB_CB(skb)->tx.delivered_ce	= tp->delivered_ce;
1500 	TCP_SKB_CB(skb)->tx.is_app_limited	= tp->app_limited ? 1 : 0;
1501 }
1502 
1503 INDIRECT_CALLABLE_DECLARE(int ip_queue_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl));
1504 INDIRECT_CALLABLE_DECLARE(int inet6_csk_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl));
1505 
1506 /* This routine computes an IPv4 TCP checksum. */
1507 static void tcp_v4_send_check(struct sock *sk, struct sk_buff *skb)
1508 {
1509 	const struct inet_sock *inet = inet_sk(sk);
1510 
1511 	__tcp_v4_send_check(skb, inet->inet_saddr, inet->inet_daddr);
1512 }
1513 
1514 #if IS_ENABLED(CONFIG_IPV6)
1515 #include <net/ip6_checksum.h>
1516 
1517 static void tcp_v6_send_check(struct sock *sk, struct sk_buff *skb)
1518 {
1519 	__tcp_v6_send_check(skb, &sk->sk_v6_rcv_saddr, &sk->sk_v6_daddr);
1520 }
1521 #endif
1522 
1523 /* This routine actually transmits TCP packets queued in by
1524  * tcp_do_sendmsg().  This is used by both the initial
1525  * transmission and possible later retransmissions.
1526  * All SKB's seen here are completely headerless.  It is our
1527  * job to build the TCP header, and pass the packet down to
1528  * IP so it can do the same plus pass the packet off to the
1529  * device.
1530  *
1531  * We are working here with either a clone of the original
1532  * SKB, or a fresh unique copy made by the retransmit engine.
1533  */
1534 static int __tcp_transmit_skb(struct sock *sk, struct sk_buff *skb,
1535 			      int clone_it, gfp_t gfp_mask, u32 rcv_nxt)
1536 {
1537 	const struct inet_connection_sock *icsk = inet_csk(sk);
1538 	struct inet_sock *inet;
1539 	struct tcp_sock *tp;
1540 	struct tcp_skb_cb *tcb;
1541 	struct tcp_out_options opts;
1542 	unsigned int tcp_options_size, tcp_header_size;
1543 	struct sk_buff *oskb = NULL;
1544 	struct tcp_key key;
1545 	struct tcphdr *th;
1546 	u64 prior_wstamp;
1547 	int err;
1548 
1549 	BUG_ON(!skb || !tcp_skb_pcount(skb));
1550 	tp = tcp_sk(sk);
1551 	prior_wstamp = tp->tcp_wstamp_ns;
1552 	tp->tcp_wstamp_ns = max(tp->tcp_wstamp_ns, tp->tcp_clock_cache);
1553 	skb_set_delivery_time(skb, tp->tcp_wstamp_ns, SKB_CLOCK_MONOTONIC);
1554 	if (clone_it) {
1555 		oskb = skb;
1556 
1557 		tcp_skb_tsorted_save(oskb) {
1558 			if (unlikely(skb_cloned(oskb)))
1559 				skb = pskb_copy(oskb, gfp_mask);
1560 			else
1561 				skb = skb_clone(oskb, gfp_mask);
1562 		} tcp_skb_tsorted_restore(oskb);
1563 
1564 		if (unlikely(!skb))
1565 			return -ENOBUFS;
1566 		/* retransmit skbs might have a non zero value in skb->dev
1567 		 * because skb->dev is aliased with skb->rbnode.rb_left
1568 		 */
1569 		skb->dev = NULL;
1570 	}
1571 
1572 	inet = inet_sk(sk);
1573 	tcb = TCP_SKB_CB(skb);
1574 	memset(&opts.cleared, 0, sizeof(opts.cleared));
1575 
1576 	tcp_get_current_key(sk, &key);
1577 	if (unlikely(tcb->tcp_flags & TCPHDR_SYN)) {
1578 		tcp_options_size = tcp_syn_options(sk, skb, &opts, &key);
1579 	} else {
1580 		tcp_options_size = tcp_established_options(sk, skb, &opts, &key);
1581 		/* Force a PSH flag on all (GSO) packets to expedite GRO flush
1582 		 * at receiver : This slightly improve GRO performance.
1583 		 * Note that we do not force the PSH flag for non GSO packets,
1584 		 * because they might be sent under high congestion events,
1585 		 * and in this case it is better to delay the delivery of 1-MSS
1586 		 * packets and thus the corresponding ACK packet that would
1587 		 * release the following packet.
1588 		 */
1589 		if (tcp_skb_pcount(skb) > 1)
1590 			tcb->tcp_flags |= TCPHDR_PSH;
1591 	}
1592 	tcp_header_size = tcp_options_size + sizeof(struct tcphdr);
1593 
1594 	/* We set skb->ooo_okay to one if this packet can select
1595 	 * a different TX queue than prior packets of this flow,
1596 	 * to avoid self inflicted reorders.
1597 	 * The 'other' queue decision is based on current cpu number
1598 	 * if XPS is enabled, or sk->sk_txhash otherwise.
1599 	 * We can switch to another (and better) queue if:
1600 	 * 1) No packet with payload is in qdisc/device queues.
1601 	 *    Delays in TX completion can defeat the test
1602 	 *    even if packets were already sent.
1603 	 * 2) Or rtx queue is empty.
1604 	 *    This mitigates above case if ACK packets for
1605 	 *    all prior packets were already processed.
1606 	 */
1607 	skb->ooo_okay = sk_wmem_alloc_get(sk) < SKB_TRUESIZE(1) ||
1608 			tcp_rtx_queue_empty(sk);
1609 
1610 	/* If we had to use memory reserve to allocate this skb,
1611 	 * this might cause drops if packet is looped back :
1612 	 * Other socket might not have SOCK_MEMALLOC.
1613 	 * Packets not looped back do not care about pfmemalloc.
1614 	 */
1615 	skb->pfmemalloc = 0;
1616 
1617 	__skb_push(skb, tcp_header_size);
1618 	skb_reset_transport_header(skb);
1619 
1620 	skb_orphan(skb);
1621 	skb->sk = sk;
1622 	skb->destructor = skb_is_tcp_pure_ack(skb) ? __sock_wfree : tcp_wfree;
1623 	refcount_add(skb->truesize, &sk->sk_wmem_alloc);
1624 
1625 	skb_set_dst_pending_confirm(skb, READ_ONCE(sk->sk_dst_pending_confirm));
1626 
1627 	/* Build TCP header and checksum it. */
1628 	th = (struct tcphdr *)skb->data;
1629 	th->source		= inet->inet_sport;
1630 	th->dest		= inet->inet_dport;
1631 	th->seq			= htonl(tcb->seq);
1632 	th->ack_seq		= htonl(rcv_nxt);
1633 	*(((__be16 *)th) + 6)	= htons(((tcp_header_size >> 2) << 12) |
1634 					(tcb->tcp_flags & TCPHDR_FLAGS_MASK));
1635 
1636 	th->check		= 0;
1637 	th->urg_ptr		= 0;
1638 
1639 	/* The urg_mode check is necessary during a below snd_una win probe */
1640 	if (unlikely(tcp_urg_mode(tp) && before(tcb->seq, tp->snd_up))) {
1641 		if (before(tp->snd_up, tcb->seq + 0x10000)) {
1642 			th->urg_ptr = htons(tp->snd_up - tcb->seq);
1643 			th->urg = 1;
1644 		} else if (after(tcb->seq + 0xFFFF, tp->snd_nxt)) {
1645 			th->urg_ptr = htons(0xFFFF);
1646 			th->urg = 1;
1647 		}
1648 	}
1649 
1650 	skb_shinfo(skb)->gso_type = sk->sk_gso_type;
1651 	if (likely(!(tcb->tcp_flags & TCPHDR_SYN))) {
1652 		th->window      = htons(tcp_select_window(sk));
1653 		tcp_ecn_send(sk, skb, th, tcp_header_size);
1654 	} else {
1655 		/* RFC1323: The window in SYN & SYN/ACK segments
1656 		 * is never scaled.
1657 		 */
1658 		th->window	= htons(min(tp->rcv_wnd, 65535U));
1659 	}
1660 
1661 	tcp_options_write(th, tp, NULL, &opts, &key);
1662 
1663 	if (tcp_key_is_md5(&key)) {
1664 #ifdef CONFIG_TCP_MD5SIG
1665 		/* Calculate the MD5 hash, as we have all we need now */
1666 		sk_gso_disable(sk);
1667 		tp->af_specific->calc_md5_hash(opts.hash_location,
1668 					       key.md5_key, sk, skb);
1669 #endif
1670 	} else if (tcp_key_is_ao(&key)) {
1671 		int err;
1672 
1673 		err = tcp_ao_transmit_skb(sk, skb, key.ao_key, th,
1674 					  opts.hash_location);
1675 		if (err) {
1676 			sk_skb_reason_drop(sk, skb, SKB_DROP_REASON_NOT_SPECIFIED);
1677 			return -ENOMEM;
1678 		}
1679 	}
1680 
1681 	/* BPF prog is the last one writing header option */
1682 	bpf_skops_write_hdr_opt(sk, skb, NULL, NULL, 0, &opts);
1683 
1684 #if IS_ENABLED(CONFIG_IPV6)
1685 	if (likely(icsk->icsk_af_ops->net_header_len == sizeof(struct ipv6hdr)))
1686 		tcp_v6_send_check(sk, skb);
1687 	else
1688 #endif
1689 		tcp_v4_send_check(sk, skb);
1690 
1691 	if (likely(tcb->tcp_flags & TCPHDR_ACK))
1692 		tcp_event_ack_sent(sk, rcv_nxt);
1693 
1694 	if (skb->len != tcp_header_size) {
1695 		tcp_event_data_sent(tp, sk);
1696 		tp->data_segs_out += tcp_skb_pcount(skb);
1697 		tp->bytes_sent += skb->len - tcp_header_size;
1698 	}
1699 
1700 	if (after(tcb->end_seq, tp->snd_nxt) || tcb->seq == tcb->end_seq)
1701 		TCP_ADD_STATS(sock_net(sk), TCP_MIB_OUTSEGS,
1702 			      tcp_skb_pcount(skb));
1703 
1704 	tp->segs_out += tcp_skb_pcount(skb);
1705 	skb_set_hash_from_sk(skb, sk);
1706 	/* OK, its time to fill skb_shinfo(skb)->gso_{segs|size} */
1707 	skb_shinfo(skb)->gso_segs = tcp_skb_pcount(skb);
1708 	skb_shinfo(skb)->gso_size = tcp_skb_mss(skb);
1709 
1710 	/* Leave earliest departure time in skb->tstamp (skb->skb_mstamp_ns) */
1711 
1712 	/* Cleanup our debris for IP stacks */
1713 	memset(skb->cb, 0, max(sizeof(struct inet_skb_parm),
1714 			       sizeof(struct inet6_skb_parm)));
1715 
1716 	tcp_add_tx_delay(skb, tp);
1717 
1718 	err = INDIRECT_CALL_INET(icsk->icsk_af_ops->queue_xmit,
1719 				 inet6_csk_xmit, ip_queue_xmit,
1720 				 sk, skb, &inet->cork.fl);
1721 
1722 	if (unlikely(err > 0)) {
1723 		tcp_enter_cwr(sk);
1724 		err = net_xmit_eval(err);
1725 	}
1726 	if (!err && oskb) {
1727 		tcp_update_skb_after_send(sk, oskb, prior_wstamp);
1728 		tcp_rate_skb_sent(sk, oskb);
1729 	}
1730 	return err;
1731 }
1732 
1733 static int tcp_transmit_skb(struct sock *sk, struct sk_buff *skb, int clone_it,
1734 			    gfp_t gfp_mask)
1735 {
1736 	return __tcp_transmit_skb(sk, skb, clone_it, gfp_mask,
1737 				  tcp_sk(sk)->rcv_nxt);
1738 }
1739 
1740 /* This routine just queues the buffer for sending.
1741  *
1742  * NOTE: probe0 timer is not checked, do not forget tcp_push_pending_frames,
1743  * otherwise socket can stall.
1744  */
1745 static void tcp_queue_skb(struct sock *sk, struct sk_buff *skb)
1746 {
1747 	struct tcp_sock *tp = tcp_sk(sk);
1748 
1749 	/* Advance write_seq and place onto the write_queue. */
1750 	WRITE_ONCE(tp->write_seq, TCP_SKB_CB(skb)->end_seq);
1751 	__skb_header_release(skb);
1752 	psp_enqueue_set_decrypted(sk, skb);
1753 	tcp_add_write_queue_tail(sk, skb);
1754 	sk_wmem_queued_add(sk, skb->truesize);
1755 	sk_mem_charge(sk, skb->truesize);
1756 }
1757 
1758 /* Initialize TSO segments for a packet. */
1759 static int tcp_set_skb_tso_segs(struct sk_buff *skb, unsigned int mss_now)
1760 {
1761 	int tso_segs;
1762 
1763 	if (skb->len <= mss_now) {
1764 		/* Avoid the costly divide in the normal
1765 		 * non-TSO case.
1766 		 */
1767 		TCP_SKB_CB(skb)->tcp_gso_size = 0;
1768 		tcp_skb_pcount_set(skb, 1);
1769 		return 1;
1770 	}
1771 	TCP_SKB_CB(skb)->tcp_gso_size = mss_now;
1772 	tso_segs = DIV_ROUND_UP(skb->len, mss_now);
1773 	tcp_skb_pcount_set(skb, tso_segs);
1774 	return tso_segs;
1775 }
1776 
1777 /* Pcount in the middle of the write queue got changed, we need to do various
1778  * tweaks to fix counters
1779  */
1780 static void tcp_adjust_pcount(struct sock *sk, const struct sk_buff *skb, int decr)
1781 {
1782 	struct tcp_sock *tp = tcp_sk(sk);
1783 
1784 	tp->packets_out -= decr;
1785 
1786 	if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)
1787 		tp->sacked_out -= decr;
1788 	if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS)
1789 		tp->retrans_out -= decr;
1790 	if (TCP_SKB_CB(skb)->sacked & TCPCB_LOST)
1791 		tp->lost_out -= decr;
1792 
1793 	/* Reno case is special. Sigh... */
1794 	if (tcp_is_reno(tp) && decr > 0)
1795 		tp->sacked_out -= min_t(u32, tp->sacked_out, decr);
1796 
1797 	tcp_verify_left_out(tp);
1798 }
1799 
1800 static bool tcp_has_tx_tstamp(const struct sk_buff *skb)
1801 {
1802 	return TCP_SKB_CB(skb)->txstamp_ack ||
1803 		(skb_shinfo(skb)->tx_flags & SKBTX_ANY_TSTAMP);
1804 }
1805 
1806 static void tcp_fragment_tstamp(struct sk_buff *skb, struct sk_buff *skb2)
1807 {
1808 	struct skb_shared_info *shinfo = skb_shinfo(skb);
1809 
1810 	if (unlikely(tcp_has_tx_tstamp(skb)) &&
1811 	    !before(shinfo->tskey, TCP_SKB_CB(skb2)->seq)) {
1812 		struct skb_shared_info *shinfo2 = skb_shinfo(skb2);
1813 		u8 tsflags = shinfo->tx_flags & SKBTX_ANY_TSTAMP;
1814 
1815 		shinfo->tx_flags &= ~tsflags;
1816 		shinfo2->tx_flags |= tsflags;
1817 		swap(shinfo->tskey, shinfo2->tskey);
1818 		TCP_SKB_CB(skb2)->txstamp_ack = TCP_SKB_CB(skb)->txstamp_ack;
1819 		TCP_SKB_CB(skb)->txstamp_ack = 0;
1820 	}
1821 }
1822 
1823 static void tcp_skb_fragment_eor(struct sk_buff *skb, struct sk_buff *skb2)
1824 {
1825 	TCP_SKB_CB(skb2)->eor = TCP_SKB_CB(skb)->eor;
1826 	TCP_SKB_CB(skb)->eor = 0;
1827 }
1828 
1829 /* Insert buff after skb on the write or rtx queue of sk.  */
1830 static void tcp_insert_write_queue_after(struct sk_buff *skb,
1831 					 struct sk_buff *buff,
1832 					 struct sock *sk,
1833 					 enum tcp_queue tcp_queue)
1834 {
1835 	if (tcp_queue == TCP_FRAG_IN_WRITE_QUEUE)
1836 		__skb_queue_after(&sk->sk_write_queue, skb, buff);
1837 	else
1838 		tcp_rbtree_insert(&sk->tcp_rtx_queue, buff);
1839 }
1840 
1841 /* Function to create two new TCP segments.  Shrinks the given segment
1842  * to the specified size and appends a new segment with the rest of the
1843  * packet to the list.  This won't be called frequently, I hope.
1844  * Remember, these are still headerless SKBs at this point.
1845  */
1846 int tcp_fragment(struct sock *sk, enum tcp_queue tcp_queue,
1847 		 struct sk_buff *skb, u32 len,
1848 		 unsigned int mss_now, gfp_t gfp)
1849 {
1850 	struct tcp_sock *tp = tcp_sk(sk);
1851 	struct sk_buff *buff;
1852 	int old_factor;
1853 	long limit;
1854 	u16 flags;
1855 	int nlen;
1856 
1857 	if (WARN_ON(len > skb->len))
1858 		return -EINVAL;
1859 
1860 	DEBUG_NET_WARN_ON_ONCE(skb_headlen(skb));
1861 
1862 	/* tcp_sendmsg() can overshoot sk_wmem_queued by one full size skb.
1863 	 * We need some allowance to not penalize applications setting small
1864 	 * SO_SNDBUF values.
1865 	 * Also allow first and last skb in retransmit queue to be split.
1866 	 */
1867 	limit = sk->sk_sndbuf + 2 * SKB_TRUESIZE(GSO_LEGACY_MAX_SIZE);
1868 	if (unlikely((sk->sk_wmem_queued >> 1) > limit &&
1869 		     tcp_queue != TCP_FRAG_IN_WRITE_QUEUE &&
1870 		     skb != tcp_rtx_queue_head(sk) &&
1871 		     skb != tcp_rtx_queue_tail(sk))) {
1872 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPWQUEUETOOBIG);
1873 		return -ENOMEM;
1874 	}
1875 
1876 	if (skb_unclone_keeptruesize(skb, gfp))
1877 		return -ENOMEM;
1878 
1879 	/* Get a new skb... force flag on. */
1880 	buff = tcp_stream_alloc_skb(sk, gfp, true);
1881 	if (!buff)
1882 		return -ENOMEM; /* We'll just try again later. */
1883 	skb_copy_decrypted(buff, skb);
1884 	mptcp_skb_ext_copy(buff, skb);
1885 
1886 	sk_wmem_queued_add(sk, buff->truesize);
1887 	sk_mem_charge(sk, buff->truesize);
1888 	nlen = skb->len - len;
1889 	buff->truesize += nlen;
1890 	skb->truesize -= nlen;
1891 
1892 	/* Correct the sequence numbers. */
1893 	TCP_SKB_CB(buff)->seq = TCP_SKB_CB(skb)->seq + len;
1894 	TCP_SKB_CB(buff)->end_seq = TCP_SKB_CB(skb)->end_seq;
1895 	TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(buff)->seq;
1896 
1897 	/* PSH and FIN should only be set in the second packet. */
1898 	flags = TCP_SKB_CB(skb)->tcp_flags;
1899 	TCP_SKB_CB(skb)->tcp_flags = flags & ~(TCPHDR_FIN | TCPHDR_PSH);
1900 	TCP_SKB_CB(buff)->tcp_flags = flags;
1901 	TCP_SKB_CB(buff)->sacked = TCP_SKB_CB(skb)->sacked;
1902 	tcp_skb_fragment_eor(skb, buff);
1903 
1904 	skb_split(skb, buff, len);
1905 
1906 	skb_set_delivery_time(buff, skb->tstamp, SKB_CLOCK_MONOTONIC);
1907 	tcp_fragment_tstamp(skb, buff);
1908 
1909 	old_factor = tcp_skb_pcount(skb);
1910 
1911 	/* Fix up tso_factor for both original and new SKB.  */
1912 	tcp_set_skb_tso_segs(skb, mss_now);
1913 	tcp_set_skb_tso_segs(buff, mss_now);
1914 
1915 	/* Update delivered info for the new segment */
1916 	TCP_SKB_CB(buff)->tx = TCP_SKB_CB(skb)->tx;
1917 
1918 	/* If this packet has been sent out already, we must
1919 	 * adjust the various packet counters.
1920 	 */
1921 	if (!before(tp->snd_nxt, TCP_SKB_CB(buff)->end_seq)) {
1922 		int diff = old_factor - tcp_skb_pcount(skb) -
1923 			tcp_skb_pcount(buff);
1924 
1925 		if (diff)
1926 			tcp_adjust_pcount(sk, skb, diff);
1927 	}
1928 
1929 	/* Link BUFF into the send queue. */
1930 	__skb_header_release(buff);
1931 	tcp_insert_write_queue_after(skb, buff, sk, tcp_queue);
1932 	if (tcp_queue == TCP_FRAG_IN_RTX_QUEUE)
1933 		list_add(&buff->tcp_tsorted_anchor, &skb->tcp_tsorted_anchor);
1934 
1935 	return 0;
1936 }
1937 
1938 /* This is similar to __pskb_pull_tail(). The difference is that pulled
1939  * data is not copied, but immediately discarded.
1940  */
1941 static int __pskb_trim_head(struct sk_buff *skb, int len)
1942 {
1943 	struct skb_shared_info *shinfo;
1944 	int i, k, eat;
1945 
1946 	DEBUG_NET_WARN_ON_ONCE(skb_headlen(skb));
1947 	eat = len;
1948 	k = 0;
1949 	shinfo = skb_shinfo(skb);
1950 	for (i = 0; i < shinfo->nr_frags; i++) {
1951 		int size = skb_frag_size(&shinfo->frags[i]);
1952 
1953 		if (size <= eat) {
1954 			skb_frag_unref(skb, i);
1955 			eat -= size;
1956 		} else {
1957 			shinfo->frags[k] = shinfo->frags[i];
1958 			if (eat) {
1959 				skb_frag_off_add(&shinfo->frags[k], eat);
1960 				skb_frag_size_sub(&shinfo->frags[k], eat);
1961 				eat = 0;
1962 			}
1963 			k++;
1964 		}
1965 	}
1966 	shinfo->nr_frags = k;
1967 
1968 	skb->data_len -= len;
1969 	skb->len = skb->data_len;
1970 	return len;
1971 }
1972 
1973 /* Remove acked data from a packet in the transmit queue. */
1974 int tcp_trim_head(struct sock *sk, struct sk_buff *skb, u32 len)
1975 {
1976 	u32 delta_truesize;
1977 
1978 	if (skb_unclone_keeptruesize(skb, GFP_ATOMIC))
1979 		return -ENOMEM;
1980 
1981 	delta_truesize = __pskb_trim_head(skb, len);
1982 
1983 	TCP_SKB_CB(skb)->seq += len;
1984 
1985 	skb->truesize	   -= delta_truesize;
1986 	sk_wmem_queued_add(sk, -delta_truesize);
1987 	if (!skb_zcopy_pure(skb))
1988 		sk_mem_uncharge(sk, delta_truesize);
1989 
1990 	/* Any change of skb->len requires recalculation of tso factor. */
1991 	if (tcp_skb_pcount(skb) > 1)
1992 		tcp_set_skb_tso_segs(skb, tcp_skb_mss(skb));
1993 
1994 	return 0;
1995 }
1996 
1997 /* Calculate MSS not accounting any TCP options.  */
1998 static inline int __tcp_mtu_to_mss(struct sock *sk, int pmtu)
1999 {
2000 	const struct tcp_sock *tp = tcp_sk(sk);
2001 	const struct inet_connection_sock *icsk = inet_csk(sk);
2002 	int mss_now;
2003 
2004 	/* Calculate base mss without TCP options:
2005 	   It is MMS_S - sizeof(tcphdr) of rfc1122
2006 	 */
2007 	mss_now = pmtu - icsk->icsk_af_ops->net_header_len - sizeof(struct tcphdr);
2008 
2009 	/* Clamp it (mss_clamp does not include tcp options) */
2010 	if (mss_now > tp->rx_opt.mss_clamp)
2011 		mss_now = tp->rx_opt.mss_clamp;
2012 
2013 	/* Now subtract optional transport overhead */
2014 	mss_now -= icsk->icsk_ext_hdr_len;
2015 
2016 	/* Then reserve room for full set of TCP options and 8 bytes of data */
2017 	mss_now = max(mss_now,
2018 		      READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_min_snd_mss));
2019 	return mss_now;
2020 }
2021 
2022 /* Calculate MSS. Not accounting for SACKs here.  */
2023 int tcp_mtu_to_mss(struct sock *sk, int pmtu)
2024 {
2025 	/* Subtract TCP options size, not including SACKs */
2026 	return __tcp_mtu_to_mss(sk, pmtu) -
2027 	       (tcp_sk(sk)->tcp_header_len - sizeof(struct tcphdr));
2028 }
2029 EXPORT_IPV6_MOD(tcp_mtu_to_mss);
2030 
2031 /* Inverse of above */
2032 int tcp_mss_to_mtu(struct sock *sk, int mss)
2033 {
2034 	const struct tcp_sock *tp = tcp_sk(sk);
2035 	const struct inet_connection_sock *icsk = inet_csk(sk);
2036 
2037 	return mss +
2038 	      tp->tcp_header_len +
2039 	      icsk->icsk_ext_hdr_len +
2040 	      icsk->icsk_af_ops->net_header_len;
2041 }
2042 EXPORT_SYMBOL(tcp_mss_to_mtu);
2043 
2044 /* MTU probing init per socket */
2045 void tcp_mtup_init(struct sock *sk)
2046 {
2047 	struct tcp_sock *tp = tcp_sk(sk);
2048 	struct inet_connection_sock *icsk = inet_csk(sk);
2049 	struct net *net = sock_net(sk);
2050 
2051 	icsk->icsk_mtup.enabled = READ_ONCE(net->ipv4.sysctl_tcp_mtu_probing) > 1;
2052 	icsk->icsk_mtup.search_high = tp->rx_opt.mss_clamp + sizeof(struct tcphdr) +
2053 			       icsk->icsk_af_ops->net_header_len;
2054 	icsk->icsk_mtup.search_low = tcp_mss_to_mtu(sk, READ_ONCE(net->ipv4.sysctl_tcp_base_mss));
2055 	icsk->icsk_mtup.probe_size = 0;
2056 	if (icsk->icsk_mtup.enabled)
2057 		icsk->icsk_mtup.probe_timestamp = tcp_jiffies32;
2058 }
2059 
2060 /* This function synchronize snd mss to current pmtu/exthdr set.
2061 
2062    tp->rx_opt.user_mss is mss set by user by TCP_MAXSEG. It does NOT counts
2063    for TCP options, but includes only bare TCP header.
2064 
2065    tp->rx_opt.mss_clamp is mss negotiated at connection setup.
2066    It is minimum of user_mss and mss received with SYN.
2067    It also does not include TCP options.
2068 
2069    inet_csk(sk)->icsk_pmtu_cookie is last pmtu, seen by this function.
2070 
2071    tp->mss_cache is current effective sending mss, including
2072    all tcp options except for SACKs. It is evaluated,
2073    taking into account current pmtu, but never exceeds
2074    tp->rx_opt.mss_clamp.
2075 
2076    NOTE1. rfc1122 clearly states that advertised MSS
2077    DOES NOT include either tcp or ip options.
2078 
2079    NOTE2. inet_csk(sk)->icsk_pmtu_cookie and tp->mss_cache
2080    are READ ONLY outside this function.		--ANK (980731)
2081  */
2082 unsigned int tcp_sync_mss(struct sock *sk, u32 pmtu)
2083 {
2084 	struct tcp_sock *tp = tcp_sk(sk);
2085 	struct inet_connection_sock *icsk = inet_csk(sk);
2086 	int mss_now;
2087 
2088 	if (icsk->icsk_mtup.search_high > pmtu)
2089 		icsk->icsk_mtup.search_high = pmtu;
2090 
2091 	mss_now = tcp_mtu_to_mss(sk, pmtu);
2092 	mss_now = tcp_bound_to_half_wnd(tp, mss_now);
2093 
2094 	/* And store cached results */
2095 	icsk->icsk_pmtu_cookie = pmtu;
2096 	if (icsk->icsk_mtup.enabled)
2097 		mss_now = min(mss_now, tcp_mtu_to_mss(sk, icsk->icsk_mtup.search_low));
2098 	tp->mss_cache = mss_now;
2099 
2100 	return mss_now;
2101 }
2102 EXPORT_IPV6_MOD(tcp_sync_mss);
2103 
2104 /* Compute the current effective MSS, taking SACKs and IP options,
2105  * and even PMTU discovery events into account.
2106  */
2107 unsigned int tcp_current_mss(struct sock *sk)
2108 {
2109 	const struct tcp_sock *tp = tcp_sk(sk);
2110 	const struct dst_entry *dst = __sk_dst_get(sk);
2111 	u32 mss_now;
2112 	unsigned int header_len;
2113 	struct tcp_out_options opts;
2114 	struct tcp_key key;
2115 
2116 	mss_now = tp->mss_cache;
2117 
2118 	if (dst) {
2119 		u32 mtu = dst_mtu(dst);
2120 		if (mtu != inet_csk(sk)->icsk_pmtu_cookie)
2121 			mss_now = tcp_sync_mss(sk, mtu);
2122 	}
2123 	tcp_get_current_key(sk, &key);
2124 	header_len = tcp_established_options(sk, NULL, &opts, &key) +
2125 		     sizeof(struct tcphdr);
2126 	/* The mss_cache is sized based on tp->tcp_header_len, which assumes
2127 	 * some common options. If this is an odd packet (because we have SACK
2128 	 * blocks etc) then our calculated header_len will be different, and
2129 	 * we have to adjust mss_now correspondingly */
2130 	if (header_len != tp->tcp_header_len) {
2131 		int delta = (int) header_len - tp->tcp_header_len;
2132 		mss_now -= delta;
2133 	}
2134 
2135 	return mss_now;
2136 }
2137 
2138 /* RFC2861, slow part. Adjust cwnd, after it was not full during one rto.
2139  * As additional protections, we do not touch cwnd in retransmission phases,
2140  * and if application hit its sndbuf limit recently.
2141  */
2142 static void tcp_cwnd_application_limited(struct sock *sk)
2143 {
2144 	struct tcp_sock *tp = tcp_sk(sk);
2145 
2146 	if (inet_csk(sk)->icsk_ca_state == TCP_CA_Open &&
2147 	    sk->sk_socket && !test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
2148 		/* Limited by application or receiver window. */
2149 		u32 init_win = tcp_init_cwnd(tp, __sk_dst_get(sk));
2150 		u32 win_used = max(tp->snd_cwnd_used, init_win);
2151 		if (win_used < tcp_snd_cwnd(tp)) {
2152 			tp->snd_ssthresh = tcp_current_ssthresh(sk);
2153 			tcp_snd_cwnd_set(tp, (tcp_snd_cwnd(tp) + win_used) >> 1);
2154 		}
2155 		tp->snd_cwnd_used = 0;
2156 	}
2157 	tp->snd_cwnd_stamp = tcp_jiffies32;
2158 }
2159 
2160 static void tcp_cwnd_validate(struct sock *sk, bool is_cwnd_limited)
2161 {
2162 	const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops;
2163 	struct tcp_sock *tp = tcp_sk(sk);
2164 
2165 	/* Track the strongest available signal of the degree to which the cwnd
2166 	 * is fully utilized. If cwnd-limited then remember that fact for the
2167 	 * current window. If not cwnd-limited then track the maximum number of
2168 	 * outstanding packets in the current window. (If cwnd-limited then we
2169 	 * chose to not update tp->max_packets_out to avoid an extra else
2170 	 * clause with no functional impact.)
2171 	 */
2172 	if (!before(tp->snd_una, tp->cwnd_usage_seq) ||
2173 	    is_cwnd_limited ||
2174 	    (!tp->is_cwnd_limited &&
2175 	     tp->packets_out > tp->max_packets_out)) {
2176 		tp->is_cwnd_limited = is_cwnd_limited;
2177 		tp->max_packets_out = tp->packets_out;
2178 		tp->cwnd_usage_seq = tp->snd_nxt;
2179 	}
2180 
2181 	if (tcp_is_cwnd_limited(sk)) {
2182 		/* Network is feed fully. */
2183 		tp->snd_cwnd_used = 0;
2184 		tp->snd_cwnd_stamp = tcp_jiffies32;
2185 	} else {
2186 		/* Network starves. */
2187 		if (tp->packets_out > tp->snd_cwnd_used)
2188 			tp->snd_cwnd_used = tp->packets_out;
2189 
2190 		if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_slow_start_after_idle) &&
2191 		    (s32)(tcp_jiffies32 - tp->snd_cwnd_stamp) >= inet_csk(sk)->icsk_rto &&
2192 		    !ca_ops->cong_control)
2193 			tcp_cwnd_application_limited(sk);
2194 
2195 		/* The following conditions together indicate the starvation
2196 		 * is caused by insufficient sender buffer:
2197 		 * 1) just sent some data (see tcp_write_xmit)
2198 		 * 2) not cwnd limited (this else condition)
2199 		 * 3) no more data to send (tcp_write_queue_empty())
2200 		 * 4) application is hitting buffer limit (SOCK_NOSPACE)
2201 		 */
2202 		if (tcp_write_queue_empty(sk) && sk->sk_socket &&
2203 		    test_bit(SOCK_NOSPACE, &sk->sk_socket->flags) &&
2204 		    (1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT))
2205 			tcp_chrono_start(sk, TCP_CHRONO_SNDBUF_LIMITED);
2206 	}
2207 }
2208 
2209 /* Minshall's variant of the Nagle send check. */
2210 static bool tcp_minshall_check(const struct tcp_sock *tp)
2211 {
2212 	return after(tp->snd_sml, tp->snd_una) &&
2213 		!after(tp->snd_sml, tp->snd_nxt);
2214 }
2215 
2216 /* Update snd_sml if this skb is under mss
2217  * Note that a TSO packet might end with a sub-mss segment
2218  * The test is really :
2219  * if ((skb->len % mss) != 0)
2220  *        tp->snd_sml = TCP_SKB_CB(skb)->end_seq;
2221  * But we can avoid doing the divide again given we already have
2222  *  skb_pcount = skb->len / mss_now
2223  */
2224 static void tcp_minshall_update(struct tcp_sock *tp, unsigned int mss_now,
2225 				const struct sk_buff *skb)
2226 {
2227 	if (skb->len < tcp_skb_pcount(skb) * mss_now)
2228 		tp->snd_sml = TCP_SKB_CB(skb)->end_seq;
2229 }
2230 
2231 /* Return false, if packet can be sent now without violation Nagle's rules:
2232  * 1. It is full sized. (provided by caller in %partial bool)
2233  * 2. Or it contains FIN. (already checked by caller)
2234  * 3. Or TCP_CORK is not set, and TCP_NODELAY is set.
2235  * 4. Or TCP_CORK is not set, and all sent packets are ACKed.
2236  *    With Minshall's modification: all sent small packets are ACKed.
2237  */
2238 static bool tcp_nagle_check(bool partial, const struct tcp_sock *tp,
2239 			    int nonagle)
2240 {
2241 	return partial &&
2242 		((nonagle & TCP_NAGLE_CORK) ||
2243 		 (!nonagle && tp->packets_out && tcp_minshall_check(tp)));
2244 }
2245 
2246 /* Return how many segs we'd like on a TSO packet,
2247  * depending on current pacing rate, and how close the peer is.
2248  *
2249  * Rationale is:
2250  * - For close peers, we rather send bigger packets to reduce
2251  *   cpu costs, because occasional losses will be repaired fast.
2252  * - For long distance/rtt flows, we would like to get ACK clocking
2253  *   with 1 ACK per ms.
2254  *
2255  * Use min_rtt to help adapt TSO burst size, with smaller min_rtt resulting
2256  * in bigger TSO bursts. We we cut the RTT-based allowance in half
2257  * for every 2^9 usec (aka 512 us) of RTT, so that the RTT-based allowance
2258  * is below 1500 bytes after 6 * ~500 usec = 3ms.
2259  */
2260 static u32 tcp_tso_autosize(const struct sock *sk, unsigned int mss_now,
2261 			    int min_tso_segs)
2262 {
2263 	unsigned long bytes;
2264 	u32 r;
2265 
2266 	bytes = READ_ONCE(sk->sk_pacing_rate) >> READ_ONCE(sk->sk_pacing_shift);
2267 
2268 	r = tcp_min_rtt(tcp_sk(sk)) >> READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_tso_rtt_log);
2269 	if (r < BITS_PER_TYPE(sk->sk_gso_max_size))
2270 		bytes += sk->sk_gso_max_size >> r;
2271 
2272 	bytes = min_t(unsigned long, bytes, sk->sk_gso_max_size);
2273 
2274 	return max_t(u32, bytes / mss_now, min_tso_segs);
2275 }
2276 
2277 /* Return the number of segments we want in the skb we are transmitting.
2278  * See if congestion control module wants to decide; otherwise, autosize.
2279  */
2280 static u32 tcp_tso_segs(struct sock *sk, unsigned int mss_now)
2281 {
2282 	const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops;
2283 	u32 min_tso, tso_segs;
2284 
2285 	min_tso = ca_ops->min_tso_segs ?
2286 			ca_ops->min_tso_segs(sk) :
2287 			READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_min_tso_segs);
2288 
2289 	tso_segs = tcp_tso_autosize(sk, mss_now, min_tso);
2290 	return min_t(u32, tso_segs, sk->sk_gso_max_segs);
2291 }
2292 
2293 /* Returns the portion of skb which can be sent right away */
2294 static unsigned int tcp_mss_split_point(const struct sock *sk,
2295 					const struct sk_buff *skb,
2296 					unsigned int mss_now,
2297 					unsigned int max_segs,
2298 					int nonagle)
2299 {
2300 	const struct tcp_sock *tp = tcp_sk(sk);
2301 	u32 partial, needed, window, max_len;
2302 
2303 	window = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq;
2304 	max_len = mss_now * max_segs;
2305 
2306 	if (likely(max_len <= window && skb != tcp_write_queue_tail(sk)))
2307 		return max_len;
2308 
2309 	needed = min(skb->len, window);
2310 
2311 	if (max_len <= needed)
2312 		return max_len;
2313 
2314 	partial = needed % mss_now;
2315 	/* If last segment is not a full MSS, check if Nagle rules allow us
2316 	 * to include this last segment in this skb.
2317 	 * Otherwise, we'll split the skb at last MSS boundary
2318 	 */
2319 	if (tcp_nagle_check(partial != 0, tp, nonagle))
2320 		return needed - partial;
2321 
2322 	return needed;
2323 }
2324 
2325 /* Can at least one segment of SKB be sent right now, according to the
2326  * congestion window rules?  If so, return how many segments are allowed.
2327  */
2328 static u32 tcp_cwnd_test(const struct tcp_sock *tp)
2329 {
2330 	u32 in_flight, cwnd, halfcwnd;
2331 
2332 	in_flight = tcp_packets_in_flight(tp);
2333 	cwnd = tcp_snd_cwnd(tp);
2334 	if (in_flight >= cwnd)
2335 		return 0;
2336 
2337 	/* For better scheduling, ensure we have at least
2338 	 * 2 GSO packets in flight.
2339 	 */
2340 	halfcwnd = max(cwnd >> 1, 1U);
2341 	return min(halfcwnd, cwnd - in_flight);
2342 }
2343 
2344 /* Initialize TSO state of a skb.
2345  * This must be invoked the first time we consider transmitting
2346  * SKB onto the wire.
2347  */
2348 static int tcp_init_tso_segs(struct sk_buff *skb, unsigned int mss_now)
2349 {
2350 	int tso_segs = tcp_skb_pcount(skb);
2351 
2352 	if (!tso_segs || (tso_segs > 1 && tcp_skb_mss(skb) != mss_now))
2353 		return tcp_set_skb_tso_segs(skb, mss_now);
2354 
2355 	return tso_segs;
2356 }
2357 
2358 
2359 /* Return true if the Nagle test allows this packet to be
2360  * sent now.
2361  */
2362 static inline bool tcp_nagle_test(const struct tcp_sock *tp, const struct sk_buff *skb,
2363 				  unsigned int cur_mss, int nonagle)
2364 {
2365 	/* Nagle rule does not apply to frames, which sit in the middle of the
2366 	 * write_queue (they have no chances to get new data).
2367 	 *
2368 	 * This is implemented in the callers, where they modify the 'nonagle'
2369 	 * argument based upon the location of SKB in the send queue.
2370 	 */
2371 	if (nonagle & TCP_NAGLE_PUSH)
2372 		return true;
2373 
2374 	/* Don't use the nagle rule for urgent data (or for the final FIN). */
2375 	if (tcp_urg_mode(tp) || (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN))
2376 		return true;
2377 
2378 	if (!tcp_nagle_check(skb->len < cur_mss, tp, nonagle))
2379 		return true;
2380 
2381 	return false;
2382 }
2383 
2384 /* Does at least the first segment of SKB fit into the send window? */
2385 static bool tcp_snd_wnd_test(const struct tcp_sock *tp,
2386 			     const struct sk_buff *skb,
2387 			     unsigned int cur_mss)
2388 {
2389 	u32 end_seq = TCP_SKB_CB(skb)->end_seq;
2390 
2391 	if (skb->len > cur_mss)
2392 		end_seq = TCP_SKB_CB(skb)->seq + cur_mss;
2393 
2394 	return !after(end_seq, tcp_wnd_end(tp));
2395 }
2396 
2397 /* Trim TSO SKB to LEN bytes, put the remaining data into a new packet
2398  * which is put after SKB on the list.  It is very much like
2399  * tcp_fragment() except that it may make several kinds of assumptions
2400  * in order to speed up the splitting operation.  In particular, we
2401  * know that all the data is in scatter-gather pages, and that the
2402  * packet has never been sent out before (and thus is not cloned).
2403  */
2404 static int tso_fragment(struct sock *sk, struct sk_buff *skb, unsigned int len,
2405 			unsigned int mss_now, gfp_t gfp)
2406 {
2407 	int nlen = skb->len - len;
2408 	struct sk_buff *buff;
2409 	u16 flags;
2410 
2411 	/* All of a TSO frame must be composed of paged data.  */
2412 	DEBUG_NET_WARN_ON_ONCE(skb->len != skb->data_len);
2413 
2414 	buff = tcp_stream_alloc_skb(sk, gfp, true);
2415 	if (unlikely(!buff))
2416 		return -ENOMEM;
2417 	skb_copy_decrypted(buff, skb);
2418 	mptcp_skb_ext_copy(buff, skb);
2419 
2420 	sk_wmem_queued_add(sk, buff->truesize);
2421 	sk_mem_charge(sk, buff->truesize);
2422 	buff->truesize += nlen;
2423 	skb->truesize -= nlen;
2424 
2425 	/* Correct the sequence numbers. */
2426 	TCP_SKB_CB(buff)->seq = TCP_SKB_CB(skb)->seq + len;
2427 	TCP_SKB_CB(buff)->end_seq = TCP_SKB_CB(skb)->end_seq;
2428 	TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(buff)->seq;
2429 
2430 	/* PSH and FIN should only be set in the second packet. */
2431 	flags = TCP_SKB_CB(skb)->tcp_flags;
2432 	TCP_SKB_CB(skb)->tcp_flags = flags & ~(TCPHDR_FIN | TCPHDR_PSH);
2433 	TCP_SKB_CB(buff)->tcp_flags = flags;
2434 
2435 	tcp_skb_fragment_eor(skb, buff);
2436 
2437 	skb_split(skb, buff, len);
2438 	tcp_fragment_tstamp(skb, buff);
2439 
2440 	/* Fix up tso_factor for both original and new SKB.  */
2441 	tcp_set_skb_tso_segs(skb, mss_now);
2442 	tcp_set_skb_tso_segs(buff, mss_now);
2443 
2444 	/* Link BUFF into the send queue. */
2445 	__skb_header_release(buff);
2446 	tcp_insert_write_queue_after(skb, buff, sk, TCP_FRAG_IN_WRITE_QUEUE);
2447 
2448 	return 0;
2449 }
2450 
2451 /* Try to defer sending, if possible, in order to minimize the amount
2452  * of TSO splitting we do.  View it as a kind of TSO Nagle test.
2453  *
2454  * This algorithm is from John Heffner.
2455  */
2456 static bool tcp_tso_should_defer(struct sock *sk, struct sk_buff *skb,
2457 				 bool *is_cwnd_limited,
2458 				 bool *is_rwnd_limited,
2459 				 u32 max_segs)
2460 {
2461 	const struct inet_connection_sock *icsk = inet_csk(sk);
2462 	u32 send_win, cong_win, limit, in_flight, threshold;
2463 	u64 srtt_in_ns, expected_ack, how_far_is_the_ack;
2464 	struct tcp_sock *tp = tcp_sk(sk);
2465 	struct sk_buff *head;
2466 	int win_divisor;
2467 	s64 delta;
2468 
2469 	if (icsk->icsk_ca_state >= TCP_CA_Recovery)
2470 		goto send_now;
2471 
2472 	/* Avoid bursty behavior by allowing defer
2473 	 * only if the last write was recent (1 ms).
2474 	 * Note that tp->tcp_wstamp_ns can be in the future if we have
2475 	 * packets waiting in a qdisc or device for EDT delivery.
2476 	 */
2477 	delta = tp->tcp_clock_cache - tp->tcp_wstamp_ns - NSEC_PER_MSEC;
2478 	if (delta > 0)
2479 		goto send_now;
2480 
2481 	in_flight = tcp_packets_in_flight(tp);
2482 
2483 	BUG_ON(tcp_skb_pcount(skb) <= 1);
2484 	BUG_ON(tcp_snd_cwnd(tp) <= in_flight);
2485 
2486 	send_win = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq;
2487 
2488 	/* From in_flight test above, we know that cwnd > in_flight.  */
2489 	cong_win = (tcp_snd_cwnd(tp) - in_flight) * tp->mss_cache;
2490 
2491 	limit = min(send_win, cong_win);
2492 
2493 	/* If a full-sized TSO skb can be sent, do it. */
2494 	if (limit >= max_segs * tp->mss_cache)
2495 		goto send_now;
2496 
2497 	/* Middle in queue won't get any more data, full sendable already? */
2498 	if ((skb != tcp_write_queue_tail(sk)) && (limit >= skb->len))
2499 		goto send_now;
2500 
2501 	win_divisor = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_tso_win_divisor);
2502 	if (win_divisor) {
2503 		u32 chunk = min(tp->snd_wnd, tcp_snd_cwnd(tp) * tp->mss_cache);
2504 
2505 		/* If at least some fraction of a window is available,
2506 		 * just use it.
2507 		 */
2508 		chunk /= win_divisor;
2509 		if (limit >= chunk)
2510 			goto send_now;
2511 	} else {
2512 		/* Different approach, try not to defer past a single
2513 		 * ACK.  Receiver should ACK every other full sized
2514 		 * frame, so if we have space for more than 3 frames
2515 		 * then send now.
2516 		 */
2517 		if (limit > tcp_max_tso_deferred_mss(tp) * tp->mss_cache)
2518 			goto send_now;
2519 	}
2520 
2521 	/* TODO : use tsorted_sent_queue ? */
2522 	head = tcp_rtx_queue_head(sk);
2523 	if (!head)
2524 		goto send_now;
2525 
2526 	srtt_in_ns = (u64)(NSEC_PER_USEC >> 3) * tp->srtt_us;
2527 	/* When is the ACK expected ? */
2528 	expected_ack = head->tstamp + srtt_in_ns;
2529 	/* How far from now is the ACK expected ? */
2530 	how_far_is_the_ack = expected_ack - tp->tcp_clock_cache;
2531 
2532 	/* If next ACK is likely to come too late,
2533 	 * ie in more than min(1ms, half srtt), do not defer.
2534 	 */
2535 	threshold = min(srtt_in_ns >> 1, NSEC_PER_MSEC);
2536 
2537 	if ((s64)(how_far_is_the_ack - threshold) > 0)
2538 		goto send_now;
2539 
2540 	/* Ok, it looks like it is advisable to defer.
2541 	 * Three cases are tracked :
2542 	 * 1) We are cwnd-limited
2543 	 * 2) We are rwnd-limited
2544 	 * 3) We are application limited.
2545 	 */
2546 	if (cong_win < send_win) {
2547 		if (cong_win <= skb->len) {
2548 			*is_cwnd_limited = true;
2549 			return true;
2550 		}
2551 	} else {
2552 		if (send_win <= skb->len) {
2553 			*is_rwnd_limited = true;
2554 			return true;
2555 		}
2556 	}
2557 
2558 	/* If this packet won't get more data, do not wait. */
2559 	if ((TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) ||
2560 	    TCP_SKB_CB(skb)->eor)
2561 		goto send_now;
2562 
2563 	return true;
2564 
2565 send_now:
2566 	return false;
2567 }
2568 
2569 static inline void tcp_mtu_check_reprobe(struct sock *sk)
2570 {
2571 	struct inet_connection_sock *icsk = inet_csk(sk);
2572 	struct tcp_sock *tp = tcp_sk(sk);
2573 	struct net *net = sock_net(sk);
2574 	u32 interval;
2575 	s32 delta;
2576 
2577 	interval = READ_ONCE(net->ipv4.sysctl_tcp_probe_interval);
2578 	delta = tcp_jiffies32 - icsk->icsk_mtup.probe_timestamp;
2579 	if (unlikely(delta >= interval * HZ)) {
2580 		int mss = tcp_current_mss(sk);
2581 
2582 		/* Update current search range */
2583 		icsk->icsk_mtup.probe_size = 0;
2584 		icsk->icsk_mtup.search_high = tp->rx_opt.mss_clamp +
2585 			sizeof(struct tcphdr) +
2586 			icsk->icsk_af_ops->net_header_len;
2587 		icsk->icsk_mtup.search_low = tcp_mss_to_mtu(sk, mss);
2588 
2589 		/* Update probe time stamp */
2590 		icsk->icsk_mtup.probe_timestamp = tcp_jiffies32;
2591 	}
2592 }
2593 
2594 static bool tcp_can_coalesce_send_queue_head(struct sock *sk, int len)
2595 {
2596 	struct sk_buff *skb, *next;
2597 
2598 	skb = tcp_send_head(sk);
2599 	tcp_for_write_queue_from_safe(skb, next, sk) {
2600 		if (len <= skb->len)
2601 			break;
2602 
2603 		if (tcp_has_tx_tstamp(skb) || !tcp_skb_can_collapse(skb, next))
2604 			return false;
2605 
2606 		len -= skb->len;
2607 	}
2608 
2609 	return true;
2610 }
2611 
2612 static int tcp_clone_payload(struct sock *sk, struct sk_buff *to,
2613 			     int probe_size)
2614 {
2615 	skb_frag_t *lastfrag = NULL, *fragto = skb_shinfo(to)->frags;
2616 	int i, todo, len = 0, nr_frags = 0;
2617 	const struct sk_buff *skb;
2618 
2619 	if (!sk_wmem_schedule(sk, to->truesize + probe_size))
2620 		return -ENOMEM;
2621 
2622 	skb_queue_walk(&sk->sk_write_queue, skb) {
2623 		const skb_frag_t *fragfrom = skb_shinfo(skb)->frags;
2624 
2625 		if (skb_headlen(skb))
2626 			return -EINVAL;
2627 
2628 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++, fragfrom++) {
2629 			if (len >= probe_size)
2630 				goto commit;
2631 			todo = min_t(int, skb_frag_size(fragfrom),
2632 				     probe_size - len);
2633 			len += todo;
2634 			if (lastfrag &&
2635 			    skb_frag_page(fragfrom) == skb_frag_page(lastfrag) &&
2636 			    skb_frag_off(fragfrom) == skb_frag_off(lastfrag) +
2637 						      skb_frag_size(lastfrag)) {
2638 				skb_frag_size_add(lastfrag, todo);
2639 				continue;
2640 			}
2641 			if (unlikely(nr_frags == MAX_SKB_FRAGS))
2642 				return -E2BIG;
2643 			skb_frag_page_copy(fragto, fragfrom);
2644 			skb_frag_off_copy(fragto, fragfrom);
2645 			skb_frag_size_set(fragto, todo);
2646 			nr_frags++;
2647 			lastfrag = fragto++;
2648 		}
2649 	}
2650 commit:
2651 	WARN_ON_ONCE(len != probe_size);
2652 	for (i = 0; i < nr_frags; i++)
2653 		skb_frag_ref(to, i);
2654 
2655 	skb_shinfo(to)->nr_frags = nr_frags;
2656 	to->truesize += probe_size;
2657 	to->len += probe_size;
2658 	to->data_len += probe_size;
2659 	__skb_header_release(to);
2660 	return 0;
2661 }
2662 
2663 /* tcp_mtu_probe() and tcp_grow_skb() can both eat an skb (src) if
2664  * all its payload was moved to another one (dst).
2665  * Make sure to transfer tcp_flags, eor, and tstamp.
2666  */
2667 static void tcp_eat_one_skb(struct sock *sk,
2668 			    struct sk_buff *dst,
2669 			    struct sk_buff *src)
2670 {
2671 	TCP_SKB_CB(dst)->tcp_flags |= TCP_SKB_CB(src)->tcp_flags;
2672 	TCP_SKB_CB(dst)->eor = TCP_SKB_CB(src)->eor;
2673 	tcp_skb_collapse_tstamp(dst, src);
2674 	tcp_unlink_write_queue(src, sk);
2675 	tcp_wmem_free_skb(sk, src);
2676 }
2677 
2678 /* Create a new MTU probe if we are ready.
2679  * MTU probe is regularly attempting to increase the path MTU by
2680  * deliberately sending larger packets.  This discovers routing
2681  * changes resulting in larger path MTUs.
2682  *
2683  * Returns 0 if we should wait to probe (no cwnd available),
2684  *         1 if a probe was sent,
2685  *         -1 otherwise
2686  */
2687 static int tcp_mtu_probe(struct sock *sk)
2688 {
2689 	struct inet_connection_sock *icsk = inet_csk(sk);
2690 	struct tcp_sock *tp = tcp_sk(sk);
2691 	struct sk_buff *skb, *nskb, *next;
2692 	struct net *net = sock_net(sk);
2693 	int probe_size;
2694 	int size_needed;
2695 	int copy, len;
2696 	int mss_now;
2697 	int interval;
2698 
2699 	/* Not currently probing/verifying,
2700 	 * not in recovery,
2701 	 * have enough cwnd, and
2702 	 * not SACKing (the variable headers throw things off)
2703 	 */
2704 	if (likely(!icsk->icsk_mtup.enabled ||
2705 		   icsk->icsk_mtup.probe_size ||
2706 		   inet_csk(sk)->icsk_ca_state != TCP_CA_Open ||
2707 		   tcp_snd_cwnd(tp) < 11 ||
2708 		   tp->rx_opt.num_sacks || tp->rx_opt.dsack))
2709 		return -1;
2710 
2711 	/* Use binary search for probe_size between tcp_mss_base,
2712 	 * and current mss_clamp. if (search_high - search_low)
2713 	 * smaller than a threshold, backoff from probing.
2714 	 */
2715 	mss_now = tcp_current_mss(sk);
2716 	probe_size = tcp_mtu_to_mss(sk, (icsk->icsk_mtup.search_high +
2717 				    icsk->icsk_mtup.search_low) >> 1);
2718 	size_needed = probe_size + (tp->reordering + 1) * tp->mss_cache;
2719 	interval = icsk->icsk_mtup.search_high - icsk->icsk_mtup.search_low;
2720 	/* When misfortune happens, we are reprobing actively,
2721 	 * and then reprobe timer has expired. We stick with current
2722 	 * probing process by not resetting search range to its orignal.
2723 	 */
2724 	if (probe_size > tcp_mtu_to_mss(sk, icsk->icsk_mtup.search_high) ||
2725 	    interval < READ_ONCE(net->ipv4.sysctl_tcp_probe_threshold)) {
2726 		/* Check whether enough time has elaplased for
2727 		 * another round of probing.
2728 		 */
2729 		tcp_mtu_check_reprobe(sk);
2730 		return -1;
2731 	}
2732 
2733 	/* Have enough data in the send queue to probe? */
2734 	if (tp->write_seq - tp->snd_nxt < size_needed)
2735 		return -1;
2736 
2737 	if (tp->snd_wnd < size_needed)
2738 		return -1;
2739 	if (after(tp->snd_nxt + size_needed, tcp_wnd_end(tp)))
2740 		return 0;
2741 
2742 	/* Do we need to wait to drain cwnd? With none in flight, don't stall */
2743 	if (tcp_packets_in_flight(tp) + 2 > tcp_snd_cwnd(tp)) {
2744 		if (!tcp_packets_in_flight(tp))
2745 			return -1;
2746 		else
2747 			return 0;
2748 	}
2749 
2750 	if (!tcp_can_coalesce_send_queue_head(sk, probe_size))
2751 		return -1;
2752 
2753 	/* We're allowed to probe.  Build it now. */
2754 	nskb = tcp_stream_alloc_skb(sk, GFP_ATOMIC, false);
2755 	if (!nskb)
2756 		return -1;
2757 
2758 	/* build the payload, and be prepared to abort if this fails. */
2759 	if (tcp_clone_payload(sk, nskb, probe_size)) {
2760 		tcp_skb_tsorted_anchor_cleanup(nskb);
2761 		consume_skb(nskb);
2762 		return -1;
2763 	}
2764 	sk_wmem_queued_add(sk, nskb->truesize);
2765 	sk_mem_charge(sk, nskb->truesize);
2766 
2767 	skb = tcp_send_head(sk);
2768 	skb_copy_decrypted(nskb, skb);
2769 	mptcp_skb_ext_copy(nskb, skb);
2770 
2771 	TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(skb)->seq;
2772 	TCP_SKB_CB(nskb)->end_seq = TCP_SKB_CB(skb)->seq + probe_size;
2773 	TCP_SKB_CB(nskb)->tcp_flags = TCPHDR_ACK;
2774 
2775 	tcp_insert_write_queue_before(nskb, skb, sk);
2776 	tcp_highest_sack_replace(sk, skb, nskb);
2777 
2778 	len = 0;
2779 	tcp_for_write_queue_from_safe(skb, next, sk) {
2780 		copy = min_t(int, skb->len, probe_size - len);
2781 
2782 		if (skb->len <= copy) {
2783 			tcp_eat_one_skb(sk, nskb, skb);
2784 		} else {
2785 			TCP_SKB_CB(nskb)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags &
2786 						   ~(TCPHDR_FIN|TCPHDR_PSH);
2787 			__pskb_trim_head(skb, copy);
2788 			tcp_set_skb_tso_segs(skb, mss_now);
2789 			TCP_SKB_CB(skb)->seq += copy;
2790 		}
2791 
2792 		len += copy;
2793 
2794 		if (len >= probe_size)
2795 			break;
2796 	}
2797 	tcp_init_tso_segs(nskb, nskb->len);
2798 
2799 	/* We're ready to send.  If this fails, the probe will
2800 	 * be resegmented into mss-sized pieces by tcp_write_xmit().
2801 	 */
2802 	if (!tcp_transmit_skb(sk, nskb, 1, GFP_ATOMIC)) {
2803 		/* Decrement cwnd here because we are sending
2804 		 * effectively two packets. */
2805 		tcp_snd_cwnd_set(tp, tcp_snd_cwnd(tp) - 1);
2806 		tcp_event_new_data_sent(sk, nskb);
2807 
2808 		icsk->icsk_mtup.probe_size = tcp_mss_to_mtu(sk, nskb->len);
2809 		tp->mtu_probe.probe_seq_start = TCP_SKB_CB(nskb)->seq;
2810 		tp->mtu_probe.probe_seq_end = TCP_SKB_CB(nskb)->end_seq;
2811 
2812 		return 1;
2813 	}
2814 
2815 	return -1;
2816 }
2817 
2818 static bool tcp_pacing_check(struct sock *sk)
2819 {
2820 	struct tcp_sock *tp = tcp_sk(sk);
2821 
2822 	if (!tcp_needs_internal_pacing(sk))
2823 		return false;
2824 
2825 	if (tp->tcp_wstamp_ns <= tp->tcp_clock_cache)
2826 		return false;
2827 
2828 	if (!hrtimer_is_queued(&tp->pacing_timer)) {
2829 		hrtimer_start(&tp->pacing_timer,
2830 			      ns_to_ktime(tp->tcp_wstamp_ns),
2831 			      HRTIMER_MODE_ABS_PINNED_SOFT);
2832 		sock_hold(sk);
2833 	}
2834 	return true;
2835 }
2836 
2837 static bool tcp_rtx_queue_empty_or_single_skb(const struct sock *sk)
2838 {
2839 	const struct rb_node *node = sk->tcp_rtx_queue.rb_node;
2840 
2841 	/* No skb in the rtx queue. */
2842 	if (!node)
2843 		return true;
2844 
2845 	/* Only one skb in rtx queue. */
2846 	return !node->rb_left && !node->rb_right;
2847 }
2848 
2849 /* TCP Small Queues :
2850  * Control number of packets in qdisc/devices to two packets / or ~1 ms.
2851  * (These limits are doubled for retransmits)
2852  * This allows for :
2853  *  - better RTT estimation and ACK scheduling
2854  *  - faster recovery
2855  *  - high rates
2856  * Alas, some drivers / subsystems require a fair amount
2857  * of queued bytes to ensure line rate.
2858  * One example is wifi aggregation (802.11 AMPDU)
2859  */
2860 static bool tcp_small_queue_check(struct sock *sk, const struct sk_buff *skb,
2861 				  unsigned int factor)
2862 {
2863 	unsigned long limit;
2864 
2865 	limit = max_t(unsigned long,
2866 		      2 * skb->truesize,
2867 		      READ_ONCE(sk->sk_pacing_rate) >> READ_ONCE(sk->sk_pacing_shift));
2868 	limit = min_t(unsigned long, limit,
2869 		      READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_limit_output_bytes));
2870 	limit <<= factor;
2871 
2872 	if (static_branch_unlikely(&tcp_tx_delay_enabled) &&
2873 	    tcp_sk(sk)->tcp_tx_delay) {
2874 		u64 extra_bytes = (u64)READ_ONCE(sk->sk_pacing_rate) *
2875 				  tcp_sk(sk)->tcp_tx_delay;
2876 
2877 		/* TSQ is based on skb truesize sum (sk_wmem_alloc), so we
2878 		 * approximate our needs assuming an ~100% skb->truesize overhead.
2879 		 * USEC_PER_SEC is approximated by 2^20.
2880 		 * do_div(extra_bytes, USEC_PER_SEC/2) is replaced by a right shift.
2881 		 */
2882 		extra_bytes >>= (20 - 1);
2883 		limit += extra_bytes;
2884 	}
2885 	if (refcount_read(&sk->sk_wmem_alloc) > limit) {
2886 		/* Always send skb if rtx queue is empty or has one skb.
2887 		 * No need to wait for TX completion to call us back,
2888 		 * after softirq schedule.
2889 		 * This helps when TX completions are delayed too much.
2890 		 */
2891 		if (tcp_rtx_queue_empty_or_single_skb(sk))
2892 			return false;
2893 
2894 		set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags);
2895 		/* It is possible TX completion already happened
2896 		 * before we set TSQ_THROTTLED, so we must
2897 		 * test again the condition.
2898 		 */
2899 		smp_mb__after_atomic();
2900 		if (refcount_read(&sk->sk_wmem_alloc) > limit)
2901 			return true;
2902 	}
2903 	return false;
2904 }
2905 
2906 void tcp_chrono_stop(struct sock *sk, const enum tcp_chrono type)
2907 {
2908 	struct tcp_sock *tp = tcp_sk(sk);
2909 
2910 
2911 	/* There are multiple conditions worthy of tracking in a
2912 	 * chronograph, so that the highest priority enum takes
2913 	 * precedence over the other conditions (see tcp_chrono_start).
2914 	 * If a condition stops, we only stop chrono tracking if
2915 	 * it's the "most interesting" or current chrono we are
2916 	 * tracking and starts busy chrono if we have pending data.
2917 	 */
2918 	if (tcp_rtx_and_write_queues_empty(sk))
2919 		tcp_chrono_set(tp, TCP_CHRONO_UNSPEC);
2920 	else if (type == tp->chrono_type)
2921 		tcp_chrono_set(tp, TCP_CHRONO_BUSY);
2922 }
2923 
2924 /* First skb in the write queue is smaller than ideal packet size.
2925  * Check if we can move payload from the second skb in the queue.
2926  */
2927 static void tcp_grow_skb(struct sock *sk, struct sk_buff *skb, int amount)
2928 {
2929 	struct sk_buff *next_skb = skb->next;
2930 	unsigned int nlen;
2931 
2932 	if (tcp_skb_is_last(sk, skb))
2933 		return;
2934 
2935 	if (!tcp_skb_can_collapse(skb, next_skb))
2936 		return;
2937 
2938 	nlen = min_t(u32, amount, next_skb->len);
2939 	if (!nlen || !skb_shift(skb, next_skb, nlen))
2940 		return;
2941 
2942 	TCP_SKB_CB(skb)->end_seq += nlen;
2943 	TCP_SKB_CB(next_skb)->seq += nlen;
2944 
2945 	if (!next_skb->len) {
2946 		/* In case FIN is set, we need to update end_seq */
2947 		TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(next_skb)->end_seq;
2948 
2949 		tcp_eat_one_skb(sk, skb, next_skb);
2950 	}
2951 }
2952 
2953 /* This routine writes packets to the network.  It advances the
2954  * send_head.  This happens as incoming acks open up the remote
2955  * window for us.
2956  *
2957  * LARGESEND note: !tcp_urg_mode is overkill, only frames between
2958  * snd_up-64k-mss .. snd_up cannot be large. However, taking into
2959  * account rare use of URG, this is not a big flaw.
2960  *
2961  * Send at most one packet when push_one > 0. Temporarily ignore
2962  * cwnd limit to force at most one packet out when push_one == 2.
2963 
2964  * Returns true, if no segments are in flight and we have queued segments,
2965  * but cannot send anything now because of SWS or another problem.
2966  */
2967 static bool tcp_write_xmit(struct sock *sk, unsigned int mss_now, int nonagle,
2968 			   int push_one, gfp_t gfp)
2969 {
2970 	struct tcp_sock *tp = tcp_sk(sk);
2971 	struct sk_buff *skb;
2972 	unsigned int tso_segs, sent_pkts;
2973 	u32 cwnd_quota, max_segs;
2974 	int result;
2975 	bool is_cwnd_limited = false, is_rwnd_limited = false;
2976 
2977 	sent_pkts = 0;
2978 
2979 	tcp_mstamp_refresh(tp);
2980 
2981 	/* AccECN option beacon depends on mstamp, it may change mss */
2982 	if (tcp_ecn_mode_accecn(tp) && tcp_accecn_option_beacon_check(sk))
2983 		mss_now = tcp_current_mss(sk);
2984 
2985 	if (!push_one) {
2986 		/* Do MTU probing. */
2987 		result = tcp_mtu_probe(sk);
2988 		if (!result) {
2989 			return false;
2990 		} else if (result > 0) {
2991 			sent_pkts = 1;
2992 		}
2993 	}
2994 
2995 	max_segs = tcp_tso_segs(sk, mss_now);
2996 	while ((skb = tcp_send_head(sk))) {
2997 		unsigned int limit;
2998 		int missing_bytes;
2999 
3000 		if (unlikely(tp->repair) && tp->repair_queue == TCP_SEND_QUEUE) {
3001 			/* "skb_mstamp_ns" is used as a start point for the retransmit timer */
3002 			tp->tcp_wstamp_ns = tp->tcp_clock_cache;
3003 			skb_set_delivery_time(skb, tp->tcp_wstamp_ns, SKB_CLOCK_MONOTONIC);
3004 			list_move_tail(&skb->tcp_tsorted_anchor, &tp->tsorted_sent_queue);
3005 			tcp_init_tso_segs(skb, mss_now);
3006 			goto repair; /* Skip network transmission */
3007 		}
3008 
3009 		if (tcp_pacing_check(sk))
3010 			break;
3011 
3012 		cwnd_quota = tcp_cwnd_test(tp);
3013 		if (!cwnd_quota) {
3014 			if (push_one == 2)
3015 				/* Force out a loss probe pkt. */
3016 				cwnd_quota = 1;
3017 			else
3018 				break;
3019 		}
3020 		cwnd_quota = min(cwnd_quota, max_segs);
3021 		missing_bytes = cwnd_quota * mss_now - skb->len;
3022 		if (missing_bytes > 0)
3023 			tcp_grow_skb(sk, skb, missing_bytes);
3024 
3025 		tso_segs = tcp_set_skb_tso_segs(skb, mss_now);
3026 
3027 		if (unlikely(!tcp_snd_wnd_test(tp, skb, mss_now))) {
3028 			is_rwnd_limited = true;
3029 			break;
3030 		}
3031 
3032 		if (tso_segs == 1) {
3033 			if (unlikely(!tcp_nagle_test(tp, skb, mss_now,
3034 						     (tcp_skb_is_last(sk, skb) ?
3035 						      nonagle : TCP_NAGLE_PUSH))))
3036 				break;
3037 		} else {
3038 			if (!push_one &&
3039 			    tcp_tso_should_defer(sk, skb, &is_cwnd_limited,
3040 						 &is_rwnd_limited, max_segs))
3041 				break;
3042 		}
3043 
3044 		limit = mss_now;
3045 		if (tso_segs > 1 && !tcp_urg_mode(tp))
3046 			limit = tcp_mss_split_point(sk, skb, mss_now,
3047 						    cwnd_quota,
3048 						    nonagle);
3049 
3050 		if (skb->len > limit &&
3051 		    unlikely(tso_fragment(sk, skb, limit, mss_now, gfp)))
3052 			break;
3053 
3054 		if (tcp_small_queue_check(sk, skb, 0))
3055 			break;
3056 
3057 		/* Argh, we hit an empty skb(), presumably a thread
3058 		 * is sleeping in sendmsg()/sk_stream_wait_memory().
3059 		 * We do not want to send a pure-ack packet and have
3060 		 * a strange looking rtx queue with empty packet(s).
3061 		 */
3062 		if (TCP_SKB_CB(skb)->end_seq == TCP_SKB_CB(skb)->seq)
3063 			break;
3064 
3065 		if (unlikely(tcp_transmit_skb(sk, skb, 1, gfp)))
3066 			break;
3067 
3068 repair:
3069 		/* Advance the send_head.  This one is sent out.
3070 		 * This call will increment packets_out.
3071 		 */
3072 		tcp_event_new_data_sent(sk, skb);
3073 
3074 		tcp_minshall_update(tp, mss_now, skb);
3075 		sent_pkts += tcp_skb_pcount(skb);
3076 
3077 		if (push_one)
3078 			break;
3079 	}
3080 
3081 	if (is_rwnd_limited)
3082 		tcp_chrono_start(sk, TCP_CHRONO_RWND_LIMITED);
3083 	else
3084 		tcp_chrono_stop(sk, TCP_CHRONO_RWND_LIMITED);
3085 
3086 	is_cwnd_limited |= (tcp_packets_in_flight(tp) >= tcp_snd_cwnd(tp));
3087 	if (likely(sent_pkts || is_cwnd_limited))
3088 		tcp_cwnd_validate(sk, is_cwnd_limited);
3089 
3090 	if (likely(sent_pkts)) {
3091 		if (tcp_in_cwnd_reduction(sk))
3092 			tp->prr_out += sent_pkts;
3093 
3094 		/* Send one loss probe per tail loss episode. */
3095 		if (push_one != 2)
3096 			tcp_schedule_loss_probe(sk, false);
3097 		return false;
3098 	}
3099 	return !tp->packets_out && !tcp_write_queue_empty(sk);
3100 }
3101 
3102 bool tcp_schedule_loss_probe(struct sock *sk, bool advancing_rto)
3103 {
3104 	struct inet_connection_sock *icsk = inet_csk(sk);
3105 	struct tcp_sock *tp = tcp_sk(sk);
3106 	u32 timeout, timeout_us, rto_delta_us;
3107 	int early_retrans;
3108 
3109 	/* Don't do any loss probe on a Fast Open connection before 3WHS
3110 	 * finishes.
3111 	 */
3112 	if (rcu_access_pointer(tp->fastopen_rsk))
3113 		return false;
3114 
3115 	early_retrans = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_early_retrans);
3116 	/* Schedule a loss probe in 2*RTT for SACK capable connections
3117 	 * not in loss recovery, that are either limited by cwnd or application.
3118 	 */
3119 	if ((early_retrans != 3 && early_retrans != 4) ||
3120 	    !tcp_is_sack(tp) ||
3121 	    (icsk->icsk_ca_state != TCP_CA_Open &&
3122 	     icsk->icsk_ca_state != TCP_CA_CWR))
3123 		return false;
3124 
3125 	/* Probe timeout is 2*rtt. Add minimum RTO to account
3126 	 * for delayed ack when there's one outstanding packet. If no RTT
3127 	 * sample is available then probe after TCP_TIMEOUT_INIT.
3128 	 */
3129 	if (tp->srtt_us) {
3130 		timeout_us = tp->srtt_us >> 2;
3131 		if (tp->packets_out == 1)
3132 			timeout_us += tcp_rto_min_us(sk);
3133 		else
3134 			timeout_us += TCP_TIMEOUT_MIN_US;
3135 		timeout = usecs_to_jiffies(timeout_us);
3136 	} else {
3137 		timeout = TCP_TIMEOUT_INIT;
3138 	}
3139 
3140 	/* If the RTO formula yields an earlier time, then use that time. */
3141 	rto_delta_us = advancing_rto ?
3142 			jiffies_to_usecs(inet_csk(sk)->icsk_rto) :
3143 			tcp_rto_delta_us(sk);  /* How far in future is RTO? */
3144 	if (rto_delta_us > 0)
3145 		timeout = min_t(u32, timeout, usecs_to_jiffies(rto_delta_us));
3146 
3147 	tcp_reset_xmit_timer(sk, ICSK_TIME_LOSS_PROBE, timeout, true);
3148 	return true;
3149 }
3150 
3151 /* Thanks to skb fast clones, we can detect if a prior transmit of
3152  * a packet is still in a qdisc or driver queue.
3153  * In this case, there is very little point doing a retransmit !
3154  */
3155 static bool skb_still_in_host_queue(struct sock *sk,
3156 				    const struct sk_buff *skb)
3157 {
3158 	if (unlikely(skb_fclone_busy(sk, skb))) {
3159 		set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags);
3160 		smp_mb__after_atomic();
3161 		if (skb_fclone_busy(sk, skb)) {
3162 			NET_INC_STATS(sock_net(sk),
3163 				      LINUX_MIB_TCPSPURIOUS_RTX_HOSTQUEUES);
3164 			return true;
3165 		}
3166 	}
3167 	return false;
3168 }
3169 
3170 /* When probe timeout (PTO) fires, try send a new segment if possible, else
3171  * retransmit the last segment.
3172  */
3173 void tcp_send_loss_probe(struct sock *sk)
3174 {
3175 	struct tcp_sock *tp = tcp_sk(sk);
3176 	struct sk_buff *skb;
3177 	int pcount;
3178 	int mss = tcp_current_mss(sk);
3179 
3180 	/* At most one outstanding TLP */
3181 	if (tp->tlp_high_seq)
3182 		goto rearm_timer;
3183 
3184 	tp->tlp_retrans = 0;
3185 	skb = tcp_send_head(sk);
3186 	if (skb && tcp_snd_wnd_test(tp, skb, mss)) {
3187 		pcount = tp->packets_out;
3188 		tcp_write_xmit(sk, mss, TCP_NAGLE_OFF, 2, GFP_ATOMIC);
3189 		if (tp->packets_out > pcount)
3190 			goto probe_sent;
3191 		goto rearm_timer;
3192 	}
3193 	skb = skb_rb_last(&sk->tcp_rtx_queue);
3194 	if (unlikely(!skb)) {
3195 		tcp_warn_once(sk, tp->packets_out, "invalid inflight: ");
3196 		smp_store_release(&inet_csk(sk)->icsk_pending, 0);
3197 		return;
3198 	}
3199 
3200 	if (skb_still_in_host_queue(sk, skb))
3201 		goto rearm_timer;
3202 
3203 	pcount = tcp_skb_pcount(skb);
3204 	if (WARN_ON(!pcount))
3205 		goto rearm_timer;
3206 
3207 	if ((pcount > 1) && (skb->len > (pcount - 1) * mss)) {
3208 		if (unlikely(tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb,
3209 					  (pcount - 1) * mss, mss,
3210 					  GFP_ATOMIC)))
3211 			goto rearm_timer;
3212 		skb = skb_rb_next(skb);
3213 	}
3214 
3215 	if (WARN_ON(!skb || !tcp_skb_pcount(skb)))
3216 		goto rearm_timer;
3217 
3218 	if (__tcp_retransmit_skb(sk, skb, 1))
3219 		goto rearm_timer;
3220 
3221 	tp->tlp_retrans = 1;
3222 
3223 probe_sent:
3224 	/* Record snd_nxt for loss detection. */
3225 	tp->tlp_high_seq = tp->snd_nxt;
3226 
3227 	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPLOSSPROBES);
3228 	/* Reset s.t. tcp_rearm_rto will restart timer from now */
3229 	smp_store_release(&inet_csk(sk)->icsk_pending, 0);
3230 rearm_timer:
3231 	tcp_rearm_rto(sk);
3232 }
3233 
3234 /* Push out any pending frames which were held back due to
3235  * TCP_CORK or attempt at coalescing tiny packets.
3236  * The socket must be locked by the caller.
3237  */
3238 void __tcp_push_pending_frames(struct sock *sk, unsigned int cur_mss,
3239 			       int nonagle)
3240 {
3241 	/* If we are closed, the bytes will have to remain here.
3242 	 * In time closedown will finish, we empty the write queue and
3243 	 * all will be happy.
3244 	 */
3245 	if (unlikely(sk->sk_state == TCP_CLOSE))
3246 		return;
3247 
3248 	if (tcp_write_xmit(sk, cur_mss, nonagle, 0,
3249 			   sk_gfp_mask(sk, GFP_ATOMIC)))
3250 		tcp_check_probe_timer(sk);
3251 }
3252 
3253 /* Send _single_ skb sitting at the send head. This function requires
3254  * true push pending frames to setup probe timer etc.
3255  */
3256 void tcp_push_one(struct sock *sk, unsigned int mss_now)
3257 {
3258 	struct sk_buff *skb = tcp_send_head(sk);
3259 
3260 	BUG_ON(!skb || skb->len < mss_now);
3261 
3262 	tcp_write_xmit(sk, mss_now, TCP_NAGLE_PUSH, 1, sk->sk_allocation);
3263 }
3264 
3265 /* This function returns the amount that we can raise the
3266  * usable window based on the following constraints
3267  *
3268  * 1. The window can never be shrunk once it is offered (RFC 793)
3269  * 2. We limit memory per socket
3270  *
3271  * RFC 1122:
3272  * "the suggested [SWS] avoidance algorithm for the receiver is to keep
3273  *  RECV.NEXT + RCV.WIN fixed until:
3274  *  RCV.BUFF - RCV.USER - RCV.WINDOW >= min(1/2 RCV.BUFF, MSS)"
3275  *
3276  * i.e. don't raise the right edge of the window until you can raise
3277  * it at least MSS bytes.
3278  *
3279  * Unfortunately, the recommended algorithm breaks header prediction,
3280  * since header prediction assumes th->window stays fixed.
3281  *
3282  * Strictly speaking, keeping th->window fixed violates the receiver
3283  * side SWS prevention criteria. The problem is that under this rule
3284  * a stream of single byte packets will cause the right side of the
3285  * window to always advance by a single byte.
3286  *
3287  * Of course, if the sender implements sender side SWS prevention
3288  * then this will not be a problem.
3289  *
3290  * BSD seems to make the following compromise:
3291  *
3292  *	If the free space is less than the 1/4 of the maximum
3293  *	space available and the free space is less than 1/2 mss,
3294  *	then set the window to 0.
3295  *	[ Actually, bsd uses MSS and 1/4 of maximal _window_ ]
3296  *	Otherwise, just prevent the window from shrinking
3297  *	and from being larger than the largest representable value.
3298  *
3299  * This prevents incremental opening of the window in the regime
3300  * where TCP is limited by the speed of the reader side taking
3301  * data out of the TCP receive queue. It does nothing about
3302  * those cases where the window is constrained on the sender side
3303  * because the pipeline is full.
3304  *
3305  * BSD also seems to "accidentally" limit itself to windows that are a
3306  * multiple of MSS, at least until the free space gets quite small.
3307  * This would appear to be a side effect of the mbuf implementation.
3308  * Combining these two algorithms results in the observed behavior
3309  * of having a fixed window size at almost all times.
3310  *
3311  * Below we obtain similar behavior by forcing the offered window to
3312  * a multiple of the mss when it is feasible to do so.
3313  *
3314  * Note, we don't "adjust" for TIMESTAMP or SACK option bytes.
3315  * Regular options like TIMESTAMP are taken into account.
3316  */
3317 u32 __tcp_select_window(struct sock *sk)
3318 {
3319 	struct inet_connection_sock *icsk = inet_csk(sk);
3320 	struct tcp_sock *tp = tcp_sk(sk);
3321 	struct net *net = sock_net(sk);
3322 	/* MSS for the peer's data.  Previous versions used mss_clamp
3323 	 * here.  I don't know if the value based on our guesses
3324 	 * of peer's MSS is better for the performance.  It's more correct
3325 	 * but may be worse for the performance because of rcv_mss
3326 	 * fluctuations.  --SAW  1998/11/1
3327 	 */
3328 	int mss = icsk->icsk_ack.rcv_mss;
3329 	int free_space = tcp_space(sk);
3330 	int allowed_space = tcp_full_space(sk);
3331 	int full_space, window;
3332 
3333 	if (sk_is_mptcp(sk))
3334 		mptcp_space(sk, &free_space, &allowed_space);
3335 
3336 	full_space = min_t(int, tp->window_clamp, allowed_space);
3337 
3338 	if (unlikely(mss > full_space)) {
3339 		mss = full_space;
3340 		if (mss <= 0)
3341 			return 0;
3342 	}
3343 
3344 	/* Only allow window shrink if the sysctl is enabled and we have
3345 	 * a non-zero scaling factor in effect.
3346 	 */
3347 	if (READ_ONCE(net->ipv4.sysctl_tcp_shrink_window) && tp->rx_opt.rcv_wscale)
3348 		goto shrink_window_allowed;
3349 
3350 	/* do not allow window to shrink */
3351 
3352 	if (free_space < (full_space >> 1)) {
3353 		icsk->icsk_ack.quick = 0;
3354 
3355 		if (tcp_under_memory_pressure(sk))
3356 			tcp_adjust_rcv_ssthresh(sk);
3357 
3358 		/* free_space might become our new window, make sure we don't
3359 		 * increase it due to wscale.
3360 		 */
3361 		free_space = round_down(free_space, 1 << tp->rx_opt.rcv_wscale);
3362 
3363 		/* if free space is less than mss estimate, or is below 1/16th
3364 		 * of the maximum allowed, try to move to zero-window, else
3365 		 * tcp_clamp_window() will grow rcv buf up to tcp_rmem[2], and
3366 		 * new incoming data is dropped due to memory limits.
3367 		 * With large window, mss test triggers way too late in order
3368 		 * to announce zero window in time before rmem limit kicks in.
3369 		 */
3370 		if (free_space < (allowed_space >> 4) || free_space < mss)
3371 			return 0;
3372 	}
3373 
3374 	if (free_space > tp->rcv_ssthresh)
3375 		free_space = tp->rcv_ssthresh;
3376 
3377 	/* Don't do rounding if we are using window scaling, since the
3378 	 * scaled window will not line up with the MSS boundary anyway.
3379 	 */
3380 	if (tp->rx_opt.rcv_wscale) {
3381 		window = free_space;
3382 
3383 		/* Advertise enough space so that it won't get scaled away.
3384 		 * Import case: prevent zero window announcement if
3385 		 * 1<<rcv_wscale > mss.
3386 		 */
3387 		window = ALIGN(window, (1 << tp->rx_opt.rcv_wscale));
3388 	} else {
3389 		window = tp->rcv_wnd;
3390 		/* Get the largest window that is a nice multiple of mss.
3391 		 * Window clamp already applied above.
3392 		 * If our current window offering is within 1 mss of the
3393 		 * free space we just keep it. This prevents the divide
3394 		 * and multiply from happening most of the time.
3395 		 * We also don't do any window rounding when the free space
3396 		 * is too small.
3397 		 */
3398 		if (window <= free_space - mss || window > free_space)
3399 			window = rounddown(free_space, mss);
3400 		else if (mss == full_space &&
3401 			 free_space > window + (full_space >> 1))
3402 			window = free_space;
3403 	}
3404 
3405 	return window;
3406 
3407 shrink_window_allowed:
3408 	/* new window should always be an exact multiple of scaling factor */
3409 	free_space = round_down(free_space, 1 << tp->rx_opt.rcv_wscale);
3410 
3411 	if (free_space < (full_space >> 1)) {
3412 		icsk->icsk_ack.quick = 0;
3413 
3414 		if (tcp_under_memory_pressure(sk))
3415 			tcp_adjust_rcv_ssthresh(sk);
3416 
3417 		/* if free space is too low, return a zero window */
3418 		if (free_space < (allowed_space >> 4) || free_space < mss ||
3419 			free_space < (1 << tp->rx_opt.rcv_wscale))
3420 			return 0;
3421 	}
3422 
3423 	if (free_space > tp->rcv_ssthresh) {
3424 		free_space = tp->rcv_ssthresh;
3425 		/* new window should always be an exact multiple of scaling factor
3426 		 *
3427 		 * For this case, we ALIGN "up" (increase free_space) because
3428 		 * we know free_space is not zero here, it has been reduced from
3429 		 * the memory-based limit, and rcv_ssthresh is not a hard limit
3430 		 * (unlike sk_rcvbuf).
3431 		 */
3432 		free_space = ALIGN(free_space, (1 << tp->rx_opt.rcv_wscale));
3433 	}
3434 
3435 	return free_space;
3436 }
3437 
3438 void tcp_skb_collapse_tstamp(struct sk_buff *skb,
3439 			     const struct sk_buff *next_skb)
3440 {
3441 	if (unlikely(tcp_has_tx_tstamp(next_skb))) {
3442 		const struct skb_shared_info *next_shinfo =
3443 			skb_shinfo(next_skb);
3444 		struct skb_shared_info *shinfo = skb_shinfo(skb);
3445 
3446 		shinfo->tx_flags |= next_shinfo->tx_flags & SKBTX_ANY_TSTAMP;
3447 		shinfo->tskey = next_shinfo->tskey;
3448 		TCP_SKB_CB(skb)->txstamp_ack |=
3449 			TCP_SKB_CB(next_skb)->txstamp_ack;
3450 	}
3451 }
3452 
3453 /* Collapses two adjacent SKB's during retransmission. */
3454 static bool tcp_collapse_retrans(struct sock *sk, struct sk_buff *skb)
3455 {
3456 	struct tcp_sock *tp = tcp_sk(sk);
3457 	struct sk_buff *next_skb = skb_rb_next(skb);
3458 	int next_skb_size;
3459 
3460 	next_skb_size = next_skb->len;
3461 
3462 	BUG_ON(tcp_skb_pcount(skb) != 1 || tcp_skb_pcount(next_skb) != 1);
3463 
3464 	if (next_skb_size && !tcp_skb_shift(skb, next_skb, 1, next_skb_size))
3465 		return false;
3466 
3467 	tcp_highest_sack_replace(sk, next_skb, skb);
3468 
3469 	/* Update sequence range on original skb. */
3470 	TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(next_skb)->end_seq;
3471 
3472 	/* Merge over control information. This moves PSH/FIN etc. over */
3473 	TCP_SKB_CB(skb)->tcp_flags |= TCP_SKB_CB(next_skb)->tcp_flags;
3474 
3475 	/* All done, get rid of second SKB and account for it so
3476 	 * packet counting does not break.
3477 	 */
3478 	TCP_SKB_CB(skb)->sacked |= TCP_SKB_CB(next_skb)->sacked & TCPCB_EVER_RETRANS;
3479 	TCP_SKB_CB(skb)->eor = TCP_SKB_CB(next_skb)->eor;
3480 
3481 	/* changed transmit queue under us so clear hints */
3482 	if (next_skb == tp->retransmit_skb_hint)
3483 		tp->retransmit_skb_hint = skb;
3484 
3485 	tcp_adjust_pcount(sk, next_skb, tcp_skb_pcount(next_skb));
3486 
3487 	tcp_skb_collapse_tstamp(skb, next_skb);
3488 
3489 	tcp_rtx_queue_unlink_and_free(next_skb, sk);
3490 	return true;
3491 }
3492 
3493 /* Check if coalescing SKBs is legal. */
3494 static bool tcp_can_collapse(const struct sock *sk, const struct sk_buff *skb)
3495 {
3496 	if (tcp_skb_pcount(skb) > 1)
3497 		return false;
3498 	if (skb_cloned(skb))
3499 		return false;
3500 	if (!skb_frags_readable(skb))
3501 		return false;
3502 	/* Some heuristics for collapsing over SACK'd could be invented */
3503 	if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)
3504 		return false;
3505 
3506 	return true;
3507 }
3508 
3509 /* Collapse packets in the retransmit queue to make to create
3510  * less packets on the wire. This is only done on retransmission.
3511  */
3512 static void tcp_retrans_try_collapse(struct sock *sk, struct sk_buff *to,
3513 				     int space)
3514 {
3515 	struct tcp_sock *tp = tcp_sk(sk);
3516 	struct sk_buff *skb = to, *tmp;
3517 	bool first = true;
3518 
3519 	if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_retrans_collapse))
3520 		return;
3521 	if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)
3522 		return;
3523 
3524 	skb_rbtree_walk_from_safe(skb, tmp) {
3525 		if (!tcp_can_collapse(sk, skb))
3526 			break;
3527 
3528 		if (!tcp_skb_can_collapse(to, skb))
3529 			break;
3530 
3531 		space -= skb->len;
3532 
3533 		if (first) {
3534 			first = false;
3535 			continue;
3536 		}
3537 
3538 		if (space < 0)
3539 			break;
3540 
3541 		if (after(TCP_SKB_CB(skb)->end_seq, tcp_wnd_end(tp)))
3542 			break;
3543 
3544 		if (!tcp_collapse_retrans(sk, to))
3545 			break;
3546 	}
3547 }
3548 
3549 /* This retransmits one SKB.  Policy decisions and retransmit queue
3550  * state updates are done by the caller.  Returns non-zero if an
3551  * error occurred which prevented the send.
3552  */
3553 int __tcp_retransmit_skb(struct sock *sk, struct sk_buff *skb, int segs)
3554 {
3555 	struct inet_connection_sock *icsk = inet_csk(sk);
3556 	struct tcp_sock *tp = tcp_sk(sk);
3557 	unsigned int cur_mss;
3558 	int diff, len, err;
3559 	int avail_wnd;
3560 
3561 	/* Inconclusive MTU probe */
3562 	if (icsk->icsk_mtup.probe_size)
3563 		icsk->icsk_mtup.probe_size = 0;
3564 
3565 	if (skb_still_in_host_queue(sk, skb)) {
3566 		err = -EBUSY;
3567 		goto out;
3568 	}
3569 
3570 start:
3571 	if (before(TCP_SKB_CB(skb)->seq, tp->snd_una)) {
3572 		if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
3573 			TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_SYN;
3574 			TCP_SKB_CB(skb)->seq++;
3575 			goto start;
3576 		}
3577 		if (unlikely(before(TCP_SKB_CB(skb)->end_seq, tp->snd_una))) {
3578 			WARN_ON_ONCE(1);
3579 			err = -EINVAL;
3580 			goto out;
3581 		}
3582 		if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq)) {
3583 			err = -ENOMEM;
3584 			goto out;
3585 		}
3586 	}
3587 
3588 	if (inet_csk(sk)->icsk_af_ops->rebuild_header(sk)) {
3589 		err = -EHOSTUNREACH; /* Routing failure or similar. */
3590 		goto out;
3591 	}
3592 
3593 	cur_mss = tcp_current_mss(sk);
3594 	avail_wnd = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq;
3595 
3596 	/* If receiver has shrunk his window, and skb is out of
3597 	 * new window, do not retransmit it. The exception is the
3598 	 * case, when window is shrunk to zero. In this case
3599 	 * our retransmit of one segment serves as a zero window probe.
3600 	 */
3601 	if (avail_wnd <= 0) {
3602 		if (TCP_SKB_CB(skb)->seq != tp->snd_una) {
3603 			err = -EAGAIN;
3604 			goto out;
3605 		}
3606 		avail_wnd = cur_mss;
3607 	}
3608 
3609 	len = cur_mss * segs;
3610 	if (len > avail_wnd) {
3611 		len = rounddown(avail_wnd, cur_mss);
3612 		if (!len)
3613 			len = avail_wnd;
3614 	}
3615 	if (skb->len > len) {
3616 		if (tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb, len,
3617 				 cur_mss, GFP_ATOMIC)) {
3618 			err = -ENOMEM;  /* We'll try again later. */
3619 			goto out;
3620 		}
3621 	} else {
3622 		if (skb_unclone_keeptruesize(skb, GFP_ATOMIC)) {
3623 			err = -ENOMEM;
3624 			goto out;
3625 		}
3626 
3627 		diff = tcp_skb_pcount(skb);
3628 		tcp_set_skb_tso_segs(skb, cur_mss);
3629 		diff -= tcp_skb_pcount(skb);
3630 		if (diff)
3631 			tcp_adjust_pcount(sk, skb, diff);
3632 		avail_wnd = min_t(int, avail_wnd, cur_mss);
3633 		if (skb->len < avail_wnd)
3634 			tcp_retrans_try_collapse(sk, skb, avail_wnd);
3635 	}
3636 
3637 	if (!tcp_ecn_mode_pending(tp) || icsk->icsk_retransmits > 1) {
3638 		/* RFC3168, section 6.1.1.1. ECN fallback
3639 		 * As AccECN uses the same SYN flags (+ AE), this check
3640 		 * covers both cases.
3641 		 */
3642 		if ((TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN_ECN) ==
3643 		    TCPHDR_SYN_ECN)
3644 			tcp_ecn_clear_syn(sk, skb);
3645 	}
3646 
3647 	/* Update global and local TCP statistics. */
3648 	segs = tcp_skb_pcount(skb);
3649 	TCP_ADD_STATS(sock_net(sk), TCP_MIB_RETRANSSEGS, segs);
3650 	if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)
3651 		__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSYNRETRANS);
3652 	tp->total_retrans += segs;
3653 	tp->bytes_retrans += skb->len;
3654 
3655 	/* make sure skb->data is aligned on arches that require it
3656 	 * and check if ack-trimming & collapsing extended the headroom
3657 	 * beyond what csum_start can cover.
3658 	 */
3659 	if (unlikely((NET_IP_ALIGN && ((unsigned long)skb->data & 3)) ||
3660 		     skb_headroom(skb) >= 0xFFFF)) {
3661 		struct sk_buff *nskb;
3662 
3663 		tcp_skb_tsorted_save(skb) {
3664 			nskb = __pskb_copy(skb, MAX_TCP_HEADER, GFP_ATOMIC);
3665 			if (nskb) {
3666 				nskb->dev = NULL;
3667 				err = tcp_transmit_skb(sk, nskb, 0, GFP_ATOMIC);
3668 			} else {
3669 				err = -ENOBUFS;
3670 			}
3671 		} tcp_skb_tsorted_restore(skb);
3672 
3673 		if (!err) {
3674 			tcp_update_skb_after_send(sk, skb, tp->tcp_wstamp_ns);
3675 			tcp_rate_skb_sent(sk, skb);
3676 		}
3677 	} else {
3678 		err = tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC);
3679 	}
3680 
3681 	if (BPF_SOCK_OPS_TEST_FLAG(tp, BPF_SOCK_OPS_RETRANS_CB_FLAG))
3682 		tcp_call_bpf_3arg(sk, BPF_SOCK_OPS_RETRANS_CB,
3683 				  TCP_SKB_CB(skb)->seq, segs, err);
3684 
3685 	if (unlikely(err) && err != -EBUSY)
3686 		NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPRETRANSFAIL, segs);
3687 
3688 	/* To avoid taking spuriously low RTT samples based on a timestamp
3689 	 * for a transmit that never happened, always mark EVER_RETRANS
3690 	 */
3691 	TCP_SKB_CB(skb)->sacked |= TCPCB_EVER_RETRANS;
3692 
3693 out:
3694 	trace_tcp_retransmit_skb(sk, skb, err);
3695 	return err;
3696 }
3697 
3698 int tcp_retransmit_skb(struct sock *sk, struct sk_buff *skb, int segs)
3699 {
3700 	struct tcp_sock *tp = tcp_sk(sk);
3701 	int err = __tcp_retransmit_skb(sk, skb, segs);
3702 
3703 	if (err == 0) {
3704 #if FASTRETRANS_DEBUG > 0
3705 		if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) {
3706 			net_dbg_ratelimited("retrans_out leaked\n");
3707 		}
3708 #endif
3709 		TCP_SKB_CB(skb)->sacked |= TCPCB_RETRANS;
3710 		tp->retrans_out += tcp_skb_pcount(skb);
3711 	}
3712 
3713 	/* Save stamp of the first (attempted) retransmit. */
3714 	if (!tp->retrans_stamp)
3715 		tp->retrans_stamp = tcp_skb_timestamp_ts(tp->tcp_usec_ts, skb);
3716 
3717 	if (tp->undo_retrans < 0)
3718 		tp->undo_retrans = 0;
3719 	tp->undo_retrans += tcp_skb_pcount(skb);
3720 	return err;
3721 }
3722 
3723 /* This gets called after a retransmit timeout, and the initially
3724  * retransmitted data is acknowledged.  It tries to continue
3725  * resending the rest of the retransmit queue, until either
3726  * we've sent it all or the congestion window limit is reached.
3727  */
3728 void tcp_xmit_retransmit_queue(struct sock *sk)
3729 {
3730 	const struct inet_connection_sock *icsk = inet_csk(sk);
3731 	struct sk_buff *skb, *rtx_head, *hole = NULL;
3732 	struct tcp_sock *tp = tcp_sk(sk);
3733 	bool rearm_timer = false;
3734 	u32 max_segs;
3735 	int mib_idx;
3736 
3737 	if (!tp->packets_out)
3738 		return;
3739 
3740 	rtx_head = tcp_rtx_queue_head(sk);
3741 	skb = tp->retransmit_skb_hint ?: rtx_head;
3742 	max_segs = tcp_tso_segs(sk, tcp_current_mss(sk));
3743 	skb_rbtree_walk_from(skb) {
3744 		__u8 sacked;
3745 		int segs;
3746 
3747 		if (tcp_pacing_check(sk))
3748 			break;
3749 
3750 		/* we could do better than to assign each time */
3751 		if (!hole)
3752 			tp->retransmit_skb_hint = skb;
3753 
3754 		segs = tcp_snd_cwnd(tp) - tcp_packets_in_flight(tp);
3755 		if (segs <= 0)
3756 			break;
3757 		sacked = TCP_SKB_CB(skb)->sacked;
3758 		/* In case tcp_shift_skb_data() have aggregated large skbs,
3759 		 * we need to make sure not sending too bigs TSO packets
3760 		 */
3761 		segs = min_t(int, segs, max_segs);
3762 
3763 		if (tp->retrans_out >= tp->lost_out) {
3764 			break;
3765 		} else if (!(sacked & TCPCB_LOST)) {
3766 			if (!hole && !(sacked & (TCPCB_SACKED_RETRANS|TCPCB_SACKED_ACKED)))
3767 				hole = skb;
3768 			continue;
3769 
3770 		} else {
3771 			if (icsk->icsk_ca_state != TCP_CA_Loss)
3772 				mib_idx = LINUX_MIB_TCPFASTRETRANS;
3773 			else
3774 				mib_idx = LINUX_MIB_TCPSLOWSTARTRETRANS;
3775 		}
3776 
3777 		if (sacked & (TCPCB_SACKED_ACKED|TCPCB_SACKED_RETRANS))
3778 			continue;
3779 
3780 		if (tcp_small_queue_check(sk, skb, 1))
3781 			break;
3782 
3783 		if (tcp_retransmit_skb(sk, skb, segs))
3784 			break;
3785 
3786 		NET_ADD_STATS(sock_net(sk), mib_idx, tcp_skb_pcount(skb));
3787 
3788 		if (tcp_in_cwnd_reduction(sk))
3789 			tp->prr_out += tcp_skb_pcount(skb);
3790 
3791 		if (skb == rtx_head &&
3792 		    icsk->icsk_pending != ICSK_TIME_REO_TIMEOUT)
3793 			rearm_timer = true;
3794 
3795 	}
3796 	if (rearm_timer)
3797 		tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
3798 				     inet_csk(sk)->icsk_rto, true);
3799 }
3800 
3801 /* Send a FIN. The caller locks the socket for us.
3802  * We should try to send a FIN packet really hard, but eventually give up.
3803  */
3804 void tcp_send_fin(struct sock *sk)
3805 {
3806 	struct sk_buff *skb, *tskb, *tail = tcp_write_queue_tail(sk);
3807 	struct tcp_sock *tp = tcp_sk(sk);
3808 
3809 	/* Optimization, tack on the FIN if we have one skb in write queue and
3810 	 * this skb was not yet sent, or we are under memory pressure.
3811 	 * Note: in the latter case, FIN packet will be sent after a timeout,
3812 	 * as TCP stack thinks it has already been transmitted.
3813 	 */
3814 	tskb = tail;
3815 	if (!tskb && tcp_under_memory_pressure(sk))
3816 		tskb = skb_rb_last(&sk->tcp_rtx_queue);
3817 
3818 	if (tskb) {
3819 		TCP_SKB_CB(tskb)->tcp_flags |= TCPHDR_FIN;
3820 		TCP_SKB_CB(tskb)->end_seq++;
3821 		tp->write_seq++;
3822 		if (!tail) {
3823 			/* This means tskb was already sent.
3824 			 * Pretend we included the FIN on previous transmit.
3825 			 * We need to set tp->snd_nxt to the value it would have
3826 			 * if FIN had been sent. This is because retransmit path
3827 			 * does not change tp->snd_nxt.
3828 			 */
3829 			WRITE_ONCE(tp->snd_nxt, tp->snd_nxt + 1);
3830 			return;
3831 		}
3832 	} else {
3833 		skb = alloc_skb_fclone(MAX_TCP_HEADER,
3834 				       sk_gfp_mask(sk, GFP_ATOMIC |
3835 						       __GFP_NOWARN));
3836 		if (unlikely(!skb))
3837 			return;
3838 
3839 		INIT_LIST_HEAD(&skb->tcp_tsorted_anchor);
3840 		skb_reserve(skb, MAX_TCP_HEADER);
3841 		sk_forced_mem_schedule(sk, skb->truesize);
3842 		/* FIN eats a sequence byte, write_seq advanced by tcp_queue_skb(). */
3843 		tcp_init_nondata_skb(skb, sk, tp->write_seq,
3844 				     TCPHDR_ACK | TCPHDR_FIN);
3845 		tcp_queue_skb(sk, skb);
3846 	}
3847 	__tcp_push_pending_frames(sk, tcp_current_mss(sk), TCP_NAGLE_OFF);
3848 }
3849 
3850 /* We get here when a process closes a file descriptor (either due to
3851  * an explicit close() or as a byproduct of exit()'ing) and there
3852  * was unread data in the receive queue.  This behavior is recommended
3853  * by RFC 2525, section 2.17.  -DaveM
3854  */
3855 void tcp_send_active_reset(struct sock *sk, gfp_t priority,
3856 			   enum sk_rst_reason reason)
3857 {
3858 	struct sk_buff *skb;
3859 
3860 	TCP_INC_STATS(sock_net(sk), TCP_MIB_OUTRSTS);
3861 
3862 	/* NOTE: No TCP options attached and we never retransmit this. */
3863 	skb = alloc_skb(MAX_TCP_HEADER, priority);
3864 	if (!skb) {
3865 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTFAILED);
3866 		return;
3867 	}
3868 
3869 	/* Reserve space for headers and prepare control bits. */
3870 	skb_reserve(skb, MAX_TCP_HEADER);
3871 	tcp_init_nondata_skb(skb, sk, tcp_acceptable_seq(sk),
3872 			     TCPHDR_ACK | TCPHDR_RST);
3873 	tcp_mstamp_refresh(tcp_sk(sk));
3874 	/* Send it off. */
3875 	if (tcp_transmit_skb(sk, skb, 0, priority))
3876 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTFAILED);
3877 
3878 	/* skb of trace_tcp_send_reset() keeps the skb that caused RST,
3879 	 * skb here is different to the troublesome skb, so use NULL
3880 	 */
3881 	trace_tcp_send_reset(sk, NULL, reason);
3882 }
3883 
3884 /* Send a crossed SYN-ACK during socket establishment.
3885  * WARNING: This routine must only be called when we have already sent
3886  * a SYN packet that crossed the incoming SYN that caused this routine
3887  * to get called. If this assumption fails then the initial rcv_wnd
3888  * and rcv_wscale values will not be correct.
3889  */
3890 int tcp_send_synack(struct sock *sk)
3891 {
3892 	struct sk_buff *skb;
3893 
3894 	skb = tcp_rtx_queue_head(sk);
3895 	if (!skb || !(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
3896 		pr_err("%s: wrong queue state\n", __func__);
3897 		return -EFAULT;
3898 	}
3899 	if (!(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_ACK)) {
3900 		if (skb_cloned(skb)) {
3901 			struct sk_buff *nskb;
3902 
3903 			tcp_skb_tsorted_save(skb) {
3904 				nskb = skb_copy(skb, GFP_ATOMIC);
3905 			} tcp_skb_tsorted_restore(skb);
3906 			if (!nskb)
3907 				return -ENOMEM;
3908 			INIT_LIST_HEAD(&nskb->tcp_tsorted_anchor);
3909 			tcp_highest_sack_replace(sk, skb, nskb);
3910 			tcp_rtx_queue_unlink_and_free(skb, sk);
3911 			__skb_header_release(nskb);
3912 			tcp_rbtree_insert(&sk->tcp_rtx_queue, nskb);
3913 			sk_wmem_queued_add(sk, nskb->truesize);
3914 			sk_mem_charge(sk, nskb->truesize);
3915 			skb = nskb;
3916 		}
3917 
3918 		TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_ACK;
3919 		tcp_ecn_send_synack(sk, skb);
3920 	}
3921 	return tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC);
3922 }
3923 
3924 /**
3925  * tcp_make_synack - Allocate one skb and build a SYNACK packet.
3926  * @sk: listener socket
3927  * @dst: dst entry attached to the SYNACK. It is consumed and caller
3928  *       should not use it again.
3929  * @req: request_sock pointer
3930  * @foc: cookie for tcp fast open
3931  * @synack_type: Type of synack to prepare
3932  * @syn_skb: SYN packet just received.  It could be NULL for rtx case.
3933  */
3934 struct sk_buff *tcp_make_synack(const struct sock *sk, struct dst_entry *dst,
3935 				struct request_sock *req,
3936 				struct tcp_fastopen_cookie *foc,
3937 				enum tcp_synack_type synack_type,
3938 				struct sk_buff *syn_skb)
3939 {
3940 	struct inet_request_sock *ireq = inet_rsk(req);
3941 	const struct tcp_sock *tp = tcp_sk(sk);
3942 	struct tcp_out_options opts;
3943 	struct tcp_key key = {};
3944 	struct sk_buff *skb;
3945 	int tcp_header_size;
3946 	struct tcphdr *th;
3947 	int mss;
3948 	u64 now;
3949 
3950 	skb = alloc_skb(MAX_TCP_HEADER, GFP_ATOMIC);
3951 	if (unlikely(!skb)) {
3952 		dst_release(dst);
3953 		return NULL;
3954 	}
3955 	/* Reserve space for headers. */
3956 	skb_reserve(skb, MAX_TCP_HEADER);
3957 
3958 	switch (synack_type) {
3959 	case TCP_SYNACK_NORMAL:
3960 	case TCP_SYNACK_RETRANS:
3961 		skb_set_owner_edemux(skb, req_to_sk(req));
3962 		break;
3963 	case TCP_SYNACK_COOKIE:
3964 		/* Under synflood, we do not attach skb to a socket,
3965 		 * to avoid false sharing.
3966 		 */
3967 		break;
3968 	case TCP_SYNACK_FASTOPEN:
3969 		/* sk is a const pointer, because we want to express multiple
3970 		 * cpu might call us concurrently.
3971 		 * sk->sk_wmem_alloc in an atomic, we can promote to rw.
3972 		 */
3973 		skb_set_owner_w(skb, (struct sock *)sk);
3974 		break;
3975 	}
3976 	skb_dst_set(skb, dst);
3977 
3978 	mss = tcp_mss_clamp(tp, dst_metric_advmss(dst));
3979 
3980 	memset(&opts, 0, sizeof(opts));
3981 	now = tcp_clock_ns();
3982 #ifdef CONFIG_SYN_COOKIES
3983 	if (unlikely(synack_type == TCP_SYNACK_COOKIE && ireq->tstamp_ok))
3984 		skb_set_delivery_time(skb, cookie_init_timestamp(req, now),
3985 				      SKB_CLOCK_MONOTONIC);
3986 	else
3987 #endif
3988 	{
3989 		skb_set_delivery_time(skb, now, SKB_CLOCK_MONOTONIC);
3990 		if (!tcp_rsk(req)->snt_synack) /* Timestamp first SYNACK */
3991 			tcp_rsk(req)->snt_synack = tcp_skb_timestamp_us(skb);
3992 	}
3993 
3994 #if defined(CONFIG_TCP_MD5SIG) || defined(CONFIG_TCP_AO)
3995 	rcu_read_lock();
3996 #endif
3997 	if (tcp_rsk_used_ao(req)) {
3998 #ifdef CONFIG_TCP_AO
3999 		struct tcp_ao_key *ao_key = NULL;
4000 		u8 keyid = tcp_rsk(req)->ao_keyid;
4001 		u8 rnext = tcp_rsk(req)->ao_rcv_next;
4002 
4003 		ao_key = tcp_sk(sk)->af_specific->ao_lookup(sk, req_to_sk(req),
4004 							    keyid, -1);
4005 		/* If there is no matching key - avoid sending anything,
4006 		 * especially usigned segments. It could try harder and lookup
4007 		 * for another peer-matching key, but the peer has requested
4008 		 * ao_keyid (RFC5925 RNextKeyID), so let's keep it simple here.
4009 		 */
4010 		if (unlikely(!ao_key)) {
4011 			trace_tcp_ao_synack_no_key(sk, keyid, rnext);
4012 			rcu_read_unlock();
4013 			kfree_skb(skb);
4014 			net_warn_ratelimited("TCP-AO: the keyid %u from SYN packet is not present - not sending SYNACK\n",
4015 					     keyid);
4016 			return NULL;
4017 		}
4018 		key.ao_key = ao_key;
4019 		key.type = TCP_KEY_AO;
4020 #endif
4021 	} else {
4022 #ifdef CONFIG_TCP_MD5SIG
4023 		key.md5_key = tcp_rsk(req)->af_specific->req_md5_lookup(sk,
4024 					req_to_sk(req));
4025 		if (key.md5_key)
4026 			key.type = TCP_KEY_MD5;
4027 #endif
4028 	}
4029 	skb_set_hash(skb, READ_ONCE(tcp_rsk(req)->txhash), PKT_HASH_TYPE_L4);
4030 	/* bpf program will be interested in the tcp_flags */
4031 	TCP_SKB_CB(skb)->tcp_flags = TCPHDR_SYN | TCPHDR_ACK;
4032 	tcp_header_size = tcp_synack_options(sk, req, mss, skb, &opts,
4033 					     &key, foc, synack_type, syn_skb)
4034 					+ sizeof(*th);
4035 
4036 	skb_push(skb, tcp_header_size);
4037 	skb_reset_transport_header(skb);
4038 
4039 	th = (struct tcphdr *)skb->data;
4040 	memset(th, 0, sizeof(struct tcphdr));
4041 	th->syn = 1;
4042 	th->ack = 1;
4043 	tcp_ecn_make_synack(req, th, synack_type);
4044 	th->source = htons(ireq->ir_num);
4045 	th->dest = ireq->ir_rmt_port;
4046 	skb->mark = ireq->ir_mark;
4047 	skb->ip_summed = CHECKSUM_PARTIAL;
4048 	th->seq = htonl(tcp_rsk(req)->snt_isn);
4049 	/* XXX data is queued and acked as is. No buffer/window check */
4050 	th->ack_seq = htonl(tcp_rsk(req)->rcv_nxt);
4051 
4052 	/* RFC1323: The window in SYN & SYN/ACK segments is never scaled. */
4053 	th->window = htons(min(req->rsk_rcv_wnd, 65535U));
4054 	tcp_options_write(th, NULL, tcp_rsk(req), &opts, &key);
4055 	th->doff = (tcp_header_size >> 2);
4056 	TCP_INC_STATS(sock_net(sk), TCP_MIB_OUTSEGS);
4057 
4058 	/* Okay, we have all we need - do the md5 hash if needed */
4059 	if (tcp_key_is_md5(&key)) {
4060 #ifdef CONFIG_TCP_MD5SIG
4061 		tcp_rsk(req)->af_specific->calc_md5_hash(opts.hash_location,
4062 					key.md5_key, req_to_sk(req), skb);
4063 #endif
4064 	} else if (tcp_key_is_ao(&key)) {
4065 #ifdef CONFIG_TCP_AO
4066 		tcp_rsk(req)->af_specific->ao_synack_hash(opts.hash_location,
4067 					key.ao_key, req, skb,
4068 					opts.hash_location - (u8 *)th, 0);
4069 #endif
4070 	}
4071 #if defined(CONFIG_TCP_MD5SIG) || defined(CONFIG_TCP_AO)
4072 	rcu_read_unlock();
4073 #endif
4074 
4075 	bpf_skops_write_hdr_opt((struct sock *)sk, skb, req, syn_skb,
4076 				synack_type, &opts);
4077 
4078 	skb_set_delivery_time(skb, now, SKB_CLOCK_MONOTONIC);
4079 	tcp_add_tx_delay(skb, tp);
4080 
4081 	return skb;
4082 }
4083 EXPORT_IPV6_MOD(tcp_make_synack);
4084 
4085 static void tcp_ca_dst_init(struct sock *sk, const struct dst_entry *dst)
4086 {
4087 	struct inet_connection_sock *icsk = inet_csk(sk);
4088 	const struct tcp_congestion_ops *ca;
4089 	u32 ca_key = dst_metric(dst, RTAX_CC_ALGO);
4090 
4091 	if (ca_key == TCP_CA_UNSPEC)
4092 		return;
4093 
4094 	rcu_read_lock();
4095 	ca = tcp_ca_find_key(ca_key);
4096 	if (likely(ca && bpf_try_module_get(ca, ca->owner))) {
4097 		bpf_module_put(icsk->icsk_ca_ops, icsk->icsk_ca_ops->owner);
4098 		icsk->icsk_ca_dst_locked = tcp_ca_dst_locked(dst);
4099 		icsk->icsk_ca_ops = ca;
4100 	}
4101 	rcu_read_unlock();
4102 }
4103 
4104 /* Do all connect socket setups that can be done AF independent. */
4105 static void tcp_connect_init(struct sock *sk)
4106 {
4107 	const struct dst_entry *dst = __sk_dst_get(sk);
4108 	struct tcp_sock *tp = tcp_sk(sk);
4109 	__u8 rcv_wscale;
4110 	u16 user_mss;
4111 	u32 rcv_wnd;
4112 
4113 	/* We'll fix this up when we get a response from the other end.
4114 	 * See tcp_input.c:tcp_rcv_state_process case TCP_SYN_SENT.
4115 	 */
4116 	tp->tcp_header_len = sizeof(struct tcphdr);
4117 	if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_timestamps))
4118 		tp->tcp_header_len += TCPOLEN_TSTAMP_ALIGNED;
4119 
4120 	tcp_ao_connect_init(sk);
4121 
4122 	/* If user gave his TCP_MAXSEG, record it to clamp */
4123 	user_mss = READ_ONCE(tp->rx_opt.user_mss);
4124 	if (user_mss)
4125 		tp->rx_opt.mss_clamp = user_mss;
4126 	tp->max_window = 0;
4127 	tcp_mtup_init(sk);
4128 	tcp_sync_mss(sk, dst_mtu(dst));
4129 
4130 	tcp_ca_dst_init(sk, dst);
4131 
4132 	if (!tp->window_clamp)
4133 		WRITE_ONCE(tp->window_clamp, dst_metric(dst, RTAX_WINDOW));
4134 	tp->advmss = tcp_mss_clamp(tp, dst_metric_advmss(dst));
4135 
4136 	tcp_initialize_rcv_mss(sk);
4137 
4138 	/* limit the window selection if the user enforce a smaller rx buffer */
4139 	if (sk->sk_userlocks & SOCK_RCVBUF_LOCK &&
4140 	    (tp->window_clamp > tcp_full_space(sk) || tp->window_clamp == 0))
4141 		WRITE_ONCE(tp->window_clamp, tcp_full_space(sk));
4142 
4143 	rcv_wnd = tcp_rwnd_init_bpf(sk);
4144 	if (rcv_wnd == 0)
4145 		rcv_wnd = dst_metric(dst, RTAX_INITRWND);
4146 
4147 	tcp_select_initial_window(sk, tcp_full_space(sk),
4148 				  tp->advmss - (tp->rx_opt.ts_recent_stamp ? tp->tcp_header_len - sizeof(struct tcphdr) : 0),
4149 				  &tp->rcv_wnd,
4150 				  &tp->window_clamp,
4151 				  READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_window_scaling),
4152 				  &rcv_wscale,
4153 				  rcv_wnd);
4154 
4155 	tp->rx_opt.rcv_wscale = rcv_wscale;
4156 	tp->rcv_ssthresh = tp->rcv_wnd;
4157 
4158 	WRITE_ONCE(sk->sk_err, 0);
4159 	sock_reset_flag(sk, SOCK_DONE);
4160 	tp->snd_wnd = 0;
4161 	tcp_init_wl(tp, 0);
4162 	tcp_write_queue_purge(sk);
4163 	tp->snd_una = tp->write_seq;
4164 	tp->snd_sml = tp->write_seq;
4165 	tp->snd_up = tp->write_seq;
4166 	WRITE_ONCE(tp->snd_nxt, tp->write_seq);
4167 
4168 	if (likely(!tp->repair))
4169 		tp->rcv_nxt = 0;
4170 	else
4171 		tp->rcv_tstamp = tcp_jiffies32;
4172 	tp->rcv_wup = tp->rcv_nxt;
4173 	WRITE_ONCE(tp->copied_seq, tp->rcv_nxt);
4174 
4175 	inet_csk(sk)->icsk_rto = tcp_timeout_init(sk);
4176 	WRITE_ONCE(inet_csk(sk)->icsk_retransmits, 0);
4177 	tcp_clear_retrans(tp);
4178 }
4179 
4180 static void tcp_connect_queue_skb(struct sock *sk, struct sk_buff *skb)
4181 {
4182 	struct tcp_sock *tp = tcp_sk(sk);
4183 	struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
4184 
4185 	tcb->end_seq += skb->len;
4186 	__skb_header_release(skb);
4187 	sk_wmem_queued_add(sk, skb->truesize);
4188 	sk_mem_charge(sk, skb->truesize);
4189 	WRITE_ONCE(tp->write_seq, tcb->end_seq);
4190 	tp->packets_out += tcp_skb_pcount(skb);
4191 }
4192 
4193 /* Build and send a SYN with data and (cached) Fast Open cookie. However,
4194  * queue a data-only packet after the regular SYN, such that regular SYNs
4195  * are retransmitted on timeouts. Also if the remote SYN-ACK acknowledges
4196  * only the SYN sequence, the data are retransmitted in the first ACK.
4197  * If cookie is not cached or other error occurs, falls back to send a
4198  * regular SYN with Fast Open cookie request option.
4199  */
4200 static int tcp_send_syn_data(struct sock *sk, struct sk_buff *syn)
4201 {
4202 	struct inet_connection_sock *icsk = inet_csk(sk);
4203 	struct tcp_sock *tp = tcp_sk(sk);
4204 	struct tcp_fastopen_request *fo = tp->fastopen_req;
4205 	struct page_frag *pfrag = sk_page_frag(sk);
4206 	struct sk_buff *syn_data;
4207 	int space, err = 0;
4208 
4209 	tp->rx_opt.mss_clamp = tp->advmss;  /* If MSS is not cached */
4210 	if (!tcp_fastopen_cookie_check(sk, &tp->rx_opt.mss_clamp, &fo->cookie))
4211 		goto fallback;
4212 
4213 	/* MSS for SYN-data is based on cached MSS and bounded by PMTU and
4214 	 * user-MSS. Reserve maximum option space for middleboxes that add
4215 	 * private TCP options. The cost is reduced data space in SYN :(
4216 	 */
4217 	tp->rx_opt.mss_clamp = tcp_mss_clamp(tp, tp->rx_opt.mss_clamp);
4218 	/* Sync mss_cache after updating the mss_clamp */
4219 	tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
4220 
4221 	space = __tcp_mtu_to_mss(sk, icsk->icsk_pmtu_cookie) -
4222 		MAX_TCP_OPTION_SPACE;
4223 
4224 	space = min_t(size_t, space, fo->size);
4225 
4226 	if (space &&
4227 	    !skb_page_frag_refill(min_t(size_t, space, PAGE_SIZE),
4228 				  pfrag, sk->sk_allocation))
4229 		goto fallback;
4230 	syn_data = tcp_stream_alloc_skb(sk, sk->sk_allocation, false);
4231 	if (!syn_data)
4232 		goto fallback;
4233 	memcpy(syn_data->cb, syn->cb, sizeof(syn->cb));
4234 	if (space) {
4235 		space = min_t(size_t, space, pfrag->size - pfrag->offset);
4236 		space = tcp_wmem_schedule(sk, space);
4237 	}
4238 	if (space) {
4239 		space = copy_page_from_iter(pfrag->page, pfrag->offset,
4240 					    space, &fo->data->msg_iter);
4241 		if (unlikely(!space)) {
4242 			tcp_skb_tsorted_anchor_cleanup(syn_data);
4243 			kfree_skb(syn_data);
4244 			goto fallback;
4245 		}
4246 		skb_fill_page_desc(syn_data, 0, pfrag->page,
4247 				   pfrag->offset, space);
4248 		page_ref_inc(pfrag->page);
4249 		pfrag->offset += space;
4250 		skb_len_add(syn_data, space);
4251 		skb_zcopy_set(syn_data, fo->uarg, NULL);
4252 	}
4253 	/* No more data pending in inet_wait_for_connect() */
4254 	if (space == fo->size)
4255 		fo->data = NULL;
4256 	fo->copied = space;
4257 
4258 	tcp_connect_queue_skb(sk, syn_data);
4259 	if (syn_data->len)
4260 		tcp_chrono_start(sk, TCP_CHRONO_BUSY);
4261 
4262 	err = tcp_transmit_skb(sk, syn_data, 1, sk->sk_allocation);
4263 
4264 	skb_set_delivery_time(syn, syn_data->skb_mstamp_ns, SKB_CLOCK_MONOTONIC);
4265 
4266 	/* Now full SYN+DATA was cloned and sent (or not),
4267 	 * remove the SYN from the original skb (syn_data)
4268 	 * we keep in write queue in case of a retransmit, as we
4269 	 * also have the SYN packet (with no data) in the same queue.
4270 	 */
4271 	TCP_SKB_CB(syn_data)->seq++;
4272 	TCP_SKB_CB(syn_data)->tcp_flags = TCPHDR_ACK | TCPHDR_PSH;
4273 	if (!err) {
4274 		tp->syn_data = (fo->copied > 0);
4275 		tcp_rbtree_insert(&sk->tcp_rtx_queue, syn_data);
4276 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPORIGDATASENT);
4277 		goto done;
4278 	}
4279 
4280 	/* data was not sent, put it in write_queue */
4281 	__skb_queue_tail(&sk->sk_write_queue, syn_data);
4282 	tp->packets_out -= tcp_skb_pcount(syn_data);
4283 
4284 fallback:
4285 	/* Send a regular SYN with Fast Open cookie request option */
4286 	if (fo->cookie.len > 0)
4287 		fo->cookie.len = 0;
4288 	err = tcp_transmit_skb(sk, syn, 1, sk->sk_allocation);
4289 	if (err)
4290 		tp->syn_fastopen = 0;
4291 done:
4292 	fo->cookie.len = -1;  /* Exclude Fast Open option for SYN retries */
4293 	return err;
4294 }
4295 
4296 /* Build a SYN and send it off. */
4297 int tcp_connect(struct sock *sk)
4298 {
4299 	struct tcp_sock *tp = tcp_sk(sk);
4300 	struct sk_buff *buff;
4301 	int err;
4302 
4303 	tcp_call_bpf(sk, BPF_SOCK_OPS_TCP_CONNECT_CB, 0, NULL);
4304 
4305 #if defined(CONFIG_TCP_MD5SIG) && defined(CONFIG_TCP_AO)
4306 	/* Has to be checked late, after setting daddr/saddr/ops.
4307 	 * Return error if the peer has both a md5 and a tcp-ao key
4308 	 * configured as this is ambiguous.
4309 	 */
4310 	if (unlikely(rcu_dereference_protected(tp->md5sig_info,
4311 					       lockdep_sock_is_held(sk)))) {
4312 		bool needs_ao = !!tp->af_specific->ao_lookup(sk, sk, -1, -1);
4313 		bool needs_md5 = !!tp->af_specific->md5_lookup(sk, sk);
4314 		struct tcp_ao_info *ao_info;
4315 
4316 		ao_info = rcu_dereference_check(tp->ao_info,
4317 						lockdep_sock_is_held(sk));
4318 		if (ao_info) {
4319 			/* This is an extra check: tcp_ao_required() in
4320 			 * tcp_v{4,6}_parse_md5_keys() should prevent adding
4321 			 * md5 keys on ao_required socket.
4322 			 */
4323 			needs_ao |= ao_info->ao_required;
4324 			WARN_ON_ONCE(ao_info->ao_required && needs_md5);
4325 		}
4326 		if (needs_md5 && needs_ao)
4327 			return -EKEYREJECTED;
4328 
4329 		/* If we have a matching md5 key and no matching tcp-ao key
4330 		 * then free up ao_info if allocated.
4331 		 */
4332 		if (needs_md5) {
4333 			tcp_ao_destroy_sock(sk, false);
4334 		} else if (needs_ao) {
4335 			tcp_clear_md5_list(sk);
4336 			kfree(rcu_replace_pointer(tp->md5sig_info, NULL,
4337 						  lockdep_sock_is_held(sk)));
4338 		}
4339 	}
4340 #endif
4341 #ifdef CONFIG_TCP_AO
4342 	if (unlikely(rcu_dereference_protected(tp->ao_info,
4343 					       lockdep_sock_is_held(sk)))) {
4344 		/* Don't allow connecting if ao is configured but no
4345 		 * matching key is found.
4346 		 */
4347 		if (!tp->af_specific->ao_lookup(sk, sk, -1, -1))
4348 			return -EKEYREJECTED;
4349 	}
4350 #endif
4351 
4352 	if (inet_csk(sk)->icsk_af_ops->rebuild_header(sk))
4353 		return -EHOSTUNREACH; /* Routing failure or similar. */
4354 
4355 	tcp_connect_init(sk);
4356 
4357 	if (unlikely(tp->repair)) {
4358 		tcp_finish_connect(sk, NULL);
4359 		return 0;
4360 	}
4361 
4362 	buff = tcp_stream_alloc_skb(sk, sk->sk_allocation, true);
4363 	if (unlikely(!buff))
4364 		return -ENOBUFS;
4365 
4366 	/* SYN eats a sequence byte, write_seq updated by
4367 	 * tcp_connect_queue_skb().
4368 	 */
4369 	tcp_init_nondata_skb(buff, sk, tp->write_seq, TCPHDR_SYN);
4370 	tcp_mstamp_refresh(tp);
4371 	tp->retrans_stamp = tcp_time_stamp_ts(tp);
4372 	tcp_connect_queue_skb(sk, buff);
4373 	tcp_ecn_send_syn(sk, buff);
4374 	tcp_rbtree_insert(&sk->tcp_rtx_queue, buff);
4375 
4376 	/* Send off SYN; include data in Fast Open. */
4377 	err = tp->fastopen_req ? tcp_send_syn_data(sk, buff) :
4378 	      tcp_transmit_skb(sk, buff, 1, sk->sk_allocation);
4379 	if (err == -ECONNREFUSED)
4380 		return err;
4381 
4382 	/* We change tp->snd_nxt after the tcp_transmit_skb() call
4383 	 * in order to make this packet get counted in tcpOutSegs.
4384 	 */
4385 	WRITE_ONCE(tp->snd_nxt, tp->write_seq);
4386 	tp->pushed_seq = tp->write_seq;
4387 	buff = tcp_send_head(sk);
4388 	if (unlikely(buff)) {
4389 		WRITE_ONCE(tp->snd_nxt, TCP_SKB_CB(buff)->seq);
4390 		tp->pushed_seq	= TCP_SKB_CB(buff)->seq;
4391 	}
4392 	TCP_INC_STATS(sock_net(sk), TCP_MIB_ACTIVEOPENS);
4393 
4394 	/* Timer for repeating the SYN until an answer. */
4395 	tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
4396 			     inet_csk(sk)->icsk_rto, false);
4397 	return 0;
4398 }
4399 EXPORT_SYMBOL(tcp_connect);
4400 
4401 u32 tcp_delack_max(const struct sock *sk)
4402 {
4403 	u32 delack_from_rto_min = max(tcp_rto_min(sk), 2) - 1;
4404 
4405 	return min(READ_ONCE(inet_csk(sk)->icsk_delack_max), delack_from_rto_min);
4406 }
4407 
4408 /* Send out a delayed ack, the caller does the policy checking
4409  * to see if we should even be here.  See tcp_input.c:tcp_ack_snd_check()
4410  * for details.
4411  */
4412 void tcp_send_delayed_ack(struct sock *sk)
4413 {
4414 	struct inet_connection_sock *icsk = inet_csk(sk);
4415 	int ato = icsk->icsk_ack.ato;
4416 	unsigned long timeout;
4417 
4418 	if (ato > TCP_DELACK_MIN) {
4419 		const struct tcp_sock *tp = tcp_sk(sk);
4420 		int max_ato = HZ / 2;
4421 
4422 		if (inet_csk_in_pingpong_mode(sk) ||
4423 		    (icsk->icsk_ack.pending & ICSK_ACK_PUSHED))
4424 			max_ato = TCP_DELACK_MAX;
4425 
4426 		/* Slow path, intersegment interval is "high". */
4427 
4428 		/* If some rtt estimate is known, use it to bound delayed ack.
4429 		 * Do not use inet_csk(sk)->icsk_rto here, use results of rtt measurements
4430 		 * directly.
4431 		 */
4432 		if (tp->srtt_us) {
4433 			int rtt = max_t(int, usecs_to_jiffies(tp->srtt_us >> 3),
4434 					TCP_DELACK_MIN);
4435 
4436 			if (rtt < max_ato)
4437 				max_ato = rtt;
4438 		}
4439 
4440 		ato = min(ato, max_ato);
4441 	}
4442 
4443 	ato = min_t(u32, ato, tcp_delack_max(sk));
4444 
4445 	/* Stay within the limit we were given */
4446 	timeout = jiffies + ato;
4447 
4448 	/* Use new timeout only if there wasn't a older one earlier. */
4449 	if (icsk->icsk_ack.pending & ICSK_ACK_TIMER) {
4450 		/* If delack timer is about to expire, send ACK now. */
4451 		if (time_before_eq(icsk_delack_timeout(icsk), jiffies + (ato >> 2))) {
4452 			tcp_send_ack(sk);
4453 			return;
4454 		}
4455 
4456 		if (!time_before(timeout, icsk_delack_timeout(icsk)))
4457 			timeout = icsk_delack_timeout(icsk);
4458 	}
4459 	smp_store_release(&icsk->icsk_ack.pending,
4460 			  icsk->icsk_ack.pending | ICSK_ACK_SCHED | ICSK_ACK_TIMER);
4461 	sk_reset_timer(sk, &icsk->icsk_delack_timer, timeout);
4462 }
4463 
4464 /* This routine sends an ack and also updates the window. */
4465 void __tcp_send_ack(struct sock *sk, u32 rcv_nxt, u16 flags)
4466 {
4467 	struct sk_buff *buff;
4468 
4469 	/* If we have been reset, we may not send again. */
4470 	if (sk->sk_state == TCP_CLOSE)
4471 		return;
4472 
4473 	/* We are not putting this on the write queue, so
4474 	 * tcp_transmit_skb() will set the ownership to this
4475 	 * sock.
4476 	 */
4477 	buff = alloc_skb(MAX_TCP_HEADER,
4478 			 sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN));
4479 	if (unlikely(!buff)) {
4480 		struct inet_connection_sock *icsk = inet_csk(sk);
4481 		unsigned long delay;
4482 
4483 		delay = TCP_DELACK_MAX << icsk->icsk_ack.retry;
4484 		if (delay < tcp_rto_max(sk))
4485 			icsk->icsk_ack.retry++;
4486 		inet_csk_schedule_ack(sk);
4487 		icsk->icsk_ack.ato = TCP_ATO_MIN;
4488 		tcp_reset_xmit_timer(sk, ICSK_TIME_DACK, delay, false);
4489 		return;
4490 	}
4491 
4492 	/* Reserve space for headers and prepare control bits. */
4493 	skb_reserve(buff, MAX_TCP_HEADER);
4494 	tcp_init_nondata_skb(buff, sk,
4495 			     tcp_acceptable_seq(sk), TCPHDR_ACK | flags);
4496 
4497 	/* We do not want pure acks influencing TCP Small Queues or fq/pacing
4498 	 * too much.
4499 	 * SKB_TRUESIZE(max(1 .. 66, MAX_TCP_HEADER)) is unfortunately ~784
4500 	 */
4501 	skb_set_tcp_pure_ack(buff);
4502 
4503 	/* Send it off, this clears delayed acks for us. */
4504 	__tcp_transmit_skb(sk, buff, 0, (__force gfp_t)0, rcv_nxt);
4505 }
4506 EXPORT_SYMBOL_GPL(__tcp_send_ack);
4507 
4508 void tcp_send_ack(struct sock *sk)
4509 {
4510 	__tcp_send_ack(sk, tcp_sk(sk)->rcv_nxt, 0);
4511 }
4512 
4513 /* This routine sends a packet with an out of date sequence
4514  * number. It assumes the other end will try to ack it.
4515  *
4516  * Question: what should we make while urgent mode?
4517  * 4.4BSD forces sending single byte of data. We cannot send
4518  * out of window data, because we have SND.NXT==SND.MAX...
4519  *
4520  * Current solution: to send TWO zero-length segments in urgent mode:
4521  * one is with SEG.SEQ=SND.UNA to deliver urgent pointer, another is
4522  * out-of-date with SND.UNA-1 to probe window.
4523  */
4524 static int tcp_xmit_probe_skb(struct sock *sk, int urgent, int mib)
4525 {
4526 	struct tcp_sock *tp = tcp_sk(sk);
4527 	struct sk_buff *skb;
4528 
4529 	/* We don't queue it, tcp_transmit_skb() sets ownership. */
4530 	skb = alloc_skb(MAX_TCP_HEADER,
4531 			sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN));
4532 	if (!skb)
4533 		return -1;
4534 
4535 	/* Reserve space for headers and set control bits. */
4536 	skb_reserve(skb, MAX_TCP_HEADER);
4537 	/* Use a previous sequence.  This should cause the other
4538 	 * end to send an ack.  Don't queue or clone SKB, just
4539 	 * send it.
4540 	 */
4541 	tcp_init_nondata_skb(skb, sk, tp->snd_una - !urgent, TCPHDR_ACK);
4542 	NET_INC_STATS(sock_net(sk), mib);
4543 	return tcp_transmit_skb(sk, skb, 0, (__force gfp_t)0);
4544 }
4545 
4546 /* Called from setsockopt( ... TCP_REPAIR ) */
4547 void tcp_send_window_probe(struct sock *sk)
4548 {
4549 	if (sk->sk_state == TCP_ESTABLISHED) {
4550 		tcp_sk(sk)->snd_wl1 = tcp_sk(sk)->rcv_nxt - 1;
4551 		tcp_mstamp_refresh(tcp_sk(sk));
4552 		tcp_xmit_probe_skb(sk, 0, LINUX_MIB_TCPWINPROBE);
4553 	}
4554 }
4555 
4556 /* Initiate keepalive or window probe from timer. */
4557 int tcp_write_wakeup(struct sock *sk, int mib)
4558 {
4559 	struct tcp_sock *tp = tcp_sk(sk);
4560 	struct sk_buff *skb;
4561 
4562 	if (sk->sk_state == TCP_CLOSE)
4563 		return -1;
4564 
4565 	skb = tcp_send_head(sk);
4566 	if (skb && before(TCP_SKB_CB(skb)->seq, tcp_wnd_end(tp))) {
4567 		int err;
4568 		unsigned int mss = tcp_current_mss(sk);
4569 		unsigned int seg_size = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq;
4570 
4571 		if (before(tp->pushed_seq, TCP_SKB_CB(skb)->end_seq))
4572 			tp->pushed_seq = TCP_SKB_CB(skb)->end_seq;
4573 
4574 		/* We are probing the opening of a window
4575 		 * but the window size is != 0
4576 		 * must have been a result SWS avoidance ( sender )
4577 		 */
4578 		if (seg_size < TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq ||
4579 		    skb->len > mss) {
4580 			seg_size = min(seg_size, mss);
4581 			TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH;
4582 			if (tcp_fragment(sk, TCP_FRAG_IN_WRITE_QUEUE,
4583 					 skb, seg_size, mss, GFP_ATOMIC))
4584 				return -1;
4585 		} else if (!tcp_skb_pcount(skb))
4586 			tcp_set_skb_tso_segs(skb, mss);
4587 
4588 		TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH;
4589 		err = tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC);
4590 		if (!err)
4591 			tcp_event_new_data_sent(sk, skb);
4592 		return err;
4593 	} else {
4594 		if (between(tp->snd_up, tp->snd_una + 1, tp->snd_una + 0xFFFF))
4595 			tcp_xmit_probe_skb(sk, 1, mib);
4596 		return tcp_xmit_probe_skb(sk, 0, mib);
4597 	}
4598 }
4599 
4600 /* A window probe timeout has occurred.  If window is not closed send
4601  * a partial packet else a zero probe.
4602  */
4603 void tcp_send_probe0(struct sock *sk)
4604 {
4605 	struct inet_connection_sock *icsk = inet_csk(sk);
4606 	struct tcp_sock *tp = tcp_sk(sk);
4607 	struct net *net = sock_net(sk);
4608 	unsigned long timeout;
4609 	int err;
4610 
4611 	err = tcp_write_wakeup(sk, LINUX_MIB_TCPWINPROBE);
4612 
4613 	if (tp->packets_out || tcp_write_queue_empty(sk)) {
4614 		/* Cancel probe timer, if it is not required. */
4615 		WRITE_ONCE(icsk->icsk_probes_out, 0);
4616 		icsk->icsk_backoff = 0;
4617 		icsk->icsk_probes_tstamp = 0;
4618 		return;
4619 	}
4620 
4621 	WRITE_ONCE(icsk->icsk_probes_out, icsk->icsk_probes_out + 1);
4622 	if (err <= 0) {
4623 		if (icsk->icsk_backoff < READ_ONCE(net->ipv4.sysctl_tcp_retries2))
4624 			icsk->icsk_backoff++;
4625 		timeout = tcp_probe0_when(sk, tcp_rto_max(sk));
4626 	} else {
4627 		/* If packet was not sent due to local congestion,
4628 		 * Let senders fight for local resources conservatively.
4629 		 */
4630 		timeout = TCP_RESOURCE_PROBE_INTERVAL;
4631 	}
4632 
4633 	timeout = tcp_clamp_probe0_to_user_timeout(sk, timeout);
4634 	tcp_reset_xmit_timer(sk, ICSK_TIME_PROBE0, timeout, true);
4635 }
4636 
4637 int tcp_rtx_synack(const struct sock *sk, struct request_sock *req)
4638 {
4639 	const struct tcp_request_sock_ops *af_ops = tcp_rsk(req)->af_specific;
4640 	struct flowi fl;
4641 	int res;
4642 
4643 	/* Paired with WRITE_ONCE() in sock_setsockopt() */
4644 	if (READ_ONCE(sk->sk_txrehash) == SOCK_TXREHASH_ENABLED)
4645 		WRITE_ONCE(tcp_rsk(req)->txhash, net_tx_rndhash());
4646 	res = af_ops->send_synack(sk, NULL, &fl, req, NULL, TCP_SYNACK_RETRANS,
4647 				  NULL);
4648 	if (!res) {
4649 		TCP_INC_STATS(sock_net(sk), TCP_MIB_RETRANSSEGS);
4650 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSYNRETRANS);
4651 		if (unlikely(tcp_passive_fastopen(sk))) {
4652 			/* sk has const attribute because listeners are lockless.
4653 			 * However in this case, we are dealing with a passive fastopen
4654 			 * socket thus we can change total_retrans value.
4655 			 */
4656 			tcp_sk_rw(sk)->total_retrans++;
4657 		}
4658 		trace_tcp_retransmit_synack(sk, req);
4659 		WRITE_ONCE(req->num_retrans, req->num_retrans + 1);
4660 	}
4661 	return res;
4662 }
4663 EXPORT_IPV6_MOD(tcp_rtx_synack);
4664