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