xref: /linux/net/ipv4/tcp.c (revision 55fbedcec622a943cb09a969aef1ddcba87ee40a)
1 // SPDX-License-Identifier: GPL-2.0-or-later
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  * Fixes:
22  *		Alan Cox	:	Numerous verify_area() calls
23  *		Alan Cox	:	Set the ACK bit on a reset
24  *		Alan Cox	:	Stopped it crashing if it closed while
25  *					sk->inuse=1 and was trying to connect
26  *					(tcp_err()).
27  *		Alan Cox	:	All icmp error handling was broken
28  *					pointers passed where wrong and the
29  *					socket was looked up backwards. Nobody
30  *					tested any icmp error code obviously.
31  *		Alan Cox	:	tcp_err() now handled properly. It
32  *					wakes people on errors. poll
33  *					behaves and the icmp error race
34  *					has gone by moving it into sock.c
35  *		Alan Cox	:	tcp_send_reset() fixed to work for
36  *					everything not just packets for
37  *					unknown sockets.
38  *		Alan Cox	:	tcp option processing.
39  *		Alan Cox	:	Reset tweaked (still not 100%) [Had
40  *					syn rule wrong]
41  *		Herp Rosmanith  :	More reset fixes
42  *		Alan Cox	:	No longer acks invalid rst frames.
43  *					Acking any kind of RST is right out.
44  *		Alan Cox	:	Sets an ignore me flag on an rst
45  *					receive otherwise odd bits of prattle
46  *					escape still
47  *		Alan Cox	:	Fixed another acking RST frame bug.
48  *					Should stop LAN workplace lockups.
49  *		Alan Cox	: 	Some tidyups using the new skb list
50  *					facilities
51  *		Alan Cox	:	sk->keepopen now seems to work
52  *		Alan Cox	:	Pulls options out correctly on accepts
53  *		Alan Cox	:	Fixed assorted sk->rqueue->next errors
54  *		Alan Cox	:	PSH doesn't end a TCP read. Switched a
55  *					bit to skb ops.
56  *		Alan Cox	:	Tidied tcp_data to avoid a potential
57  *					nasty.
58  *		Alan Cox	:	Added some better commenting, as the
59  *					tcp is hard to follow
60  *		Alan Cox	:	Removed incorrect check for 20 * psh
61  *	Michael O'Reilly	:	ack < copied bug fix.
62  *	Johannes Stille		:	Misc tcp fixes (not all in yet).
63  *		Alan Cox	:	FIN with no memory -> CRASH
64  *		Alan Cox	:	Added socket option proto entries.
65  *					Also added awareness of them to accept.
66  *		Alan Cox	:	Added TCP options (SOL_TCP)
67  *		Alan Cox	:	Switched wakeup calls to callbacks,
68  *					so the kernel can layer network
69  *					sockets.
70  *		Alan Cox	:	Use ip_tos/ip_ttl settings.
71  *		Alan Cox	:	Handle FIN (more) properly (we hope).
72  *		Alan Cox	:	RST frames sent on unsynchronised
73  *					state ack error.
74  *		Alan Cox	:	Put in missing check for SYN bit.
75  *		Alan Cox	:	Added tcp_select_window() aka NET2E
76  *					window non shrink trick.
77  *		Alan Cox	:	Added a couple of small NET2E timer
78  *					fixes
79  *		Charles Hedrick :	TCP fixes
80  *		Toomas Tamm	:	TCP window fixes
81  *		Alan Cox	:	Small URG fix to rlogin ^C ack fight
82  *		Charles Hedrick	:	Rewrote most of it to actually work
83  *		Linus		:	Rewrote tcp_read() and URG handling
84  *					completely
85  *		Gerhard Koerting:	Fixed some missing timer handling
86  *		Matthew Dillon  :	Reworked TCP machine states as per RFC
87  *		Gerhard Koerting:	PC/TCP workarounds
88  *		Adam Caldwell	:	Assorted timer/timing errors
89  *		Matthew Dillon	:	Fixed another RST bug
90  *		Alan Cox	:	Move to kernel side addressing changes.
91  *		Alan Cox	:	Beginning work on TCP fastpathing
92  *					(not yet usable)
93  *		Arnt Gulbrandsen:	Turbocharged tcp_check() routine.
94  *		Alan Cox	:	TCP fast path debugging
95  *		Alan Cox	:	Window clamping
96  *		Michael Riepe	:	Bug in tcp_check()
97  *		Matt Dillon	:	More TCP improvements and RST bug fixes
98  *		Matt Dillon	:	Yet more small nasties remove from the
99  *					TCP code (Be very nice to this man if
100  *					tcp finally works 100%) 8)
101  *		Alan Cox	:	BSD accept semantics.
102  *		Alan Cox	:	Reset on closedown bug.
103  *	Peter De Schrijver	:	ENOTCONN check missing in tcp_sendto().
104  *		Michael Pall	:	Handle poll() after URG properly in
105  *					all cases.
106  *		Michael Pall	:	Undo the last fix in tcp_read_urg()
107  *					(multi URG PUSH broke rlogin).
108  *		Michael Pall	:	Fix the multi URG PUSH problem in
109  *					tcp_readable(), poll() after URG
110  *					works now.
111  *		Michael Pall	:	recv(...,MSG_OOB) never blocks in the
112  *					BSD api.
113  *		Alan Cox	:	Changed the semantics of sk->socket to
114  *					fix a race and a signal problem with
115  *					accept() and async I/O.
116  *		Alan Cox	:	Relaxed the rules on tcp_sendto().
117  *		Yury Shevchuk	:	Really fixed accept() blocking problem.
118  *		Craig I. Hagan  :	Allow for BSD compatible TIME_WAIT for
119  *					clients/servers which listen in on
120  *					fixed ports.
121  *		Alan Cox	:	Cleaned the above up and shrank it to
122  *					a sensible code size.
123  *		Alan Cox	:	Self connect lockup fix.
124  *		Alan Cox	:	No connect to multicast.
125  *		Ross Biro	:	Close unaccepted children on master
126  *					socket close.
127  *		Alan Cox	:	Reset tracing code.
128  *		Alan Cox	:	Spurious resets on shutdown.
129  *		Alan Cox	:	Giant 15 minute/60 second timer error
130  *		Alan Cox	:	Small whoops in polling before an
131  *					accept.
132  *		Alan Cox	:	Kept the state trace facility since
133  *					it's handy for debugging.
134  *		Alan Cox	:	More reset handler fixes.
135  *		Alan Cox	:	Started rewriting the code based on
136  *					the RFC's for other useful protocol
137  *					references see: Comer, KA9Q NOS, and
138  *					for a reference on the difference
139  *					between specifications and how BSD
140  *					works see the 4.4lite source.
141  *		A.N.Kuznetsov	:	Don't time wait on completion of tidy
142  *					close.
143  *		Linus Torvalds	:	Fin/Shutdown & copied_seq changes.
144  *		Linus Torvalds	:	Fixed BSD port reuse to work first syn
145  *		Alan Cox	:	Reimplemented timers as per the RFC
146  *					and using multiple timers for sanity.
147  *		Alan Cox	:	Small bug fixes, and a lot of new
148  *					comments.
149  *		Alan Cox	:	Fixed dual reader crash by locking
150  *					the buffers (much like datagram.c)
151  *		Alan Cox	:	Fixed stuck sockets in probe. A probe
152  *					now gets fed up of retrying without
153  *					(even a no space) answer.
154  *		Alan Cox	:	Extracted closing code better
155  *		Alan Cox	:	Fixed the closing state machine to
156  *					resemble the RFC.
157  *		Alan Cox	:	More 'per spec' fixes.
158  *		Jorge Cwik	:	Even faster checksumming.
159  *		Alan Cox	:	tcp_data() doesn't ack illegal PSH
160  *					only frames. At least one pc tcp stack
161  *					generates them.
162  *		Alan Cox	:	Cache last socket.
163  *		Alan Cox	:	Per route irtt.
164  *		Matt Day	:	poll()->select() match BSD precisely on error
165  *		Alan Cox	:	New buffers
166  *		Marc Tamsky	:	Various sk->prot->retransmits and
167  *					sk->retransmits misupdating fixed.
168  *					Fixed tcp_write_timeout: stuck close,
169  *					and TCP syn retries gets used now.
170  *		Mark Yarvis	:	In tcp_read_wakeup(), don't send an
171  *					ack if state is TCP_CLOSED.
172  *		Alan Cox	:	Look up device on a retransmit - routes may
173  *					change. Doesn't yet cope with MSS shrink right
174  *					but it's a start!
175  *		Marc Tamsky	:	Closing in closing fixes.
176  *		Mike Shaver	:	RFC1122 verifications.
177  *		Alan Cox	:	rcv_saddr errors.
178  *		Alan Cox	:	Block double connect().
179  *		Alan Cox	:	Small hooks for enSKIP.
180  *		Alexey Kuznetsov:	Path MTU discovery.
181  *		Alan Cox	:	Support soft errors.
182  *		Alan Cox	:	Fix MTU discovery pathological case
183  *					when the remote claims no mtu!
184  *		Marc Tamsky	:	TCP_CLOSE fix.
185  *		Colin (G3TNE)	:	Send a reset on syn ack replies in
186  *					window but wrong (fixes NT lpd problems)
187  *		Pedro Roque	:	Better TCP window handling, delayed ack.
188  *		Joerg Reuter	:	No modification of locked buffers in
189  *					tcp_do_retransmit()
190  *		Eric Schenk	:	Changed receiver side silly window
191  *					avoidance algorithm to BSD style
192  *					algorithm. This doubles throughput
193  *					against machines running Solaris,
194  *					and seems to result in general
195  *					improvement.
196  *	Stefan Magdalinski	:	adjusted tcp_readable() to fix FIONREAD
197  *	Willy Konynenberg	:	Transparent proxying support.
198  *	Mike McLagan		:	Routing by source
199  *		Keith Owens	:	Do proper merging with partial SKB's in
200  *					tcp_do_sendmsg to avoid burstiness.
201  *		Eric Schenk	:	Fix fast close down bug with
202  *					shutdown() followed by close().
203  *		Andi Kleen 	:	Make poll agree with SIGIO
204  *	Salvatore Sanfilippo	:	Support SO_LINGER with linger == 1 and
205  *					lingertime == 0 (RFC 793 ABORT Call)
206  *	Hirokazu Takahashi	:	Use copy_from_user() instead of
207  *					csum_and_copy_from_user() if possible.
208  *
209  * Description of States:
210  *
211  *	TCP_SYN_SENT		sent a connection request, waiting for ack
212  *
213  *	TCP_SYN_RECV		received a connection request, sent ack,
214  *				waiting for final ack in three-way handshake.
215  *
216  *	TCP_ESTABLISHED		connection established
217  *
218  *	TCP_FIN_WAIT1		our side has shutdown, waiting to complete
219  *				transmission of remaining buffered data
220  *
221  *	TCP_FIN_WAIT2		all buffered data sent, waiting for remote
222  *				to shutdown
223  *
224  *	TCP_CLOSING		both sides have shutdown but we still have
225  *				data we have to finish sending
226  *
227  *	TCP_TIME_WAIT		timeout to catch resent junk before entering
228  *				closed, can only be entered from FIN_WAIT2
229  *				or CLOSING.  Required because the other end
230  *				may not have gotten our last ACK causing it
231  *				to retransmit the data packet (which we ignore)
232  *
233  *	TCP_CLOSE_WAIT		remote side has shutdown and is waiting for
234  *				us to finish writing our data and to shutdown
235  *				(we have to close() to move on to LAST_ACK)
236  *
237  *	TCP_LAST_ACK		out side has shutdown after remote has
238  *				shutdown.  There may still be data in our
239  *				buffer that we have to finish sending
240  *
241  *	TCP_CLOSE		socket is finished
242  */
243 
244 #define pr_fmt(fmt) "TCP: " fmt
245 
246 #include <crypto/md5.h>
247 #include <crypto/utils.h>
248 #include <linux/kernel.h>
249 #include <linux/module.h>
250 #include <linux/types.h>
251 #include <linux/fcntl.h>
252 #include <linux/poll.h>
253 #include <linux/inet_diag.h>
254 #include <linux/init.h>
255 #include <linux/fs.h>
256 #include <linux/skbuff.h>
257 #include <linux/skbuff_ref.h>
258 #include <linux/splice.h>
259 #include <linux/net.h>
260 #include <linux/socket.h>
261 #include <linux/random.h>
262 #include <linux/memblock.h>
263 #include <linux/highmem.h>
264 #include <linux/cache.h>
265 #include <linux/err.h>
266 #include <linux/time.h>
267 #include <linux/slab.h>
268 #include <linux/errqueue.h>
269 #include <linux/static_key.h>
270 #include <linux/btf.h>
271 
272 #include <net/icmp.h>
273 #include <net/inet_common.h>
274 #include <net/inet_ecn.h>
275 #include <net/tcp.h>
276 #include <net/tcp_ecn.h>
277 #include <net/mptcp.h>
278 #include <net/proto_memory.h>
279 #include <net/xfrm.h>
280 #include <net/ip.h>
281 #include <net/psp.h>
282 #include <net/sock.h>
283 #include <net/rstreason.h>
284 
285 #include <linux/uaccess.h>
286 #include <asm/ioctls.h>
287 #include <net/busy_poll.h>
288 #include <net/hotdata.h>
289 #include <trace/events/tcp.h>
290 #include <net/rps.h>
291 
292 #include "../core/devmem.h"
293 
294 /* Track pending CMSGs. */
295 enum {
296 	TCP_CMSG_INQ = 1,
297 	TCP_CMSG_TS = 2
298 };
299 
300 DEFINE_PER_CPU(unsigned int, tcp_orphan_count);
301 
302 long sysctl_tcp_mem[3] __read_mostly;
303 
304 DEFINE_PER_CPU(int, tcp_memory_per_cpu_fw_alloc);
305 EXPORT_PER_CPU_SYMBOL_GPL(tcp_memory_per_cpu_fw_alloc);
306 
307 #if IS_ENABLED(CONFIG_SMC)
308 DEFINE_STATIC_KEY_FALSE(tcp_have_smc);
309 EXPORT_SYMBOL(tcp_have_smc);
310 #endif
311 
312 /*
313  * Current number of TCP sockets.
314  */
315 struct percpu_counter tcp_sockets_allocated ____cacheline_aligned_in_smp;
316 
317 /*
318  * Pressure flag: try to collapse.
319  * Technical note: it is used by multiple contexts non atomically.
320  * All the __sk_mem_schedule() is of this nature: accounting
321  * is strict, actions are advisory and have some latency.
322  */
323 unsigned long tcp_memory_pressure __read_mostly;
324 EXPORT_SYMBOL_GPL(tcp_memory_pressure);
325 
326 void tcp_enter_memory_pressure(struct sock *sk)
327 {
328 	unsigned long val;
329 
330 	if (READ_ONCE(tcp_memory_pressure))
331 		return;
332 	val = jiffies;
333 
334 	if (!val)
335 		val--;
336 	if (!cmpxchg(&tcp_memory_pressure, 0, val))
337 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURES);
338 }
339 
340 void tcp_leave_memory_pressure(struct sock *sk)
341 {
342 	unsigned long val;
343 
344 	if (!READ_ONCE(tcp_memory_pressure))
345 		return;
346 	val = xchg(&tcp_memory_pressure, 0);
347 	if (val)
348 		NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURESCHRONO,
349 			      jiffies_to_msecs(jiffies - val));
350 }
351 
352 /* Convert seconds to retransmits based on initial and max timeout */
353 static u8 secs_to_retrans(int seconds, int timeout, int rto_max)
354 {
355 	u8 res = 0;
356 
357 	if (seconds > 0) {
358 		int period = timeout;
359 
360 		res = 1;
361 		while (seconds > period && res < 255) {
362 			res++;
363 			timeout <<= 1;
364 			if (timeout > rto_max)
365 				timeout = rto_max;
366 			period += timeout;
367 		}
368 	}
369 	return res;
370 }
371 
372 /* Convert retransmits to seconds based on initial and max timeout */
373 static int retrans_to_secs(u8 retrans, int timeout, int rto_max)
374 {
375 	int period = 0;
376 
377 	if (retrans > 0) {
378 		period = timeout;
379 		while (--retrans) {
380 			timeout <<= 1;
381 			if (timeout > rto_max)
382 				timeout = rto_max;
383 			period += timeout;
384 		}
385 	}
386 	return period;
387 }
388 
389 static u64 tcp_compute_delivery_rate(const struct tcp_sock *tp)
390 {
391 	u32 rate = READ_ONCE(tp->rate_delivered);
392 	u32 intv = READ_ONCE(tp->rate_interval_us);
393 	u64 rate64 = 0;
394 
395 	if (rate && intv) {
396 		rate64 = (u64)rate * tp->mss_cache * USEC_PER_SEC;
397 		do_div(rate64, intv);
398 	}
399 	return rate64;
400 }
401 
402 #ifdef CONFIG_TCP_MD5SIG
403 void tcp_md5_destruct_sock(struct sock *sk)
404 {
405 	struct tcp_sock *tp = tcp_sk(sk);
406 
407 	if (tp->md5sig_info) {
408 
409 		tcp_clear_md5_list(sk);
410 		kfree(rcu_replace_pointer(tp->md5sig_info, NULL, 1));
411 		static_branch_slow_dec_deferred(&tcp_md5_needed);
412 	}
413 }
414 #endif
415 
416 /* Address-family independent initialization for a tcp_sock.
417  *
418  * NOTE: A lot of things set to zero explicitly by call to
419  *       sk_alloc() so need not be done here.
420  */
421 void tcp_init_sock(struct sock *sk)
422 {
423 	struct inet_connection_sock *icsk = inet_csk(sk);
424 	struct tcp_sock *tp = tcp_sk(sk);
425 	int rto_min_us, rto_max_ms;
426 
427 	tp->out_of_order_queue = RB_ROOT;
428 	sk->tcp_rtx_queue = RB_ROOT;
429 	tcp_init_xmit_timers(sk);
430 	INIT_LIST_HEAD(&tp->tsq_node);
431 	INIT_LIST_HEAD(&tp->tsorted_sent_queue);
432 
433 	icsk->icsk_rto = TCP_TIMEOUT_INIT;
434 
435 	rto_max_ms = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rto_max_ms);
436 	icsk->icsk_rto_max = msecs_to_jiffies(rto_max_ms);
437 
438 	rto_min_us = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rto_min_us);
439 	icsk->icsk_rto_min = usecs_to_jiffies(rto_min_us);
440 	icsk->icsk_delack_max = TCP_DELACK_MAX;
441 	tp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT);
442 	minmax_reset(&tp->rtt_min, tcp_jiffies32, ~0U);
443 
444 	/* So many TCP implementations out there (incorrectly) count the
445 	 * initial SYN frame in their delayed-ACK and congestion control
446 	 * algorithms that we must have the following bandaid to talk
447 	 * efficiently to them.  -DaveM
448 	 */
449 	tcp_snd_cwnd_set(tp, TCP_INIT_CWND);
450 
451 	/* There's a bubble in the pipe until at least the first ACK. */
452 	tp->app_limited = ~0U;
453 	tp->rate_app_limited = 1;
454 
455 	/* See draft-stevens-tcpca-spec-01 for discussion of the
456 	 * initialization of these values.
457 	 */
458 	tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
459 	tp->snd_cwnd_clamp = ~0;
460 	tp->mss_cache = TCP_MSS_DEFAULT;
461 
462 	tp->reordering = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reordering);
463 	tcp_assign_congestion_control(sk);
464 
465 	tp->tsoffset = 0;
466 	tp->rack.reo_wnd_steps = 1;
467 
468 	sk->sk_write_space = sk_stream_write_space;
469 	sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
470 
471 	icsk->icsk_sync_mss = tcp_sync_mss;
472 
473 	WRITE_ONCE(sk->sk_sndbuf, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_wmem[1]));
474 	WRITE_ONCE(sk->sk_rcvbuf, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[1]));
475 	tcp_scaling_ratio_init(sk);
476 
477 	set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
478 	sk_sockets_allocated_inc(sk);
479 	xa_init_flags(&sk->sk_user_frags, XA_FLAGS_ALLOC1);
480 }
481 
482 static void tcp_tx_timestamp(struct sock *sk, struct sockcm_cookie *sockc)
483 {
484 	struct sk_buff *skb = tcp_write_queue_tail(sk);
485 	u32 tsflags = sockc->tsflags;
486 
487 	if (unlikely(!skb))
488 		skb = skb_rb_last(&sk->tcp_rtx_queue);
489 
490 	if (tsflags && skb) {
491 		struct skb_shared_info *shinfo = skb_shinfo(skb);
492 		struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
493 
494 		sock_tx_timestamp(sk, sockc, &shinfo->tx_flags);
495 		if (tsflags & SOF_TIMESTAMPING_TX_ACK)
496 			tcb->txstamp_ack |= TSTAMP_ACK_SK;
497 		if (tsflags & SOF_TIMESTAMPING_TX_RECORD_MASK)
498 			shinfo->tskey = TCP_SKB_CB(skb)->seq + skb->len - 1;
499 	}
500 
501 	if (cgroup_bpf_enabled(CGROUP_SOCK_OPS) &&
502 	    SK_BPF_CB_FLAG_TEST(sk, SK_BPF_CB_TX_TIMESTAMPING) && skb)
503 		bpf_skops_tx_timestamping(sk, skb, BPF_SOCK_OPS_TSTAMP_SENDMSG_CB);
504 }
505 
506 /* @wake is one when sk_stream_write_space() calls us.
507  * This sends EPOLLOUT only if notsent_bytes is half the limit.
508  * This mimics the strategy used in sock_def_write_space().
509  */
510 bool tcp_stream_memory_free(const struct sock *sk, int wake)
511 {
512 	const struct tcp_sock *tp = tcp_sk(sk);
513 	u32 notsent_bytes = READ_ONCE(tp->write_seq) - READ_ONCE(tp->snd_nxt);
514 
515 	return (notsent_bytes << wake) < tcp_notsent_lowat(tp);
516 }
517 EXPORT_SYMBOL(tcp_stream_memory_free);
518 
519 static bool tcp_stream_is_readable(struct sock *sk, int target)
520 {
521 	if (tcp_epollin_ready(sk, target))
522 		return true;
523 	return sk_is_readable(sk);
524 }
525 
526 /*
527  *	Wait for a TCP event.
528  *
529  *	Note that we don't need to lock the socket, as the upper poll layers
530  *	take care of normal races (between the test and the event) and we don't
531  *	go look at any of the socket buffers directly.
532  */
533 __poll_t tcp_poll(struct file *file, struct socket *sock, poll_table *wait)
534 {
535 	__poll_t mask;
536 	struct sock *sk = sock->sk;
537 	const struct tcp_sock *tp = tcp_sk(sk);
538 	u8 shutdown;
539 	int state;
540 
541 	sock_poll_wait(file, sock, wait);
542 
543 	state = inet_sk_state_load(sk);
544 	if (state == TCP_LISTEN)
545 		return inet_csk_listen_poll(sk);
546 
547 	/* Socket is not locked. We are protected from async events
548 	 * by poll logic and correct handling of state changes
549 	 * made by other threads is impossible in any case.
550 	 */
551 
552 	mask = 0;
553 
554 	/*
555 	 * EPOLLHUP is certainly not done right. But poll() doesn't
556 	 * have a notion of HUP in just one direction, and for a
557 	 * socket the read side is more interesting.
558 	 *
559 	 * Some poll() documentation says that EPOLLHUP is incompatible
560 	 * with the EPOLLOUT/POLLWR flags, so somebody should check this
561 	 * all. But careful, it tends to be safer to return too many
562 	 * bits than too few, and you can easily break real applications
563 	 * if you don't tell them that something has hung up!
564 	 *
565 	 * Check-me.
566 	 *
567 	 * Check number 1. EPOLLHUP is _UNMASKABLE_ event (see UNIX98 and
568 	 * our fs/select.c). It means that after we received EOF,
569 	 * poll always returns immediately, making impossible poll() on write()
570 	 * in state CLOSE_WAIT. One solution is evident --- to set EPOLLHUP
571 	 * if and only if shutdown has been made in both directions.
572 	 * Actually, it is interesting to look how Solaris and DUX
573 	 * solve this dilemma. I would prefer, if EPOLLHUP were maskable,
574 	 * then we could set it on SND_SHUTDOWN. BTW examples given
575 	 * in Stevens' books assume exactly this behaviour, it explains
576 	 * why EPOLLHUP is incompatible with EPOLLOUT.	--ANK
577 	 *
578 	 * NOTE. Check for TCP_CLOSE is added. The goal is to prevent
579 	 * blocking on fresh not-connected or disconnected socket. --ANK
580 	 */
581 	shutdown = READ_ONCE(sk->sk_shutdown);
582 	if (shutdown == SHUTDOWN_MASK || state == TCP_CLOSE) {
583 		mask |= EPOLLHUP;
584 		/* Coupled with smp_wmb() in tcp_done_with_error() to ensure
585 		 * sk->sk_err is visible if socket closure was observed.
586 		 */
587 		smp_rmb();
588 	}
589 	if (shutdown & RCV_SHUTDOWN)
590 		mask |= EPOLLIN | EPOLLRDNORM | EPOLLRDHUP;
591 
592 	/* Connected or passive Fast Open socket? */
593 	if (state != TCP_SYN_SENT &&
594 	    (state != TCP_SYN_RECV || rcu_access_pointer(tp->fastopen_rsk))) {
595 		int target = sock_rcvlowat(sk, 0, INT_MAX);
596 		u16 urg_data = READ_ONCE(tp->urg_data);
597 
598 		if (unlikely(urg_data) &&
599 		    READ_ONCE(tp->urg_seq) == READ_ONCE(tp->copied_seq) &&
600 		    !sock_flag(sk, SOCK_URGINLINE))
601 			target++;
602 
603 		if (tcp_stream_is_readable(sk, target))
604 			mask |= EPOLLIN | EPOLLRDNORM;
605 
606 		if (!(shutdown & SEND_SHUTDOWN)) {
607 			if (__sk_stream_is_writeable(sk, 1)) {
608 				mask |= EPOLLOUT | EPOLLWRNORM;
609 			} else {  /* send SIGIO later */
610 				sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
611 				sk_set_nospace(sk);
612 
613 				/* Race breaker. If space is freed after
614 				 * wspace test but before the flags are set,
615 				 * IO signal will be lost. Memory barrier
616 				 * pairs with the input side.
617 				 */
618 				smp_mb__after_atomic();
619 				if (__sk_stream_is_writeable(sk, 1))
620 					mask |= EPOLLOUT | EPOLLWRNORM;
621 			}
622 		} else
623 			mask |= EPOLLOUT | EPOLLWRNORM;
624 
625 		if (urg_data & TCP_URG_VALID)
626 			mask |= EPOLLPRI;
627 	} else if (state == TCP_SYN_SENT &&
628 		   inet_test_bit(DEFER_CONNECT, sk)) {
629 		/* Active TCP fastopen socket with defer_connect
630 		 * Return EPOLLOUT so application can call write()
631 		 * in order for kernel to generate SYN+data
632 		 */
633 		mask |= EPOLLOUT | EPOLLWRNORM;
634 	}
635 	if (READ_ONCE(sk->sk_err) ||
636 	    !skb_queue_empty_lockless(&sk->sk_error_queue))
637 		mask |= EPOLLERR;
638 
639 	return mask;
640 }
641 EXPORT_SYMBOL(tcp_poll);
642 
643 int tcp_ioctl(struct sock *sk, int cmd, int *karg)
644 {
645 	struct tcp_sock *tp = tcp_sk(sk);
646 	int answ;
647 	bool slow;
648 
649 	switch (cmd) {
650 	case SIOCINQ:
651 		if (sk->sk_state == TCP_LISTEN)
652 			return -EINVAL;
653 
654 		slow = lock_sock_fast(sk);
655 		answ = tcp_inq(sk);
656 		unlock_sock_fast(sk, slow);
657 		break;
658 	case SIOCATMARK:
659 		answ = READ_ONCE(tp->urg_data) &&
660 		       READ_ONCE(tp->urg_seq) == READ_ONCE(tp->copied_seq);
661 		break;
662 	case SIOCOUTQ:
663 		if (sk->sk_state == TCP_LISTEN)
664 			return -EINVAL;
665 
666 		if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
667 			answ = 0;
668 		else
669 			answ = READ_ONCE(tp->write_seq) - tp->snd_una;
670 		break;
671 	case SIOCOUTQNSD:
672 		if (sk->sk_state == TCP_LISTEN)
673 			return -EINVAL;
674 
675 		if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
676 			answ = 0;
677 		else
678 			answ = READ_ONCE(tp->write_seq) -
679 			       READ_ONCE(tp->snd_nxt);
680 		break;
681 	default:
682 		return -ENOIOCTLCMD;
683 	}
684 
685 	*karg = answ;
686 	return 0;
687 }
688 
689 void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb)
690 {
691 	TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH;
692 	tp->pushed_seq = tp->write_seq;
693 }
694 
695 static inline bool forced_push(const struct tcp_sock *tp)
696 {
697 	return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1));
698 }
699 
700 void tcp_skb_entail(struct sock *sk, struct sk_buff *skb)
701 {
702 	struct tcp_sock *tp = tcp_sk(sk);
703 	struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
704 
705 	tcb->seq     = tcb->end_seq = tp->write_seq;
706 	tcb->tcp_flags = TCPHDR_ACK;
707 	__skb_header_release(skb);
708 	psp_enqueue_set_decrypted(sk, skb);
709 	tcp_add_write_queue_tail(sk, skb);
710 	sk_wmem_queued_add(sk, skb->truesize);
711 	sk_mem_charge(sk, skb->truesize);
712 	if (tp->nonagle & TCP_NAGLE_PUSH)
713 		tp->nonagle &= ~TCP_NAGLE_PUSH;
714 
715 	tcp_slow_start_after_idle_check(sk);
716 }
717 
718 static inline void tcp_mark_urg(struct tcp_sock *tp, int flags)
719 {
720 	if (flags & MSG_OOB)
721 		tp->snd_up = tp->write_seq;
722 }
723 
724 /* If a not yet filled skb is pushed, do not send it if
725  * we have data packets in Qdisc or NIC queues :
726  * Because TX completion will happen shortly, it gives a chance
727  * to coalesce future sendmsg() payload into this skb, without
728  * need for a timer, and with no latency trade off.
729  * As packets containing data payload have a bigger truesize
730  * than pure acks (dataless) packets, the last checks prevent
731  * autocorking if we only have an ACK in Qdisc/NIC queues,
732  * or if TX completion was delayed after we processed ACK packet.
733  */
734 static bool tcp_should_autocork(struct sock *sk, struct sk_buff *skb,
735 				int size_goal)
736 {
737 	return skb->len < size_goal &&
738 	       READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_autocorking) &&
739 	       !tcp_rtx_queue_empty(sk) &&
740 	       refcount_read(&sk->sk_wmem_alloc) > skb->truesize &&
741 	       tcp_skb_can_collapse_to(skb);
742 }
743 
744 void tcp_push(struct sock *sk, int flags, int mss_now,
745 	      int nonagle, int size_goal)
746 {
747 	struct tcp_sock *tp = tcp_sk(sk);
748 	struct sk_buff *skb;
749 
750 	skb = tcp_write_queue_tail(sk);
751 	if (!skb)
752 		return;
753 	if (!(flags & MSG_MORE) || forced_push(tp))
754 		tcp_mark_push(tp, skb);
755 
756 	tcp_mark_urg(tp, flags);
757 
758 	if (tcp_should_autocork(sk, skb, size_goal)) {
759 
760 		/* avoid atomic op if TSQ_THROTTLED bit is already set */
761 		if (!test_bit(TSQ_THROTTLED, &sk->sk_tsq_flags)) {
762 			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAUTOCORKING);
763 			set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags);
764 			smp_mb__after_atomic();
765 		}
766 		/* It is possible TX completion already happened
767 		 * before we set TSQ_THROTTLED.
768 		 */
769 		if (refcount_read(&sk->sk_wmem_alloc) > skb->truesize)
770 			return;
771 	}
772 
773 	if (flags & MSG_MORE)
774 		nonagle = TCP_NAGLE_CORK;
775 
776 	__tcp_push_pending_frames(sk, mss_now, nonagle);
777 }
778 
779 int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
780 			 unsigned int offset, size_t len)
781 {
782 	struct tcp_splice_state *tss = rd_desc->arg.data;
783 	int ret;
784 
785 	ret = skb_splice_bits(skb, skb->sk, offset, tss->pipe,
786 			      min(rd_desc->count, len), tss->flags);
787 	if (ret > 0)
788 		rd_desc->count -= ret;
789 	return ret;
790 }
791 
792 static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss)
793 {
794 	/* Store TCP splice context information in read_descriptor_t. */
795 	read_descriptor_t rd_desc = {
796 		.arg.data = tss,
797 		.count	  = tss->len,
798 	};
799 
800 	return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv);
801 }
802 
803 /**
804  *  tcp_splice_read - splice data from TCP socket to a pipe
805  * @sock:	socket to splice from
806  * @ppos:	position (not valid)
807  * @pipe:	pipe to splice to
808  * @len:	number of bytes to splice
809  * @flags:	splice modifier flags
810  *
811  * Description:
812  *    Will read pages from given socket and fill them into a pipe.
813  *
814  **/
815 ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
816 			struct pipe_inode_info *pipe, size_t len,
817 			unsigned int flags)
818 {
819 	struct sock *sk = sock->sk;
820 	struct tcp_splice_state tss = {
821 		.pipe = pipe,
822 		.len = len,
823 		.flags = flags,
824 	};
825 	long timeo;
826 	ssize_t spliced;
827 	int ret;
828 
829 	sock_rps_record_flow(sk);
830 	/*
831 	 * We can't seek on a socket input
832 	 */
833 	if (unlikely(*ppos))
834 		return -ESPIPE;
835 
836 	ret = spliced = 0;
837 
838 	lock_sock(sk);
839 
840 	timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK);
841 	while (tss.len) {
842 		ret = __tcp_splice_read(sk, &tss);
843 		if (ret < 0)
844 			break;
845 		else if (!ret) {
846 			if (spliced)
847 				break;
848 			if (sock_flag(sk, SOCK_DONE))
849 				break;
850 			ret = sock_error(sk);
851 			if (ret)
852 				break;
853 			if (sk->sk_shutdown & RCV_SHUTDOWN)
854 				break;
855 			if (sk->sk_state == TCP_CLOSE) {
856 				/*
857 				 * This occurs when user tries to read
858 				 * from never connected socket.
859 				 */
860 				ret = -ENOTCONN;
861 				break;
862 			}
863 			if (!timeo) {
864 				ret = -EAGAIN;
865 				break;
866 			}
867 			/* if __tcp_splice_read() got nothing while we have
868 			 * an skb in receive queue, we do not want to loop.
869 			 * This might happen with URG data.
870 			 */
871 			if (!skb_queue_empty(&sk->sk_receive_queue))
872 				break;
873 			ret = sk_wait_data(sk, &timeo, NULL);
874 			if (ret < 0)
875 				break;
876 			if (signal_pending(current)) {
877 				ret = sock_intr_errno(timeo);
878 				break;
879 			}
880 			continue;
881 		}
882 		tss.len -= ret;
883 		spliced += ret;
884 
885 		if (!tss.len || !timeo)
886 			break;
887 		release_sock(sk);
888 		lock_sock(sk);
889 
890 		if (tcp_recv_should_stop(sk))
891 			break;
892 	}
893 
894 	release_sock(sk);
895 
896 	if (spliced)
897 		return spliced;
898 
899 	return ret;
900 }
901 
902 /* We allow to exceed memory limits for FIN packets to expedite
903  * connection tear down and (memory) recovery.
904  * Otherwise tcp_send_fin() could be tempted to either delay FIN
905  * or even be forced to close flow without any FIN.
906  * In general, we want to allow one skb per socket to avoid hangs
907  * with edge trigger epoll()
908  */
909 void sk_forced_mem_schedule(struct sock *sk, int size)
910 {
911 	int delta, amt;
912 
913 	delta = size - sk->sk_forward_alloc;
914 	if (delta <= 0)
915 		return;
916 
917 	amt = sk_mem_pages(delta);
918 	sk_forward_alloc_add(sk, amt << PAGE_SHIFT);
919 
920 	if (mem_cgroup_sk_enabled(sk))
921 		mem_cgroup_sk_charge(sk, amt, gfp_memcg_charge() | __GFP_NOFAIL);
922 
923 	if (sk->sk_bypass_prot_mem)
924 		return;
925 
926 	sk_memory_allocated_add(sk, amt);
927 }
928 
929 struct sk_buff *tcp_stream_alloc_skb(struct sock *sk, gfp_t gfp,
930 				     bool force_schedule)
931 {
932 	struct sk_buff *skb;
933 
934 	skb = alloc_skb_fclone(MAX_TCP_HEADER, gfp);
935 	if (likely(skb)) {
936 		bool mem_scheduled;
937 
938 		skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
939 		if (force_schedule) {
940 			mem_scheduled = true;
941 			sk_forced_mem_schedule(sk, skb->truesize);
942 		} else {
943 			mem_scheduled = sk_wmem_schedule(sk, skb->truesize);
944 		}
945 		if (likely(mem_scheduled)) {
946 			skb_reserve(skb, MAX_TCP_HEADER);
947 			skb->ip_summed = CHECKSUM_PARTIAL;
948 			INIT_LIST_HEAD(&skb->tcp_tsorted_anchor);
949 			return skb;
950 		}
951 		__kfree_skb(skb);
952 	} else {
953 		if (!sk->sk_bypass_prot_mem)
954 			tcp_enter_memory_pressure(sk);
955 		sk_stream_moderate_sndbuf(sk);
956 	}
957 	return NULL;
958 }
959 
960 static unsigned int tcp_xmit_size_goal(struct sock *sk, u32 mss_now,
961 				       int large_allowed)
962 {
963 	struct tcp_sock *tp = tcp_sk(sk);
964 	u32 new_size_goal, size_goal;
965 
966 	if (!large_allowed)
967 		return mss_now;
968 
969 	/* Note : tcp_tso_autosize() will eventually split this later */
970 	new_size_goal = tcp_bound_to_half_wnd(tp, sk->sk_gso_max_size);
971 
972 	/* We try hard to avoid divides here */
973 	size_goal = tp->gso_segs * mss_now;
974 	if (unlikely(new_size_goal < size_goal ||
975 		     new_size_goal >= size_goal + mss_now)) {
976 		tp->gso_segs = min_t(u16, new_size_goal / mss_now,
977 				     sk->sk_gso_max_segs);
978 		size_goal = tp->gso_segs * mss_now;
979 	}
980 
981 	return max(size_goal, mss_now);
982 }
983 
984 int tcp_send_mss(struct sock *sk, int *size_goal, int flags)
985 {
986 	int mss_now;
987 
988 	mss_now = tcp_current_mss(sk);
989 	*size_goal = tcp_xmit_size_goal(sk, mss_now, !(flags & MSG_OOB));
990 
991 	return mss_now;
992 }
993 
994 /* In some cases, sendmsg() could have added an skb to the write queue,
995  * but failed adding payload on it. We need to remove it to consume less
996  * memory, but more importantly be able to generate EPOLLOUT for Edge Trigger
997  * epoll() users. Another reason is that tcp_write_xmit() does not like
998  * finding an empty skb in the write queue.
999  */
1000 void tcp_remove_empty_skb(struct sock *sk)
1001 {
1002 	struct sk_buff *skb = tcp_write_queue_tail(sk);
1003 
1004 	if (skb && TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq) {
1005 		tcp_unlink_write_queue(skb, sk);
1006 		if (tcp_write_queue_empty(sk))
1007 			tcp_chrono_stop(sk, TCP_CHRONO_BUSY);
1008 		tcp_wmem_free_skb(sk, skb);
1009 	}
1010 }
1011 
1012 /* skb changing from pure zc to mixed, must charge zc */
1013 static int tcp_downgrade_zcopy_pure(struct sock *sk, struct sk_buff *skb)
1014 {
1015 	if (unlikely(skb_zcopy_pure(skb))) {
1016 		u32 extra = skb->truesize -
1017 			    SKB_TRUESIZE(skb_end_offset(skb));
1018 
1019 		if (!sk_wmem_schedule(sk, extra))
1020 			return -ENOMEM;
1021 
1022 		sk_mem_charge(sk, extra);
1023 		skb_shinfo(skb)->flags &= ~SKBFL_PURE_ZEROCOPY;
1024 	}
1025 	return 0;
1026 }
1027 
1028 
1029 int tcp_wmem_schedule(struct sock *sk, int copy)
1030 {
1031 	int left;
1032 
1033 	if (likely(sk_wmem_schedule(sk, copy)))
1034 		return copy;
1035 
1036 	/* We could be in trouble if we have nothing queued.
1037 	 * Use whatever is left in sk->sk_forward_alloc and tcp_wmem[0]
1038 	 * to guarantee some progress.
1039 	 */
1040 	left = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_wmem[0]) - sk->sk_wmem_queued;
1041 	if (left > 0)
1042 		sk_forced_mem_schedule(sk, min(left, copy));
1043 	return min(copy, sk->sk_forward_alloc);
1044 }
1045 
1046 void tcp_free_fastopen_req(struct tcp_sock *tp)
1047 {
1048 	if (tp->fastopen_req) {
1049 		kfree(tp->fastopen_req);
1050 		tp->fastopen_req = NULL;
1051 	}
1052 }
1053 
1054 int tcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg, int *copied,
1055 			 size_t size, struct ubuf_info *uarg)
1056 {
1057 	struct tcp_sock *tp = tcp_sk(sk);
1058 	struct inet_sock *inet = inet_sk(sk);
1059 	struct sockaddr *uaddr = msg->msg_name;
1060 	int err, flags;
1061 
1062 	if (!(READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_fastopen) &
1063 	      TFO_CLIENT_ENABLE) ||
1064 	    (uaddr && msg->msg_namelen >= sizeof(uaddr->sa_family) &&
1065 	     uaddr->sa_family == AF_UNSPEC))
1066 		return -EOPNOTSUPP;
1067 	if (tp->fastopen_req)
1068 		return -EALREADY; /* Another Fast Open is in progress */
1069 
1070 	tp->fastopen_req = kzalloc_obj(struct tcp_fastopen_request,
1071 				       sk->sk_allocation);
1072 	if (unlikely(!tp->fastopen_req))
1073 		return -ENOBUFS;
1074 	tp->fastopen_req->data = msg;
1075 	tp->fastopen_req->size = size;
1076 	tp->fastopen_req->uarg = uarg;
1077 
1078 	if (inet_test_bit(DEFER_CONNECT, sk)) {
1079 		err = tcp_connect(sk);
1080 		/* Same failure procedure as in tcp_v4/6_connect */
1081 		if (err) {
1082 			tcp_set_state(sk, TCP_CLOSE);
1083 			inet->inet_dport = 0;
1084 			sk->sk_route_caps = 0;
1085 		}
1086 	}
1087 	flags = (msg->msg_flags & MSG_DONTWAIT) ? O_NONBLOCK : 0;
1088 	err = __inet_stream_connect(sk->sk_socket, (struct sockaddr_unsized *)uaddr,
1089 				    msg->msg_namelen, flags, 1);
1090 	/* fastopen_req could already be freed in __inet_stream_connect
1091 	 * if the connection times out or gets rst
1092 	 */
1093 	if (tp->fastopen_req) {
1094 		*copied = tp->fastopen_req->copied;
1095 		tcp_free_fastopen_req(tp);
1096 		inet_clear_bit(DEFER_CONNECT, sk);
1097 	}
1098 	return err;
1099 }
1100 
1101 /* If a gap is detected between sends, mark the socket application-limited. */
1102 void tcp_rate_check_app_limited(struct sock *sk)
1103 {
1104 	struct tcp_sock *tp = tcp_sk(sk);
1105 
1106 	if (/* We have less than one packet to send. */
1107 	    tp->write_seq - tp->snd_nxt < tp->mss_cache &&
1108 	    /* Nothing in sending host's qdisc queues or NIC tx queue. */
1109 	    sk_wmem_alloc_get(sk) < SKB_TRUESIZE(1) &&
1110 	    /* We are not limited by CWND. */
1111 	    tcp_packets_in_flight(tp) < tcp_snd_cwnd(tp) &&
1112 	    /* All lost packets have been retransmitted. */
1113 	    tp->lost_out <= tp->retrans_out)
1114 		tp->app_limited =
1115 			(tp->delivered + tcp_packets_in_flight(tp)) ? : 1;
1116 }
1117 EXPORT_SYMBOL_GPL(tcp_rate_check_app_limited);
1118 
1119 int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
1120 {
1121 	struct net_devmem_dmabuf_binding *binding = NULL;
1122 	struct tcp_sock *tp = tcp_sk(sk);
1123 	struct ubuf_info *uarg = NULL;
1124 	struct sk_buff *skb;
1125 	struct sockcm_cookie sockc;
1126 	int flags, err, copied = 0;
1127 	int mss_now = 0, size_goal, copied_syn = 0;
1128 	int process_backlog = 0;
1129 	int sockc_err = 0;
1130 	int zc = 0;
1131 	long timeo;
1132 
1133 	flags = msg->msg_flags;
1134 
1135 	sockc = (struct sockcm_cookie){ .tsflags = READ_ONCE(sk->sk_tsflags) };
1136 	if (msg->msg_controllen) {
1137 		sockc_err = sock_cmsg_send(sk, msg, &sockc);
1138 		/* Don't return error until MSG_FASTOPEN has been processed;
1139 		 * that may succeed even if the cmsg is invalid.
1140 		 */
1141 	}
1142 
1143 	if ((flags & MSG_ZEROCOPY) && size) {
1144 		if (msg->msg_ubuf) {
1145 			uarg = msg->msg_ubuf;
1146 			if (sk->sk_route_caps & NETIF_F_SG)
1147 				zc = MSG_ZEROCOPY;
1148 		} else if (sock_flag(sk, SOCK_ZEROCOPY)) {
1149 			skb = tcp_write_queue_tail(sk);
1150 			uarg = msg_zerocopy_realloc(sk, size, skb_zcopy(skb),
1151 						    !sockc_err && sockc.dmabuf_id);
1152 			if (!uarg) {
1153 				err = -ENOBUFS;
1154 				goto out_err;
1155 			}
1156 			if (sk->sk_route_caps & NETIF_F_SG)
1157 				zc = MSG_ZEROCOPY;
1158 			else
1159 				uarg_to_msgzc(uarg)->zerocopy = 0;
1160 
1161 			if (!sockc_err && sockc.dmabuf_id) {
1162 				binding = net_devmem_get_binding(sk, sockc.dmabuf_id);
1163 				if (IS_ERR(binding)) {
1164 					err = PTR_ERR(binding);
1165 					binding = NULL;
1166 					goto out_err;
1167 				}
1168 			}
1169 		}
1170 	} else if (unlikely(msg->msg_flags & MSG_SPLICE_PAGES) && size) {
1171 		if (sk->sk_route_caps & NETIF_F_SG)
1172 			zc = MSG_SPLICE_PAGES;
1173 	}
1174 
1175 	if (!sockc_err && sockc.dmabuf_id && (zc != MSG_ZEROCOPY || !binding)) {
1176 		err = -EINVAL;
1177 		goto out_err;
1178 	}
1179 
1180 	if (unlikely(flags & MSG_FASTOPEN ||
1181 		     inet_test_bit(DEFER_CONNECT, sk)) &&
1182 	    !tp->repair) {
1183 		err = tcp_sendmsg_fastopen(sk, msg, &copied_syn, size, uarg);
1184 		if (err == -EINPROGRESS && copied_syn > 0)
1185 			goto out;
1186 		else if (err)
1187 			goto out_err;
1188 	}
1189 
1190 	timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
1191 
1192 	tcp_rate_check_app_limited(sk);  /* is sending application-limited? */
1193 
1194 	/* Wait for a connection to finish. One exception is TCP Fast Open
1195 	 * (passive side) where data is allowed to be sent before a connection
1196 	 * is fully established.
1197 	 */
1198 	if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
1199 	    !tcp_passive_fastopen(sk)) {
1200 		err = sk_stream_wait_connect(sk, &timeo);
1201 		if (err != 0)
1202 			goto do_error;
1203 	}
1204 
1205 	if (unlikely(tp->repair)) {
1206 		if (tp->repair_queue == TCP_RECV_QUEUE) {
1207 			copied = tcp_send_rcvq(sk, msg, size);
1208 			goto out_nopush;
1209 		}
1210 
1211 		err = -EINVAL;
1212 		if (tp->repair_queue == TCP_NO_QUEUE)
1213 			goto out_err;
1214 
1215 		/* 'common' sending to sendq */
1216 	}
1217 
1218 	if (sockc_err) {
1219 		err = sockc_err;
1220 		goto out_err;
1221 	}
1222 
1223 	/* This should be in poll */
1224 	sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
1225 
1226 	/* Ok commence sending. */
1227 	copied = 0;
1228 
1229 restart:
1230 	mss_now = tcp_send_mss(sk, &size_goal, flags);
1231 
1232 	err = -EPIPE;
1233 	if (READ_ONCE(sk->sk_err) || (sk->sk_shutdown & SEND_SHUTDOWN))
1234 		goto do_error;
1235 
1236 	while (msg_data_left(msg)) {
1237 		int copy = 0;
1238 
1239 		skb = tcp_write_queue_tail(sk);
1240 		if (skb)
1241 			copy = size_goal - skb->len;
1242 
1243 		trace_tcp_sendmsg_locked(sk, msg, skb, size_goal);
1244 
1245 		if (copy <= 0 || !tcp_skb_can_collapse_to(skb) ||
1246 		    unlikely(skb_frags_readable(skb) != !binding)) {
1247 			bool first_skb;
1248 
1249 new_segment:
1250 			if (!sk_stream_memory_free(sk))
1251 				goto wait_for_space;
1252 
1253 			if (unlikely(process_backlog >= 16)) {
1254 				process_backlog = 0;
1255 				if (sk_flush_backlog(sk))
1256 					goto restart;
1257 			}
1258 			first_skb = tcp_rtx_and_write_queues_empty(sk);
1259 			skb = tcp_stream_alloc_skb(sk, sk->sk_allocation,
1260 						   first_skb);
1261 			if (!skb)
1262 				goto wait_for_space;
1263 
1264 			process_backlog++;
1265 
1266 #ifdef CONFIG_SKB_DECRYPTED
1267 			skb->decrypted = !!(flags & MSG_SENDPAGE_DECRYPTED);
1268 #endif
1269 			tcp_skb_entail(sk, skb);
1270 			copy = size_goal;
1271 
1272 			/* All packets are restored as if they have
1273 			 * already been sent. skb_mstamp_ns isn't set to
1274 			 * avoid wrong rtt estimation.
1275 			 */
1276 			if (tp->repair)
1277 				TCP_SKB_CB(skb)->sacked |= TCPCB_REPAIRED;
1278 		}
1279 
1280 		/* Try to append data to the end of skb. */
1281 		if (copy > msg_data_left(msg))
1282 			copy = msg_data_left(msg);
1283 
1284 		if (zc == 0) {
1285 			bool merge = true;
1286 			int i = skb_shinfo(skb)->nr_frags;
1287 			struct page_frag *pfrag = sk_page_frag(sk);
1288 
1289 			if (!sk_page_frag_refill(sk, pfrag))
1290 				goto wait_for_space;
1291 
1292 			if (!skb_can_coalesce(skb, i, pfrag->page,
1293 					      pfrag->offset)) {
1294 				if (i >= READ_ONCE(net_hotdata.sysctl_max_skb_frags)) {
1295 					tcp_mark_push(tp, skb);
1296 					goto new_segment;
1297 				}
1298 				merge = false;
1299 			}
1300 
1301 			copy = min_t(int, copy, pfrag->size - pfrag->offset);
1302 
1303 			if (unlikely(skb_zcopy_pure(skb) || skb_zcopy_managed(skb))) {
1304 				if (tcp_downgrade_zcopy_pure(sk, skb))
1305 					goto wait_for_space;
1306 				skb_zcopy_downgrade_managed(skb);
1307 			}
1308 
1309 			copy = tcp_wmem_schedule(sk, copy);
1310 			if (!copy)
1311 				goto wait_for_space;
1312 
1313 			err = skb_copy_to_page_nocache(sk, &msg->msg_iter, skb,
1314 						       pfrag->page,
1315 						       pfrag->offset,
1316 						       copy);
1317 			if (err)
1318 				goto do_error;
1319 
1320 			/* Update the skb. */
1321 			if (merge) {
1322 				skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
1323 			} else {
1324 				skb_fill_page_desc(skb, i, pfrag->page,
1325 						   pfrag->offset, copy);
1326 				page_ref_inc(pfrag->page);
1327 			}
1328 			pfrag->offset += copy;
1329 		} else if (zc == MSG_ZEROCOPY)  {
1330 			/* First append to a fragless skb builds initial
1331 			 * pure zerocopy skb
1332 			 */
1333 			if (!skb->len)
1334 				skb_shinfo(skb)->flags |= SKBFL_PURE_ZEROCOPY;
1335 
1336 			if (!skb_zcopy_pure(skb)) {
1337 				copy = tcp_wmem_schedule(sk, copy);
1338 				if (!copy)
1339 					goto wait_for_space;
1340 			}
1341 
1342 			err = skb_zerocopy_iter_stream(sk, skb, msg, copy, uarg,
1343 						       binding);
1344 			if (err == -EMSGSIZE || err == -EEXIST) {
1345 				tcp_mark_push(tp, skb);
1346 				goto new_segment;
1347 			}
1348 			if (err < 0)
1349 				goto do_error;
1350 			copy = err;
1351 		} else if (zc == MSG_SPLICE_PAGES) {
1352 			/* Splice in data if we can; copy if we can't. */
1353 			if (tcp_downgrade_zcopy_pure(sk, skb))
1354 				goto wait_for_space;
1355 			copy = tcp_wmem_schedule(sk, copy);
1356 			if (!copy)
1357 				goto wait_for_space;
1358 
1359 			err = skb_splice_from_iter(skb, &msg->msg_iter, copy);
1360 			if (err < 0) {
1361 				if (err == -EMSGSIZE) {
1362 					tcp_mark_push(tp, skb);
1363 					goto new_segment;
1364 				}
1365 				goto do_error;
1366 			}
1367 			copy = err;
1368 
1369 			if (!(flags & MSG_NO_SHARED_FRAGS))
1370 				skb_shinfo(skb)->flags |= SKBFL_SHARED_FRAG;
1371 
1372 			sk_wmem_queued_add(sk, copy);
1373 			sk_mem_charge(sk, copy);
1374 		}
1375 
1376 		if (!copied)
1377 			TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
1378 
1379 		WRITE_ONCE(tp->write_seq, tp->write_seq + copy);
1380 		TCP_SKB_CB(skb)->end_seq += copy;
1381 		tcp_skb_pcount_set(skb, 0);
1382 
1383 		copied += copy;
1384 		if (!msg_data_left(msg)) {
1385 			if (unlikely(flags & MSG_EOR))
1386 				TCP_SKB_CB(skb)->eor = 1;
1387 			goto out;
1388 		}
1389 
1390 		if (skb->len < size_goal || (flags & MSG_OOB) || unlikely(tp->repair))
1391 			continue;
1392 
1393 		if (forced_push(tp)) {
1394 			tcp_mark_push(tp, skb);
1395 			__tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
1396 		} else if (skb == tcp_send_head(sk))
1397 			tcp_push_one(sk, mss_now);
1398 		continue;
1399 
1400 wait_for_space:
1401 		sk_set_nospace(sk);
1402 		tcp_remove_empty_skb(sk);
1403 		if (copied)
1404 			tcp_push(sk, flags & ~MSG_MORE, mss_now,
1405 				 TCP_NAGLE_PUSH, size_goal);
1406 
1407 		err = sk_stream_wait_memory(sk, &timeo);
1408 		if (err != 0)
1409 			goto do_error;
1410 
1411 		mss_now = tcp_send_mss(sk, &size_goal, flags);
1412 	}
1413 
1414 out:
1415 	if (copied) {
1416 		tcp_tx_timestamp(sk, &sockc);
1417 		tcp_push(sk, flags, mss_now, tp->nonagle, size_goal);
1418 	}
1419 out_nopush:
1420 	/* msg->msg_ubuf is pinned by the caller so we don't take extra refs */
1421 	if (uarg && !msg->msg_ubuf)
1422 		net_zcopy_put(uarg);
1423 	if (binding)
1424 		net_devmem_dmabuf_binding_put(binding);
1425 	return copied + copied_syn;
1426 
1427 do_error:
1428 	tcp_remove_empty_skb(sk);
1429 
1430 	if (copied + copied_syn)
1431 		goto out;
1432 out_err:
1433 	/* msg->msg_ubuf is pinned by the caller so we don't take extra refs */
1434 	if (uarg && !msg->msg_ubuf)
1435 		net_zcopy_put_abort(uarg, true);
1436 	err = sk_stream_error(sk, flags, err);
1437 	/* make sure we wake any epoll edge trigger waiter */
1438 	if (unlikely(tcp_rtx_and_write_queues_empty(sk) && err == -EAGAIN)) {
1439 		READ_ONCE(sk->sk_write_space)(sk);
1440 		tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
1441 	}
1442 	if (binding)
1443 		net_devmem_dmabuf_binding_put(binding);
1444 
1445 	return err;
1446 }
1447 EXPORT_SYMBOL_GPL(tcp_sendmsg_locked);
1448 
1449 int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
1450 {
1451 	int ret;
1452 
1453 	lock_sock(sk);
1454 	ret = tcp_sendmsg_locked(sk, msg, size);
1455 	release_sock(sk);
1456 
1457 	return ret;
1458 }
1459 EXPORT_SYMBOL(tcp_sendmsg);
1460 
1461 void tcp_splice_eof(struct socket *sock)
1462 {
1463 	struct sock *sk = sock->sk;
1464 	struct tcp_sock *tp = tcp_sk(sk);
1465 	int mss_now, size_goal;
1466 
1467 	if (!tcp_write_queue_tail(sk))
1468 		return;
1469 
1470 	lock_sock(sk);
1471 	mss_now = tcp_send_mss(sk, &size_goal, 0);
1472 	tcp_push(sk, 0, mss_now, tp->nonagle, size_goal);
1473 	release_sock(sk);
1474 }
1475 
1476 /*
1477  *	Handle reading urgent data. BSD has very simple semantics for
1478  *	this, no blocking and very strange errors 8)
1479  */
1480 
1481 static int tcp_recv_urg(struct sock *sk, struct msghdr *msg, int len, int flags)
1482 {
1483 	struct tcp_sock *tp = tcp_sk(sk);
1484 
1485 	/* No URG data to read. */
1486 	if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data ||
1487 	    tp->urg_data == TCP_URG_READ)
1488 		return -EINVAL;	/* Yes this is right ! */
1489 
1490 	if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE))
1491 		return -ENOTCONN;
1492 
1493 	if (tp->urg_data & TCP_URG_VALID) {
1494 		int err = 0;
1495 		char c = tp->urg_data;
1496 
1497 		if (!(flags & MSG_PEEK))
1498 			WRITE_ONCE(tp->urg_data, TCP_URG_READ);
1499 
1500 		/* Read urgent data. */
1501 		msg->msg_flags |= MSG_OOB;
1502 
1503 		if (len > 0) {
1504 			if (!(flags & MSG_TRUNC))
1505 				err = memcpy_to_msg(msg, &c, 1);
1506 			len = 1;
1507 		} else
1508 			msg->msg_flags |= MSG_TRUNC;
1509 
1510 		return err ? -EFAULT : len;
1511 	}
1512 
1513 	if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN))
1514 		return 0;
1515 
1516 	/* Fixed the recv(..., MSG_OOB) behaviour.  BSD docs and
1517 	 * the available implementations agree in this case:
1518 	 * this call should never block, independent of the
1519 	 * blocking state of the socket.
1520 	 * Mike <pall@rz.uni-karlsruhe.de>
1521 	 */
1522 	return -EAGAIN;
1523 }
1524 
1525 static int tcp_peek_sndq(struct sock *sk, struct msghdr *msg, int len)
1526 {
1527 	struct sk_buff *skb;
1528 	int copied = 0, err = 0;
1529 
1530 	skb_rbtree_walk(skb, &sk->tcp_rtx_queue) {
1531 		err = skb_copy_datagram_msg(skb, 0, msg, skb->len);
1532 		if (err)
1533 			return err;
1534 		copied += skb->len;
1535 	}
1536 
1537 	skb_queue_walk(&sk->sk_write_queue, skb) {
1538 		err = skb_copy_datagram_msg(skb, 0, msg, skb->len);
1539 		if (err)
1540 			break;
1541 
1542 		copied += skb->len;
1543 	}
1544 
1545 	return err ?: copied;
1546 }
1547 
1548 /* Clean up the receive buffer for full frames taken by the user,
1549  * then send an ACK if necessary.  COPIED is the number of bytes
1550  * tcp_recvmsg has given to the user so far, it speeds up the
1551  * calculation of whether or not we must ACK for the sake of
1552  * a window update.
1553  */
1554 void __tcp_cleanup_rbuf(struct sock *sk, int copied)
1555 {
1556 	struct tcp_sock *tp = tcp_sk(sk);
1557 	bool time_to_ack = false;
1558 
1559 	if (inet_csk_ack_scheduled(sk)) {
1560 		const struct inet_connection_sock *icsk = inet_csk(sk);
1561 
1562 		if (/* Once-per-two-segments ACK was not sent by tcp_input.c */
1563 		    tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss ||
1564 		    /*
1565 		     * If this read emptied read buffer, we send ACK, if
1566 		     * connection is not bidirectional, user drained
1567 		     * receive buffer and there was a small segment
1568 		     * in queue.
1569 		     */
1570 		    (copied > 0 &&
1571 		     ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) ||
1572 		      ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) &&
1573 		       !inet_csk_in_pingpong_mode(sk))) &&
1574 		      !atomic_read(&sk->sk_rmem_alloc)))
1575 			time_to_ack = true;
1576 	}
1577 
1578 	/* We send an ACK if we can now advertise a non-zero window
1579 	 * which has been raised "significantly".
1580 	 *
1581 	 * Even if window raised up to infinity, do not send window open ACK
1582 	 * in states, where we will not receive more. It is useless.
1583 	 */
1584 	if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
1585 		__u32 rcv_window_now = tcp_receive_window(tp);
1586 
1587 		/* Optimize, __tcp_select_window() is not cheap. */
1588 		if (2*rcv_window_now <= tp->window_clamp) {
1589 			__u32 new_window = __tcp_select_window(sk);
1590 
1591 			/* Send ACK now, if this read freed lots of space
1592 			 * in our buffer. Certainly, new_window is new window.
1593 			 * We can advertise it now, if it is not less than current one.
1594 			 * "Lots" means "at least twice" here.
1595 			 */
1596 			if (new_window && new_window >= 2 * rcv_window_now)
1597 				time_to_ack = true;
1598 		}
1599 	}
1600 	if (time_to_ack) {
1601 		tcp_mstamp_refresh(tp);
1602 		tcp_send_ack(sk);
1603 	}
1604 }
1605 
1606 void tcp_cleanup_rbuf(struct sock *sk, int copied)
1607 {
1608 	struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
1609 	struct tcp_sock *tp = tcp_sk(sk);
1610 
1611 	WARN(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq),
1612 	     "cleanup rbuf bug: copied %X seq %X rcvnxt %X\n",
1613 	     tp->copied_seq, TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt);
1614 	__tcp_cleanup_rbuf(sk, copied);
1615 
1616 	bpf_tcp_ops_call_flag(dequeue_rcvq, RCVQ, sk);
1617 }
1618 
1619 static void tcp_eat_recv_skb(struct sock *sk, struct sk_buff *skb)
1620 {
1621 	__skb_unlink(skb, &sk->sk_receive_queue);
1622 	if (likely(skb->destructor == sock_rfree)) {
1623 		sock_rfree(skb);
1624 		skb->destructor = NULL;
1625 		skb->sk = NULL;
1626 		return skb_attempt_defer_free(skb);
1627 	}
1628 	__kfree_skb(skb);
1629 }
1630 
1631 struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off)
1632 {
1633 	struct sk_buff *skb;
1634 	u32 offset;
1635 
1636 	while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) {
1637 		offset = seq - TCP_SKB_CB(skb)->seq;
1638 		if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
1639 			pr_err_once("%s: found a SYN, please report !\n", __func__);
1640 			offset--;
1641 		}
1642 		if (offset < skb->len || (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)) {
1643 			*off = offset;
1644 			return skb;
1645 		}
1646 		/* This looks weird, but this can happen if TCP collapsing
1647 		 * splitted a fat GRO packet, while we released socket lock
1648 		 * in skb_splice_bits()
1649 		 */
1650 		tcp_eat_recv_skb(sk, skb);
1651 	}
1652 	return NULL;
1653 }
1654 EXPORT_SYMBOL(tcp_recv_skb);
1655 
1656 /*
1657  * This routine provides an alternative to tcp_recvmsg() for routines
1658  * that would like to handle copying from skbuffs directly in 'sendfile'
1659  * fashion.
1660  * Note:
1661  *	- It is assumed that the socket was locked by the caller.
1662  *	- The routine does not block.
1663  *	- At present, there is no support for reading OOB data
1664  *	  or for 'peeking' the socket using this routine
1665  *	  (although both would be easy to implement).
1666  */
1667 static int __tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
1668 			   sk_read_actor_t recv_actor, bool noack,
1669 			   u32 *copied_seq)
1670 {
1671 	struct sk_buff *skb;
1672 	struct tcp_sock *tp = tcp_sk(sk);
1673 	u32 seq = *copied_seq;
1674 	u32 offset;
1675 	int copied = 0;
1676 
1677 	if (sk->sk_state == TCP_LISTEN)
1678 		return -ENOTCONN;
1679 	while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
1680 		if (offset < skb->len) {
1681 			int used;
1682 			size_t len;
1683 
1684 			len = skb->len - offset;
1685 			/* Stop reading if we hit a patch of urgent data */
1686 			if (unlikely(tp->urg_data)) {
1687 				u32 urg_offset = tp->urg_seq - seq;
1688 				if (urg_offset < len)
1689 					len = urg_offset;
1690 				if (!len)
1691 					break;
1692 			}
1693 			used = recv_actor(desc, skb, offset, len);
1694 			if (used <= 0) {
1695 				if (!copied)
1696 					copied = used;
1697 				break;
1698 			}
1699 			if (WARN_ON_ONCE(used > len))
1700 				used = len;
1701 			seq += used;
1702 			copied += used;
1703 			offset += used;
1704 
1705 			/* If recv_actor drops the lock (e.g. TCP splice
1706 			 * receive) the skb pointer might be invalid when
1707 			 * getting here: tcp_collapse might have deleted it
1708 			 * while aggregating skbs from the socket queue.
1709 			 */
1710 			skb = tcp_recv_skb(sk, seq - 1, &offset);
1711 			if (!skb)
1712 				break;
1713 			/* TCP coalescing might have appended data to the skb.
1714 			 * Try to splice more frags
1715 			 */
1716 			if (offset + 1 != skb->len)
1717 				continue;
1718 		}
1719 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) {
1720 			tcp_eat_recv_skb(sk, skb);
1721 			++seq;
1722 			break;
1723 		}
1724 		tcp_eat_recv_skb(sk, skb);
1725 		if (!desc->count)
1726 			break;
1727 		WRITE_ONCE(*copied_seq, seq);
1728 	}
1729 	WRITE_ONCE(*copied_seq, seq);
1730 
1731 	if (noack)
1732 		goto out;
1733 
1734 	tcp_rcv_space_adjust(sk);
1735 
1736 	/* Clean up data we have read: This will do ACK frames. */
1737 	if (copied > 0) {
1738 		tcp_recv_skb(sk, seq, &offset);
1739 		tcp_cleanup_rbuf(sk, copied);
1740 	}
1741 out:
1742 	return copied;
1743 }
1744 
1745 int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
1746 		  sk_read_actor_t recv_actor)
1747 {
1748 	return __tcp_read_sock(sk, desc, recv_actor, false,
1749 			       &tcp_sk(sk)->copied_seq);
1750 }
1751 EXPORT_SYMBOL(tcp_read_sock);
1752 
1753 int tcp_read_sock_noack(struct sock *sk, read_descriptor_t *desc,
1754 			sk_read_actor_t recv_actor, bool noack,
1755 			u32 *copied_seq)
1756 {
1757 	return __tcp_read_sock(sk, desc, recv_actor, noack, copied_seq);
1758 }
1759 
1760 int tcp_read_skb(struct sock *sk, skb_read_actor_t recv_actor)
1761 {
1762 	struct sk_buff *skb;
1763 	int copied = 0;
1764 
1765 	if (sk->sk_state == TCP_LISTEN)
1766 		return -ENOTCONN;
1767 
1768 	while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) {
1769 		u8 tcp_flags;
1770 		int used;
1771 
1772 		__skb_unlink(skb, &sk->sk_receive_queue);
1773 		WARN_ON_ONCE(!skb_set_owner_sk_safe(skb, sk));
1774 		tcp_flags = TCP_SKB_CB(skb)->tcp_flags;
1775 		used = recv_actor(sk, skb);
1776 		if (used < 0) {
1777 			if (!copied)
1778 				copied = used;
1779 			break;
1780 		}
1781 		copied += used;
1782 
1783 		if (tcp_flags & TCPHDR_FIN)
1784 			break;
1785 	}
1786 	return copied;
1787 }
1788 
1789 void tcp_read_done(struct sock *sk, size_t len)
1790 {
1791 	struct tcp_sock *tp = tcp_sk(sk);
1792 	u32 seq = tp->copied_seq;
1793 	struct sk_buff *skb;
1794 	size_t left;
1795 	u32 offset;
1796 
1797 	if (sk->sk_state == TCP_LISTEN)
1798 		return;
1799 
1800 	left = len;
1801 	while (left && (skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
1802 		int used;
1803 
1804 		used = min_t(size_t, skb->len - offset, left);
1805 		seq += used;
1806 		left -= used;
1807 
1808 		if (skb->len > offset + used)
1809 			break;
1810 
1811 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) {
1812 			tcp_eat_recv_skb(sk, skb);
1813 			++seq;
1814 			break;
1815 		}
1816 		tcp_eat_recv_skb(sk, skb);
1817 	}
1818 	WRITE_ONCE(tp->copied_seq, seq);
1819 
1820 	tcp_rcv_space_adjust(sk);
1821 
1822 	/* Clean up data we have read: This will do ACK frames. */
1823 	if (left != len)
1824 		tcp_cleanup_rbuf(sk, len - left);
1825 }
1826 EXPORT_SYMBOL(tcp_read_done);
1827 
1828 int tcp_peek_len(struct socket *sock)
1829 {
1830 	return tcp_inq(sock->sk);
1831 }
1832 
1833 int __tcp_set_rcvlowat(struct sock *sk, int val, bool wakeup)
1834 {
1835 	struct tcp_sock *tp = tcp_sk(sk);
1836 	int space, cap;
1837 
1838 	if (sk->sk_userlocks & SOCK_RCVBUF_LOCK)
1839 		cap = sk->sk_rcvbuf >> 1;
1840 	else
1841 		cap = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2]) >> 1;
1842 	val = min(val, cap);
1843 	WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
1844 
1845 	/* Check if we need to signal EPOLLIN right now */
1846 	if (wakeup)
1847 		tcp_data_ready(sk);
1848 
1849 	if (sk->sk_userlocks & SOCK_RCVBUF_LOCK)
1850 		return 0;
1851 
1852 	space = tcp_space_from_win(sk, val);
1853 	if (space > sk->sk_rcvbuf) {
1854 		WRITE_ONCE(sk->sk_rcvbuf, space);
1855 
1856 		if (tp->window_clamp && tp->window_clamp < val)
1857 			WRITE_ONCE(tp->window_clamp, val);
1858 	}
1859 	return 0;
1860 }
1861 
1862 /* Make sure sk_rcvbuf is big enough to satisfy SO_RCVLOWAT hint */
1863 int tcp_set_rcvlowat(struct sock *sk, int val)
1864 {
1865 	return __tcp_set_rcvlowat(sk, val, true);
1866 }
1867 
1868 void tcp_set_rcvbuf(struct sock *sk, int val)
1869 {
1870 	tcp_set_window_clamp(sk, tcp_win_from_space(sk, val));
1871 }
1872 
1873 #ifdef CONFIG_MMU
1874 static const struct vm_operations_struct tcp_vm_ops = {
1875 };
1876 
1877 int tcp_mmap(struct file *file, struct socket *sock,
1878 	     struct vm_area_struct *vma)
1879 {
1880 	if (vma->vm_flags & (VM_WRITE | VM_EXEC))
1881 		return -EPERM;
1882 	vm_flags_clear(vma, VM_MAYWRITE | VM_MAYEXEC);
1883 
1884 	/* Instruct vm_insert_page() to not mmap_read_lock(mm) */
1885 	vm_flags_set(vma, VM_MIXEDMAP);
1886 
1887 	vma->vm_ops = &tcp_vm_ops;
1888 	return 0;
1889 }
1890 
1891 static skb_frag_t *skb_advance_to_frag(struct sk_buff *skb, u32 offset_skb,
1892 				       u32 *offset_frag)
1893 {
1894 	skb_frag_t *frag;
1895 
1896 	if (unlikely(offset_skb >= skb->len))
1897 		return NULL;
1898 
1899 	offset_skb -= skb_headlen(skb);
1900 	if ((int)offset_skb < 0 || skb_has_frag_list(skb))
1901 		return NULL;
1902 
1903 	frag = skb_shinfo(skb)->frags;
1904 	while (offset_skb) {
1905 		if (skb_frag_size(frag) > offset_skb) {
1906 			*offset_frag = offset_skb;
1907 			return frag;
1908 		}
1909 		offset_skb -= skb_frag_size(frag);
1910 		++frag;
1911 	}
1912 	*offset_frag = 0;
1913 	return frag;
1914 }
1915 
1916 static bool can_map_frag(const skb_frag_t *frag)
1917 {
1918 	struct page *page;
1919 
1920 	if (skb_frag_size(frag) != PAGE_SIZE || skb_frag_off(frag))
1921 		return false;
1922 	if (skb_frag_is_net_iov(frag))
1923 		return false;
1924 
1925 	page = skb_frag_page(frag);
1926 
1927 	if (PageCompound(page) || page->mapping)
1928 		return false;
1929 
1930 	return true;
1931 }
1932 
1933 static int find_next_mappable_frag(const skb_frag_t *frag,
1934 				   int remaining_in_skb)
1935 {
1936 	int offset = 0;
1937 
1938 	if (likely(can_map_frag(frag)))
1939 		return 0;
1940 
1941 	while (offset < remaining_in_skb && !can_map_frag(frag)) {
1942 		offset += skb_frag_size(frag);
1943 		++frag;
1944 	}
1945 	return offset;
1946 }
1947 
1948 static void tcp_zerocopy_set_hint_for_skb(struct sock *sk,
1949 					  struct tcp_zerocopy_receive *zc,
1950 					  struct sk_buff *skb, u32 offset)
1951 {
1952 	u32 frag_offset, partial_frag_remainder = 0;
1953 	int mappable_offset;
1954 	skb_frag_t *frag;
1955 
1956 	/* worst case: skip to next skb. try to improve on this case below */
1957 	zc->recv_skip_hint = skb->len - offset;
1958 
1959 	/* Find the frag containing this offset (and how far into that frag) */
1960 	frag = skb_advance_to_frag(skb, offset, &frag_offset);
1961 	if (!frag)
1962 		return;
1963 
1964 	if (frag_offset) {
1965 		struct skb_shared_info *info = skb_shinfo(skb);
1966 
1967 		/* We read part of the last frag, must recvmsg() rest of skb. */
1968 		if (frag == &info->frags[info->nr_frags - 1])
1969 			return;
1970 
1971 		/* Else, we must at least read the remainder in this frag. */
1972 		partial_frag_remainder = skb_frag_size(frag) - frag_offset;
1973 		zc->recv_skip_hint -= partial_frag_remainder;
1974 		++frag;
1975 	}
1976 
1977 	/* partial_frag_remainder: If part way through a frag, must read rest.
1978 	 * mappable_offset: Bytes till next mappable frag, *not* counting bytes
1979 	 * in partial_frag_remainder.
1980 	 */
1981 	mappable_offset = find_next_mappable_frag(frag, zc->recv_skip_hint);
1982 	zc->recv_skip_hint = mappable_offset + partial_frag_remainder;
1983 }
1984 
1985 static int tcp_recvmsg_locked(struct sock *sk, struct msghdr *msg, size_t len,
1986 			      int flags, struct scm_timestamping_internal *tss,
1987 			      int *cmsg_flags);
1988 static int receive_fallback_to_copy(struct sock *sk,
1989 				    struct tcp_zerocopy_receive *zc, int inq,
1990 				    struct scm_timestamping_internal *tss)
1991 {
1992 	unsigned long copy_address = (unsigned long)zc->copybuf_address;
1993 	struct msghdr msg = {};
1994 	int err;
1995 
1996 	zc->length = 0;
1997 	zc->recv_skip_hint = 0;
1998 
1999 	if (copy_address != zc->copybuf_address)
2000 		return -EINVAL;
2001 
2002 	err = import_ubuf(ITER_DEST, (void __user *)copy_address, inq,
2003 			  &msg.msg_iter);
2004 	if (err)
2005 		return err;
2006 
2007 	err = tcp_recvmsg_locked(sk, &msg, inq, MSG_DONTWAIT,
2008 				 tss, &zc->msg_flags);
2009 	if (err < 0)
2010 		return err;
2011 
2012 	zc->copybuf_len = err;
2013 	if (likely(zc->copybuf_len)) {
2014 		struct sk_buff *skb;
2015 		u32 offset;
2016 
2017 		skb = tcp_recv_skb(sk, tcp_sk(sk)->copied_seq, &offset);
2018 		if (skb)
2019 			tcp_zerocopy_set_hint_for_skb(sk, zc, skb, offset);
2020 	}
2021 	return 0;
2022 }
2023 
2024 static int tcp_copy_straggler_data(struct tcp_zerocopy_receive *zc,
2025 				   struct sk_buff *skb, u32 copylen,
2026 				   u32 *offset, u32 *seq)
2027 {
2028 	unsigned long copy_address = (unsigned long)zc->copybuf_address;
2029 	struct msghdr msg = {};
2030 	int err;
2031 
2032 	if (copy_address != zc->copybuf_address)
2033 		return -EINVAL;
2034 
2035 	err = import_ubuf(ITER_DEST, (void __user *)copy_address, copylen,
2036 			  &msg.msg_iter);
2037 	if (err)
2038 		return err;
2039 	err = skb_copy_datagram_msg(skb, *offset, &msg, copylen);
2040 	if (err)
2041 		return err;
2042 	zc->recv_skip_hint -= copylen;
2043 	*offset += copylen;
2044 	*seq += copylen;
2045 	return (__s32)copylen;
2046 }
2047 
2048 static int tcp_zc_handle_leftover(struct tcp_zerocopy_receive *zc,
2049 				  struct sock *sk,
2050 				  struct sk_buff *skb,
2051 				  u32 *seq,
2052 				  s32 copybuf_len,
2053 				  struct scm_timestamping_internal *tss)
2054 {
2055 	u32 offset, copylen = min_t(u32, copybuf_len, zc->recv_skip_hint);
2056 
2057 	if (!copylen)
2058 		return 0;
2059 	/* skb is null if inq < PAGE_SIZE. */
2060 	if (skb) {
2061 		offset = *seq - TCP_SKB_CB(skb)->seq;
2062 	} else {
2063 		skb = tcp_recv_skb(sk, *seq, &offset);
2064 		if (TCP_SKB_CB(skb)->has_rxtstamp) {
2065 			tcp_update_recv_tstamps(skb, tss);
2066 			zc->msg_flags |= TCP_CMSG_TS;
2067 		}
2068 	}
2069 
2070 	zc->copybuf_len = tcp_copy_straggler_data(zc, skb, copylen, &offset,
2071 						  seq);
2072 	return zc->copybuf_len < 0 ? 0 : copylen;
2073 }
2074 
2075 static int tcp_zerocopy_vm_insert_batch_error(struct vm_area_struct *vma,
2076 					      struct page **pending_pages,
2077 					      unsigned long pages_remaining,
2078 					      unsigned long *address,
2079 					      u32 *length,
2080 					      u32 *seq,
2081 					      struct tcp_zerocopy_receive *zc,
2082 					      u32 total_bytes_to_map,
2083 					      int err)
2084 {
2085 	/* At least one page did not map. Try zapping if we skipped earlier. */
2086 	if (err == -EBUSY &&
2087 	    zc->flags & TCP_RECEIVE_ZEROCOPY_FLAG_TLB_CLEAN_HINT) {
2088 		u32 maybe_zap_len;
2089 
2090 		maybe_zap_len = total_bytes_to_map -  /* All bytes to map */
2091 				*length + /* Mapped or pending */
2092 				(pages_remaining * PAGE_SIZE); /* Failed map. */
2093 		zap_vma_range(vma, *address, maybe_zap_len);
2094 		err = 0;
2095 	}
2096 
2097 	if (!err) {
2098 		unsigned long leftover_pages = pages_remaining;
2099 		int bytes_mapped;
2100 
2101 		/* We called zap_vma_range, try to reinsert. */
2102 		err = vm_insert_pages(vma, *address,
2103 				      pending_pages,
2104 				      &pages_remaining);
2105 		bytes_mapped = PAGE_SIZE * (leftover_pages - pages_remaining);
2106 		*seq += bytes_mapped;
2107 		*address += bytes_mapped;
2108 	}
2109 	if (err) {
2110 		/* Either we were unable to zap, OR we zapped, retried an
2111 		 * insert, and still had an issue. Either ways, pages_remaining
2112 		 * is the number of pages we were unable to map, and we unroll
2113 		 * some state we speculatively touched before.
2114 		 */
2115 		const int bytes_not_mapped = PAGE_SIZE * pages_remaining;
2116 
2117 		*length -= bytes_not_mapped;
2118 		zc->recv_skip_hint += bytes_not_mapped;
2119 	}
2120 	return err;
2121 }
2122 
2123 static int tcp_zerocopy_vm_insert_batch(struct vm_area_struct *vma,
2124 					struct page **pages,
2125 					unsigned int pages_to_map,
2126 					unsigned long *address,
2127 					u32 *length,
2128 					u32 *seq,
2129 					struct tcp_zerocopy_receive *zc,
2130 					u32 total_bytes_to_map)
2131 {
2132 	unsigned long pages_remaining = pages_to_map;
2133 	unsigned int pages_mapped;
2134 	unsigned int bytes_mapped;
2135 	int err;
2136 
2137 	err = vm_insert_pages(vma, *address, pages, &pages_remaining);
2138 	pages_mapped = pages_to_map - (unsigned int)pages_remaining;
2139 	bytes_mapped = PAGE_SIZE * pages_mapped;
2140 	/* Even if vm_insert_pages fails, it may have partially succeeded in
2141 	 * mapping (some but not all of the pages).
2142 	 */
2143 	*seq += bytes_mapped;
2144 	*address += bytes_mapped;
2145 
2146 	if (likely(!err))
2147 		return 0;
2148 
2149 	/* Error: maybe zap and retry + rollback state for failed inserts. */
2150 	return tcp_zerocopy_vm_insert_batch_error(vma, pages + pages_mapped,
2151 		pages_remaining, address, length, seq, zc, total_bytes_to_map,
2152 		err);
2153 }
2154 
2155 #define TCP_VALID_ZC_MSG_FLAGS   (TCP_CMSG_TS)
2156 static void tcp_zc_finalize_rx_tstamp(struct sock *sk,
2157 				      struct tcp_zerocopy_receive *zc,
2158 				      struct scm_timestamping_internal *tss)
2159 {
2160 	unsigned long msg_control_addr;
2161 	struct msghdr cmsg_dummy;
2162 
2163 	msg_control_addr = (unsigned long)zc->msg_control;
2164 	cmsg_dummy.msg_control_user = (void __user *)msg_control_addr;
2165 	cmsg_dummy.msg_controllen =
2166 		(__kernel_size_t)zc->msg_controllen;
2167 	cmsg_dummy.msg_flags = in_compat_syscall()
2168 		? MSG_CMSG_COMPAT : 0;
2169 	cmsg_dummy.msg_control_is_user = true;
2170 	zc->msg_flags = 0;
2171 	if (zc->msg_control == msg_control_addr &&
2172 	    zc->msg_controllen == cmsg_dummy.msg_controllen) {
2173 		tcp_recv_timestamp(&cmsg_dummy, sk, tss);
2174 		zc->msg_control = (__u64)
2175 			((uintptr_t)cmsg_dummy.msg_control_user);
2176 		zc->msg_controllen =
2177 			(__u64)cmsg_dummy.msg_controllen;
2178 		zc->msg_flags = (__u32)cmsg_dummy.msg_flags;
2179 	}
2180 }
2181 
2182 static struct vm_area_struct *find_tcp_vma(struct mm_struct *mm,
2183 					   unsigned long address)
2184 {
2185 	struct vm_area_struct *vma = vma_start_read_unlocked(mm, address);
2186 
2187 	if (!vma)
2188 		return NULL;
2189 
2190 	if (vma->vm_ops != &tcp_vm_ops) {
2191 		vma_end_read(vma);
2192 		return NULL;
2193 	}
2194 
2195 	return vma;
2196 }
2197 
2198 #define TCP_ZEROCOPY_PAGE_BATCH_SIZE 32
2199 static int tcp_zerocopy_receive(struct sock *sk,
2200 				struct tcp_zerocopy_receive *zc,
2201 				struct scm_timestamping_internal *tss)
2202 {
2203 	u32 length = 0, offset, vma_len, avail_len, copylen = 0;
2204 	unsigned long address = (unsigned long)zc->address;
2205 	struct page *pages[TCP_ZEROCOPY_PAGE_BATCH_SIZE];
2206 	s32 copybuf_len = zc->copybuf_len;
2207 	struct tcp_sock *tp = tcp_sk(sk);
2208 	const skb_frag_t *frags = NULL;
2209 	unsigned int pages_to_map = 0;
2210 	struct vm_area_struct *vma;
2211 	struct sk_buff *skb = NULL;
2212 	u32 seq = tp->copied_seq;
2213 	u32 total_bytes_to_map;
2214 	int inq = tcp_inq(sk);
2215 	int ret;
2216 
2217 	zc->copybuf_len = 0;
2218 	zc->msg_flags = 0;
2219 
2220 	if (address & (PAGE_SIZE - 1) || address != zc->address)
2221 		return -EINVAL;
2222 
2223 	if (sk->sk_state == TCP_LISTEN)
2224 		return -ENOTCONN;
2225 
2226 	sock_rps_record_flow(sk);
2227 
2228 	if (inq && inq <= copybuf_len)
2229 		return receive_fallback_to_copy(sk, zc, inq, tss);
2230 
2231 	if (inq < PAGE_SIZE) {
2232 		zc->length = 0;
2233 		zc->recv_skip_hint = inq;
2234 		if (!inq && sock_flag(sk, SOCK_DONE))
2235 			return -EIO;
2236 		return 0;
2237 	}
2238 
2239 	vma = find_tcp_vma(current->mm, address);
2240 	if (!vma)
2241 		return -EINVAL;
2242 
2243 	vma_len = min_t(unsigned long, zc->length, vma->vm_end - address);
2244 	avail_len = min_t(u32, vma_len, inq);
2245 	total_bytes_to_map = avail_len & ~(PAGE_SIZE - 1);
2246 	if (total_bytes_to_map) {
2247 		if (!(zc->flags & TCP_RECEIVE_ZEROCOPY_FLAG_TLB_CLEAN_HINT))
2248 			zap_vma_range(vma, address, total_bytes_to_map);
2249 		zc->length = total_bytes_to_map;
2250 		zc->recv_skip_hint = 0;
2251 	} else {
2252 		zc->length = avail_len;
2253 		zc->recv_skip_hint = avail_len;
2254 	}
2255 	ret = 0;
2256 	while (length + PAGE_SIZE <= zc->length) {
2257 		int mappable_offset;
2258 		struct page *page;
2259 
2260 		if (zc->recv_skip_hint < PAGE_SIZE) {
2261 			u32 offset_frag;
2262 
2263 			if (skb) {
2264 				if (zc->recv_skip_hint > 0)
2265 					break;
2266 				skb = skb->next;
2267 				offset = seq - TCP_SKB_CB(skb)->seq;
2268 			} else {
2269 				skb = tcp_recv_skb(sk, seq, &offset);
2270 			}
2271 
2272 			if (!skb_frags_readable(skb))
2273 				break;
2274 
2275 			if (TCP_SKB_CB(skb)->has_rxtstamp) {
2276 				tcp_update_recv_tstamps(skb, tss);
2277 				zc->msg_flags |= TCP_CMSG_TS;
2278 			}
2279 			zc->recv_skip_hint = skb->len - offset;
2280 			frags = skb_advance_to_frag(skb, offset, &offset_frag);
2281 			if (!frags || offset_frag)
2282 				break;
2283 		}
2284 
2285 		mappable_offset = find_next_mappable_frag(frags,
2286 							  zc->recv_skip_hint);
2287 		if (mappable_offset) {
2288 			zc->recv_skip_hint = mappable_offset;
2289 			break;
2290 		}
2291 		page = skb_frag_page(frags);
2292 		if (WARN_ON_ONCE(!page))
2293 			break;
2294 
2295 		prefetchw(page);
2296 		pages[pages_to_map++] = page;
2297 		length += PAGE_SIZE;
2298 		zc->recv_skip_hint -= PAGE_SIZE;
2299 		frags++;
2300 		if (pages_to_map == TCP_ZEROCOPY_PAGE_BATCH_SIZE ||
2301 		    zc->recv_skip_hint < PAGE_SIZE) {
2302 			/* Either full batch, or we're about to go to next skb
2303 			 * (and we cannot unroll failed ops across skbs).
2304 			 */
2305 			ret = tcp_zerocopy_vm_insert_batch(vma, pages,
2306 							   pages_to_map,
2307 							   &address, &length,
2308 							   &seq, zc,
2309 							   total_bytes_to_map);
2310 			if (ret)
2311 				goto out;
2312 			pages_to_map = 0;
2313 		}
2314 	}
2315 	if (pages_to_map) {
2316 		ret = tcp_zerocopy_vm_insert_batch(vma, pages, pages_to_map,
2317 						   &address, &length, &seq,
2318 						   zc, total_bytes_to_map);
2319 	}
2320 out:
2321 	vma_end_read(vma);
2322 	/* Try to copy straggler data. */
2323 	if (!ret)
2324 		copylen = tcp_zc_handle_leftover(zc, sk, skb, &seq, copybuf_len, tss);
2325 
2326 	if (length + copylen) {
2327 		WRITE_ONCE(tp->copied_seq, seq);
2328 		tcp_rcv_space_adjust(sk);
2329 
2330 		/* Clean up data we have read: This will do ACK frames. */
2331 		tcp_recv_skb(sk, seq, &offset);
2332 		tcp_cleanup_rbuf(sk, length + copylen);
2333 		ret = 0;
2334 		if (length == zc->length)
2335 			zc->recv_skip_hint = 0;
2336 	} else {
2337 		if (!zc->recv_skip_hint && sock_flag(sk, SOCK_DONE))
2338 			ret = -EIO;
2339 	}
2340 	zc->length = length;
2341 	return ret;
2342 }
2343 #endif
2344 
2345 /* Similar to __sock_recv_timestamp, but does not require an skb */
2346 void tcp_recv_timestamp(struct msghdr *msg, const struct sock *sk,
2347 			struct scm_timestamping_internal *tss)
2348 {
2349 	int new_tstamp = sock_flag(sk, SOCK_TSTAMP_NEW);
2350 	u32 tsflags = READ_ONCE(sk->sk_tsflags);
2351 
2352 	if (tss->ts[0]) {
2353 		if (sock_flag(sk, SOCK_RCVTSTAMP)) {
2354 			struct timespec64 tv = ktime_to_timespec64(tss->ts[0]);
2355 
2356 			if (sock_flag(sk, SOCK_RCVTSTAMPNS)) {
2357 				if (new_tstamp) {
2358 					struct __kernel_timespec kts = {
2359 						.tv_sec = tv.tv_sec,
2360 						.tv_nsec = tv.tv_nsec,
2361 					};
2362 					put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMPNS_NEW,
2363 						 sizeof(kts), &kts);
2364 				} else {
2365 					struct __kernel_old_timespec ts_old = {
2366 						.tv_sec = tv.tv_sec,
2367 						.tv_nsec = tv.tv_nsec,
2368 					};
2369 					put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMPNS_OLD,
2370 						 sizeof(ts_old), &ts_old);
2371 				}
2372 			} else {
2373 				if (new_tstamp) {
2374 					struct __kernel_sock_timeval stv = {
2375 						.tv_sec = tv.tv_sec,
2376 						.tv_usec = tv.tv_nsec / 1000,
2377 					};
2378 					put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_NEW,
2379 						 sizeof(stv), &stv);
2380 				} else {
2381 					struct __kernel_old_timeval otv = {
2382 						.tv_sec = tv.tv_sec,
2383 						.tv_usec = tv.tv_nsec / 1000,
2384 					};
2385 					put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_OLD,
2386 						 sizeof(otv), &otv);
2387 				}
2388 			}
2389 		}
2390 
2391 		if (!(tsflags & SOF_TIMESTAMPING_SOFTWARE &&
2392 		    (tsflags & SOF_TIMESTAMPING_RX_SOFTWARE ||
2393 		     !(tsflags & SOF_TIMESTAMPING_OPT_RX_FILTER))))
2394 			tss->ts[0] = 0;
2395 	}
2396 
2397 	if (tss->ts[2]) {
2398 		if (!(tsflags & SOF_TIMESTAMPING_RAW_HARDWARE &&
2399 		    (tsflags & SOF_TIMESTAMPING_RX_HARDWARE ||
2400 		     !(tsflags & SOF_TIMESTAMPING_OPT_RX_FILTER))))
2401 			tss->ts[2] = 0;
2402 	}
2403 
2404 	if (tss->ts[0] | tss->ts[2]) {
2405 		tss->ts[1] = 0;
2406 		if (sock_flag(sk, SOCK_TSTAMP_NEW))
2407 			put_cmsg_scm_timestamping64(msg, tss);
2408 		else
2409 			put_cmsg_scm_timestamping(msg, tss);
2410 	}
2411 }
2412 
2413 static int tcp_inq_hint(struct sock *sk)
2414 {
2415 	const struct tcp_sock *tp = tcp_sk(sk);
2416 	u32 copied_seq = READ_ONCE(tp->copied_seq);
2417 	u32 rcv_nxt = READ_ONCE(tp->rcv_nxt);
2418 	int inq;
2419 
2420 	inq = rcv_nxt - copied_seq;
2421 	if (unlikely(inq < 0 || copied_seq != READ_ONCE(tp->copied_seq))) {
2422 		lock_sock(sk);
2423 		inq = tp->rcv_nxt - tp->copied_seq;
2424 		release_sock(sk);
2425 	}
2426 	/* After receiving a FIN, tell the user-space to continue reading
2427 	 * by returning a non-zero inq.
2428 	 */
2429 	if (inq == 0 && sock_flag(sk, SOCK_DONE))
2430 		inq = 1;
2431 	return inq;
2432 }
2433 
2434 /* batch __xa_alloc() calls and reduce xa_lock()/xa_unlock() overhead. */
2435 struct tcp_xa_pool {
2436 	u8		max; /* max <= MAX_SKB_FRAGS */
2437 	u8		idx; /* idx <= max */
2438 	__u32		tokens[MAX_SKB_FRAGS];
2439 	netmem_ref	netmems[MAX_SKB_FRAGS];
2440 };
2441 
2442 static void tcp_xa_pool_commit_locked(struct sock *sk, struct tcp_xa_pool *p)
2443 {
2444 	int i;
2445 
2446 	/* Commit part that has been copied to user space. */
2447 	for (i = 0; i < p->idx; i++)
2448 		__xa_cmpxchg(&sk->sk_user_frags, p->tokens[i], XA_ZERO_ENTRY,
2449 			     (__force void *)p->netmems[i], GFP_KERNEL);
2450 	/* Rollback what has been pre-allocated and is no longer needed. */
2451 	for (; i < p->max; i++)
2452 		__xa_erase(&sk->sk_user_frags, p->tokens[i]);
2453 
2454 	p->max = 0;
2455 	p->idx = 0;
2456 }
2457 
2458 static void tcp_xa_pool_commit(struct sock *sk, struct tcp_xa_pool *p)
2459 {
2460 	if (!p->max)
2461 		return;
2462 
2463 	xa_lock_bh(&sk->sk_user_frags);
2464 
2465 	tcp_xa_pool_commit_locked(sk, p);
2466 
2467 	xa_unlock_bh(&sk->sk_user_frags);
2468 }
2469 
2470 static int tcp_xa_pool_refill(struct sock *sk, struct tcp_xa_pool *p,
2471 			      unsigned int max_frags)
2472 {
2473 	int err, k;
2474 
2475 	if (p->idx < p->max)
2476 		return 0;
2477 
2478 	xa_lock_bh(&sk->sk_user_frags);
2479 
2480 	tcp_xa_pool_commit_locked(sk, p);
2481 
2482 	for (k = 0; k < max_frags; k++) {
2483 		err = __xa_alloc(&sk->sk_user_frags, &p->tokens[k],
2484 				 XA_ZERO_ENTRY, xa_limit_31b, GFP_KERNEL);
2485 		if (err)
2486 			break;
2487 	}
2488 
2489 	xa_unlock_bh(&sk->sk_user_frags);
2490 
2491 	p->max = k;
2492 	p->idx = 0;
2493 	return k ? 0 : err;
2494 }
2495 
2496 /* On error, returns the -errno. On success, returns number of bytes sent to the
2497  * user. May not consume all of @remaining_len.
2498  */
2499 static int tcp_recvmsg_dmabuf(struct sock *sk, const struct sk_buff *skb,
2500 			      unsigned int offset, struct msghdr *msg,
2501 			      int remaining_len)
2502 {
2503 	struct dmabuf_cmsg dmabuf_cmsg = { 0 };
2504 	struct tcp_xa_pool tcp_xa_pool;
2505 	unsigned int start;
2506 	int i, copy, n;
2507 	int sent = 0;
2508 	int err = 0;
2509 
2510 	tcp_xa_pool.max = 0;
2511 	tcp_xa_pool.idx = 0;
2512 	do {
2513 		start = skb_headlen(skb);
2514 
2515 		if (skb_frags_readable(skb)) {
2516 			err = -ENODEV;
2517 			goto out;
2518 		}
2519 
2520 		/* Copy header. */
2521 		copy = start - offset;
2522 		if (copy > 0) {
2523 			copy = min(copy, remaining_len);
2524 
2525 			n = copy_to_iter(skb->data + offset, copy,
2526 					 &msg->msg_iter);
2527 			if (n != copy) {
2528 				err = -EFAULT;
2529 				goto out;
2530 			}
2531 
2532 			offset += copy;
2533 			remaining_len -= copy;
2534 
2535 			/* First a dmabuf_cmsg for # bytes copied to user
2536 			 * buffer.
2537 			 */
2538 			memset(&dmabuf_cmsg, 0, sizeof(dmabuf_cmsg));
2539 			dmabuf_cmsg.frag_size = copy;
2540 			err = put_cmsg_notrunc(msg, SOL_SOCKET,
2541 					       SO_DEVMEM_LINEAR,
2542 					       sizeof(dmabuf_cmsg),
2543 					       &dmabuf_cmsg);
2544 			if (err)
2545 				goto out;
2546 
2547 			sent += copy;
2548 
2549 			if (remaining_len == 0)
2550 				goto out;
2551 		}
2552 
2553 		/* after that, send information of dmabuf pages through a
2554 		 * sequence of cmsg
2555 		 */
2556 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2557 			skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2558 			netmem_ref netmem = skb_frag_netmem(frag);
2559 			struct net_iov *niov;
2560 			u64 frag_offset;
2561 			int end;
2562 
2563 			/* !skb_frags_readable() should indicate that ALL the
2564 			 * frags in this skb are dmabuf net_iovs. We're checking
2565 			 * for that flag above, but also check individual frags
2566 			 * here. If the tcp stack is not setting
2567 			 * skb_frags_readable() correctly, we still don't want
2568 			 * to crash here.
2569 			 */
2570 			if (!skb_frag_net_iov(frag)) {
2571 				net_err_ratelimited("Found non-dmabuf skb with net_iov");
2572 				err = -ENODEV;
2573 				goto out;
2574 			}
2575 
2576 			niov = skb_frag_net_iov(frag);
2577 			if (!net_is_devmem_iov(niov)) {
2578 				err = -ENODEV;
2579 				goto out;
2580 			}
2581 
2582 			end = start + skb_frag_size(frag);
2583 			copy = end - offset;
2584 
2585 			if (copy > 0) {
2586 				copy = min(copy, remaining_len);
2587 
2588 				frag_offset = net_iov_virtual_addr(niov) +
2589 					      skb_frag_off(frag) + offset -
2590 					      start;
2591 				dmabuf_cmsg.frag_offset = frag_offset;
2592 				dmabuf_cmsg.frag_size = copy;
2593 				err = tcp_xa_pool_refill(sk, &tcp_xa_pool,
2594 							 skb_shinfo(skb)->nr_frags - i);
2595 				if (err)
2596 					goto out;
2597 
2598 				/* Will perform the exchange later */
2599 				dmabuf_cmsg.frag_token = tcp_xa_pool.tokens[tcp_xa_pool.idx];
2600 				dmabuf_cmsg.dmabuf_id = net_devmem_iov_binding_id(niov);
2601 
2602 				offset += copy;
2603 				remaining_len -= copy;
2604 
2605 				err = put_cmsg_notrunc(msg, SOL_SOCKET,
2606 						       SO_DEVMEM_DMABUF,
2607 						       sizeof(dmabuf_cmsg),
2608 						       &dmabuf_cmsg);
2609 				if (err)
2610 					goto out;
2611 
2612 				WARN_ON_ONCE(!napi_pp_get_page(netmem));
2613 				tcp_xa_pool.netmems[tcp_xa_pool.idx++] = netmem;
2614 
2615 				sent += copy;
2616 
2617 				if (remaining_len == 0)
2618 					goto out;
2619 			}
2620 			start = end;
2621 		}
2622 
2623 		tcp_xa_pool_commit(sk, &tcp_xa_pool);
2624 		if (!remaining_len)
2625 			goto out;
2626 
2627 		/* if remaining_len is not satisfied yet, we need to go to the
2628 		 * next frag in the frag_list to satisfy remaining_len.
2629 		 */
2630 		skb = skb_shinfo(skb)->frag_list ?: skb->next;
2631 
2632 		offset = offset - start;
2633 	} while (skb);
2634 
2635 	if (remaining_len) {
2636 		err = -EFAULT;
2637 		goto out;
2638 	}
2639 
2640 out:
2641 	tcp_xa_pool_commit(sk, &tcp_xa_pool);
2642 	if (!sent)
2643 		sent = err;
2644 
2645 	return sent;
2646 }
2647 
2648 /*
2649  *	This routine copies from a sock struct into the user buffer.
2650  *
2651  *	Technical note: in 2.3 we work on _locked_ socket, so that
2652  *	tricks with *seq access order and skb->users are not required.
2653  *	Probably, code can be easily improved even more.
2654  */
2655 
2656 static int tcp_recvmsg_locked(struct sock *sk, struct msghdr *msg, size_t len,
2657 			      int flags, struct scm_timestamping_internal *tss,
2658 			      int *cmsg_flags)
2659 {
2660 	struct tcp_sock *tp = tcp_sk(sk);
2661 	int last_copied_dmabuf = -1; /* uninitialized */
2662 	int copied = 0;
2663 	u32 peek_seq;
2664 	u32 *seq;
2665 	unsigned long used;
2666 	int err;
2667 	int target;		/* Read at least this many bytes */
2668 	long timeo;
2669 	struct sk_buff *skb, *last;
2670 	u32 peek_offset = 0;
2671 	u32 urg_hole = 0;
2672 
2673 	err = -ENOTCONN;
2674 	if (sk->sk_state == TCP_LISTEN)
2675 		goto out;
2676 
2677 	if (tp->recvmsg_inq)
2678 		*cmsg_flags = TCP_CMSG_INQ;
2679 	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2680 
2681 	/* Urgent data needs to be handled specially. */
2682 	if (flags & MSG_OOB)
2683 		goto recv_urg;
2684 
2685 	if (unlikely(tp->repair)) {
2686 		err = -EPERM;
2687 		if (!(flags & MSG_PEEK))
2688 			goto out;
2689 
2690 		if (tp->repair_queue == TCP_SEND_QUEUE)
2691 			goto recv_sndq;
2692 
2693 		err = -EINVAL;
2694 		if (tp->repair_queue == TCP_NO_QUEUE)
2695 			goto out;
2696 
2697 		/* 'common' recv queue MSG_PEEK-ing */
2698 	}
2699 
2700 	seq = &tp->copied_seq;
2701 	if (flags & MSG_PEEK) {
2702 		peek_offset = max(sk_peek_offset(sk, flags), 0);
2703 		peek_seq = tp->copied_seq + peek_offset;
2704 		seq = &peek_seq;
2705 	}
2706 
2707 	target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
2708 
2709 	do {
2710 		u32 offset;
2711 
2712 		/* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */
2713 		if (unlikely(tp->urg_data) && tp->urg_seq == *seq) {
2714 			if (copied)
2715 				break;
2716 			if (signal_pending(current)) {
2717 				copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
2718 				break;
2719 			}
2720 		}
2721 
2722 		/* Next get a buffer. */
2723 
2724 		last = skb_peek_tail(&sk->sk_receive_queue);
2725 		skb_queue_walk(&sk->sk_receive_queue, skb) {
2726 			last = skb;
2727 			/* Now that we have two receive queues this
2728 			 * shouldn't happen.
2729 			 */
2730 			if (WARN(before(*seq, TCP_SKB_CB(skb)->seq),
2731 				 "TCP recvmsg seq # bug: copied %X, seq %X, rcvnxt %X, fl %X\n",
2732 				 *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt,
2733 				 flags))
2734 				break;
2735 
2736 			offset = *seq - TCP_SKB_CB(skb)->seq;
2737 			if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
2738 				pr_err_once("%s: found a SYN, please report !\n", __func__);
2739 				offset--;
2740 			}
2741 			if (offset < skb->len)
2742 				goto found_ok_skb;
2743 			if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
2744 				goto found_fin_ok;
2745 			WARN(!(flags & MSG_PEEK),
2746 			     "TCP recvmsg seq # bug 2: copied %X, seq %X, rcvnxt %X, fl %X\n",
2747 			     *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags);
2748 		}
2749 
2750 		/* Well, if we have backlog, try to process it now yet. */
2751 
2752 		if (copied >= target && !READ_ONCE(sk->sk_backlog.tail))
2753 			break;
2754 
2755 		if (copied) {
2756 			if (!timeo ||
2757 			    tcp_recv_should_stop(sk))
2758 				break;
2759 		} else {
2760 			if (sock_flag(sk, SOCK_DONE))
2761 				break;
2762 
2763 			copied = sock_error(sk);
2764 			if (copied)
2765 				break;
2766 
2767 			if (sk->sk_shutdown & RCV_SHUTDOWN)
2768 				break;
2769 
2770 			if (sk->sk_state == TCP_CLOSE) {
2771 				/* This occurs when user tries to read
2772 				 * from never connected socket.
2773 				 */
2774 				copied = -ENOTCONN;
2775 				break;
2776 			}
2777 
2778 			if (!timeo) {
2779 				copied = -EAGAIN;
2780 				break;
2781 			}
2782 
2783 			if (signal_pending(current)) {
2784 				copied = sock_intr_errno(timeo);
2785 				break;
2786 			}
2787 		}
2788 
2789 		if (copied >= target) {
2790 			/* Do not sleep, just process backlog. */
2791 			__sk_flush_backlog(sk);
2792 		} else {
2793 			tcp_cleanup_rbuf(sk, copied);
2794 			err = sk_wait_data(sk, &timeo, last);
2795 			if (err < 0) {
2796 				err = copied ? : err;
2797 				goto out;
2798 			}
2799 		}
2800 
2801 		if ((flags & MSG_PEEK) &&
2802 		    (peek_seq - peek_offset - copied - urg_hole != tp->copied_seq)) {
2803 			net_dbg_ratelimited("TCP(%s:%d): Application bug, race in MSG_PEEK\n",
2804 					    current->comm,
2805 					    task_pid_nr(current));
2806 			peek_seq = tp->copied_seq + peek_offset;
2807 		}
2808 		continue;
2809 
2810 found_ok_skb:
2811 		/* Ok so how much can we use? */
2812 		used = skb->len - offset;
2813 		if (len < used)
2814 			used = len;
2815 
2816 		/* Do we have urgent data here? */
2817 		if (unlikely(tp->urg_data)) {
2818 			u32 urg_offset = tp->urg_seq - *seq;
2819 			if (urg_offset < used) {
2820 				if (!urg_offset) {
2821 					if (!sock_flag(sk, SOCK_URGINLINE)) {
2822 						WRITE_ONCE(*seq, *seq + 1);
2823 						urg_hole++;
2824 						offset++;
2825 						used--;
2826 						if (!used)
2827 							goto skip_copy;
2828 					}
2829 				} else
2830 					used = urg_offset;
2831 			}
2832 		}
2833 
2834 		if (!(flags & MSG_TRUNC)) {
2835 			if (last_copied_dmabuf != -1 &&
2836 			    last_copied_dmabuf != !skb_frags_readable(skb))
2837 				break;
2838 
2839 			if (skb_frags_readable(skb)) {
2840 				err = skb_copy_datagram_msg(skb, offset, msg,
2841 							    used);
2842 				if (err) {
2843 					/* Exception. Bailout! */
2844 					if (!copied)
2845 						copied = -EFAULT;
2846 					break;
2847 				}
2848 			} else {
2849 				if (!(flags & MSG_SOCK_DEVMEM)) {
2850 					/* dmabuf skbs can only be received
2851 					 * with the MSG_SOCK_DEVMEM flag.
2852 					 */
2853 					if (!copied)
2854 						copied = -EFAULT;
2855 
2856 					break;
2857 				}
2858 
2859 				err = tcp_recvmsg_dmabuf(sk, skb, offset, msg,
2860 							 used);
2861 				if (err < 0) {
2862 					if (!copied)
2863 						copied = err;
2864 
2865 					break;
2866 				}
2867 				used = err;
2868 			}
2869 		}
2870 
2871 		last_copied_dmabuf = !skb_frags_readable(skb);
2872 
2873 		WRITE_ONCE(*seq, *seq + used);
2874 		copied += used;
2875 		len -= used;
2876 		if (flags & MSG_PEEK)
2877 			sk_peek_offset_fwd(sk, used);
2878 		else
2879 			sk_peek_offset_bwd(sk, used);
2880 		tcp_rcv_space_adjust(sk);
2881 
2882 skip_copy:
2883 		if (unlikely(tp->urg_data) && after(tp->copied_seq, tp->urg_seq)) {
2884 			WRITE_ONCE(tp->urg_data, 0);
2885 			tcp_fast_path_check(sk);
2886 		}
2887 
2888 		if (TCP_SKB_CB(skb)->has_rxtstamp) {
2889 			tcp_update_recv_tstamps(skb, tss);
2890 			*cmsg_flags |= TCP_CMSG_TS;
2891 		}
2892 
2893 		if (used + offset < skb->len)
2894 			continue;
2895 
2896 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
2897 			goto found_fin_ok;
2898 		if (!(flags & MSG_PEEK))
2899 			tcp_eat_recv_skb(sk, skb);
2900 		continue;
2901 
2902 found_fin_ok:
2903 		/* Process the FIN. */
2904 		WRITE_ONCE(*seq, *seq + 1);
2905 		if (!(flags & MSG_PEEK))
2906 			tcp_eat_recv_skb(sk, skb);
2907 		break;
2908 	} while (len > 0);
2909 
2910 	/* According to UNIX98, msg_name/msg_namelen are ignored
2911 	 * on connected socket. I was just happy when found this 8) --ANK
2912 	 */
2913 
2914 	/* Clean up data we have read: This will do ACK frames. */
2915 	tcp_cleanup_rbuf(sk, copied);
2916 	return copied;
2917 
2918 out:
2919 	return err;
2920 
2921 recv_urg:
2922 	err = tcp_recv_urg(sk, msg, len, flags);
2923 	goto out;
2924 
2925 recv_sndq:
2926 	err = tcp_peek_sndq(sk, msg, len);
2927 	goto out;
2928 }
2929 
2930 int tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags)
2931 {
2932 	int cmsg_flags = 0, ret;
2933 	struct scm_timestamping_internal tss;
2934 
2935 	if (unlikely(flags & MSG_ERRQUEUE))
2936 		return inet_recv_error(sk, msg, len);
2937 
2938 	if (sk_can_busy_loop(sk) &&
2939 	    skb_queue_empty_lockless(&sk->sk_receive_queue) &&
2940 	    sk->sk_state == TCP_ESTABLISHED)
2941 		sk_busy_loop(sk, flags & MSG_DONTWAIT);
2942 
2943 	lock_sock(sk);
2944 	ret = tcp_recvmsg_locked(sk, msg, len, flags, &tss, &cmsg_flags);
2945 	release_sock(sk);
2946 
2947 	if ((cmsg_flags | msg->msg_get_inq) && ret >= 0) {
2948 		if (cmsg_flags & TCP_CMSG_TS)
2949 			tcp_recv_timestamp(msg, sk, &tss);
2950 		if ((cmsg_flags & TCP_CMSG_INQ) | msg->msg_get_inq) {
2951 			msg->msg_inq = tcp_inq_hint(sk);
2952 			if (cmsg_flags & TCP_CMSG_INQ)
2953 				put_cmsg(msg, SOL_TCP, TCP_CM_INQ,
2954 					 sizeof(msg->msg_inq), &msg->msg_inq);
2955 		}
2956 	}
2957 	return ret;
2958 }
2959 
2960 void tcp_set_state(struct sock *sk, int state)
2961 {
2962 	int oldstate = sk->sk_state;
2963 
2964 	/* We defined a new enum for TCP states that are exported in BPF
2965 	 * so as not force the internal TCP states to be frozen. The
2966 	 * following checks will detect if an internal state value ever
2967 	 * differs from the BPF value. If this ever happens, then we will
2968 	 * need to remap the internal value to the BPF value before calling
2969 	 * tcp_call_bpf_2arg.
2970 	 */
2971 	BUILD_BUG_ON((int)BPF_TCP_ESTABLISHED != (int)TCP_ESTABLISHED);
2972 	BUILD_BUG_ON((int)BPF_TCP_SYN_SENT != (int)TCP_SYN_SENT);
2973 	BUILD_BUG_ON((int)BPF_TCP_SYN_RECV != (int)TCP_SYN_RECV);
2974 	BUILD_BUG_ON((int)BPF_TCP_FIN_WAIT1 != (int)TCP_FIN_WAIT1);
2975 	BUILD_BUG_ON((int)BPF_TCP_FIN_WAIT2 != (int)TCP_FIN_WAIT2);
2976 	BUILD_BUG_ON((int)BPF_TCP_TIME_WAIT != (int)TCP_TIME_WAIT);
2977 	BUILD_BUG_ON((int)BPF_TCP_CLOSE != (int)TCP_CLOSE);
2978 	BUILD_BUG_ON((int)BPF_TCP_CLOSE_WAIT != (int)TCP_CLOSE_WAIT);
2979 	BUILD_BUG_ON((int)BPF_TCP_LAST_ACK != (int)TCP_LAST_ACK);
2980 	BUILD_BUG_ON((int)BPF_TCP_LISTEN != (int)TCP_LISTEN);
2981 	BUILD_BUG_ON((int)BPF_TCP_CLOSING != (int)TCP_CLOSING);
2982 	BUILD_BUG_ON((int)BPF_TCP_NEW_SYN_RECV != (int)TCP_NEW_SYN_RECV);
2983 	BUILD_BUG_ON((int)BPF_TCP_BOUND_INACTIVE != (int)TCP_BOUND_INACTIVE);
2984 	BUILD_BUG_ON((int)BPF_TCP_MAX_STATES != (int)TCP_MAX_STATES);
2985 
2986 	/* bpf uapi header bpf.h defines an anonymous enum with values
2987 	 * BPF_TCP_* used by bpf programs. Currently gcc built vmlinux
2988 	 * is able to emit this enum in DWARF due to the above BUILD_BUG_ON.
2989 	 * But clang built vmlinux does not have this enum in DWARF
2990 	 * since clang removes the above code before generating IR/debuginfo.
2991 	 * Let us explicitly emit the type debuginfo to ensure the
2992 	 * above-mentioned anonymous enum in the vmlinux DWARF and hence BTF
2993 	 * regardless of which compiler is used.
2994 	 */
2995 	BTF_TYPE_EMIT_ENUM(BPF_TCP_ESTABLISHED);
2996 
2997 	tcp_call_bpf_flag(sk, BPF_SOCK_OPS_STATE_CB, oldstate, state);
2998 	bpf_tcp_ops_call(set_state, sk, state);
2999 
3000 	switch (state) {
3001 	case TCP_ESTABLISHED:
3002 		if (oldstate != TCP_ESTABLISHED)
3003 			TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
3004 		break;
3005 	case TCP_CLOSE_WAIT:
3006 		if (oldstate == TCP_SYN_RECV)
3007 			TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
3008 		break;
3009 
3010 	case TCP_CLOSE:
3011 		if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED)
3012 			TCP_INC_STATS(sock_net(sk), TCP_MIB_ESTABRESETS);
3013 
3014 		sk->sk_prot->unhash(sk);
3015 		if (inet_csk(sk)->icsk_bind_hash &&
3016 		    !(sk->sk_userlocks & SOCK_BINDPORT_LOCK))
3017 			inet_put_port(sk);
3018 		fallthrough;
3019 	default:
3020 		if (oldstate == TCP_ESTABLISHED || oldstate == TCP_CLOSE_WAIT)
3021 			TCP_DEC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
3022 	}
3023 
3024 	/* Change state AFTER socket is unhashed to avoid closed
3025 	 * socket sitting in hash tables.
3026 	 */
3027 	inet_sk_state_store(sk, state);
3028 }
3029 
3030 /*
3031  *	State processing on a close. This implements the state shift for
3032  *	sending our FIN frame. Note that we only send a FIN for some
3033  *	states. A shutdown() may have already sent the FIN, or we may be
3034  *	closed.
3035  */
3036 
3037 static const unsigned char new_state[16] = {
3038   /* current state:        new state:      action:	*/
3039   [0 /* (Invalid) */]	= TCP_CLOSE,
3040   [TCP_ESTABLISHED]	= TCP_FIN_WAIT1 | TCP_ACTION_FIN,
3041   [TCP_SYN_SENT]	= TCP_CLOSE,
3042   [TCP_SYN_RECV]	= TCP_FIN_WAIT1 | TCP_ACTION_FIN,
3043   [TCP_FIN_WAIT1]	= TCP_FIN_WAIT1,
3044   [TCP_FIN_WAIT2]	= TCP_FIN_WAIT2,
3045   [TCP_TIME_WAIT]	= TCP_CLOSE,
3046   [TCP_CLOSE]		= TCP_CLOSE,
3047   [TCP_CLOSE_WAIT]	= TCP_LAST_ACK  | TCP_ACTION_FIN,
3048   [TCP_LAST_ACK]	= TCP_LAST_ACK,
3049   [TCP_LISTEN]		= TCP_CLOSE,
3050   [TCP_CLOSING]		= TCP_CLOSING,
3051   [TCP_NEW_SYN_RECV]	= TCP_CLOSE,	/* should not happen ! */
3052 };
3053 
3054 static int tcp_close_state(struct sock *sk)
3055 {
3056 	int next = (int)new_state[sk->sk_state];
3057 	int ns = next & TCP_STATE_MASK;
3058 
3059 	tcp_set_state(sk, ns);
3060 
3061 	return next & TCP_ACTION_FIN;
3062 }
3063 
3064 /*
3065  *	Shutdown the sending side of a connection. Much like close except
3066  *	that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD).
3067  */
3068 
3069 void tcp_shutdown(struct sock *sk, int how)
3070 {
3071 	/*	We need to grab some memory, and put together a FIN,
3072 	 *	and then put it into the queue to be sent.
3073 	 *		Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92.
3074 	 */
3075 	if (!(how & SEND_SHUTDOWN))
3076 		return;
3077 
3078 	/* If we've already sent a FIN, or it's a closed state, skip this. */
3079 	if ((1 << sk->sk_state) &
3080 	    (TCPF_ESTABLISHED | TCPF_SYN_SENT |
3081 	     TCPF_CLOSE_WAIT)) {
3082 		/* Clear out any half completed packets.  FIN if needed. */
3083 		if (tcp_close_state(sk))
3084 			tcp_send_fin(sk);
3085 	}
3086 }
3087 
3088 int tcp_orphan_count_sum(void)
3089 {
3090 	int i, total = 0;
3091 
3092 	for_each_possible_cpu(i)
3093 		total += per_cpu(tcp_orphan_count, i);
3094 
3095 	return max(total, 0);
3096 }
3097 
3098 static int tcp_orphan_cache;
3099 static struct timer_list tcp_orphan_timer;
3100 #define TCP_ORPHAN_TIMER_PERIOD msecs_to_jiffies(100)
3101 
3102 static void tcp_orphan_update(struct timer_list *unused)
3103 {
3104 	WRITE_ONCE(tcp_orphan_cache, tcp_orphan_count_sum());
3105 	mod_timer(&tcp_orphan_timer, jiffies + TCP_ORPHAN_TIMER_PERIOD);
3106 }
3107 
3108 static bool tcp_too_many_orphans(int shift)
3109 {
3110 	return READ_ONCE(tcp_orphan_cache) << shift >
3111 		READ_ONCE(sysctl_tcp_max_orphans);
3112 }
3113 
3114 static bool tcp_out_of_memory(const struct sock *sk)
3115 {
3116 	if (sk->sk_wmem_queued > SOCK_MIN_SNDBUF &&
3117 	    sk_memory_allocated(sk) > sk_prot_mem_limits(sk, 2))
3118 		return true;
3119 	return false;
3120 }
3121 
3122 bool tcp_check_oom(const struct sock *sk, int shift)
3123 {
3124 	bool too_many_orphans, out_of_socket_memory;
3125 
3126 	too_many_orphans = tcp_too_many_orphans(shift);
3127 	out_of_socket_memory = tcp_out_of_memory(sk);
3128 
3129 	if (too_many_orphans)
3130 		net_info_ratelimited("too many orphaned sockets\n");
3131 	if (out_of_socket_memory)
3132 		net_info_ratelimited("out of memory -- consider tuning tcp_mem\n");
3133 	return too_many_orphans || out_of_socket_memory;
3134 }
3135 
3136 void __tcp_close(struct sock *sk, long timeout)
3137 {
3138 	bool data_was_unread = false;
3139 	struct sk_buff *skb;
3140 	int state;
3141 
3142 	WRITE_ONCE(sk->sk_shutdown, SHUTDOWN_MASK);
3143 
3144 	if (sk->sk_state == TCP_LISTEN) {
3145 		tcp_set_state(sk, TCP_CLOSE);
3146 
3147 		/* Special case. */
3148 		inet_csk_listen_stop(sk);
3149 
3150 		goto adjudge_to_death;
3151 	}
3152 
3153 	/*  We need to flush the recv. buffs.  We do this only on the
3154 	 *  descriptor close, not protocol-sourced closes, because the
3155 	 *  reader process may not have drained the data yet!
3156 	 */
3157 	while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) {
3158 		u32 end_seq = TCP_SKB_CB(skb)->end_seq;
3159 
3160 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
3161 			end_seq--;
3162 		if (after(end_seq, tcp_sk(sk)->copied_seq))
3163 			data_was_unread = true;
3164 		tcp_eat_recv_skb(sk, skb);
3165 	}
3166 
3167 	/* If socket has been already reset (e.g. in tcp_reset()) - kill it. */
3168 	if (sk->sk_state == TCP_CLOSE)
3169 		goto adjudge_to_death;
3170 
3171 	/* As outlined in RFC 2525, section 2.17, we send a RST here because
3172 	 * data was lost. To witness the awful effects of the old behavior of
3173 	 * always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk
3174 	 * GET in an FTP client, suspend the process, wait for the client to
3175 	 * advertise a zero window, then kill -9 the FTP client, wheee...
3176 	 * Note: timeout is always zero in such a case.
3177 	 */
3178 	if (unlikely(tcp_sk(sk)->repair)) {
3179 		sk->sk_prot->disconnect(sk, 0);
3180 	} else if (data_was_unread) {
3181 		/* Unread data was tossed, zap the connection. */
3182 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE);
3183 		tcp_set_state(sk, TCP_CLOSE);
3184 		tcp_send_active_reset(sk, SK_RST_REASON_TCP_ABORT_ON_CLOSE);
3185 	} else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
3186 		/* Check zero linger _after_ checking for unread data. */
3187 		sk->sk_prot->disconnect(sk, 0);
3188 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
3189 	} else if (tcp_close_state(sk)) {
3190 		/* We FIN if the application ate all the data before
3191 		 * zapping the connection.
3192 		 */
3193 
3194 		/* RED-PEN. Formally speaking, we have broken TCP state
3195 		 * machine. State transitions:
3196 		 *
3197 		 * TCP_ESTABLISHED -> TCP_FIN_WAIT1
3198 		 * TCP_SYN_RECV	-> TCP_FIN_WAIT1 (it is difficult)
3199 		 * TCP_CLOSE_WAIT -> TCP_LAST_ACK
3200 		 *
3201 		 * are legal only when FIN has been sent (i.e. in window),
3202 		 * rather than queued out of window. Purists blame.
3203 		 *
3204 		 * F.e. "RFC state" is ESTABLISHED,
3205 		 * if Linux state is FIN-WAIT-1, but FIN is still not sent.
3206 		 *
3207 		 * The visible declinations are that sometimes
3208 		 * we enter time-wait state, when it is not required really
3209 		 * (harmless), do not send active resets, when they are
3210 		 * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when
3211 		 * they look as CLOSING or LAST_ACK for Linux)
3212 		 * Probably, I missed some more holelets.
3213 		 * 						--ANK
3214 		 * XXX (TFO) - To start off we don't support SYN+ACK+FIN
3215 		 * in a single packet! (May consider it later but will
3216 		 * probably need API support or TCP_CORK SYN-ACK until
3217 		 * data is written and socket is closed.)
3218 		 */
3219 		tcp_send_fin(sk);
3220 	}
3221 
3222 	sk_stream_wait_close(sk, timeout);
3223 
3224 adjudge_to_death:
3225 	state = sk->sk_state;
3226 	sock_hold(sk);
3227 	sock_orphan(sk);
3228 
3229 	local_bh_disable();
3230 	bh_lock_sock(sk);
3231 	/* remove backlog if any, without releasing ownership. */
3232 	__release_sock(sk);
3233 
3234 	tcp_orphan_count_inc();
3235 
3236 	/* Have we already been destroyed by a softirq or backlog? */
3237 	if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE)
3238 		goto out;
3239 
3240 	/*	This is a (useful) BSD violating of the RFC. There is a
3241 	 *	problem with TCP as specified in that the other end could
3242 	 *	keep a socket open forever with no application left this end.
3243 	 *	We use a 1 minute timeout (about the same as BSD) then kill
3244 	 *	our end. If they send after that then tough - BUT: long enough
3245 	 *	that we won't make the old 4*rto = almost no time - whoops
3246 	 *	reset mistake.
3247 	 *
3248 	 *	Nope, it was not mistake. It is really desired behaviour
3249 	 *	f.e. on http servers, when such sockets are useless, but
3250 	 *	consume significant resources. Let's do it with special
3251 	 *	linger2	option.					--ANK
3252 	 */
3253 
3254 	if (sk->sk_state == TCP_FIN_WAIT2) {
3255 		struct tcp_sock *tp = tcp_sk(sk);
3256 		if (READ_ONCE(tp->linger2) < 0) {
3257 			tcp_set_state(sk, TCP_CLOSE);
3258 			tcp_send_active_reset(sk,
3259 					      SK_RST_REASON_TCP_ABORT_ON_LINGER);
3260 			__NET_INC_STATS(sock_net(sk),
3261 					LINUX_MIB_TCPABORTONLINGER);
3262 		} else {
3263 			const int tmo = tcp_fin_time(sk);
3264 
3265 			if (tmo > TCP_TIMEWAIT_LEN) {
3266 				tcp_reset_keepalive_timer(sk,
3267 						tmo - TCP_TIMEWAIT_LEN);
3268 			} else {
3269 				tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
3270 				goto out;
3271 			}
3272 		}
3273 	}
3274 	if (sk->sk_state != TCP_CLOSE) {
3275 		if (tcp_check_oom(sk, 0)) {
3276 			tcp_set_state(sk, TCP_CLOSE);
3277 			tcp_send_active_reset(sk,
3278 					      SK_RST_REASON_TCP_ABORT_ON_MEMORY);
3279 			__NET_INC_STATS(sock_net(sk),
3280 					LINUX_MIB_TCPABORTONMEMORY);
3281 		} else if (!check_net(sock_net(sk))) {
3282 			/* Not possible to send reset; just close */
3283 			tcp_set_state(sk, TCP_CLOSE);
3284 		}
3285 	}
3286 
3287 	if (sk->sk_state == TCP_CLOSE) {
3288 		struct request_sock *req;
3289 
3290 		req = rcu_dereference_protected(tcp_sk(sk)->fastopen_rsk,
3291 						lockdep_sock_is_held(sk));
3292 		/* We could get here with a non-NULL req if the socket is
3293 		 * aborted (e.g., closed with unread data) before 3WHS
3294 		 * finishes.
3295 		 */
3296 		if (req)
3297 			reqsk_fastopen_remove(sk, req, false);
3298 		inet_csk_destroy_sock(sk);
3299 	}
3300 	/* Otherwise, socket is reprieved until protocol close. */
3301 
3302 out:
3303 	bh_unlock_sock(sk);
3304 	local_bh_enable();
3305 }
3306 
3307 void tcp_close(struct sock *sk, long timeout)
3308 {
3309 	lock_sock(sk);
3310 	__tcp_close(sk, timeout);
3311 	release_sock(sk);
3312 	if (!sk->sk_net_refcnt)
3313 		inet_csk_clear_xmit_timers_sync(sk);
3314 	sock_put(sk);
3315 }
3316 EXPORT_SYMBOL(tcp_close);
3317 
3318 /* These states need RST on ABORT according to RFC793 */
3319 
3320 static inline bool tcp_need_reset(int state)
3321 {
3322 	return (1 << state) &
3323 	       (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 |
3324 		TCPF_FIN_WAIT2 | TCPF_SYN_RECV);
3325 }
3326 
3327 static void tcp_rtx_queue_purge(struct sock *sk)
3328 {
3329 	struct rb_node *p = rb_first(&sk->tcp_rtx_queue);
3330 
3331 	tcp_sk(sk)->highest_sack = NULL;
3332 	while (p) {
3333 		struct sk_buff *skb = rb_to_skb(p);
3334 
3335 		p = rb_next(p);
3336 		/* Since we are deleting whole queue, no need to
3337 		 * list_del(&skb->tcp_tsorted_anchor)
3338 		 */
3339 		tcp_rtx_queue_unlink(skb, sk);
3340 		tcp_wmem_free_skb(sk, skb);
3341 	}
3342 }
3343 
3344 void tcp_write_queue_purge(struct sock *sk)
3345 {
3346 	struct sk_buff *skb;
3347 
3348 	tcp_chrono_stop(sk, TCP_CHRONO_BUSY);
3349 	while ((skb = __skb_dequeue(&sk->sk_write_queue)) != NULL) {
3350 		tcp_skb_tsorted_anchor_cleanup(skb);
3351 		tcp_wmem_free_skb(sk, skb);
3352 	}
3353 	tcp_rtx_queue_purge(sk);
3354 	INIT_LIST_HEAD(&tcp_sk(sk)->tsorted_sent_queue);
3355 	tcp_clear_all_retrans_hints(tcp_sk(sk));
3356 	tcp_sk(sk)->packets_out = 0;
3357 	inet_csk(sk)->icsk_backoff = 0;
3358 }
3359 
3360 int tcp_disconnect(struct sock *sk, int flags)
3361 {
3362 	struct inet_sock *inet = inet_sk(sk);
3363 	struct inet_connection_sock *icsk = inet_csk(sk);
3364 	struct tcp_sock *tp = tcp_sk(sk);
3365 	int old_state = sk->sk_state;
3366 	struct request_sock *req;
3367 	u32 seq;
3368 
3369 	if (old_state != TCP_CLOSE)
3370 		tcp_set_state(sk, TCP_CLOSE);
3371 
3372 	/* ABORT function of RFC793 */
3373 	if (old_state == TCP_LISTEN) {
3374 		inet_csk_listen_stop(sk);
3375 	} else if (unlikely(tp->repair)) {
3376 		WRITE_ONCE(sk->sk_err, ECONNABORTED);
3377 	} else if (tcp_need_reset(old_state)) {
3378 		tcp_send_active_reset(sk, SK_RST_REASON_TCP_STATE);
3379 		WRITE_ONCE(sk->sk_err, ECONNRESET);
3380 	} else if (tp->snd_nxt != tp->write_seq &&
3381 		   (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK)) {
3382 		/* The last check adjusts for discrepancy of Linux wrt. RFC
3383 		 * states
3384 		 */
3385 		tcp_send_active_reset(sk,
3386 				      SK_RST_REASON_TCP_DISCONNECT_WITH_DATA);
3387 		WRITE_ONCE(sk->sk_err, ECONNRESET);
3388 	} else if (old_state == TCP_SYN_SENT)
3389 		WRITE_ONCE(sk->sk_err, ECONNRESET);
3390 
3391 	tcp_clear_xmit_timers(sk);
3392 	__skb_queue_purge(&sk->sk_receive_queue);
3393 	WRITE_ONCE(tp->copied_seq, tp->rcv_nxt);
3394 	WRITE_ONCE(tp->urg_data, 0);
3395 	sk_set_peek_off(sk, -1);
3396 	tcp_write_queue_purge(sk);
3397 	tcp_fastopen_active_disable_ofo_check(sk);
3398 	skb_rbtree_purge(&tp->out_of_order_queue);
3399 
3400 	inet->inet_dport = 0;
3401 
3402 	inet_bhash2_reset_saddr(sk);
3403 
3404 	WRITE_ONCE(sk->sk_shutdown, 0);
3405 	sock_reset_flag(sk, SOCK_DONE);
3406 	tp->srtt_us = 0;
3407 	tp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT);
3408 	tp->rcv_rtt_last_tsecr = 0;
3409 
3410 	seq = tp->write_seq + tp->max_window + 2;
3411 	if (!seq)
3412 		seq = 1;
3413 	WRITE_ONCE(tp->write_seq, seq);
3414 
3415 	icsk->icsk_backoff = 0;
3416 	WRITE_ONCE(icsk->icsk_probes_out, 0);
3417 	icsk->icsk_probes_tstamp = 0;
3418 	icsk->icsk_rto = TCP_TIMEOUT_INIT;
3419 	WRITE_ONCE(icsk->icsk_rto_min, TCP_RTO_MIN);
3420 	WRITE_ONCE(icsk->icsk_delack_max, TCP_DELACK_MAX);
3421 	WRITE_ONCE(tp->snd_ssthresh, TCP_INFINITE_SSTHRESH);
3422 	tcp_snd_cwnd_set(tp, TCP_INIT_CWND);
3423 	tp->snd_cwnd_cnt = 0;
3424 	tp->is_cwnd_limited = 0;
3425 	tp->max_packets_out = 0;
3426 	tp->window_clamp = 0;
3427 	tp->delivered = 0;
3428 	tp->delivered_ce = 0;
3429 	tp->accecn_fail_mode = 0;
3430 	tp->saw_accecn_opt = TCP_ACCECN_OPT_NOT_SEEN;
3431 	tcp_accecn_init_counters(tp);
3432 	tp->prev_ecnfield = 0;
3433 	tp->accecn_opt_tstamp = 0;
3434 	tp->pkts_acked_ewma = 0;
3435 	if (icsk->icsk_ca_initialized && icsk->icsk_ca_ops->release)
3436 		icsk->icsk_ca_ops->release(sk);
3437 	memset(icsk->icsk_ca_priv, 0, sizeof(icsk->icsk_ca_priv));
3438 	icsk->icsk_ca_initialized = 0;
3439 	tcp_set_ca_state(sk, TCP_CA_Open);
3440 	tp->is_sack_reneg = 0;
3441 	tcp_clear_retrans(tp);
3442 	tp->total_retrans = 0;
3443 	inet_csk_delack_init(sk);
3444 	/* Initialize rcv_mss to TCP_MIN_MSS to avoid division by 0
3445 	 * issue in __tcp_select_window()
3446 	 */
3447 	icsk->icsk_ack.rcv_mss = TCP_MIN_MSS;
3448 	memset(&tp->rx_opt, 0, sizeof(tp->rx_opt));
3449 	__sk_dst_reset(sk);
3450 	dst_release(unrcu_pointer(xchg(&sk->sk_rx_dst, NULL)));
3451 	tcp_saved_syn_free(tp);
3452 	tp->compressed_ack = 0;
3453 	tp->segs_in = 0;
3454 	tp->segs_out = 0;
3455 	tp->bytes_sent = 0;
3456 	tp->bytes_acked = 0;
3457 	tp->bytes_received = 0;
3458 	tp->bytes_retrans = 0;
3459 	tp->data_segs_in = 0;
3460 	tp->data_segs_out = 0;
3461 	tp->duplicate_sack[0].start_seq = 0;
3462 	tp->duplicate_sack[0].end_seq = 0;
3463 	tp->dsack_dups = 0;
3464 	tp->reord_seen = 0;
3465 	tp->retrans_out = 0;
3466 	tp->sacked_out = 0;
3467 	tp->tlp_high_seq = 0;
3468 	tp->last_oow_ack_time = 0;
3469 	tp->plb_rehash = 0;
3470 	/* There's a bubble in the pipe until at least the first ACK. */
3471 	tp->app_limited = ~0U;
3472 	tp->rate_app_limited = 1;
3473 	tp->rack.mstamp = 0;
3474 	tp->rack.advanced = 0;
3475 	tp->rack.reo_wnd_steps = 1;
3476 	tp->rack.last_delivered = 0;
3477 	tp->rack.reo_wnd_persist = 0;
3478 	tp->rack.dsack_seen = 0;
3479 	tp->syn_data_acked = 0;
3480 	tp->syn_fastopen_child = 0;
3481 	tp->rx_opt.saw_tstamp = 0;
3482 	tp->rx_opt.dsack = 0;
3483 	tp->rx_opt.num_sacks = 0;
3484 	tp->rcv_ooopack = 0;
3485 
3486 
3487 	/* Clean up fastopen related fields */
3488 	req = rcu_dereference_protected(tp->fastopen_rsk,
3489 					lockdep_sock_is_held(sk));
3490 	if (req)
3491 		reqsk_fastopen_remove(sk, req, false);
3492 	tcp_free_fastopen_req(tp);
3493 	inet_clear_bit(DEFER_CONNECT, sk);
3494 	tp->fastopen_client_fail = 0;
3495 
3496 	WARN_ON(inet->inet_num && !icsk->icsk_bind_hash);
3497 
3498 	if (sk->sk_frag.page) {
3499 		put_page(sk->sk_frag.page);
3500 		sk->sk_frag.page = NULL;
3501 		sk->sk_frag.offset = 0;
3502 	}
3503 	sk_error_report(sk);
3504 	return 0;
3505 }
3506 
3507 static inline bool tcp_can_repair_sock(const struct sock *sk)
3508 {
3509 	return sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN) &&
3510 		(sk->sk_state != TCP_LISTEN);
3511 }
3512 
3513 static int tcp_repair_set_window(struct tcp_sock *tp, sockptr_t optbuf, int len)
3514 {
3515 	struct tcp_repair_window opt;
3516 
3517 	if (!tp->repair)
3518 		return -EPERM;
3519 
3520 	if (len != sizeof(opt))
3521 		return -EINVAL;
3522 
3523 	if (copy_from_sockptr(&opt, optbuf, sizeof(opt)))
3524 		return -EFAULT;
3525 
3526 	if (opt.max_window < opt.snd_wnd)
3527 		return -EINVAL;
3528 
3529 	if (after(opt.snd_wl1, tp->rcv_nxt + opt.rcv_wnd))
3530 		return -EINVAL;
3531 
3532 	if (after(opt.rcv_wup, tp->rcv_nxt))
3533 		return -EINVAL;
3534 
3535 	tp->snd_wl1	= opt.snd_wl1;
3536 	tp->snd_wnd	= opt.snd_wnd;
3537 	tp->max_window	= opt.max_window;
3538 
3539 	tp->rcv_wnd	= opt.rcv_wnd;
3540 	tp->rcv_wup	= opt.rcv_wup;
3541 	tp->rcv_mwnd_seq = opt.rcv_wup + opt.rcv_wnd;
3542 
3543 	return 0;
3544 }
3545 
3546 static int tcp_repair_options_est(struct sock *sk, sockptr_t optbuf,
3547 		unsigned int len)
3548 {
3549 	struct tcp_sock *tp = tcp_sk(sk);
3550 	struct tcp_repair_opt opt;
3551 	size_t offset = 0;
3552 
3553 	while (len >= sizeof(opt)) {
3554 		if (copy_from_sockptr_offset(&opt, optbuf, offset, sizeof(opt)))
3555 			return -EFAULT;
3556 
3557 		offset += sizeof(opt);
3558 		len -= sizeof(opt);
3559 
3560 		switch (opt.opt_code) {
3561 		case TCPOPT_MSS:
3562 			tp->rx_opt.mss_clamp = opt.opt_val;
3563 			tcp_mtup_init(sk);
3564 			break;
3565 		case TCPOPT_WINDOW:
3566 			{
3567 				u16 snd_wscale = opt.opt_val & 0xFFFF;
3568 				u16 rcv_wscale = opt.opt_val >> 16;
3569 
3570 				if (snd_wscale > TCP_MAX_WSCALE || rcv_wscale > TCP_MAX_WSCALE)
3571 					return -EFBIG;
3572 
3573 				tp->rx_opt.snd_wscale = snd_wscale;
3574 				tp->rx_opt.rcv_wscale = rcv_wscale;
3575 				tp->rx_opt.wscale_ok = 1;
3576 			}
3577 			break;
3578 		case TCPOPT_SACK_PERM:
3579 			if (opt.opt_val != 0)
3580 				return -EINVAL;
3581 
3582 			tp->rx_opt.sack_ok |= TCP_SACK_SEEN;
3583 			break;
3584 		case TCPOPT_TIMESTAMP:
3585 			if (opt.opt_val != 0)
3586 				return -EINVAL;
3587 
3588 			tp->rx_opt.tstamp_ok = 1;
3589 			break;
3590 		}
3591 	}
3592 
3593 	return 0;
3594 }
3595 
3596 DEFINE_STATIC_KEY_FALSE(tcp_tx_delay_enabled);
3597 
3598 static void tcp_enable_tx_delay(struct sock *sk, int val)
3599 {
3600 	struct tcp_sock *tp = tcp_sk(sk);
3601 	s32 delta = (val - tp->tcp_tx_delay) << 3;
3602 
3603 	if (val && !static_branch_unlikely(&tcp_tx_delay_enabled)) {
3604 		static int __tcp_tx_delay_enabled = 0;
3605 
3606 		if (cmpxchg(&__tcp_tx_delay_enabled, 0, 1) == 0) {
3607 			static_branch_enable(&tcp_tx_delay_enabled);
3608 			pr_info("TCP_TX_DELAY enabled\n");
3609 		}
3610 	}
3611 	/* If we change tcp_tx_delay on a live flow, adjust tp->srtt_us,
3612 	 * tp->rtt_min, icsk_rto and sk->sk_pacing_rate.
3613 	 * This is best effort.
3614 	 */
3615 	if (delta && sk->sk_state == TCP_ESTABLISHED) {
3616 		s64 srtt = (s64)tp->srtt_us + delta;
3617 
3618 		WRITE_ONCE(tp->srtt_us,
3619 			   clamp_t(s64, srtt, 1, ~0U));
3620 
3621 		/* Note: does not deal with non zero icsk_backoff */
3622 		tcp_set_rto(sk);
3623 
3624 		minmax_reset(&tp->rtt_min, tcp_jiffies32, ~0U);
3625 
3626 		tcp_update_pacing_rate(sk);
3627 	}
3628 }
3629 
3630 /* When set indicates to always queue non-full frames.  Later the user clears
3631  * this option and we transmit any pending partial frames in the queue.  This is
3632  * meant to be used alongside sendfile() to get properly filled frames when the
3633  * user (for example) must write out headers with a write() call first and then
3634  * use sendfile to send out the data parts.
3635  *
3636  * TCP_CORK can be set together with TCP_NODELAY and it is stronger than
3637  * TCP_NODELAY.
3638  */
3639 void __tcp_sock_set_cork(struct sock *sk, bool on)
3640 {
3641 	struct tcp_sock *tp = tcp_sk(sk);
3642 
3643 	if (on) {
3644 		tp->nonagle |= TCP_NAGLE_CORK;
3645 	} else {
3646 		tp->nonagle &= ~TCP_NAGLE_CORK;
3647 		if (tp->nonagle & TCP_NAGLE_OFF)
3648 			tp->nonagle |= TCP_NAGLE_PUSH;
3649 		tcp_push_pending_frames(sk);
3650 	}
3651 }
3652 
3653 void tcp_sock_set_cork(struct sock *sk, bool on)
3654 {
3655 	lock_sock(sk);
3656 	__tcp_sock_set_cork(sk, on);
3657 	release_sock(sk);
3658 }
3659 EXPORT_SYMBOL(tcp_sock_set_cork);
3660 
3661 /* TCP_NODELAY is weaker than TCP_CORK, so that this option on corked socket is
3662  * remembered, but it is not activated until cork is cleared.
3663  *
3664  * However, when TCP_NODELAY is set we make an explicit push, which overrides
3665  * even TCP_CORK for currently queued segments.
3666  */
3667 void __tcp_sock_set_nodelay(struct sock *sk, bool on)
3668 {
3669 	if (on) {
3670 		tcp_sk(sk)->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH;
3671 		tcp_push_pending_frames(sk);
3672 	} else {
3673 		tcp_sk(sk)->nonagle &= ~TCP_NAGLE_OFF;
3674 	}
3675 }
3676 
3677 void tcp_sock_set_nodelay(struct sock *sk)
3678 {
3679 	lock_sock(sk);
3680 	__tcp_sock_set_nodelay(sk, true);
3681 	release_sock(sk);
3682 }
3683 EXPORT_SYMBOL(tcp_sock_set_nodelay);
3684 
3685 static void __tcp_sock_set_quickack(struct sock *sk, int val)
3686 {
3687 	if (!val) {
3688 		inet_csk_enter_pingpong_mode(sk);
3689 		return;
3690 	}
3691 
3692 	inet_csk_exit_pingpong_mode(sk);
3693 	if ((1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) &&
3694 	    inet_csk_ack_scheduled(sk)) {
3695 		inet_csk(sk)->icsk_ack.pending |= ICSK_ACK_PUSHED;
3696 		tcp_cleanup_rbuf(sk, 1);
3697 		if (!(val & 1))
3698 			inet_csk_enter_pingpong_mode(sk);
3699 	}
3700 }
3701 
3702 void tcp_sock_set_quickack(struct sock *sk, int val)
3703 {
3704 	lock_sock(sk);
3705 	__tcp_sock_set_quickack(sk, val);
3706 	release_sock(sk);
3707 }
3708 EXPORT_SYMBOL(tcp_sock_set_quickack);
3709 
3710 int tcp_sock_set_syncnt(struct sock *sk, int val)
3711 {
3712 	if (val < 1 || val > MAX_TCP_SYNCNT)
3713 		return -EINVAL;
3714 
3715 	WRITE_ONCE(inet_csk(sk)->icsk_syn_retries, val);
3716 	return 0;
3717 }
3718 EXPORT_SYMBOL(tcp_sock_set_syncnt);
3719 
3720 int tcp_sock_set_user_timeout(struct sock *sk, int val)
3721 {
3722 	/* Cap the max time in ms TCP will retry or probe the window
3723 	 * before giving up and aborting (ETIMEDOUT) a connection.
3724 	 */
3725 	if (val < 0)
3726 		return -EINVAL;
3727 
3728 	WRITE_ONCE(inet_csk(sk)->icsk_user_timeout, val);
3729 	return 0;
3730 }
3731 EXPORT_SYMBOL(tcp_sock_set_user_timeout);
3732 
3733 int tcp_sock_set_keepidle_locked(struct sock *sk, int val)
3734 {
3735 	struct tcp_sock *tp = tcp_sk(sk);
3736 
3737 	if (val < 1 || val > MAX_TCP_KEEPIDLE)
3738 		return -EINVAL;
3739 
3740 	/* Paired with WRITE_ONCE() in keepalive_time_when() */
3741 	WRITE_ONCE(tp->keepalive_time, val * HZ);
3742 	if (sock_flag(sk, SOCK_KEEPOPEN) &&
3743 	    !((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) {
3744 		u32 elapsed = keepalive_time_elapsed(tp);
3745 
3746 		if (tp->keepalive_time > elapsed)
3747 			elapsed = tp->keepalive_time - elapsed;
3748 		else
3749 			elapsed = 0;
3750 		tcp_reset_keepalive_timer(sk, elapsed);
3751 	}
3752 
3753 	return 0;
3754 }
3755 
3756 int tcp_sock_set_keepidle(struct sock *sk, int val)
3757 {
3758 	int err;
3759 
3760 	lock_sock(sk);
3761 	err = tcp_sock_set_keepidle_locked(sk, val);
3762 	release_sock(sk);
3763 	return err;
3764 }
3765 EXPORT_SYMBOL(tcp_sock_set_keepidle);
3766 
3767 int tcp_sock_set_keepintvl(struct sock *sk, int val)
3768 {
3769 	if (val < 1 || val > MAX_TCP_KEEPINTVL)
3770 		return -EINVAL;
3771 
3772 	WRITE_ONCE(tcp_sk(sk)->keepalive_intvl, val * HZ);
3773 	return 0;
3774 }
3775 EXPORT_SYMBOL(tcp_sock_set_keepintvl);
3776 
3777 int tcp_sock_set_keepcnt(struct sock *sk, int val)
3778 {
3779 	if (val < 1 || val > MAX_TCP_KEEPCNT)
3780 		return -EINVAL;
3781 
3782 	/* Paired with READ_ONCE() in keepalive_probes() */
3783 	WRITE_ONCE(tcp_sk(sk)->keepalive_probes, val);
3784 	return 0;
3785 }
3786 EXPORT_SYMBOL(tcp_sock_set_keepcnt);
3787 
3788 int tcp_set_window_clamp(struct sock *sk, int val)
3789 {
3790 	u32 old_window_clamp, new_window_clamp, new_rcv_ssthresh;
3791 	struct tcp_sock *tp = tcp_sk(sk);
3792 
3793 	if (!val) {
3794 		if (sk->sk_state != TCP_CLOSE)
3795 			return -EINVAL;
3796 		WRITE_ONCE(tp->window_clamp, 0);
3797 		return 0;
3798 	}
3799 
3800 	old_window_clamp = tp->window_clamp;
3801 	new_window_clamp = max_t(int, SOCK_MIN_RCVBUF / 2, val);
3802 
3803 	if (new_window_clamp == old_window_clamp)
3804 		return 0;
3805 
3806 	WRITE_ONCE(tp->window_clamp, new_window_clamp);
3807 
3808 	/* Need to apply the reserved mem provisioning only
3809 	 * when shrinking the window clamp.
3810 	 */
3811 	if (new_window_clamp < old_window_clamp) {
3812 		__tcp_adjust_rcv_ssthresh(sk, new_window_clamp);
3813 	} else {
3814 		new_rcv_ssthresh = min(tp->rcv_wnd, new_window_clamp);
3815 		tp->rcv_ssthresh = max(new_rcv_ssthresh, tp->rcv_ssthresh);
3816 	}
3817 	return 0;
3818 }
3819 
3820 int tcp_sock_set_maxseg(struct sock *sk, int val)
3821 {
3822 	/* Values greater than interface MTU won't take effect. However
3823 	 * at the point when this call is done we typically don't yet
3824 	 * know which interface is going to be used
3825 	 */
3826 	if (val && (val < TCP_MIN_MSS || val > MAX_TCP_WINDOW))
3827 		return -EINVAL;
3828 
3829 	WRITE_ONCE(tcp_sk(sk)->rx_opt.user_mss, val);
3830 	return 0;
3831 }
3832 
3833 /*
3834  *	Socket option code for TCP.
3835  */
3836 int do_tcp_setsockopt(struct sock *sk, int level, int optname,
3837 		      sockptr_t optval, unsigned int optlen)
3838 {
3839 	struct tcp_sock *tp = tcp_sk(sk);
3840 	struct inet_connection_sock *icsk = inet_csk(sk);
3841 	struct net *net = sock_net(sk);
3842 	int val;
3843 	int err = 0;
3844 
3845 	/* These are data/string values, all the others are ints */
3846 	switch (optname) {
3847 	case TCP_CONGESTION: {
3848 		char name[TCP_CA_NAME_MAX];
3849 
3850 		if (optlen < 1)
3851 			return -EINVAL;
3852 
3853 		val = strncpy_from_sockptr(name, optval,
3854 					min_t(long, TCP_CA_NAME_MAX-1, optlen));
3855 		if (val < 0)
3856 			return -EFAULT;
3857 		name[val] = 0;
3858 
3859 		sockopt_lock_sock(sk);
3860 		err = tcp_set_congestion_control(sk, name, !has_current_bpf_ctx(),
3861 						 sockopt_ns_capable(sock_net(sk)->user_ns,
3862 								    CAP_NET_ADMIN));
3863 		sockopt_release_sock(sk);
3864 		return err;
3865 	}
3866 	case TCP_ULP: {
3867 		char name[TCP_ULP_NAME_MAX];
3868 
3869 		if (optlen < 1)
3870 			return -EINVAL;
3871 
3872 		val = strncpy_from_sockptr(name, optval,
3873 					min_t(long, TCP_ULP_NAME_MAX - 1,
3874 					      optlen));
3875 		if (val < 0)
3876 			return -EFAULT;
3877 		name[val] = 0;
3878 
3879 		sockopt_lock_sock(sk);
3880 		err = tcp_set_ulp(sk, name);
3881 		sockopt_release_sock(sk);
3882 		return err;
3883 	}
3884 	case TCP_FASTOPEN_KEY: {
3885 		__u8 key[TCP_FASTOPEN_KEY_BUF_LENGTH];
3886 		__u8 *backup_key = NULL;
3887 
3888 		/* Allow a backup key as well to facilitate key rotation
3889 		 * First key is the active one.
3890 		 */
3891 		if (optlen != TCP_FASTOPEN_KEY_LENGTH &&
3892 		    optlen != TCP_FASTOPEN_KEY_BUF_LENGTH)
3893 			return -EINVAL;
3894 
3895 		if (copy_from_sockptr(key, optval, optlen))
3896 			return -EFAULT;
3897 
3898 		if (optlen == TCP_FASTOPEN_KEY_BUF_LENGTH)
3899 			backup_key = key + TCP_FASTOPEN_KEY_LENGTH;
3900 
3901 		return tcp_fastopen_reset_cipher(net, sk, key, backup_key);
3902 	}
3903 	default:
3904 		/* fallthru */
3905 		break;
3906 	}
3907 
3908 	if (optlen < sizeof(int))
3909 		return -EINVAL;
3910 
3911 	if (copy_from_sockptr(&val, optval, sizeof(val)))
3912 		return -EFAULT;
3913 
3914 	/* Handle options that can be set without locking the socket. */
3915 	switch (optname) {
3916 	case TCP_SYNCNT:
3917 		return tcp_sock_set_syncnt(sk, val);
3918 	case TCP_USER_TIMEOUT:
3919 		return tcp_sock_set_user_timeout(sk, val);
3920 	case TCP_KEEPINTVL:
3921 		return tcp_sock_set_keepintvl(sk, val);
3922 	case TCP_KEEPCNT:
3923 		return tcp_sock_set_keepcnt(sk, val);
3924 	case TCP_LINGER2:
3925 		if (val < 0)
3926 			WRITE_ONCE(tp->linger2, -1);
3927 		else if (val > TCP_FIN_TIMEOUT_MAX / HZ)
3928 			WRITE_ONCE(tp->linger2, TCP_FIN_TIMEOUT_MAX);
3929 		else
3930 			WRITE_ONCE(tp->linger2, val * HZ);
3931 		return 0;
3932 	case TCP_DEFER_ACCEPT:
3933 		/* Translate value in seconds to number of retransmits */
3934 		WRITE_ONCE(icsk->icsk_accept_queue.rskq_defer_accept,
3935 			   secs_to_retrans(val, TCP_TIMEOUT_INIT / HZ,
3936 					   TCP_RTO_MAX / HZ));
3937 		return 0;
3938 	case TCP_RTO_MAX_MS:
3939 		if (val < MSEC_PER_SEC || val > TCP_RTO_MAX_SEC * MSEC_PER_SEC)
3940 			return -EINVAL;
3941 		WRITE_ONCE(inet_csk(sk)->icsk_rto_max, msecs_to_jiffies(val));
3942 		return 0;
3943 	case TCP_RTO_MIN_US: {
3944 		int rto_min = usecs_to_jiffies(val);
3945 
3946 		if (rto_min > TCP_RTO_MIN || rto_min < TCP_TIMEOUT_MIN)
3947 			return -EINVAL;
3948 		WRITE_ONCE(inet_csk(sk)->icsk_rto_min, rto_min);
3949 		return 0;
3950 	}
3951 	case TCP_DELACK_MAX_US: {
3952 		int delack_max = usecs_to_jiffies(val);
3953 
3954 		if (delack_max > TCP_DELACK_MAX || delack_max < TCP_TIMEOUT_MIN)
3955 			return -EINVAL;
3956 		WRITE_ONCE(inet_csk(sk)->icsk_delack_max, delack_max);
3957 		return 0;
3958 	}
3959 	case TCP_MAXSEG:
3960 		return tcp_sock_set_maxseg(sk, val);
3961 	}
3962 
3963 	sockopt_lock_sock(sk);
3964 
3965 	switch (optname) {
3966 	case TCP_NODELAY:
3967 		__tcp_sock_set_nodelay(sk, val);
3968 		break;
3969 
3970 	case TCP_THIN_LINEAR_TIMEOUTS:
3971 		if (val < 0 || val > 1)
3972 			err = -EINVAL;
3973 		else
3974 			tp->thin_lto = val;
3975 		break;
3976 
3977 	case TCP_THIN_DUPACK:
3978 		if (val < 0 || val > 1)
3979 			err = -EINVAL;
3980 		break;
3981 
3982 	case TCP_REPAIR:
3983 		if (!tcp_can_repair_sock(sk))
3984 			err = -EPERM;
3985 		else if (val == TCP_REPAIR_ON) {
3986 			tp->repair = 1;
3987 			sk->sk_reuse = SK_FORCE_REUSE;
3988 			tp->repair_queue = TCP_NO_QUEUE;
3989 		} else if (val == TCP_REPAIR_OFF) {
3990 			tp->repair = 0;
3991 			sk->sk_reuse = SK_NO_REUSE;
3992 			tcp_send_window_probe(sk);
3993 		} else if (val == TCP_REPAIR_OFF_NO_WP) {
3994 			tp->repair = 0;
3995 			sk->sk_reuse = SK_NO_REUSE;
3996 		} else
3997 			err = -EINVAL;
3998 
3999 		break;
4000 
4001 	case TCP_REPAIR_QUEUE:
4002 		if (!tp->repair)
4003 			err = -EPERM;
4004 		else if ((unsigned int)val < TCP_QUEUES_NR)
4005 			tp->repair_queue = val;
4006 		else
4007 			err = -EINVAL;
4008 		break;
4009 
4010 	case TCP_QUEUE_SEQ:
4011 		if (sk->sk_state != TCP_CLOSE) {
4012 			err = -EPERM;
4013 		} else if (tp->repair_queue == TCP_SEND_QUEUE) {
4014 			if (!tcp_rtx_queue_empty(sk))
4015 				err = -EPERM;
4016 			else
4017 				WRITE_ONCE(tp->write_seq, val);
4018 		} else if (tp->repair_queue == TCP_RECV_QUEUE) {
4019 			if (tp->rcv_nxt != tp->copied_seq) {
4020 				err = -EPERM;
4021 			} else {
4022 				WRITE_ONCE(tp->rcv_nxt, val);
4023 				WRITE_ONCE(tp->copied_seq, val);
4024 			}
4025 		} else {
4026 			err = -EINVAL;
4027 		}
4028 		break;
4029 
4030 	case TCP_REPAIR_OPTIONS:
4031 		if (!tp->repair)
4032 			err = -EINVAL;
4033 		else if (sk->sk_state == TCP_ESTABLISHED && !tp->bytes_sent)
4034 			err = tcp_repair_options_est(sk, optval, optlen);
4035 		else
4036 			err = -EPERM;
4037 		break;
4038 
4039 	case TCP_CORK:
4040 		__tcp_sock_set_cork(sk, val);
4041 		break;
4042 
4043 	case TCP_KEEPIDLE:
4044 		err = tcp_sock_set_keepidle_locked(sk, val);
4045 		break;
4046 	case TCP_SAVE_SYN:
4047 		/* 0: disable, 1: enable, 2: start from ether_header */
4048 		if (val < 0 || val > 2)
4049 			err = -EINVAL;
4050 		else
4051 			tp->save_syn = val;
4052 		break;
4053 
4054 	case TCP_WINDOW_CLAMP:
4055 		err = tcp_set_window_clamp(sk, val);
4056 		break;
4057 
4058 	case TCP_QUICKACK:
4059 		__tcp_sock_set_quickack(sk, val);
4060 		break;
4061 
4062 	case TCP_AO_REPAIR:
4063 		if (!tcp_can_repair_sock(sk)) {
4064 			err = -EPERM;
4065 			break;
4066 		}
4067 		err = tcp_ao_set_repair(sk, optval, optlen);
4068 		break;
4069 #ifdef CONFIG_TCP_AO
4070 	case TCP_AO_ADD_KEY:
4071 	case TCP_AO_DEL_KEY:
4072 	case TCP_AO_INFO: {
4073 		/* If this is the first TCP-AO setsockopt() on the socket,
4074 		 * sk_state has to be LISTEN or CLOSE. Allow TCP_REPAIR
4075 		 * in any state.
4076 		 */
4077 		if ((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE))
4078 			goto ao_parse;
4079 		if (rcu_dereference_protected(tcp_sk(sk)->ao_info,
4080 					      lockdep_sock_is_held(sk)))
4081 			goto ao_parse;
4082 		if (tp->repair)
4083 			goto ao_parse;
4084 		err = -EISCONN;
4085 		break;
4086 ao_parse:
4087 		err = tp->af_specific->ao_parse(sk, optname, optval, optlen);
4088 		break;
4089 	}
4090 #endif
4091 #ifdef CONFIG_TCP_MD5SIG
4092 	case TCP_MD5SIG:
4093 	case TCP_MD5SIG_EXT:
4094 		err = tp->af_specific->md5_parse(sk, optname, optval, optlen);
4095 		break;
4096 #endif
4097 	case TCP_FASTOPEN:
4098 		if (val >= 0 && ((1 << sk->sk_state) & (TCPF_CLOSE |
4099 		    TCPF_LISTEN))) {
4100 			tcp_fastopen_init_key_once(net);
4101 
4102 			fastopen_queue_tune(sk, val);
4103 		} else {
4104 			err = -EINVAL;
4105 		}
4106 		break;
4107 	case TCP_FASTOPEN_CONNECT:
4108 		if (val > 1 || val < 0) {
4109 			err = -EINVAL;
4110 		} else if (READ_ONCE(net->ipv4.sysctl_tcp_fastopen) &
4111 			   TFO_CLIENT_ENABLE) {
4112 			if (sk->sk_state == TCP_CLOSE)
4113 				tp->fastopen_connect = val;
4114 			else
4115 				err = -EINVAL;
4116 		} else {
4117 			err = -EOPNOTSUPP;
4118 		}
4119 		break;
4120 	case TCP_FASTOPEN_NO_COOKIE:
4121 		if (val > 1 || val < 0)
4122 			err = -EINVAL;
4123 		else if (!((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
4124 			err = -EINVAL;
4125 		else
4126 			tp->fastopen_no_cookie = val;
4127 		break;
4128 	case TCP_TIMESTAMP:
4129 		if (!tp->repair) {
4130 			err = -EPERM;
4131 			break;
4132 		}
4133 		/* val is an opaque field,
4134 		 * and low order bit contains usec_ts enable bit.
4135 		 * Its a best effort, and we do not care if user makes an error.
4136 		 */
4137 		tp->tcp_usec_ts = val & 1;
4138 		WRITE_ONCE(tp->tsoffset, val - tcp_clock_ts(tp->tcp_usec_ts));
4139 		break;
4140 	case TCP_REPAIR_WINDOW:
4141 		err = tcp_repair_set_window(tp, optval, optlen);
4142 		break;
4143 	case TCP_NOTSENT_LOWAT:
4144 		WRITE_ONCE(tp->notsent_lowat, val);
4145 		READ_ONCE(sk->sk_write_space)(sk);
4146 		break;
4147 	case TCP_INQ:
4148 		if (val > 1 || val < 0)
4149 			err = -EINVAL;
4150 		else
4151 			tp->recvmsg_inq = val;
4152 		break;
4153 	case TCP_TX_DELAY:
4154 		/* tp->srtt_us is u32, and is shifted by 3 */
4155 		if (val < 0 || val >= (1U << (31 - 3))) {
4156 			err = -EINVAL;
4157 			break;
4158 		}
4159 		tcp_enable_tx_delay(sk, val);
4160 		WRITE_ONCE(tp->tcp_tx_delay, val);
4161 		break;
4162 	default:
4163 		err = -ENOPROTOOPT;
4164 		break;
4165 	}
4166 
4167 	sockopt_release_sock(sk);
4168 	return err;
4169 }
4170 
4171 int tcp_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval,
4172 		   unsigned int optlen)
4173 {
4174 	const struct inet_connection_sock *icsk = inet_csk(sk);
4175 
4176 	if (level != SOL_TCP)
4177 		/* Paired with WRITE_ONCE() in do_ipv6_setsockopt() and tcp_v6_connect() */
4178 		return READ_ONCE(icsk->icsk_af_ops)->setsockopt(sk, level, optname,
4179 								optval, optlen);
4180 	return do_tcp_setsockopt(sk, level, optname, optval, optlen);
4181 }
4182 
4183 static void tcp_get_info_chrono_stats(const struct tcp_sock *tp,
4184 				      struct tcp_info *info)
4185 {
4186 	u64 stats[__TCP_CHRONO_MAX], total = 0;
4187 	enum tcp_chrono i, cur;
4188 
4189 	/* Following READ_ONCE()s pair with WRITE_ONCE()s in tcp_chrono_set().
4190 	 * This is because socket lock might not be owned by us at this point.
4191 	 * This is best effort, tcp_get_timestamping_opt_stats() can
4192 	 * see wrong values. A real fix would be too costly for TCP fast path.
4193 	 */
4194 	cur = READ_ONCE(tp->chrono_type);
4195 	for (i = TCP_CHRONO_BUSY; i < __TCP_CHRONO_MAX; ++i) {
4196 		stats[i] = READ_ONCE(tp->chrono_stat[i - 1]);
4197 		if (i == cur)
4198 			stats[i] += tcp_jiffies32 - READ_ONCE(tp->chrono_start);
4199 		stats[i] *= USEC_PER_SEC / HZ;
4200 		total += stats[i];
4201 	}
4202 
4203 	info->tcpi_busy_time = total;
4204 	info->tcpi_rwnd_limited = stats[TCP_CHRONO_RWND_LIMITED];
4205 	info->tcpi_sndbuf_limited = stats[TCP_CHRONO_SNDBUF_LIMITED];
4206 }
4207 
4208 /* Return information about state of tcp endpoint in API format. */
4209 void tcp_get_info(struct sock *sk, struct tcp_info *info)
4210 {
4211 	const struct tcp_sock *tp = tcp_sk(sk); /* iff sk_type == SOCK_STREAM */
4212 	const struct inet_connection_sock *icsk = inet_csk(sk);
4213 	const u8 ect1_idx = INET_ECN_ECT_1 - 1;
4214 	const u8 ect0_idx = INET_ECN_ECT_0 - 1;
4215 	const u8 ce_idx = INET_ECN_CE - 1;
4216 	unsigned long rate;
4217 	u32 now;
4218 	u64 rate64;
4219 	bool slow;
4220 
4221 	memset(info, 0, sizeof(*info));
4222 	if (sk->sk_type != SOCK_STREAM)
4223 		return;
4224 
4225 	info->tcpi_state = inet_sk_state_load(sk);
4226 
4227 	/* Report meaningful fields for all TCP states, including listeners */
4228 	rate = READ_ONCE(sk->sk_pacing_rate);
4229 	rate64 = (rate != ~0UL) ? rate : ~0ULL;
4230 	info->tcpi_pacing_rate = rate64;
4231 
4232 	rate = READ_ONCE(sk->sk_max_pacing_rate);
4233 	rate64 = (rate != ~0UL) ? rate : ~0ULL;
4234 	info->tcpi_max_pacing_rate = rate64;
4235 
4236 	info->tcpi_reordering = tp->reordering;
4237 	info->tcpi_snd_cwnd = tcp_snd_cwnd(tp);
4238 
4239 	if (info->tcpi_state == TCP_LISTEN) {
4240 		/* listeners aliased fields :
4241 		 * tcpi_unacked -> Number of children ready for accept()
4242 		 * tcpi_sacked  -> max backlog
4243 		 */
4244 		info->tcpi_unacked = READ_ONCE(sk->sk_ack_backlog);
4245 		info->tcpi_sacked = READ_ONCE(sk->sk_max_ack_backlog);
4246 		return;
4247 	}
4248 
4249 	slow = lock_sock_fast(sk);
4250 
4251 	info->tcpi_ca_state = icsk->icsk_ca_state;
4252 	info->tcpi_retransmits = icsk->icsk_retransmits;
4253 	info->tcpi_probes = icsk->icsk_probes_out;
4254 	info->tcpi_backoff = icsk->icsk_backoff;
4255 
4256 	if (tp->rx_opt.tstamp_ok)
4257 		info->tcpi_options |= TCPI_OPT_TIMESTAMPS;
4258 	if (tcp_is_sack(tp))
4259 		info->tcpi_options |= TCPI_OPT_SACK;
4260 	if (tp->rx_opt.wscale_ok) {
4261 		info->tcpi_options |= TCPI_OPT_WSCALE;
4262 		info->tcpi_snd_wscale = tp->rx_opt.snd_wscale;
4263 		info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale;
4264 	}
4265 
4266 	if (tcp_ecn_mode_any(tp))
4267 		info->tcpi_options |= TCPI_OPT_ECN;
4268 	if (tp->ecn_flags & TCP_ECN_SEEN)
4269 		info->tcpi_options |= TCPI_OPT_ECN_SEEN;
4270 	if (tp->syn_data_acked)
4271 		info->tcpi_options |= TCPI_OPT_SYN_DATA;
4272 	if (tp->tcp_usec_ts)
4273 		info->tcpi_options |= TCPI_OPT_USEC_TS;
4274 	if (tp->syn_fastopen_child)
4275 		info->tcpi_options |= TCPI_OPT_TFO_CHILD;
4276 
4277 	info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto);
4278 	info->tcpi_ato = jiffies_to_usecs(min_t(u32, icsk->icsk_ack.ato,
4279 						tcp_delack_max(sk)));
4280 	info->tcpi_snd_mss = tp->mss_cache;
4281 	info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss;
4282 
4283 	info->tcpi_unacked = tp->packets_out;
4284 	info->tcpi_sacked = tp->sacked_out;
4285 
4286 	info->tcpi_lost = tp->lost_out;
4287 	info->tcpi_retrans = tp->retrans_out;
4288 
4289 	now = tcp_jiffies32;
4290 	info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime);
4291 	info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime);
4292 	info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp);
4293 
4294 	info->tcpi_pmtu = icsk->icsk_pmtu_cookie;
4295 	info->tcpi_rcv_ssthresh = tp->rcv_ssthresh;
4296 	info->tcpi_rtt = tp->srtt_us >> 3;
4297 	info->tcpi_rttvar = tp->mdev_us >> 2;
4298 	info->tcpi_snd_ssthresh = tp->snd_ssthresh;
4299 	info->tcpi_advmss = tp->advmss;
4300 
4301 	info->tcpi_rcv_rtt = tp->rcv_rtt_est.rtt_us >> 3;
4302 	info->tcpi_rcv_space = tp->rcvq_space.space;
4303 
4304 	info->tcpi_total_retrans = tp->total_retrans;
4305 
4306 	info->tcpi_bytes_acked = tp->bytes_acked;
4307 	info->tcpi_bytes_received = tp->bytes_received;
4308 	info->tcpi_notsent_bytes = max_t(int, 0, tp->write_seq - tp->snd_nxt);
4309 	tcp_get_info_chrono_stats(tp, info);
4310 
4311 	info->tcpi_segs_out = tp->segs_out;
4312 
4313 	/* segs_in and data_segs_in can be updated from tcp_segs_in() from BH */
4314 	info->tcpi_segs_in = READ_ONCE(tp->segs_in);
4315 	info->tcpi_data_segs_in = READ_ONCE(tp->data_segs_in);
4316 
4317 	info->tcpi_min_rtt = tcp_min_rtt(tp);
4318 	info->tcpi_data_segs_out = tp->data_segs_out;
4319 
4320 	info->tcpi_delivery_rate_app_limited = tp->rate_app_limited ? 1 : 0;
4321 	rate64 = tcp_compute_delivery_rate(tp);
4322 	if (rate64)
4323 		info->tcpi_delivery_rate = rate64;
4324 	info->tcpi_delivered = tp->delivered;
4325 	info->tcpi_delivered_ce = tp->delivered_ce;
4326 	info->tcpi_bytes_sent = tp->bytes_sent;
4327 	info->tcpi_bytes_retrans = tp->bytes_retrans;
4328 	info->tcpi_dsack_dups = tp->dsack_dups;
4329 	info->tcpi_reord_seen = tp->reord_seen;
4330 	info->tcpi_rcv_ooopack = tp->rcv_ooopack;
4331 	info->tcpi_snd_wnd = tp->snd_wnd;
4332 	info->tcpi_rcv_wnd = tp->rcv_wnd;
4333 	info->tcpi_rehash = tp->plb_rehash + tp->timeout_rehash;
4334 	info->tcpi_fastopen_client_fail = tp->fastopen_client_fail;
4335 
4336 	info->tcpi_total_rto = tp->total_rto;
4337 	info->tcpi_total_rto_recoveries = tp->total_rto_recoveries;
4338 	info->tcpi_total_rto_time = tp->total_rto_time;
4339 	if (tp->rto_stamp)
4340 		info->tcpi_total_rto_time += tcp_clock_ms() - tp->rto_stamp;
4341 
4342 	if (tcp_ecn_disabled(tp))
4343 		info->tcpi_ecn_mode = TCPI_ECN_MODE_DISABLED;
4344 	else if (tcp_ecn_mode_rfc3168(tp))
4345 		info->tcpi_ecn_mode = TCPI_ECN_MODE_RFC3168;
4346 	else if (tcp_ecn_mode_accecn(tp))
4347 		info->tcpi_ecn_mode = TCPI_ECN_MODE_ACCECN;
4348 	else if (tcp_ecn_mode_pending(tp))
4349 		info->tcpi_ecn_mode = TCPI_ECN_MODE_PENDING;
4350 	info->tcpi_accecn_fail_mode = tp->accecn_fail_mode;
4351 	info->tcpi_accecn_opt_seen = tp->saw_accecn_opt;
4352 	info->tcpi_received_ce = tp->received_ce;
4353 	info->tcpi_delivered_e1_bytes = tp->delivered_ecn_bytes[ect1_idx];
4354 	info->tcpi_delivered_e0_bytes = tp->delivered_ecn_bytes[ect0_idx];
4355 	info->tcpi_delivered_ce_bytes = tp->delivered_ecn_bytes[ce_idx];
4356 	info->tcpi_received_e1_bytes = tp->received_ecn_bytes[ect1_idx];
4357 	info->tcpi_received_e0_bytes = tp->received_ecn_bytes[ect0_idx];
4358 	info->tcpi_received_ce_bytes = tp->received_ecn_bytes[ce_idx];
4359 
4360 	unlock_sock_fast(sk, slow);
4361 }
4362 EXPORT_SYMBOL_GPL(tcp_get_info);
4363 
4364 static size_t tcp_opt_stats_get_size(void)
4365 {
4366 	return
4367 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_BUSY */
4368 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_RWND_LIMITED */
4369 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_SNDBUF_LIMITED */
4370 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_DATA_SEGS_OUT */
4371 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_TOTAL_RETRANS */
4372 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_PACING_RATE */
4373 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_DELIVERY_RATE */
4374 		nla_total_size(sizeof(u32)) + /* TCP_NLA_SND_CWND */
4375 		nla_total_size(sizeof(u32)) + /* TCP_NLA_REORDERING */
4376 		nla_total_size(sizeof(u32)) + /* TCP_NLA_MIN_RTT */
4377 		nla_total_size(sizeof(u8)) + /* TCP_NLA_RECUR_RETRANS */
4378 		nla_total_size(sizeof(u8)) + /* TCP_NLA_DELIVERY_RATE_APP_LMT */
4379 		nla_total_size(sizeof(u32)) + /* TCP_NLA_SNDQ_SIZE */
4380 		nla_total_size(sizeof(u8)) + /* TCP_NLA_CA_STATE */
4381 		nla_total_size(sizeof(u32)) + /* TCP_NLA_SND_SSTHRESH */
4382 		nla_total_size(sizeof(u32)) + /* TCP_NLA_DELIVERED */
4383 		nla_total_size(sizeof(u32)) + /* TCP_NLA_DELIVERED_CE */
4384 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_BYTES_SENT */
4385 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_BYTES_RETRANS */
4386 		nla_total_size(sizeof(u32)) + /* TCP_NLA_DSACK_DUPS */
4387 		nla_total_size(sizeof(u32)) + /* TCP_NLA_REORD_SEEN */
4388 		nla_total_size(sizeof(u32)) + /* TCP_NLA_SRTT */
4389 		nla_total_size(sizeof(u16)) + /* TCP_NLA_TIMEOUT_REHASH */
4390 		nla_total_size(sizeof(u32)) + /* TCP_NLA_BYTES_NOTSENT */
4391 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_EDT */
4392 		nla_total_size(sizeof(u8)) + /* TCP_NLA_TTL */
4393 		nla_total_size(sizeof(u32)) + /* TCP_NLA_REHASH */
4394 		0;
4395 }
4396 
4397 /* Returns TTL or hop limit of an incoming packet from skb. */
4398 static u8 tcp_skb_ttl_or_hop_limit(const struct sk_buff *skb)
4399 {
4400 	if (skb->protocol == htons(ETH_P_IP))
4401 		return ip_hdr(skb)->ttl;
4402 	else if (skb->protocol == htons(ETH_P_IPV6))
4403 		return ipv6_hdr(skb)->hop_limit;
4404 	else
4405 		return 0;
4406 }
4407 
4408 struct sk_buff *tcp_get_timestamping_opt_stats(const struct sock *sk,
4409 					       const struct sk_buff *orig_skb,
4410 					       const struct sk_buff *ack_skb)
4411 {
4412 	const struct tcp_sock *tp = tcp_sk(sk);
4413 	struct sk_buff *stats;
4414 	struct tcp_info info;
4415 	unsigned long rate;
4416 	u64 rate64;
4417 
4418 	stats = alloc_skb(tcp_opt_stats_get_size(), GFP_ATOMIC);
4419 	if (!stats)
4420 		return NULL;
4421 
4422 	tcp_get_info_chrono_stats(tp, &info);
4423 	nla_put_u64_64bit(stats, TCP_NLA_BUSY,
4424 			  info.tcpi_busy_time, TCP_NLA_PAD);
4425 	nla_put_u64_64bit(stats, TCP_NLA_RWND_LIMITED,
4426 			  info.tcpi_rwnd_limited, TCP_NLA_PAD);
4427 	nla_put_u64_64bit(stats, TCP_NLA_SNDBUF_LIMITED,
4428 			  info.tcpi_sndbuf_limited, TCP_NLA_PAD);
4429 	nla_put_u64_64bit(stats, TCP_NLA_DATA_SEGS_OUT,
4430 			  READ_ONCE(tp->data_segs_out), TCP_NLA_PAD);
4431 	nla_put_u64_64bit(stats, TCP_NLA_TOTAL_RETRANS,
4432 			  READ_ONCE(tp->total_retrans), TCP_NLA_PAD);
4433 
4434 	rate = READ_ONCE(sk->sk_pacing_rate);
4435 	rate64 = (rate != ~0UL) ? rate : ~0ULL;
4436 	nla_put_u64_64bit(stats, TCP_NLA_PACING_RATE, rate64, TCP_NLA_PAD);
4437 
4438 	rate64 = tcp_compute_delivery_rate(tp);
4439 	nla_put_u64_64bit(stats, TCP_NLA_DELIVERY_RATE, rate64, TCP_NLA_PAD);
4440 
4441 	nla_put_u32(stats, TCP_NLA_SND_CWND, READ_ONCE(tp->snd_cwnd));
4442 	nla_put_u32(stats, TCP_NLA_REORDERING, READ_ONCE(tp->reordering));
4443 	nla_put_u32(stats, TCP_NLA_MIN_RTT, data_race(tcp_min_rtt(tp)));
4444 
4445 	nla_put_u8(stats, TCP_NLA_RECUR_RETRANS,
4446 		   READ_ONCE(inet_csk(sk)->icsk_retransmits));
4447 	nla_put_u8(stats, TCP_NLA_DELIVERY_RATE_APP_LMT, data_race(!!tp->rate_app_limited));
4448 	nla_put_u32(stats, TCP_NLA_SND_SSTHRESH, READ_ONCE(tp->snd_ssthresh));
4449 	nla_put_u32(stats, TCP_NLA_DELIVERED, READ_ONCE(tp->delivered));
4450 	nla_put_u32(stats, TCP_NLA_DELIVERED_CE, READ_ONCE(tp->delivered_ce));
4451 
4452 	nla_put_u32(stats, TCP_NLA_SNDQ_SIZE,
4453 		    max_t(int, 0,
4454 			  READ_ONCE(tp->write_seq) - READ_ONCE(tp->snd_una)));
4455 	nla_put_u8(stats, TCP_NLA_CA_STATE, inet_csk(sk)->icsk_ca_state);
4456 
4457 	nla_put_u64_64bit(stats, TCP_NLA_BYTES_SENT, READ_ONCE(tp->bytes_sent),
4458 			  TCP_NLA_PAD);
4459 	nla_put_u64_64bit(stats, TCP_NLA_BYTES_RETRANS,
4460 			  READ_ONCE(tp->bytes_retrans), TCP_NLA_PAD);
4461 	nla_put_u32(stats, TCP_NLA_DSACK_DUPS, READ_ONCE(tp->dsack_dups));
4462 	nla_put_u32(stats, TCP_NLA_REORD_SEEN, READ_ONCE(tp->reord_seen));
4463 	nla_put_u32(stats, TCP_NLA_SRTT, READ_ONCE(tp->srtt_us) >> 3);
4464 	nla_put_u16(stats, TCP_NLA_TIMEOUT_REHASH,
4465 		    READ_ONCE(tp->timeout_rehash));
4466 	nla_put_u32(stats, TCP_NLA_BYTES_NOTSENT,
4467 		    max_t(int, 0,
4468 			  READ_ONCE(tp->write_seq) - READ_ONCE(tp->snd_nxt)));
4469 	nla_put_u64_64bit(stats, TCP_NLA_EDT, orig_skb->skb_mstamp_ns,
4470 			  TCP_NLA_PAD);
4471 	if (ack_skb)
4472 		nla_put_u8(stats, TCP_NLA_TTL,
4473 			   tcp_skb_ttl_or_hop_limit(ack_skb));
4474 
4475 	nla_put_u32(stats, TCP_NLA_REHASH,
4476 		    READ_ONCE(tp->plb_rehash) + READ_ONCE(tp->timeout_rehash));
4477 	return stats;
4478 }
4479 
4480 int do_tcp_getsockopt(struct sock *sk, int level,
4481 		      int optname, sockptr_t optval, sockptr_t optlen)
4482 {
4483 	struct inet_connection_sock *icsk = inet_csk(sk);
4484 	struct tcp_sock *tp = tcp_sk(sk);
4485 	struct net *net = sock_net(sk);
4486 	int user_mss;
4487 	int val, len;
4488 
4489 	if (copy_from_sockptr(&len, optlen, sizeof(int)))
4490 		return -EFAULT;
4491 
4492 	if (len < 0)
4493 		return -EINVAL;
4494 
4495 	len = min_t(unsigned int, len, sizeof(int));
4496 
4497 	switch (optname) {
4498 	case TCP_MAXSEG:
4499 		val = tp->mss_cache;
4500 		user_mss = READ_ONCE(tp->rx_opt.user_mss);
4501 		if (user_mss &&
4502 		    ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
4503 			val = user_mss;
4504 		if (tp->repair)
4505 			val = tp->rx_opt.mss_clamp;
4506 		break;
4507 	case TCP_NODELAY:
4508 		val = !!(tp->nonagle&TCP_NAGLE_OFF);
4509 		break;
4510 	case TCP_CORK:
4511 		val = !!(tp->nonagle&TCP_NAGLE_CORK);
4512 		break;
4513 	case TCP_KEEPIDLE:
4514 		val = keepalive_time_when(tp) / HZ;
4515 		break;
4516 	case TCP_KEEPINTVL:
4517 		val = keepalive_intvl_when(tp) / HZ;
4518 		break;
4519 	case TCP_KEEPCNT:
4520 		val = keepalive_probes(tp);
4521 		break;
4522 	case TCP_SYNCNT:
4523 		val = READ_ONCE(icsk->icsk_syn_retries) ? :
4524 			READ_ONCE(net->ipv4.sysctl_tcp_syn_retries);
4525 		break;
4526 	case TCP_LINGER2:
4527 		val = READ_ONCE(tp->linger2);
4528 		if (val >= 0)
4529 			val = (val ? : READ_ONCE(net->ipv4.sysctl_tcp_fin_timeout)) / HZ;
4530 		break;
4531 	case TCP_DEFER_ACCEPT:
4532 		val = READ_ONCE(icsk->icsk_accept_queue.rskq_defer_accept);
4533 		val = retrans_to_secs(val, TCP_TIMEOUT_INIT / HZ,
4534 				      TCP_RTO_MAX / HZ);
4535 		break;
4536 	case TCP_WINDOW_CLAMP:
4537 		val = READ_ONCE(tp->window_clamp);
4538 		break;
4539 	case TCP_INFO: {
4540 		struct tcp_info info;
4541 
4542 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4543 			return -EFAULT;
4544 
4545 		tcp_get_info(sk, &info);
4546 
4547 		len = min_t(unsigned int, len, sizeof(info));
4548 		if (copy_to_sockptr(optlen, &len, sizeof(int)))
4549 			return -EFAULT;
4550 		if (copy_to_sockptr(optval, &info, len))
4551 			return -EFAULT;
4552 		return 0;
4553 	}
4554 	case TCP_CC_INFO: {
4555 		const struct tcp_congestion_ops *ca_ops;
4556 		union tcp_cc_info info;
4557 		size_t sz = 0;
4558 		int attr;
4559 
4560 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4561 			return -EFAULT;
4562 
4563 		rcu_read_lock();
4564 		ca_ops = READ_ONCE(icsk->icsk_ca_ops);
4565 		if (ca_ops && ca_ops->get_info)
4566 			sz = ca_ops->get_info(sk, ~0U, &attr, &info);
4567 		rcu_read_unlock();
4568 
4569 		len = min_t(unsigned int, len, sz);
4570 		if (copy_to_sockptr(optlen, &len, sizeof(int)))
4571 			return -EFAULT;
4572 		if (copy_to_sockptr(optval, &info, len))
4573 			return -EFAULT;
4574 		return 0;
4575 	}
4576 	case TCP_QUICKACK:
4577 		val = !inet_csk_in_pingpong_mode(sk);
4578 		break;
4579 
4580 	case TCP_CONGESTION: {
4581 		char ca_name[TCP_CA_NAME_MAX] = {};
4582 
4583 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4584 			return -EFAULT;
4585 		len = min_t(unsigned int, len, TCP_CA_NAME_MAX);
4586 		if (copy_to_sockptr(optlen, &len, sizeof(int)))
4587 			return -EFAULT;
4588 
4589 		rcu_read_lock();
4590 		memcpy(ca_name, READ_ONCE(icsk->icsk_ca_ops)->name,
4591 		       sizeof(ca_name));
4592 		rcu_read_unlock();
4593 
4594 		if (copy_to_sockptr(optval, ca_name, len))
4595 			return -EFAULT;
4596 		return 0;
4597 	}
4598 	case TCP_ULP:
4599 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4600 			return -EFAULT;
4601 		len = min_t(unsigned int, len, TCP_ULP_NAME_MAX);
4602 		if (!icsk->icsk_ulp_ops) {
4603 			len = 0;
4604 			if (copy_to_sockptr(optlen, &len, sizeof(int)))
4605 				return -EFAULT;
4606 			return 0;
4607 		}
4608 		if (copy_to_sockptr(optlen, &len, sizeof(int)))
4609 			return -EFAULT;
4610 		if (copy_to_sockptr(optval, icsk->icsk_ulp_ops->name, len))
4611 			return -EFAULT;
4612 		return 0;
4613 
4614 	case TCP_FASTOPEN_KEY: {
4615 		u64 key[TCP_FASTOPEN_KEY_BUF_LENGTH / sizeof(u64)];
4616 		unsigned int key_len;
4617 
4618 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4619 			return -EFAULT;
4620 
4621 		key_len = tcp_fastopen_get_cipher(net, icsk, key) *
4622 				TCP_FASTOPEN_KEY_LENGTH;
4623 		len = min_t(unsigned int, len, key_len);
4624 		if (copy_to_sockptr(optlen, &len, sizeof(int)))
4625 			return -EFAULT;
4626 		if (copy_to_sockptr(optval, key, len))
4627 			return -EFAULT;
4628 		return 0;
4629 	}
4630 	case TCP_THIN_LINEAR_TIMEOUTS:
4631 		val = tp->thin_lto;
4632 		break;
4633 
4634 	case TCP_THIN_DUPACK:
4635 		val = 0;
4636 		break;
4637 
4638 	case TCP_REPAIR:
4639 		val = tp->repair;
4640 		break;
4641 
4642 	case TCP_REPAIR_QUEUE:
4643 		if (tp->repair)
4644 			val = tp->repair_queue;
4645 		else
4646 			return -EINVAL;
4647 		break;
4648 
4649 	case TCP_REPAIR_WINDOW: {
4650 		struct tcp_repair_window opt;
4651 
4652 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4653 			return -EFAULT;
4654 
4655 		if (len != sizeof(opt))
4656 			return -EINVAL;
4657 
4658 		if (!tp->repair)
4659 			return -EPERM;
4660 
4661 		opt.snd_wl1	= tp->snd_wl1;
4662 		opt.snd_wnd	= tp->snd_wnd;
4663 		opt.max_window	= tp->max_window;
4664 		opt.rcv_wnd	= tp->rcv_wnd;
4665 		opt.rcv_wup	= tp->rcv_wup;
4666 
4667 		if (copy_to_sockptr(optval, &opt, len))
4668 			return -EFAULT;
4669 		return 0;
4670 	}
4671 	case TCP_QUEUE_SEQ:
4672 		if (tp->repair_queue == TCP_SEND_QUEUE)
4673 			val = tp->write_seq;
4674 		else if (tp->repair_queue == TCP_RECV_QUEUE)
4675 			val = tp->rcv_nxt;
4676 		else
4677 			return -EINVAL;
4678 		break;
4679 
4680 	case TCP_USER_TIMEOUT:
4681 		val = READ_ONCE(icsk->icsk_user_timeout);
4682 		break;
4683 
4684 	case TCP_FASTOPEN:
4685 		val = READ_ONCE(icsk->icsk_accept_queue.fastopenq.max_qlen);
4686 		break;
4687 
4688 	case TCP_FASTOPEN_CONNECT:
4689 		val = tp->fastopen_connect;
4690 		break;
4691 
4692 	case TCP_FASTOPEN_NO_COOKIE:
4693 		val = tp->fastopen_no_cookie;
4694 		break;
4695 
4696 	case TCP_TX_DELAY:
4697 		val = READ_ONCE(tp->tcp_tx_delay);
4698 		break;
4699 
4700 	case TCP_TIMESTAMP:
4701 		val = tcp_clock_ts(tp->tcp_usec_ts) + READ_ONCE(tp->tsoffset);
4702 		if (tp->tcp_usec_ts)
4703 			val |= 1;
4704 		else
4705 			val &= ~1;
4706 		break;
4707 	case TCP_NOTSENT_LOWAT:
4708 		val = READ_ONCE(tp->notsent_lowat);
4709 		break;
4710 	case TCP_INQ:
4711 		val = tp->recvmsg_inq;
4712 		break;
4713 	case TCP_SAVE_SYN:
4714 		val = tp->save_syn;
4715 		break;
4716 	case TCP_SAVED_SYN: {
4717 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4718 			return -EFAULT;
4719 
4720 		sockopt_lock_sock(sk);
4721 		if (tp->saved_syn) {
4722 			if (len < tcp_saved_syn_len(tp->saved_syn)) {
4723 				len = tcp_saved_syn_len(tp->saved_syn);
4724 				if (copy_to_sockptr(optlen, &len, sizeof(int))) {
4725 					sockopt_release_sock(sk);
4726 					return -EFAULT;
4727 				}
4728 				sockopt_release_sock(sk);
4729 				return -EINVAL;
4730 			}
4731 			len = tcp_saved_syn_len(tp->saved_syn);
4732 			if (copy_to_sockptr(optlen, &len, sizeof(int))) {
4733 				sockopt_release_sock(sk);
4734 				return -EFAULT;
4735 			}
4736 			if (copy_to_sockptr(optval, tp->saved_syn->data, len)) {
4737 				sockopt_release_sock(sk);
4738 				return -EFAULT;
4739 			}
4740 			tcp_saved_syn_free(tp);
4741 			sockopt_release_sock(sk);
4742 		} else {
4743 			sockopt_release_sock(sk);
4744 			len = 0;
4745 			if (copy_to_sockptr(optlen, &len, sizeof(int)))
4746 				return -EFAULT;
4747 		}
4748 		return 0;
4749 	}
4750 #ifdef CONFIG_MMU
4751 	case TCP_ZEROCOPY_RECEIVE: {
4752 		struct scm_timestamping_internal tss;
4753 		struct tcp_zerocopy_receive zc = {};
4754 		int err;
4755 
4756 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4757 			return -EFAULT;
4758 		if (len < 0 ||
4759 		    len < offsetofend(struct tcp_zerocopy_receive, length))
4760 			return -EINVAL;
4761 		if (unlikely(len > sizeof(zc))) {
4762 			err = check_zeroed_sockptr(optval, sizeof(zc),
4763 						   len - sizeof(zc));
4764 			if (err < 1)
4765 				return err == 0 ? -EINVAL : err;
4766 			len = sizeof(zc);
4767 			if (copy_to_sockptr(optlen, &len, sizeof(int)))
4768 				return -EFAULT;
4769 		}
4770 		if (copy_from_sockptr(&zc, optval, len))
4771 			return -EFAULT;
4772 		if (zc.reserved)
4773 			return -EINVAL;
4774 		if (zc.msg_flags &  ~(TCP_VALID_ZC_MSG_FLAGS))
4775 			return -EINVAL;
4776 		sockopt_lock_sock(sk);
4777 		err = tcp_zerocopy_receive(sk, &zc, &tss);
4778 		err = BPF_CGROUP_RUN_PROG_GETSOCKOPT_KERN(sk, level, optname,
4779 							  &zc, &len, err);
4780 		sockopt_release_sock(sk);
4781 		if (len >= offsetofend(struct tcp_zerocopy_receive, msg_flags))
4782 			goto zerocopy_rcv_cmsg;
4783 		switch (len) {
4784 		case offsetofend(struct tcp_zerocopy_receive, msg_flags):
4785 			goto zerocopy_rcv_cmsg;
4786 		case offsetofend(struct tcp_zerocopy_receive, msg_controllen):
4787 		case offsetofend(struct tcp_zerocopy_receive, msg_control):
4788 		case offsetofend(struct tcp_zerocopy_receive, flags):
4789 		case offsetofend(struct tcp_zerocopy_receive, copybuf_len):
4790 		case offsetofend(struct tcp_zerocopy_receive, copybuf_address):
4791 		case offsetofend(struct tcp_zerocopy_receive, err):
4792 			goto zerocopy_rcv_sk_err;
4793 		case offsetofend(struct tcp_zerocopy_receive, inq):
4794 			goto zerocopy_rcv_inq;
4795 		case offsetofend(struct tcp_zerocopy_receive, length):
4796 		default:
4797 			goto zerocopy_rcv_out;
4798 		}
4799 zerocopy_rcv_cmsg:
4800 		if (zc.msg_flags & TCP_CMSG_TS)
4801 			tcp_zc_finalize_rx_tstamp(sk, &zc, &tss);
4802 		else
4803 			zc.msg_flags = 0;
4804 zerocopy_rcv_sk_err:
4805 		if (!err)
4806 			zc.err = sock_error(sk);
4807 zerocopy_rcv_inq:
4808 		zc.inq = tcp_inq_hint(sk);
4809 zerocopy_rcv_out:
4810 		if (!err && copy_to_sockptr(optval, &zc, len))
4811 			err = -EFAULT;
4812 		return err;
4813 	}
4814 #endif
4815 	case TCP_AO_REPAIR:
4816 		if (!tcp_can_repair_sock(sk))
4817 			return -EPERM;
4818 		return tcp_ao_get_repair(sk, optval, optlen);
4819 	case TCP_AO_GET_KEYS:
4820 	case TCP_AO_INFO: {
4821 		int err;
4822 
4823 		sockopt_lock_sock(sk);
4824 		if (optname == TCP_AO_GET_KEYS)
4825 			err = tcp_ao_get_mkts(sk, optval, optlen);
4826 		else
4827 			err = tcp_ao_get_sock_info(sk, optval, optlen);
4828 		sockopt_release_sock(sk);
4829 
4830 		return err;
4831 	}
4832 	case TCP_IS_MPTCP:
4833 		val = 0;
4834 		break;
4835 	case TCP_RTO_MAX_MS:
4836 		val = jiffies_to_msecs(tcp_rto_max(sk));
4837 		break;
4838 	case TCP_RTO_MIN_US:
4839 		val = jiffies_to_usecs(READ_ONCE(inet_csk(sk)->icsk_rto_min));
4840 		break;
4841 	case TCP_DELACK_MAX_US:
4842 		val = jiffies_to_usecs(READ_ONCE(inet_csk(sk)->icsk_delack_max));
4843 		break;
4844 	default:
4845 		return -ENOPROTOOPT;
4846 	}
4847 
4848 	if (copy_to_sockptr(optlen, &len, sizeof(int)))
4849 		return -EFAULT;
4850 	if (copy_to_sockptr(optval, &val, len))
4851 		return -EFAULT;
4852 	return 0;
4853 }
4854 
4855 bool tcp_bpf_bypass_getsockopt(int level, int optname)
4856 {
4857 	/* TCP do_tcp_getsockopt has optimized getsockopt implementation
4858 	 * to avoid extra socket lock for TCP_ZEROCOPY_RECEIVE.
4859 	 */
4860 	if (level == SOL_TCP && optname == TCP_ZEROCOPY_RECEIVE)
4861 		return true;
4862 
4863 	return false;
4864 }
4865 
4866 int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval,
4867 		   int __user *optlen)
4868 {
4869 	struct inet_connection_sock *icsk = inet_csk(sk);
4870 
4871 	if (level != SOL_TCP)
4872 		/* Paired with WRITE_ONCE() in do_ipv6_setsockopt() and tcp_v6_connect() */
4873 		return READ_ONCE(icsk->icsk_af_ops)->getsockopt(sk, level, optname,
4874 								optval, optlen);
4875 	return do_tcp_getsockopt(sk, level, optname, USER_SOCKPTR(optval),
4876 				 USER_SOCKPTR(optlen));
4877 }
4878 
4879 #ifdef CONFIG_TCP_MD5SIG
4880 void tcp_md5_hash_skb_data(struct md5_ctx *ctx, const struct sk_buff *skb,
4881 			   unsigned int header_len)
4882 {
4883 	const unsigned int head_data_len = skb_headlen(skb) > header_len ?
4884 					   skb_headlen(skb) - header_len : 0;
4885 	const struct skb_shared_info *shi = skb_shinfo(skb);
4886 	struct sk_buff *frag_iter;
4887 	unsigned int i;
4888 
4889 	md5_update(ctx, (const u8 *)tcp_hdr(skb) + header_len, head_data_len);
4890 
4891 	for (i = 0; i < shi->nr_frags; ++i) {
4892 		const skb_frag_t *f = &shi->frags[i];
4893 		u32 p_off, p_len, copied;
4894 		const void *vaddr;
4895 		struct page *p;
4896 
4897 		skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
4898 				      p, p_off, p_len, copied) {
4899 			vaddr = kmap_local_page(p);
4900 			md5_update(ctx, vaddr + p_off, p_len);
4901 			kunmap_local(vaddr);
4902 		}
4903 	}
4904 
4905 	skb_walk_frags(skb, frag_iter)
4906 		tcp_md5_hash_skb_data(ctx, frag_iter, 0);
4907 }
4908 
4909 void tcp_md5_hash_key(struct md5_ctx *ctx,
4910 		      const struct tcp_md5sig_key *key)
4911 {
4912 	u8 keylen = READ_ONCE(key->keylen); /* paired with WRITE_ONCE() in tcp_md5_do_add */
4913 
4914 	/* We use data_race() because tcp_md5_do_add() might change
4915 	 * key->key under us
4916 	 */
4917 	data_race(({ md5_update(ctx, key->key, keylen), 0; }));
4918 }
4919 
4920 /* Called with rcu_read_lock() */
4921 static enum skb_drop_reason
4922 tcp_inbound_md5_hash(const struct sock *sk, const struct sk_buff *skb,
4923 		     const void *saddr, const void *daddr,
4924 		     int family, int l3index, const __u8 *hash_location)
4925 {
4926 	/* This gets called for each TCP segment that has TCP-MD5 option.
4927 	 * We have 2 drop cases:
4928 	 * o An MD5 signature is present, but we're not expecting one.
4929 	 * o The MD5 signature is wrong.
4930 	 */
4931 	const struct tcp_sock *tp = tcp_sk(sk);
4932 	struct tcp_md5sig_key *key;
4933 	u8 newhash[16];
4934 
4935 	key = tcp_md5_do_lookup(sk, l3index, saddr, family);
4936 	if (!key) {
4937 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5UNEXPECTED);
4938 		trace_tcp_hash_md5_unexpected(sk, skb);
4939 		return SKB_DROP_REASON_TCP_MD5UNEXPECTED;
4940 	}
4941 
4942 	/* Check the signature.
4943 	 * To support dual stack listeners, we need to handle
4944 	 * IPv4-mapped case.
4945 	 */
4946 	if (family == AF_INET)
4947 		tcp_v4_md5_hash_skb(newhash, key, NULL, skb);
4948 	else
4949 		tp->af_specific->calc_md5_hash(newhash, key, NULL, skb);
4950 	if (crypto_memneq(hash_location, newhash, 16)) {
4951 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5FAILURE);
4952 		trace_tcp_hash_md5_mismatch(sk, skb);
4953 		return SKB_DROP_REASON_TCP_MD5FAILURE;
4954 	}
4955 	return SKB_NOT_DROPPED_YET;
4956 }
4957 #else
4958 static inline enum skb_drop_reason
4959 tcp_inbound_md5_hash(const struct sock *sk, const struct sk_buff *skb,
4960 		     const void *saddr, const void *daddr,
4961 		     int family, int l3index, const __u8 *hash_location)
4962 {
4963 	return SKB_NOT_DROPPED_YET;
4964 }
4965 
4966 #endif
4967 
4968 #if defined(CONFIG_TCP_MD5SIG) || defined(CONFIG_TCP_AO)
4969 /*
4970  * Parse Signature options
4971  */
4972 int tcp_do_parse_auth_options(const struct tcphdr *th,
4973 			      const u8 **md5_hash, const u8 **ao_hash)
4974 {
4975 	int length = (th->doff << 2) - sizeof(*th);
4976 	const u8 *ptr = (const u8 *)(th + 1);
4977 	unsigned int minlen = TCPOLEN_MD5SIG;
4978 
4979 	if (IS_ENABLED(CONFIG_TCP_AO))
4980 		minlen = sizeof(struct tcp_ao_hdr) + 1;
4981 
4982 	*md5_hash = NULL;
4983 	*ao_hash = NULL;
4984 
4985 	/* If not enough data remaining, we can short cut */
4986 	while (length >= minlen) {
4987 		int opcode = *ptr++;
4988 		int opsize;
4989 
4990 		switch (opcode) {
4991 		case TCPOPT_EOL:
4992 			return 0;
4993 		case TCPOPT_NOP:
4994 			length--;
4995 			continue;
4996 		default:
4997 			opsize = *ptr++;
4998 			if (opsize < 2 || opsize > length)
4999 				return -EINVAL;
5000 			if (opcode == TCPOPT_MD5SIG) {
5001 				if (opsize != TCPOLEN_MD5SIG)
5002 					return -EINVAL;
5003 				if (unlikely(*md5_hash || *ao_hash))
5004 					return -EEXIST;
5005 				*md5_hash = ptr;
5006 			} else if (opcode == TCPOPT_AO) {
5007 				if (opsize <= sizeof(struct tcp_ao_hdr))
5008 					return -EINVAL;
5009 				if (unlikely(*md5_hash || *ao_hash))
5010 					return -EEXIST;
5011 				*ao_hash = ptr;
5012 			}
5013 		}
5014 		ptr += opsize - 2;
5015 		length -= opsize;
5016 	}
5017 	return 0;
5018 }
5019 #endif
5020 
5021 /* Called with rcu_read_lock() */
5022 enum skb_drop_reason
5023 tcp_inbound_hash(struct sock *sk, const struct request_sock *req,
5024 		 const struct sk_buff *skb,
5025 		 const void *saddr, const void *daddr,
5026 		 int family, int dif, int sdif)
5027 {
5028 	const struct tcphdr *th = tcp_hdr(skb);
5029 	const struct tcp_ao_hdr *aoh;
5030 	const __u8 *md5_location;
5031 	int l3index;
5032 
5033 	/* Invalid option or two times meet any of auth options */
5034 	if (tcp_parse_auth_options(th, &md5_location, &aoh)) {
5035 		trace_tcp_hash_bad_header(sk, skb);
5036 		return SKB_DROP_REASON_TCP_AUTH_HDR;
5037 	}
5038 
5039 	if (req) {
5040 		if (tcp_rsk_used_ao(req) != !!aoh) {
5041 			u8 keyid, rnext, maclen;
5042 
5043 			if (aoh) {
5044 				keyid = aoh->keyid;
5045 				rnext = aoh->rnext_keyid;
5046 				maclen = tcp_ao_hdr_maclen(aoh);
5047 			} else {
5048 				keyid = rnext = maclen = 0;
5049 			}
5050 
5051 			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAOBAD);
5052 			trace_tcp_ao_handshake_failure(sk, skb, keyid, rnext, maclen);
5053 			return SKB_DROP_REASON_TCP_AOFAILURE;
5054 		}
5055 	}
5056 
5057 	/* sdif set, means packet ingressed via a device
5058 	 * in an L3 domain and dif is set to the l3mdev
5059 	 */
5060 	l3index = sdif ? dif : 0;
5061 
5062 	/* Fast path: unsigned segments */
5063 	if (likely(!md5_location && !aoh)) {
5064 		/* Drop if there's TCP-MD5 or TCP-AO key with any rcvid/sndid
5065 		 * for the remote peer. On TCP-AO established connection
5066 		 * the last key is impossible to remove, so there's
5067 		 * always at least one current_key.
5068 		 */
5069 		if (tcp_ao_required(sk, saddr, family, l3index, true)) {
5070 			trace_tcp_hash_ao_required(sk, skb);
5071 			return SKB_DROP_REASON_TCP_AONOTFOUND;
5072 		}
5073 		if (unlikely(tcp_md5_do_lookup(sk, l3index, saddr, family))) {
5074 			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5NOTFOUND);
5075 			trace_tcp_hash_md5_required(sk, skb);
5076 			return SKB_DROP_REASON_TCP_MD5NOTFOUND;
5077 		}
5078 		return SKB_NOT_DROPPED_YET;
5079 	}
5080 
5081 	if (aoh)
5082 		return tcp_inbound_ao_hash(sk, skb, family, req, l3index, aoh);
5083 
5084 	return tcp_inbound_md5_hash(sk, skb, saddr, daddr, family,
5085 				    l3index, md5_location);
5086 }
5087 
5088 void tcp_done(struct sock *sk)
5089 {
5090 	struct request_sock *req;
5091 
5092 	/* We might be called with a new socket, after
5093 	 * inet_csk_prepare_forced_close() has been called
5094 	 * so we can not use lockdep_sock_is_held(sk)
5095 	 */
5096 	req = rcu_dereference_protected(tcp_sk(sk)->fastopen_rsk, 1);
5097 
5098 	if (sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV)
5099 		TCP_INC_STATS(sock_net(sk), TCP_MIB_ATTEMPTFAILS);
5100 
5101 	tcp_set_state(sk, TCP_CLOSE);
5102 	tcp_clear_xmit_timers(sk);
5103 	if (req)
5104 		reqsk_fastopen_remove(sk, req, false);
5105 
5106 	WRITE_ONCE(sk->sk_shutdown, SHUTDOWN_MASK);
5107 
5108 	if (!sock_flag(sk, SOCK_DEAD))
5109 		sk->sk_state_change(sk);
5110 	else
5111 		inet_csk_destroy_sock(sk);
5112 }
5113 
5114 int tcp_abort(struct sock *sk, int err)
5115 {
5116 	int state = inet_sk_state_load(sk);
5117 
5118 	if (state == TCP_NEW_SYN_RECV) {
5119 		struct request_sock *req = inet_reqsk(sk);
5120 
5121 		local_bh_disable();
5122 		inet_csk_reqsk_queue_drop(req->rsk_listener, req);
5123 		local_bh_enable();
5124 		return 0;
5125 	}
5126 	if (state == TCP_TIME_WAIT) {
5127 		struct inet_timewait_sock *tw = inet_twsk(sk);
5128 
5129 		refcount_inc(&tw->tw_refcnt);
5130 		local_bh_disable();
5131 		inet_twsk_deschedule_put(tw);
5132 		local_bh_enable();
5133 		return 0;
5134 	}
5135 
5136 	/* BPF context ensures sock locking. */
5137 	if (!has_current_bpf_ctx())
5138 		/* Don't race with userspace socket closes such as tcp_close. */
5139 		lock_sock(sk);
5140 
5141 	/* Avoid closing the same socket twice. */
5142 	if (sk->sk_state == TCP_CLOSE) {
5143 		if (!has_current_bpf_ctx())
5144 			release_sock(sk);
5145 		return -ENOENT;
5146 	}
5147 
5148 	if (sk->sk_state == TCP_LISTEN) {
5149 		tcp_set_state(sk, TCP_CLOSE);
5150 		inet_csk_listen_stop(sk);
5151 	}
5152 
5153 	/* Don't race with BH socket closes such as inet_csk_listen_stop. */
5154 	local_bh_disable();
5155 	bh_lock_sock(sk);
5156 
5157 	if (tcp_need_reset(sk->sk_state))
5158 		tcp_send_active_reset(sk, SK_RST_REASON_TCP_STATE);
5159 	tcp_done_with_error(sk, err);
5160 
5161 	bh_unlock_sock(sk);
5162 	local_bh_enable();
5163 	if (!has_current_bpf_ctx())
5164 		release_sock(sk);
5165 	return 0;
5166 }
5167 EXPORT_SYMBOL_GPL(tcp_abort);
5168 
5169 extern struct tcp_congestion_ops tcp_reno;
5170 
5171 static __initdata unsigned long thash_entries;
5172 static int __init set_thash_entries(char *str)
5173 {
5174 	ssize_t ret;
5175 
5176 	if (!str)
5177 		return 0;
5178 
5179 	ret = kstrtoul(str, 0, &thash_entries);
5180 	if (ret)
5181 		return 0;
5182 
5183 	return 1;
5184 }
5185 __setup("thash_entries=", set_thash_entries);
5186 
5187 static void __init tcp_init_mem(void)
5188 {
5189 	unsigned long limit = nr_free_buffer_pages() / 16;
5190 
5191 	limit = max(limit, 128UL);
5192 	sysctl_tcp_mem[0] = limit / 4 * 3;		/* 4.68 % */
5193 	sysctl_tcp_mem[1] = limit;			/* 6.25 % */
5194 	sysctl_tcp_mem[2] = sysctl_tcp_mem[0] * 2;	/* 9.37 % */
5195 }
5196 
5197 static void __init tcp_struct_check(void)
5198 {
5199 	/* TX read-mostly hotpath cache lines */
5200 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_tx, max_window);
5201 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_tx, rcv_ssthresh);
5202 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_tx, reordering);
5203 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_tx, notsent_lowat);
5204 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_tx, gso_segs);
5205 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_tx, retransmit_skb_hint);
5206 #if IS_ENABLED(CONFIG_TLS_DEVICE)
5207 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_tx, tcp_clean_acked);
5208 #endif
5209 
5210 	/* TXRX read-mostly hotpath cache lines */
5211 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, tsoffset);
5212 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, snd_wnd);
5213 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, mss_cache);
5214 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, snd_cwnd);
5215 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, prr_out);
5216 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, lost_out);
5217 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, sacked_out);
5218 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, scaling_ratio);
5219 #ifdef CONFIG_BPF
5220 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, bpf_tcp_ops_flags);
5221 #endif
5222 
5223 	/* RX read-mostly hotpath cache lines */
5224 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, copied_seq);
5225 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, snd_wl1);
5226 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, tlp_high_seq);
5227 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, rttvar_us);
5228 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, retrans_out);
5229 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, advmss);
5230 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, urg_data);
5231 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, lost);
5232 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, rtt_min);
5233 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, out_of_order_queue);
5234 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, snd_ssthresh);
5235 
5236 	/* TX read-write hotpath cache lines */
5237 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, data_segs_out);
5238 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, delivered);
5239 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, delivered_ce);
5240 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, bytes_acked);
5241 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, bytes_sent);
5242 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, first_tx_mstamp);
5243 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, delivered_mstamp);
5244 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, snd_sml);
5245 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, tcp_nospace);
5246 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, chrono_start);
5247 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, chrono_stat);
5248 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, write_seq);
5249 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, pushed_seq);
5250 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, lsndtime);
5251 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, mdev_us);
5252 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, tcp_wstamp_ns);
5253 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, accecn_opt_tstamp);
5254 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, rtt_seq);
5255 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, max_packets_out);
5256 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, cwnd_usage_seq);
5257 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, rate_delivered);
5258 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, rate_interval_us);
5259 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, tsorted_sent_queue);
5260 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, highest_sack);
5261 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, ecn_flags);
5262 
5263 	/* TXRX read-write hotpath cache lines */
5264 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, pred_flags);
5265 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, tcp_clock_cache);
5266 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, tcp_mstamp);
5267 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, rcv_nxt);
5268 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, snd_nxt);
5269 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, snd_una);
5270 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, window_clamp);
5271 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, srtt_us);
5272 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, packets_out);
5273 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, snd_up);
5274 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, received_ce);
5275 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, received_ecn_bytes);
5276 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, app_limited);
5277 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, rcv_wnd);
5278 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, rcv_mwnd_seq);
5279 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, rcv_tstamp);
5280 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, rx_opt);
5281 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, segs_in);
5282 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, segs_out);
5283 
5284 	/* RX read-write hotpath cache lines */
5285 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, bytes_received);
5286 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, data_segs_in);
5287 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcv_wup);
5288 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcv_rtt_last_tsecr);
5289 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, delivered_ecn_bytes);
5290 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, pkts_acked_ewma);
5291 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcv_rtt_est);
5292 	CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcvq_space);
5293 }
5294 
5295 void __init tcp_init(void)
5296 {
5297 	int max_rshare, max_wshare, cnt;
5298 	unsigned long limit;
5299 	unsigned int i;
5300 
5301 	BUILD_BUG_ON(TCP_MIN_SND_MSS <= MAX_TCP_OPTION_SPACE);
5302 	BUILD_BUG_ON(sizeof(struct tcp_skb_cb) >
5303 		     sizeof_field(struct sk_buff, cb));
5304 
5305 	tcp_struct_check();
5306 
5307 	percpu_counter_init(&tcp_sockets_allocated, 0, GFP_KERNEL);
5308 
5309 	timer_setup(&tcp_orphan_timer, tcp_orphan_update, TIMER_DEFERRABLE);
5310 	mod_timer(&tcp_orphan_timer, jiffies + TCP_ORPHAN_TIMER_PERIOD);
5311 
5312 	inet_hashinfo2_init(&tcp_hashinfo, "tcp_listen_portaddr_hash",
5313 			    thash_entries, 21,  /* one slot per 2 MB*/
5314 			    0, 64 * 1024);
5315 	tcp_hashinfo.bind_bucket_cachep =
5316 		kmem_cache_create("tcp_bind_bucket",
5317 				  sizeof(struct inet_bind_bucket), 0,
5318 				  SLAB_HWCACHE_ALIGN | SLAB_PANIC |
5319 				  SLAB_ACCOUNT,
5320 				  NULL);
5321 	tcp_hashinfo.bind2_bucket_cachep =
5322 		kmem_cache_create("tcp_bind2_bucket",
5323 				  sizeof(struct inet_bind2_bucket), 0,
5324 				  SLAB_HWCACHE_ALIGN | SLAB_PANIC |
5325 				  SLAB_ACCOUNT,
5326 				  NULL);
5327 
5328 	/* Size and allocate the main established and bind bucket
5329 	 * hash tables.
5330 	 *
5331 	 * The methodology is similar to that of the buffer cache.
5332 	 */
5333 	tcp_hashinfo.ehash =
5334 		alloc_large_system_hash("TCP established",
5335 					sizeof(struct inet_ehash_bucket),
5336 					thash_entries,
5337 					17, /* one slot per 128 KB of memory */
5338 					0,
5339 					NULL,
5340 					&tcp_hashinfo.ehash_mask,
5341 					0,
5342 					thash_entries ? 0 : 512 * 1024);
5343 	for (i = 0; i <= tcp_hashinfo.ehash_mask; i++)
5344 		INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i);
5345 
5346 	if (inet_ehash_locks_alloc(&tcp_hashinfo))
5347 		panic("TCP: failed to alloc ehash_locks");
5348 	tcp_hashinfo.bhash =
5349 		alloc_large_system_hash("TCP bind",
5350 					2 * sizeof(struct inet_bind_hashbucket),
5351 					tcp_hashinfo.ehash_mask + 1,
5352 					17, /* one slot per 128 KB of memory */
5353 					0,
5354 					&tcp_hashinfo.bhash_size,
5355 					NULL,
5356 					0,
5357 					64 * 1024);
5358 	tcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size;
5359 	tcp_hashinfo.bhash2 = tcp_hashinfo.bhash + tcp_hashinfo.bhash_size;
5360 	for (i = 0; i < tcp_hashinfo.bhash_size; i++) {
5361 		spin_lock_init(&tcp_hashinfo.bhash[i].lock);
5362 		INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain);
5363 		spin_lock_init(&tcp_hashinfo.bhash2[i].lock);
5364 		INIT_HLIST_HEAD(&tcp_hashinfo.bhash2[i].chain);
5365 	}
5366 
5367 	tcp_hashinfo.pernet = false;
5368 
5369 	cnt = tcp_hashinfo.ehash_mask + 1;
5370 	sysctl_tcp_max_orphans = cnt / 2;
5371 
5372 	tcp_init_mem();
5373 	/* Set per-socket limits to no more than 1/128 the pressure threshold */
5374 	limit = nr_free_buffer_pages() << (PAGE_SHIFT - 7);
5375 	max_wshare = min(4UL*1024*1024, limit);
5376 	max_rshare = min(32UL*1024*1024, limit);
5377 
5378 	init_net.ipv4.sysctl_tcp_wmem[0] = PAGE_SIZE;
5379 	init_net.ipv4.sysctl_tcp_wmem[1] = 16*1024;
5380 	init_net.ipv4.sysctl_tcp_wmem[2] = max(64*1024, max_wshare);
5381 
5382 	init_net.ipv4.sysctl_tcp_rmem[0] = PAGE_SIZE;
5383 	init_net.ipv4.sysctl_tcp_rmem[1] = 131072;
5384 	init_net.ipv4.sysctl_tcp_rmem[2] = max(131072, max_rshare);
5385 
5386 	pr_info("Hash tables configured (established %u bind %u)\n",
5387 		tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size);
5388 
5389 	tcp_v4_init();
5390 	tcp_metrics_init();
5391 	BUG_ON(tcp_register_congestion_control(&tcp_reno) != 0);
5392 	tcp_tsq_work_init();
5393 	mptcp_init();
5394 }
5395