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/hash.h>
247 #include <linux/kernel.h>
248 #include <linux/module.h>
249 #include <linux/types.h>
250 #include <linux/fcntl.h>
251 #include <linux/poll.h>
252 #include <linux/inet_diag.h>
253 #include <linux/init.h>
254 #include <linux/fs.h>
255 #include <linux/skbuff.h>
256 #include <linux/scatterlist.h>
257 #include <linux/splice.h>
258 #include <linux/net.h>
259 #include <linux/socket.h>
260 #include <linux/random.h>
261 #include <linux/memblock.h>
262 #include <linux/highmem.h>
263 #include <linux/cache.h>
264 #include <linux/err.h>
265 #include <linux/time.h>
266 #include <linux/slab.h>
267 #include <linux/errqueue.h>
268 #include <linux/static_key.h>
269 #include <linux/btf.h>
270 
271 #include <net/icmp.h>
272 #include <net/inet_common.h>
273 #include <net/tcp.h>
274 #include <net/mptcp.h>
275 #include <net/xfrm.h>
276 #include <net/ip.h>
277 #include <net/sock.h>
278 
279 #include <linux/uaccess.h>
280 #include <asm/ioctls.h>
281 #include <net/busy_poll.h>
282 
283 /* Track pending CMSGs. */
284 enum {
285 	TCP_CMSG_INQ = 1,
286 	TCP_CMSG_TS = 2
287 };
288 
289 DEFINE_PER_CPU(unsigned int, tcp_orphan_count);
290 EXPORT_PER_CPU_SYMBOL_GPL(tcp_orphan_count);
291 
292 long sysctl_tcp_mem[3] __read_mostly;
293 EXPORT_SYMBOL(sysctl_tcp_mem);
294 
295 atomic_long_t tcp_memory_allocated ____cacheline_aligned_in_smp;	/* Current allocated memory. */
296 EXPORT_SYMBOL(tcp_memory_allocated);
297 DEFINE_PER_CPU(int, tcp_memory_per_cpu_fw_alloc);
298 EXPORT_PER_CPU_SYMBOL_GPL(tcp_memory_per_cpu_fw_alloc);
299 
300 #if IS_ENABLED(CONFIG_SMC)
301 DEFINE_STATIC_KEY_FALSE(tcp_have_smc);
302 EXPORT_SYMBOL(tcp_have_smc);
303 #endif
304 
305 /*
306  * Current number of TCP sockets.
307  */
308 struct percpu_counter tcp_sockets_allocated ____cacheline_aligned_in_smp;
309 EXPORT_SYMBOL(tcp_sockets_allocated);
310 
311 /*
312  * TCP splice context
313  */
314 struct tcp_splice_state {
315 	struct pipe_inode_info *pipe;
316 	size_t len;
317 	unsigned int flags;
318 };
319 
320 /*
321  * Pressure flag: try to collapse.
322  * Technical note: it is used by multiple contexts non atomically.
323  * All the __sk_mem_schedule() is of this nature: accounting
324  * is strict, actions are advisory and have some latency.
325  */
326 unsigned long tcp_memory_pressure __read_mostly;
327 EXPORT_SYMBOL_GPL(tcp_memory_pressure);
328 
tcp_enter_memory_pressure(struct sock * sk)329 void tcp_enter_memory_pressure(struct sock *sk)
330 {
331 	unsigned long val;
332 
333 	if (READ_ONCE(tcp_memory_pressure))
334 		return;
335 	val = jiffies;
336 
337 	if (!val)
338 		val--;
339 	if (!cmpxchg(&tcp_memory_pressure, 0, val))
340 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURES);
341 }
342 EXPORT_SYMBOL_GPL(tcp_enter_memory_pressure);
343 
tcp_leave_memory_pressure(struct sock * sk)344 void tcp_leave_memory_pressure(struct sock *sk)
345 {
346 	unsigned long val;
347 
348 	if (!READ_ONCE(tcp_memory_pressure))
349 		return;
350 	val = xchg(&tcp_memory_pressure, 0);
351 	if (val)
352 		NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURESCHRONO,
353 			      jiffies_to_msecs(jiffies - val));
354 }
355 EXPORT_SYMBOL_GPL(tcp_leave_memory_pressure);
356 
357 /* Convert seconds to retransmits based on initial and max timeout */
secs_to_retrans(int seconds,int timeout,int rto_max)358 static u8 secs_to_retrans(int seconds, int timeout, int rto_max)
359 {
360 	u8 res = 0;
361 
362 	if (seconds > 0) {
363 		int period = timeout;
364 
365 		res = 1;
366 		while (seconds > period && res < 255) {
367 			res++;
368 			timeout <<= 1;
369 			if (timeout > rto_max)
370 				timeout = rto_max;
371 			period += timeout;
372 		}
373 	}
374 	return res;
375 }
376 
377 /* Convert retransmits to seconds based on initial and max timeout */
retrans_to_secs(u8 retrans,int timeout,int rto_max)378 static int retrans_to_secs(u8 retrans, int timeout, int rto_max)
379 {
380 	int period = 0;
381 
382 	if (retrans > 0) {
383 		period = timeout;
384 		while (--retrans) {
385 			timeout <<= 1;
386 			if (timeout > rto_max)
387 				timeout = rto_max;
388 			period += timeout;
389 		}
390 	}
391 	return period;
392 }
393 
tcp_compute_delivery_rate(const struct tcp_sock * tp)394 static u64 tcp_compute_delivery_rate(const struct tcp_sock *tp)
395 {
396 	u32 rate = READ_ONCE(tp->rate_delivered);
397 	u32 intv = READ_ONCE(tp->rate_interval_us);
398 	u64 rate64 = 0;
399 
400 	if (rate && intv) {
401 		rate64 = (u64)rate * tp->mss_cache * USEC_PER_SEC;
402 		do_div(rate64, intv);
403 	}
404 	return rate64;
405 }
406 
407 /* Address-family independent initialization for a tcp_sock.
408  *
409  * NOTE: A lot of things set to zero explicitly by call to
410  *       sk_alloc() so need not be done here.
411  */
tcp_init_sock(struct sock * sk)412 void tcp_init_sock(struct sock *sk)
413 {
414 	struct inet_connection_sock *icsk = inet_csk(sk);
415 	struct tcp_sock *tp = tcp_sk(sk);
416 
417 	tp->out_of_order_queue = RB_ROOT;
418 	sk->tcp_rtx_queue = RB_ROOT;
419 	tcp_init_xmit_timers(sk);
420 	INIT_LIST_HEAD(&tp->tsq_node);
421 	INIT_LIST_HEAD(&tp->tsorted_sent_queue);
422 
423 	icsk->icsk_rto = TCP_TIMEOUT_INIT;
424 	icsk->icsk_rto_min = TCP_RTO_MIN;
425 	icsk->icsk_delack_max = TCP_DELACK_MAX;
426 	tp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT);
427 	minmax_reset(&tp->rtt_min, tcp_jiffies32, ~0U);
428 
429 	/* So many TCP implementations out there (incorrectly) count the
430 	 * initial SYN frame in their delayed-ACK and congestion control
431 	 * algorithms that we must have the following bandaid to talk
432 	 * efficiently to them.  -DaveM
433 	 */
434 	tcp_snd_cwnd_set(tp, TCP_INIT_CWND);
435 
436 	/* There's a bubble in the pipe until at least the first ACK. */
437 	tp->app_limited = ~0U;
438 
439 	/* See draft-stevens-tcpca-spec-01 for discussion of the
440 	 * initialization of these values.
441 	 */
442 	tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
443 	tp->snd_cwnd_clamp = ~0;
444 	tp->mss_cache = TCP_MSS_DEFAULT;
445 
446 	tp->reordering = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reordering);
447 	tcp_assign_congestion_control(sk);
448 
449 	tp->tsoffset = 0;
450 	tp->rack.reo_wnd_steps = 1;
451 
452 	sk->sk_write_space = sk_stream_write_space;
453 	sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
454 
455 	icsk->icsk_sync_mss = tcp_sync_mss;
456 
457 	WRITE_ONCE(sk->sk_sndbuf, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_wmem[1]));
458 	WRITE_ONCE(sk->sk_rcvbuf, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[1]));
459 
460 	set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
461 	sk_sockets_allocated_inc(sk);
462 }
463 EXPORT_SYMBOL(tcp_init_sock);
464 
tcp_tx_timestamp(struct sock * sk,u16 tsflags)465 static void tcp_tx_timestamp(struct sock *sk, u16 tsflags)
466 {
467 	struct sk_buff *skb = tcp_write_queue_tail(sk);
468 
469 	if (tsflags && skb) {
470 		struct skb_shared_info *shinfo = skb_shinfo(skb);
471 		struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
472 
473 		sock_tx_timestamp(sk, tsflags, &shinfo->tx_flags);
474 		if (tsflags & SOF_TIMESTAMPING_TX_ACK)
475 			tcb->txstamp_ack = 1;
476 		if (tsflags & SOF_TIMESTAMPING_TX_RECORD_MASK)
477 			shinfo->tskey = TCP_SKB_CB(skb)->seq + skb->len - 1;
478 	}
479 }
480 
tcp_stream_is_readable(struct sock * sk,int target)481 static bool tcp_stream_is_readable(struct sock *sk, int target)
482 {
483 	if (tcp_epollin_ready(sk, target))
484 		return true;
485 	return sk_is_readable(sk);
486 }
487 
488 /*
489  *	Wait for a TCP event.
490  *
491  *	Note that we don't need to lock the socket, as the upper poll layers
492  *	take care of normal races (between the test and the event) and we don't
493  *	go look at any of the socket buffers directly.
494  */
tcp_poll(struct file * file,struct socket * sock,poll_table * wait)495 __poll_t tcp_poll(struct file *file, struct socket *sock, poll_table *wait)
496 {
497 	__poll_t mask;
498 	struct sock *sk = sock->sk;
499 	const struct tcp_sock *tp = tcp_sk(sk);
500 	int state;
501 
502 	sock_poll_wait(file, sock, wait);
503 
504 	state = inet_sk_state_load(sk);
505 	if (state == TCP_LISTEN)
506 		return inet_csk_listen_poll(sk);
507 
508 	/* Socket is not locked. We are protected from async events
509 	 * by poll logic and correct handling of state changes
510 	 * made by other threads is impossible in any case.
511 	 */
512 
513 	mask = 0;
514 
515 	/*
516 	 * EPOLLHUP is certainly not done right. But poll() doesn't
517 	 * have a notion of HUP in just one direction, and for a
518 	 * socket the read side is more interesting.
519 	 *
520 	 * Some poll() documentation says that EPOLLHUP is incompatible
521 	 * with the EPOLLOUT/POLLWR flags, so somebody should check this
522 	 * all. But careful, it tends to be safer to return too many
523 	 * bits than too few, and you can easily break real applications
524 	 * if you don't tell them that something has hung up!
525 	 *
526 	 * Check-me.
527 	 *
528 	 * Check number 1. EPOLLHUP is _UNMASKABLE_ event (see UNIX98 and
529 	 * our fs/select.c). It means that after we received EOF,
530 	 * poll always returns immediately, making impossible poll() on write()
531 	 * in state CLOSE_WAIT. One solution is evident --- to set EPOLLHUP
532 	 * if and only if shutdown has been made in both directions.
533 	 * Actually, it is interesting to look how Solaris and DUX
534 	 * solve this dilemma. I would prefer, if EPOLLHUP were maskable,
535 	 * then we could set it on SND_SHUTDOWN. BTW examples given
536 	 * in Stevens' books assume exactly this behaviour, it explains
537 	 * why EPOLLHUP is incompatible with EPOLLOUT.	--ANK
538 	 *
539 	 * NOTE. Check for TCP_CLOSE is added. The goal is to prevent
540 	 * blocking on fresh not-connected or disconnected socket. --ANK
541 	 */
542 	if (sk->sk_shutdown == SHUTDOWN_MASK || state == TCP_CLOSE)
543 		mask |= EPOLLHUP;
544 	if (sk->sk_shutdown & RCV_SHUTDOWN)
545 		mask |= EPOLLIN | EPOLLRDNORM | EPOLLRDHUP;
546 
547 	/* Connected or passive Fast Open socket? */
548 	if (state != TCP_SYN_SENT &&
549 	    (state != TCP_SYN_RECV || rcu_access_pointer(tp->fastopen_rsk))) {
550 		int target = sock_rcvlowat(sk, 0, INT_MAX);
551 		u16 urg_data = READ_ONCE(tp->urg_data);
552 
553 		if (unlikely(urg_data) &&
554 		    READ_ONCE(tp->urg_seq) == READ_ONCE(tp->copied_seq) &&
555 		    !sock_flag(sk, SOCK_URGINLINE))
556 			target++;
557 
558 		if (tcp_stream_is_readable(sk, target))
559 			mask |= EPOLLIN | EPOLLRDNORM;
560 
561 		if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
562 			if (__sk_stream_is_writeable(sk, 1)) {
563 				mask |= EPOLLOUT | EPOLLWRNORM;
564 			} else {  /* send SIGIO later */
565 				sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
566 				set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
567 
568 				/* Race breaker. If space is freed after
569 				 * wspace test but before the flags are set,
570 				 * IO signal will be lost. Memory barrier
571 				 * pairs with the input side.
572 				 */
573 				smp_mb__after_atomic();
574 				if (__sk_stream_is_writeable(sk, 1))
575 					mask |= EPOLLOUT | EPOLLWRNORM;
576 			}
577 		} else
578 			mask |= EPOLLOUT | EPOLLWRNORM;
579 
580 		if (urg_data & TCP_URG_VALID)
581 			mask |= EPOLLPRI;
582 	} else if (state == TCP_SYN_SENT && inet_sk(sk)->defer_connect) {
583 		/* Active TCP fastopen socket with defer_connect
584 		 * Return EPOLLOUT so application can call write()
585 		 * in order for kernel to generate SYN+data
586 		 */
587 		mask |= EPOLLOUT | EPOLLWRNORM;
588 	}
589 	/* This barrier is coupled with smp_wmb() in tcp_reset() */
590 	smp_rmb();
591 	if (sk->sk_err || !skb_queue_empty_lockless(&sk->sk_error_queue))
592 		mask |= EPOLLERR;
593 
594 	return mask;
595 }
596 EXPORT_SYMBOL(tcp_poll);
597 
tcp_ioctl(struct sock * sk,int cmd,unsigned long arg)598 int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg)
599 {
600 	struct tcp_sock *tp = tcp_sk(sk);
601 	int answ;
602 	bool slow;
603 
604 	switch (cmd) {
605 	case SIOCINQ:
606 		if (sk->sk_state == TCP_LISTEN)
607 			return -EINVAL;
608 
609 		slow = lock_sock_fast(sk);
610 		answ = tcp_inq(sk);
611 		unlock_sock_fast(sk, slow);
612 		break;
613 	case SIOCATMARK:
614 		answ = READ_ONCE(tp->urg_data) &&
615 		       READ_ONCE(tp->urg_seq) == READ_ONCE(tp->copied_seq);
616 		break;
617 	case SIOCOUTQ:
618 		if (sk->sk_state == TCP_LISTEN)
619 			return -EINVAL;
620 
621 		if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
622 			answ = 0;
623 		else
624 			answ = READ_ONCE(tp->write_seq) - tp->snd_una;
625 		break;
626 	case SIOCOUTQNSD:
627 		if (sk->sk_state == TCP_LISTEN)
628 			return -EINVAL;
629 
630 		if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
631 			answ = 0;
632 		else
633 			answ = READ_ONCE(tp->write_seq) -
634 			       READ_ONCE(tp->snd_nxt);
635 		break;
636 	default:
637 		return -ENOIOCTLCMD;
638 	}
639 
640 	return put_user(answ, (int __user *)arg);
641 }
642 EXPORT_SYMBOL(tcp_ioctl);
643 
tcp_mark_push(struct tcp_sock * tp,struct sk_buff * skb)644 void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb)
645 {
646 	TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH;
647 	tp->pushed_seq = tp->write_seq;
648 }
649 
forced_push(const struct tcp_sock * tp)650 static inline bool forced_push(const struct tcp_sock *tp)
651 {
652 	return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1));
653 }
654 
tcp_skb_entail(struct sock * sk,struct sk_buff * skb)655 void tcp_skb_entail(struct sock *sk, struct sk_buff *skb)
656 {
657 	struct tcp_sock *tp = tcp_sk(sk);
658 	struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
659 
660 	tcb->seq     = tcb->end_seq = tp->write_seq;
661 	tcb->tcp_flags = TCPHDR_ACK;
662 	__skb_header_release(skb);
663 	tcp_add_write_queue_tail(sk, skb);
664 	sk_wmem_queued_add(sk, skb->truesize);
665 	sk_mem_charge(sk, skb->truesize);
666 	if (tp->nonagle & TCP_NAGLE_PUSH)
667 		tp->nonagle &= ~TCP_NAGLE_PUSH;
668 
669 	tcp_slow_start_after_idle_check(sk);
670 }
671 
tcp_mark_urg(struct tcp_sock * tp,int flags)672 static inline void tcp_mark_urg(struct tcp_sock *tp, int flags)
673 {
674 	if (flags & MSG_OOB)
675 		tp->snd_up = tp->write_seq;
676 }
677 
678 /* If a not yet filled skb is pushed, do not send it if
679  * we have data packets in Qdisc or NIC queues :
680  * Because TX completion will happen shortly, it gives a chance
681  * to coalesce future sendmsg() payload into this skb, without
682  * need for a timer, and with no latency trade off.
683  * As packets containing data payload have a bigger truesize
684  * than pure acks (dataless) packets, the last checks prevent
685  * autocorking if we only have an ACK in Qdisc/NIC queues,
686  * or if TX completion was delayed after we processed ACK packet.
687  */
tcp_should_autocork(struct sock * sk,struct sk_buff * skb,int size_goal)688 static bool tcp_should_autocork(struct sock *sk, struct sk_buff *skb,
689 				int size_goal)
690 {
691 	return skb->len < size_goal &&
692 	       READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_autocorking) &&
693 	       !tcp_rtx_queue_empty(sk) &&
694 	       refcount_read(&sk->sk_wmem_alloc) > skb->truesize &&
695 	       tcp_skb_can_collapse_to(skb);
696 }
697 
tcp_push(struct sock * sk,int flags,int mss_now,int nonagle,int size_goal)698 void tcp_push(struct sock *sk, int flags, int mss_now,
699 	      int nonagle, int size_goal)
700 {
701 	struct tcp_sock *tp = tcp_sk(sk);
702 	struct sk_buff *skb;
703 
704 	skb = tcp_write_queue_tail(sk);
705 	if (!skb)
706 		return;
707 	if (!(flags & MSG_MORE) || forced_push(tp))
708 		tcp_mark_push(tp, skb);
709 
710 	tcp_mark_urg(tp, flags);
711 
712 	if (tcp_should_autocork(sk, skb, size_goal)) {
713 
714 		/* avoid atomic op if TSQ_THROTTLED bit is already set */
715 		if (!test_bit(TSQ_THROTTLED, &sk->sk_tsq_flags)) {
716 			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAUTOCORKING);
717 			set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags);
718 		}
719 		/* It is possible TX completion already happened
720 		 * before we set TSQ_THROTTLED.
721 		 */
722 		if (refcount_read(&sk->sk_wmem_alloc) > skb->truesize)
723 			return;
724 	}
725 
726 	if (flags & MSG_MORE)
727 		nonagle = TCP_NAGLE_CORK;
728 
729 	__tcp_push_pending_frames(sk, mss_now, nonagle);
730 }
731 
tcp_splice_data_recv(read_descriptor_t * rd_desc,struct sk_buff * skb,unsigned int offset,size_t len)732 static int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
733 				unsigned int offset, size_t len)
734 {
735 	struct tcp_splice_state *tss = rd_desc->arg.data;
736 	int ret;
737 
738 	ret = skb_splice_bits(skb, skb->sk, offset, tss->pipe,
739 			      min(rd_desc->count, len), tss->flags);
740 	if (ret > 0)
741 		rd_desc->count -= ret;
742 	return ret;
743 }
744 
__tcp_splice_read(struct sock * sk,struct tcp_splice_state * tss)745 static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss)
746 {
747 	/* Store TCP splice context information in read_descriptor_t. */
748 	read_descriptor_t rd_desc = {
749 		.arg.data = tss,
750 		.count	  = tss->len,
751 	};
752 
753 	return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv);
754 }
755 
756 /**
757  *  tcp_splice_read - splice data from TCP socket to a pipe
758  * @sock:	socket to splice from
759  * @ppos:	position (not valid)
760  * @pipe:	pipe to splice to
761  * @len:	number of bytes to splice
762  * @flags:	splice modifier flags
763  *
764  * Description:
765  *    Will read pages from given socket and fill them into a pipe.
766  *
767  **/
tcp_splice_read(struct socket * sock,loff_t * ppos,struct pipe_inode_info * pipe,size_t len,unsigned int flags)768 ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
769 			struct pipe_inode_info *pipe, size_t len,
770 			unsigned int flags)
771 {
772 	struct sock *sk = sock->sk;
773 	struct tcp_splice_state tss = {
774 		.pipe = pipe,
775 		.len = len,
776 		.flags = flags,
777 	};
778 	long timeo;
779 	ssize_t spliced;
780 	int ret;
781 
782 	sock_rps_record_flow(sk);
783 	/*
784 	 * We can't seek on a socket input
785 	 */
786 	if (unlikely(*ppos))
787 		return -ESPIPE;
788 
789 	ret = spliced = 0;
790 
791 	lock_sock(sk);
792 
793 	timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK);
794 	while (tss.len) {
795 		ret = __tcp_splice_read(sk, &tss);
796 		if (ret < 0)
797 			break;
798 		else if (!ret) {
799 			if (spliced)
800 				break;
801 			if (sock_flag(sk, SOCK_DONE))
802 				break;
803 			if (sk->sk_err) {
804 				ret = sock_error(sk);
805 				break;
806 			}
807 			if (sk->sk_shutdown & RCV_SHUTDOWN)
808 				break;
809 			if (sk->sk_state == TCP_CLOSE) {
810 				/*
811 				 * This occurs when user tries to read
812 				 * from never connected socket.
813 				 */
814 				ret = -ENOTCONN;
815 				break;
816 			}
817 			if (!timeo) {
818 				ret = -EAGAIN;
819 				break;
820 			}
821 			/* if __tcp_splice_read() got nothing while we have
822 			 * an skb in receive queue, we do not want to loop.
823 			 * This might happen with URG data.
824 			 */
825 			if (!skb_queue_empty(&sk->sk_receive_queue))
826 				break;
827 			sk_wait_data(sk, &timeo, NULL);
828 			if (signal_pending(current)) {
829 				ret = sock_intr_errno(timeo);
830 				break;
831 			}
832 			continue;
833 		}
834 		tss.len -= ret;
835 		spliced += ret;
836 
837 		if (!timeo)
838 			break;
839 		release_sock(sk);
840 		lock_sock(sk);
841 
842 		if (sk->sk_err || sk->sk_state == TCP_CLOSE ||
843 		    (sk->sk_shutdown & RCV_SHUTDOWN) ||
844 		    signal_pending(current))
845 			break;
846 	}
847 
848 	release_sock(sk);
849 
850 	if (spliced)
851 		return spliced;
852 
853 	return ret;
854 }
855 EXPORT_SYMBOL(tcp_splice_read);
856 
tcp_stream_alloc_skb(struct sock * sk,int size,gfp_t gfp,bool force_schedule)857 struct sk_buff *tcp_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp,
858 				     bool force_schedule)
859 {
860 	struct sk_buff *skb;
861 
862 	skb = alloc_skb_fclone(size + MAX_TCP_HEADER, gfp);
863 	if (likely(skb)) {
864 		bool mem_scheduled;
865 
866 		skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
867 		if (force_schedule) {
868 			mem_scheduled = true;
869 			sk_forced_mem_schedule(sk, skb->truesize);
870 		} else {
871 			mem_scheduled = sk_wmem_schedule(sk, skb->truesize);
872 		}
873 		if (likely(mem_scheduled)) {
874 			skb_reserve(skb, MAX_TCP_HEADER);
875 			skb->ip_summed = CHECKSUM_PARTIAL;
876 			INIT_LIST_HEAD(&skb->tcp_tsorted_anchor);
877 			return skb;
878 		}
879 		__kfree_skb(skb);
880 	} else {
881 		sk->sk_prot->enter_memory_pressure(sk);
882 		sk_stream_moderate_sndbuf(sk);
883 	}
884 	return NULL;
885 }
886 
tcp_xmit_size_goal(struct sock * sk,u32 mss_now,int large_allowed)887 static unsigned int tcp_xmit_size_goal(struct sock *sk, u32 mss_now,
888 				       int large_allowed)
889 {
890 	struct tcp_sock *tp = tcp_sk(sk);
891 	u32 new_size_goal, size_goal;
892 
893 	if (!large_allowed)
894 		return mss_now;
895 
896 	/* Note : tcp_tso_autosize() will eventually split this later */
897 	new_size_goal = tcp_bound_to_half_wnd(tp, sk->sk_gso_max_size);
898 
899 	/* We try hard to avoid divides here */
900 	size_goal = tp->gso_segs * mss_now;
901 	if (unlikely(new_size_goal < size_goal ||
902 		     new_size_goal >= size_goal + mss_now)) {
903 		tp->gso_segs = min_t(u16, new_size_goal / mss_now,
904 				     sk->sk_gso_max_segs);
905 		size_goal = tp->gso_segs * mss_now;
906 	}
907 
908 	return max(size_goal, mss_now);
909 }
910 
tcp_send_mss(struct sock * sk,int * size_goal,int flags)911 int tcp_send_mss(struct sock *sk, int *size_goal, int flags)
912 {
913 	int mss_now;
914 
915 	mss_now = tcp_current_mss(sk);
916 	*size_goal = tcp_xmit_size_goal(sk, mss_now, !(flags & MSG_OOB));
917 
918 	return mss_now;
919 }
920 
921 /* In some cases, both sendpage() and sendmsg() could have added
922  * an skb to the write queue, but failed adding payload on it.
923  * We need to remove it to consume less memory, but more
924  * importantly be able to generate EPOLLOUT for Edge Trigger epoll()
925  * users.
926  */
tcp_remove_empty_skb(struct sock * sk)927 void tcp_remove_empty_skb(struct sock *sk)
928 {
929 	struct sk_buff *skb = tcp_write_queue_tail(sk);
930 
931 	if (skb && TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq) {
932 		tcp_unlink_write_queue(skb, sk);
933 		if (tcp_write_queue_empty(sk))
934 			tcp_chrono_stop(sk, TCP_CHRONO_BUSY);
935 		tcp_wmem_free_skb(sk, skb);
936 	}
937 }
938 
939 /* skb changing from pure zc to mixed, must charge zc */
tcp_downgrade_zcopy_pure(struct sock * sk,struct sk_buff * skb)940 static int tcp_downgrade_zcopy_pure(struct sock *sk, struct sk_buff *skb)
941 {
942 	if (unlikely(skb_zcopy_pure(skb))) {
943 		u32 extra = skb->truesize -
944 			    SKB_TRUESIZE(skb_end_offset(skb));
945 
946 		if (!sk_wmem_schedule(sk, extra))
947 			return -ENOMEM;
948 
949 		sk_mem_charge(sk, extra);
950 		skb_shinfo(skb)->flags &= ~SKBFL_PURE_ZEROCOPY;
951 	}
952 	return 0;
953 }
954 
955 
tcp_wmem_schedule(struct sock * sk,int copy)956 static int tcp_wmem_schedule(struct sock *sk, int copy)
957 {
958 	int left;
959 
960 	if (likely(sk_wmem_schedule(sk, copy)))
961 		return copy;
962 
963 	/* We could be in trouble if we have nothing queued.
964 	 * Use whatever is left in sk->sk_forward_alloc and tcp_wmem[0]
965 	 * to guarantee some progress.
966 	 */
967 	left = sock_net(sk)->ipv4.sysctl_tcp_wmem[0] - sk->sk_wmem_queued;
968 	if (left > 0)
969 		sk_forced_mem_schedule(sk, min(left, copy));
970 	return min(copy, sk->sk_forward_alloc);
971 }
972 
tcp_build_frag(struct sock * sk,int size_goal,int flags,struct page * page,int offset,size_t * size)973 static struct sk_buff *tcp_build_frag(struct sock *sk, int size_goal, int flags,
974 				      struct page *page, int offset, size_t *size)
975 {
976 	struct sk_buff *skb = tcp_write_queue_tail(sk);
977 	struct tcp_sock *tp = tcp_sk(sk);
978 	bool can_coalesce;
979 	int copy, i;
980 
981 	if (!skb || (copy = size_goal - skb->len) <= 0 ||
982 	    !tcp_skb_can_collapse_to(skb)) {
983 new_segment:
984 		if (!sk_stream_memory_free(sk))
985 			return NULL;
986 
987 		skb = tcp_stream_alloc_skb(sk, 0, sk->sk_allocation,
988 					   tcp_rtx_and_write_queues_empty(sk));
989 		if (!skb)
990 			return NULL;
991 
992 #ifdef CONFIG_TLS_DEVICE
993 		skb->decrypted = !!(flags & MSG_SENDPAGE_DECRYPTED);
994 #endif
995 		tcp_skb_entail(sk, skb);
996 		copy = size_goal;
997 	}
998 
999 	if (copy > *size)
1000 		copy = *size;
1001 
1002 	i = skb_shinfo(skb)->nr_frags;
1003 	can_coalesce = skb_can_coalesce(skb, i, page, offset);
1004 	if (!can_coalesce && i >= READ_ONCE(sysctl_max_skb_frags)) {
1005 		tcp_mark_push(tp, skb);
1006 		goto new_segment;
1007 	}
1008 	if (tcp_downgrade_zcopy_pure(sk, skb))
1009 		return NULL;
1010 
1011 	copy = tcp_wmem_schedule(sk, copy);
1012 	if (!copy)
1013 		return NULL;
1014 
1015 	if (can_coalesce) {
1016 		skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
1017 	} else {
1018 		get_page(page);
1019 		skb_fill_page_desc_noacc(skb, i, page, offset, copy);
1020 	}
1021 
1022 	if (!(flags & MSG_NO_SHARED_FRAGS))
1023 		skb_shinfo(skb)->flags |= SKBFL_SHARED_FRAG;
1024 
1025 	skb->len += copy;
1026 	skb->data_len += copy;
1027 	skb->truesize += copy;
1028 	sk_wmem_queued_add(sk, copy);
1029 	sk_mem_charge(sk, copy);
1030 	WRITE_ONCE(tp->write_seq, tp->write_seq + copy);
1031 	TCP_SKB_CB(skb)->end_seq += copy;
1032 	tcp_skb_pcount_set(skb, 0);
1033 
1034 	*size = copy;
1035 	return skb;
1036 }
1037 
do_tcp_sendpages(struct sock * sk,struct page * page,int offset,size_t size,int flags)1038 ssize_t do_tcp_sendpages(struct sock *sk, struct page *page, int offset,
1039 			 size_t size, int flags)
1040 {
1041 	struct tcp_sock *tp = tcp_sk(sk);
1042 	int mss_now, size_goal;
1043 	int err;
1044 	ssize_t copied;
1045 	long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
1046 
1047 	if (IS_ENABLED(CONFIG_DEBUG_VM) &&
1048 	    WARN_ONCE(!sendpage_ok(page),
1049 		      "page must not be a Slab one and have page_count > 0"))
1050 		return -EINVAL;
1051 
1052 	/* Wait for a connection to finish. One exception is TCP Fast Open
1053 	 * (passive side) where data is allowed to be sent before a connection
1054 	 * is fully established.
1055 	 */
1056 	if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
1057 	    !tcp_passive_fastopen(sk)) {
1058 		err = sk_stream_wait_connect(sk, &timeo);
1059 		if (err != 0)
1060 			goto out_err;
1061 	}
1062 
1063 	sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
1064 
1065 	mss_now = tcp_send_mss(sk, &size_goal, flags);
1066 	copied = 0;
1067 
1068 	err = -EPIPE;
1069 	if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
1070 		goto out_err;
1071 
1072 	while (size > 0) {
1073 		struct sk_buff *skb;
1074 		size_t copy = size;
1075 
1076 		skb = tcp_build_frag(sk, size_goal, flags, page, offset, &copy);
1077 		if (!skb)
1078 			goto wait_for_space;
1079 
1080 		if (!copied)
1081 			TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
1082 
1083 		copied += copy;
1084 		offset += copy;
1085 		size -= copy;
1086 		if (!size)
1087 			goto out;
1088 
1089 		if (skb->len < size_goal || (flags & MSG_OOB))
1090 			continue;
1091 
1092 		if (forced_push(tp)) {
1093 			tcp_mark_push(tp, skb);
1094 			__tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
1095 		} else if (skb == tcp_send_head(sk))
1096 			tcp_push_one(sk, mss_now);
1097 		continue;
1098 
1099 wait_for_space:
1100 		set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1101 		tcp_push(sk, flags & ~MSG_MORE, mss_now,
1102 			 TCP_NAGLE_PUSH, size_goal);
1103 
1104 		err = sk_stream_wait_memory(sk, &timeo);
1105 		if (err != 0)
1106 			goto do_error;
1107 
1108 		mss_now = tcp_send_mss(sk, &size_goal, flags);
1109 	}
1110 
1111 out:
1112 	if (copied) {
1113 		tcp_tx_timestamp(sk, sk->sk_tsflags);
1114 		if (!(flags & MSG_SENDPAGE_NOTLAST))
1115 			tcp_push(sk, flags, mss_now, tp->nonagle, size_goal);
1116 	}
1117 	return copied;
1118 
1119 do_error:
1120 	tcp_remove_empty_skb(sk);
1121 	if (copied)
1122 		goto out;
1123 out_err:
1124 	/* make sure we wake any epoll edge trigger waiter */
1125 	if (unlikely(tcp_rtx_and_write_queues_empty(sk) && err == -EAGAIN)) {
1126 		sk->sk_write_space(sk);
1127 		tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
1128 	}
1129 	return sk_stream_error(sk, flags, err);
1130 }
1131 EXPORT_SYMBOL_GPL(do_tcp_sendpages);
1132 
tcp_sendpage_locked(struct sock * sk,struct page * page,int offset,size_t size,int flags)1133 int tcp_sendpage_locked(struct sock *sk, struct page *page, int offset,
1134 			size_t size, int flags)
1135 {
1136 	if (!(sk->sk_route_caps & NETIF_F_SG))
1137 		return sock_no_sendpage_locked(sk, page, offset, size, flags);
1138 
1139 	tcp_rate_check_app_limited(sk);  /* is sending application-limited? */
1140 
1141 	return do_tcp_sendpages(sk, page, offset, size, flags);
1142 }
1143 EXPORT_SYMBOL_GPL(tcp_sendpage_locked);
1144 
tcp_sendpage(struct sock * sk,struct page * page,int offset,size_t size,int flags)1145 int tcp_sendpage(struct sock *sk, struct page *page, int offset,
1146 		 size_t size, int flags)
1147 {
1148 	int ret;
1149 
1150 	lock_sock(sk);
1151 	ret = tcp_sendpage_locked(sk, page, offset, size, flags);
1152 	release_sock(sk);
1153 
1154 	return ret;
1155 }
1156 EXPORT_SYMBOL(tcp_sendpage);
1157 
tcp_free_fastopen_req(struct tcp_sock * tp)1158 void tcp_free_fastopen_req(struct tcp_sock *tp)
1159 {
1160 	if (tp->fastopen_req) {
1161 		kfree(tp->fastopen_req);
1162 		tp->fastopen_req = NULL;
1163 	}
1164 }
1165 
tcp_sendmsg_fastopen(struct sock * sk,struct msghdr * msg,int * copied,size_t size,struct ubuf_info * uarg)1166 int tcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg, int *copied,
1167 			 size_t size, struct ubuf_info *uarg)
1168 {
1169 	struct tcp_sock *tp = tcp_sk(sk);
1170 	struct inet_sock *inet = inet_sk(sk);
1171 	struct sockaddr *uaddr = msg->msg_name;
1172 	int err, flags;
1173 
1174 	if (!(READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_fastopen) &
1175 	      TFO_CLIENT_ENABLE) ||
1176 	    (uaddr && msg->msg_namelen >= sizeof(uaddr->sa_family) &&
1177 	     uaddr->sa_family == AF_UNSPEC))
1178 		return -EOPNOTSUPP;
1179 	if (tp->fastopen_req)
1180 		return -EALREADY; /* Another Fast Open is in progress */
1181 
1182 	tp->fastopen_req = kzalloc(sizeof(struct tcp_fastopen_request),
1183 				   sk->sk_allocation);
1184 	if (unlikely(!tp->fastopen_req))
1185 		return -ENOBUFS;
1186 	tp->fastopen_req->data = msg;
1187 	tp->fastopen_req->size = size;
1188 	tp->fastopen_req->uarg = uarg;
1189 
1190 	if (inet->defer_connect) {
1191 		err = tcp_connect(sk);
1192 		/* Same failure procedure as in tcp_v4/6_connect */
1193 		if (err) {
1194 			tcp_set_state(sk, TCP_CLOSE);
1195 			inet->inet_dport = 0;
1196 			sk->sk_route_caps = 0;
1197 		}
1198 	}
1199 	flags = (msg->msg_flags & MSG_DONTWAIT) ? O_NONBLOCK : 0;
1200 	err = __inet_stream_connect(sk->sk_socket, uaddr,
1201 				    msg->msg_namelen, flags, 1);
1202 	/* fastopen_req could already be freed in __inet_stream_connect
1203 	 * if the connection times out or gets rst
1204 	 */
1205 	if (tp->fastopen_req) {
1206 		*copied = tp->fastopen_req->copied;
1207 		tcp_free_fastopen_req(tp);
1208 		inet->defer_connect = 0;
1209 	}
1210 	return err;
1211 }
1212 
tcp_sendmsg_locked(struct sock * sk,struct msghdr * msg,size_t size)1213 int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
1214 {
1215 	struct tcp_sock *tp = tcp_sk(sk);
1216 	struct ubuf_info *uarg = NULL;
1217 	struct sk_buff *skb;
1218 	struct sockcm_cookie sockc;
1219 	int flags, err, copied = 0;
1220 	int mss_now = 0, size_goal, copied_syn = 0;
1221 	int process_backlog = 0;
1222 	bool zc = false;
1223 	long timeo;
1224 
1225 	flags = msg->msg_flags;
1226 
1227 	if ((flags & MSG_ZEROCOPY) && size) {
1228 		skb = tcp_write_queue_tail(sk);
1229 
1230 		if (msg->msg_ubuf) {
1231 			uarg = msg->msg_ubuf;
1232 			net_zcopy_get(uarg);
1233 			zc = sk->sk_route_caps & NETIF_F_SG;
1234 		} else if (sock_flag(sk, SOCK_ZEROCOPY)) {
1235 			uarg = msg_zerocopy_realloc(sk, size, skb_zcopy(skb));
1236 			if (!uarg) {
1237 				err = -ENOBUFS;
1238 				goto out_err;
1239 			}
1240 			zc = sk->sk_route_caps & NETIF_F_SG;
1241 			if (!zc)
1242 				uarg_to_msgzc(uarg)->zerocopy = 0;
1243 		}
1244 	}
1245 
1246 	if (unlikely(flags & MSG_FASTOPEN || inet_sk(sk)->defer_connect) &&
1247 	    !tp->repair) {
1248 		err = tcp_sendmsg_fastopen(sk, msg, &copied_syn, size, uarg);
1249 		if (err == -EINPROGRESS && copied_syn > 0)
1250 			goto out;
1251 		else if (err)
1252 			goto out_err;
1253 	}
1254 
1255 	timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
1256 
1257 	tcp_rate_check_app_limited(sk);  /* is sending application-limited? */
1258 
1259 	/* Wait for a connection to finish. One exception is TCP Fast Open
1260 	 * (passive side) where data is allowed to be sent before a connection
1261 	 * is fully established.
1262 	 */
1263 	if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
1264 	    !tcp_passive_fastopen(sk)) {
1265 		err = sk_stream_wait_connect(sk, &timeo);
1266 		if (err != 0)
1267 			goto do_error;
1268 	}
1269 
1270 	if (unlikely(tp->repair)) {
1271 		if (tp->repair_queue == TCP_RECV_QUEUE) {
1272 			copied = tcp_send_rcvq(sk, msg, size);
1273 			goto out_nopush;
1274 		}
1275 
1276 		err = -EINVAL;
1277 		if (tp->repair_queue == TCP_NO_QUEUE)
1278 			goto out_err;
1279 
1280 		/* 'common' sending to sendq */
1281 	}
1282 
1283 	sockcm_init(&sockc, sk);
1284 	if (msg->msg_controllen) {
1285 		err = sock_cmsg_send(sk, msg, &sockc);
1286 		if (unlikely(err)) {
1287 			err = -EINVAL;
1288 			goto out_err;
1289 		}
1290 	}
1291 
1292 	/* This should be in poll */
1293 	sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
1294 
1295 	/* Ok commence sending. */
1296 	copied = 0;
1297 
1298 restart:
1299 	mss_now = tcp_send_mss(sk, &size_goal, flags);
1300 
1301 	err = -EPIPE;
1302 	if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
1303 		goto do_error;
1304 
1305 	while (msg_data_left(msg)) {
1306 		int copy = 0;
1307 
1308 		skb = tcp_write_queue_tail(sk);
1309 		if (skb)
1310 			copy = size_goal - skb->len;
1311 
1312 		if (copy <= 0 || !tcp_skb_can_collapse_to(skb)) {
1313 			bool first_skb;
1314 
1315 new_segment:
1316 			if (!sk_stream_memory_free(sk))
1317 				goto wait_for_space;
1318 
1319 			if (unlikely(process_backlog >= 16)) {
1320 				process_backlog = 0;
1321 				if (sk_flush_backlog(sk))
1322 					goto restart;
1323 			}
1324 			first_skb = tcp_rtx_and_write_queues_empty(sk);
1325 			skb = tcp_stream_alloc_skb(sk, 0, sk->sk_allocation,
1326 						   first_skb);
1327 			if (!skb)
1328 				goto wait_for_space;
1329 
1330 			process_backlog++;
1331 
1332 			tcp_skb_entail(sk, skb);
1333 			copy = size_goal;
1334 
1335 			/* All packets are restored as if they have
1336 			 * already been sent. skb_mstamp_ns isn't set to
1337 			 * avoid wrong rtt estimation.
1338 			 */
1339 			if (tp->repair)
1340 				TCP_SKB_CB(skb)->sacked |= TCPCB_REPAIRED;
1341 		}
1342 
1343 		/* Try to append data to the end of skb. */
1344 		if (copy > msg_data_left(msg))
1345 			copy = msg_data_left(msg);
1346 
1347 		if (!zc) {
1348 			bool merge = true;
1349 			int i = skb_shinfo(skb)->nr_frags;
1350 			struct page_frag *pfrag = sk_page_frag(sk);
1351 
1352 			if (!sk_page_frag_refill(sk, pfrag))
1353 				goto wait_for_space;
1354 
1355 			if (!skb_can_coalesce(skb, i, pfrag->page,
1356 					      pfrag->offset)) {
1357 				if (i >= READ_ONCE(sysctl_max_skb_frags)) {
1358 					tcp_mark_push(tp, skb);
1359 					goto new_segment;
1360 				}
1361 				merge = false;
1362 			}
1363 
1364 			copy = min_t(int, copy, pfrag->size - pfrag->offset);
1365 
1366 			if (unlikely(skb_zcopy_pure(skb) || skb_zcopy_managed(skb))) {
1367 				if (tcp_downgrade_zcopy_pure(sk, skb))
1368 					goto wait_for_space;
1369 				skb_zcopy_downgrade_managed(skb);
1370 			}
1371 
1372 			copy = tcp_wmem_schedule(sk, copy);
1373 			if (!copy)
1374 				goto wait_for_space;
1375 
1376 			err = skb_copy_to_page_nocache(sk, &msg->msg_iter, skb,
1377 						       pfrag->page,
1378 						       pfrag->offset,
1379 						       copy);
1380 			if (err)
1381 				goto do_error;
1382 
1383 			/* Update the skb. */
1384 			if (merge) {
1385 				skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
1386 			} else {
1387 				skb_fill_page_desc(skb, i, pfrag->page,
1388 						   pfrag->offset, copy);
1389 				page_ref_inc(pfrag->page);
1390 			}
1391 			pfrag->offset += copy;
1392 		} else {
1393 			/* First append to a fragless skb builds initial
1394 			 * pure zerocopy skb
1395 			 */
1396 			if (!skb->len)
1397 				skb_shinfo(skb)->flags |= SKBFL_PURE_ZEROCOPY;
1398 
1399 			if (!skb_zcopy_pure(skb)) {
1400 				copy = tcp_wmem_schedule(sk, copy);
1401 				if (!copy)
1402 					goto wait_for_space;
1403 			}
1404 
1405 			err = skb_zerocopy_iter_stream(sk, skb, msg, copy, uarg);
1406 			if (err == -EMSGSIZE || err == -EEXIST) {
1407 				tcp_mark_push(tp, skb);
1408 				goto new_segment;
1409 			}
1410 			if (err < 0)
1411 				goto do_error;
1412 			copy = err;
1413 		}
1414 
1415 		if (!copied)
1416 			TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
1417 
1418 		WRITE_ONCE(tp->write_seq, tp->write_seq + copy);
1419 		TCP_SKB_CB(skb)->end_seq += copy;
1420 		tcp_skb_pcount_set(skb, 0);
1421 
1422 		copied += copy;
1423 		if (!msg_data_left(msg)) {
1424 			if (unlikely(flags & MSG_EOR))
1425 				TCP_SKB_CB(skb)->eor = 1;
1426 			goto out;
1427 		}
1428 
1429 		if (skb->len < size_goal || (flags & MSG_OOB) || unlikely(tp->repair))
1430 			continue;
1431 
1432 		if (forced_push(tp)) {
1433 			tcp_mark_push(tp, skb);
1434 			__tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
1435 		} else if (skb == tcp_send_head(sk))
1436 			tcp_push_one(sk, mss_now);
1437 		continue;
1438 
1439 wait_for_space:
1440 		set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1441 		if (copied)
1442 			tcp_push(sk, flags & ~MSG_MORE, mss_now,
1443 				 TCP_NAGLE_PUSH, size_goal);
1444 
1445 		err = sk_stream_wait_memory(sk, &timeo);
1446 		if (err != 0)
1447 			goto do_error;
1448 
1449 		mss_now = tcp_send_mss(sk, &size_goal, flags);
1450 	}
1451 
1452 out:
1453 	if (copied) {
1454 		tcp_tx_timestamp(sk, sockc.tsflags);
1455 		tcp_push(sk, flags, mss_now, tp->nonagle, size_goal);
1456 	}
1457 out_nopush:
1458 	net_zcopy_put(uarg);
1459 	return copied + copied_syn;
1460 
1461 do_error:
1462 	tcp_remove_empty_skb(sk);
1463 
1464 	if (copied + copied_syn)
1465 		goto out;
1466 out_err:
1467 	net_zcopy_put_abort(uarg, true);
1468 	err = sk_stream_error(sk, flags, err);
1469 	/* make sure we wake any epoll edge trigger waiter */
1470 	if (unlikely(tcp_rtx_and_write_queues_empty(sk) && err == -EAGAIN)) {
1471 		sk->sk_write_space(sk);
1472 		tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
1473 	}
1474 	return err;
1475 }
1476 EXPORT_SYMBOL_GPL(tcp_sendmsg_locked);
1477 
tcp_sendmsg(struct sock * sk,struct msghdr * msg,size_t size)1478 int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
1479 {
1480 	int ret;
1481 
1482 	lock_sock(sk);
1483 	ret = tcp_sendmsg_locked(sk, msg, size);
1484 	release_sock(sk);
1485 
1486 	return ret;
1487 }
1488 EXPORT_SYMBOL(tcp_sendmsg);
1489 
1490 /*
1491  *	Handle reading urgent data. BSD has very simple semantics for
1492  *	this, no blocking and very strange errors 8)
1493  */
1494 
tcp_recv_urg(struct sock * sk,struct msghdr * msg,int len,int flags)1495 static int tcp_recv_urg(struct sock *sk, struct msghdr *msg, int len, int flags)
1496 {
1497 	struct tcp_sock *tp = tcp_sk(sk);
1498 
1499 	/* No URG data to read. */
1500 	if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data ||
1501 	    tp->urg_data == TCP_URG_READ)
1502 		return -EINVAL;	/* Yes this is right ! */
1503 
1504 	if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE))
1505 		return -ENOTCONN;
1506 
1507 	if (tp->urg_data & TCP_URG_VALID) {
1508 		int err = 0;
1509 		char c = tp->urg_data;
1510 
1511 		if (!(flags & MSG_PEEK))
1512 			WRITE_ONCE(tp->urg_data, TCP_URG_READ);
1513 
1514 		/* Read urgent data. */
1515 		msg->msg_flags |= MSG_OOB;
1516 
1517 		if (len > 0) {
1518 			if (!(flags & MSG_TRUNC))
1519 				err = memcpy_to_msg(msg, &c, 1);
1520 			len = 1;
1521 		} else
1522 			msg->msg_flags |= MSG_TRUNC;
1523 
1524 		return err ? -EFAULT : len;
1525 	}
1526 
1527 	if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN))
1528 		return 0;
1529 
1530 	/* Fixed the recv(..., MSG_OOB) behaviour.  BSD docs and
1531 	 * the available implementations agree in this case:
1532 	 * this call should never block, independent of the
1533 	 * blocking state of the socket.
1534 	 * Mike <pall@rz.uni-karlsruhe.de>
1535 	 */
1536 	return -EAGAIN;
1537 }
1538 
tcp_peek_sndq(struct sock * sk,struct msghdr * msg,int len)1539 static int tcp_peek_sndq(struct sock *sk, struct msghdr *msg, int len)
1540 {
1541 	struct sk_buff *skb;
1542 	int copied = 0, err = 0;
1543 
1544 	/* XXX -- need to support SO_PEEK_OFF */
1545 
1546 	skb_rbtree_walk(skb, &sk->tcp_rtx_queue) {
1547 		err = skb_copy_datagram_msg(skb, 0, msg, skb->len);
1548 		if (err)
1549 			return err;
1550 		copied += skb->len;
1551 	}
1552 
1553 	skb_queue_walk(&sk->sk_write_queue, skb) {
1554 		err = skb_copy_datagram_msg(skb, 0, msg, skb->len);
1555 		if (err)
1556 			break;
1557 
1558 		copied += skb->len;
1559 	}
1560 
1561 	return err ?: copied;
1562 }
1563 
1564 /* Clean up the receive buffer for full frames taken by the user,
1565  * then send an ACK if necessary.  COPIED is the number of bytes
1566  * tcp_recvmsg has given to the user so far, it speeds up the
1567  * calculation of whether or not we must ACK for the sake of
1568  * a window update.
1569  */
__tcp_cleanup_rbuf(struct sock * sk,int copied)1570 static void __tcp_cleanup_rbuf(struct sock *sk, int copied)
1571 {
1572 	struct tcp_sock *tp = tcp_sk(sk);
1573 	bool time_to_ack = false;
1574 
1575 	if (inet_csk_ack_scheduled(sk)) {
1576 		const struct inet_connection_sock *icsk = inet_csk(sk);
1577 
1578 		if (/* Once-per-two-segments ACK was not sent by tcp_input.c */
1579 		    tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss ||
1580 		    /*
1581 		     * If this read emptied read buffer, we send ACK, if
1582 		     * connection is not bidirectional, user drained
1583 		     * receive buffer and there was a small segment
1584 		     * in queue.
1585 		     */
1586 		    (copied > 0 &&
1587 		     ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) ||
1588 		      ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) &&
1589 		       !inet_csk_in_pingpong_mode(sk))) &&
1590 		      !atomic_read(&sk->sk_rmem_alloc)))
1591 			time_to_ack = true;
1592 	}
1593 
1594 	/* We send an ACK if we can now advertise a non-zero window
1595 	 * which has been raised "significantly".
1596 	 *
1597 	 * Even if window raised up to infinity, do not send window open ACK
1598 	 * in states, where we will not receive more. It is useless.
1599 	 */
1600 	if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
1601 		__u32 rcv_window_now = tcp_receive_window(tp);
1602 
1603 		/* Optimize, __tcp_select_window() is not cheap. */
1604 		if (2*rcv_window_now <= tp->window_clamp) {
1605 			__u32 new_window = __tcp_select_window(sk);
1606 
1607 			/* Send ACK now, if this read freed lots of space
1608 			 * in our buffer. Certainly, new_window is new window.
1609 			 * We can advertise it now, if it is not less than current one.
1610 			 * "Lots" means "at least twice" here.
1611 			 */
1612 			if (new_window && new_window >= 2 * rcv_window_now)
1613 				time_to_ack = true;
1614 		}
1615 	}
1616 	if (time_to_ack)
1617 		tcp_send_ack(sk);
1618 }
1619 
tcp_cleanup_rbuf(struct sock * sk,int copied)1620 void tcp_cleanup_rbuf(struct sock *sk, int copied)
1621 {
1622 	struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
1623 	struct tcp_sock *tp = tcp_sk(sk);
1624 
1625 	WARN(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq),
1626 	     "cleanup rbuf bug: copied %X seq %X rcvnxt %X\n",
1627 	     tp->copied_seq, TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt);
1628 	__tcp_cleanup_rbuf(sk, copied);
1629 }
1630 
tcp_eat_recv_skb(struct sock * sk,struct sk_buff * skb)1631 static void tcp_eat_recv_skb(struct sock *sk, struct sk_buff *skb)
1632 {
1633 	__skb_unlink(skb, &sk->sk_receive_queue);
1634 	if (likely(skb->destructor == sock_rfree)) {
1635 		sock_rfree(skb);
1636 		skb->destructor = NULL;
1637 		skb->sk = NULL;
1638 		return skb_attempt_defer_free(skb);
1639 	}
1640 	__kfree_skb(skb);
1641 }
1642 
tcp_recv_skb(struct sock * sk,u32 seq,u32 * off)1643 struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off)
1644 {
1645 	struct sk_buff *skb;
1646 	u32 offset;
1647 
1648 	while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) {
1649 		offset = seq - TCP_SKB_CB(skb)->seq;
1650 		if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
1651 			pr_err_once("%s: found a SYN, please report !\n", __func__);
1652 			offset--;
1653 		}
1654 		if (offset < skb->len || (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)) {
1655 			*off = offset;
1656 			return skb;
1657 		}
1658 		/* This looks weird, but this can happen if TCP collapsing
1659 		 * splitted a fat GRO packet, while we released socket lock
1660 		 * in skb_splice_bits()
1661 		 */
1662 		tcp_eat_recv_skb(sk, skb);
1663 	}
1664 	return NULL;
1665 }
1666 EXPORT_SYMBOL(tcp_recv_skb);
1667 
1668 /*
1669  * This routine provides an alternative to tcp_recvmsg() for routines
1670  * that would like to handle copying from skbuffs directly in 'sendfile'
1671  * fashion.
1672  * Note:
1673  *	- It is assumed that the socket was locked by the caller.
1674  *	- The routine does not block.
1675  *	- At present, there is no support for reading OOB data
1676  *	  or for 'peeking' the socket using this routine
1677  *	  (although both would be easy to implement).
1678  */
tcp_read_sock(struct sock * sk,read_descriptor_t * desc,sk_read_actor_t recv_actor)1679 int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
1680 		  sk_read_actor_t recv_actor)
1681 {
1682 	struct sk_buff *skb;
1683 	struct tcp_sock *tp = tcp_sk(sk);
1684 	u32 seq = tp->copied_seq;
1685 	u32 offset;
1686 	int copied = 0;
1687 
1688 	if (sk->sk_state == TCP_LISTEN)
1689 		return -ENOTCONN;
1690 	while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
1691 		if (offset < skb->len) {
1692 			int used;
1693 			size_t len;
1694 
1695 			len = skb->len - offset;
1696 			/* Stop reading if we hit a patch of urgent data */
1697 			if (unlikely(tp->urg_data)) {
1698 				u32 urg_offset = tp->urg_seq - seq;
1699 				if (urg_offset < len)
1700 					len = urg_offset;
1701 				if (!len)
1702 					break;
1703 			}
1704 			used = recv_actor(desc, skb, offset, len);
1705 			if (used <= 0) {
1706 				if (!copied)
1707 					copied = used;
1708 				break;
1709 			}
1710 			if (WARN_ON_ONCE(used > len))
1711 				used = len;
1712 			seq += used;
1713 			copied += used;
1714 			offset += used;
1715 
1716 			/* If recv_actor drops the lock (e.g. TCP splice
1717 			 * receive) the skb pointer might be invalid when
1718 			 * getting here: tcp_collapse might have deleted it
1719 			 * while aggregating skbs from the socket queue.
1720 			 */
1721 			skb = tcp_recv_skb(sk, seq - 1, &offset);
1722 			if (!skb)
1723 				break;
1724 			/* TCP coalescing might have appended data to the skb.
1725 			 * Try to splice more frags
1726 			 */
1727 			if (offset + 1 != skb->len)
1728 				continue;
1729 		}
1730 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) {
1731 			tcp_eat_recv_skb(sk, skb);
1732 			++seq;
1733 			break;
1734 		}
1735 		tcp_eat_recv_skb(sk, skb);
1736 		if (!desc->count)
1737 			break;
1738 		WRITE_ONCE(tp->copied_seq, seq);
1739 	}
1740 	WRITE_ONCE(tp->copied_seq, seq);
1741 
1742 	tcp_rcv_space_adjust(sk);
1743 
1744 	/* Clean up data we have read: This will do ACK frames. */
1745 	if (copied > 0) {
1746 		tcp_recv_skb(sk, seq, &offset);
1747 		tcp_cleanup_rbuf(sk, copied);
1748 	}
1749 	return copied;
1750 }
1751 EXPORT_SYMBOL(tcp_read_sock);
1752 
tcp_read_skb(struct sock * sk,skb_read_actor_t recv_actor)1753 int tcp_read_skb(struct sock *sk, skb_read_actor_t recv_actor)
1754 {
1755 	struct tcp_sock *tp = tcp_sk(sk);
1756 	u32 seq = tp->copied_seq;
1757 	struct sk_buff *skb;
1758 	int copied = 0;
1759 	u32 offset;
1760 
1761 	if (sk->sk_state == TCP_LISTEN)
1762 		return -ENOTCONN;
1763 
1764 	while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
1765 		u8 tcp_flags;
1766 		int used;
1767 
1768 		__skb_unlink(skb, &sk->sk_receive_queue);
1769 		WARN_ON_ONCE(!skb_set_owner_sk_safe(skb, sk));
1770 		tcp_flags = TCP_SKB_CB(skb)->tcp_flags;
1771 		used = recv_actor(sk, skb);
1772 		consume_skb(skb);
1773 		if (used < 0) {
1774 			if (!copied)
1775 				copied = used;
1776 			break;
1777 		}
1778 		seq += used;
1779 		copied += used;
1780 
1781 		if (tcp_flags & TCPHDR_FIN) {
1782 			++seq;
1783 			break;
1784 		}
1785 	}
1786 	WRITE_ONCE(tp->copied_seq, seq);
1787 
1788 	tcp_rcv_space_adjust(sk);
1789 
1790 	/* Clean up data we have read: This will do ACK frames. */
1791 	if (copied > 0)
1792 		__tcp_cleanup_rbuf(sk, copied);
1793 
1794 	return copied;
1795 }
1796 EXPORT_SYMBOL(tcp_read_skb);
1797 
tcp_read_done(struct sock * sk,size_t len)1798 void tcp_read_done(struct sock *sk, size_t len)
1799 {
1800 	struct tcp_sock *tp = tcp_sk(sk);
1801 	u32 seq = tp->copied_seq;
1802 	struct sk_buff *skb;
1803 	size_t left;
1804 	u32 offset;
1805 
1806 	if (sk->sk_state == TCP_LISTEN)
1807 		return;
1808 
1809 	left = len;
1810 	while (left && (skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
1811 		int used;
1812 
1813 		used = min_t(size_t, skb->len - offset, left);
1814 		seq += used;
1815 		left -= used;
1816 
1817 		if (skb->len > offset + used)
1818 			break;
1819 
1820 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) {
1821 			tcp_eat_recv_skb(sk, skb);
1822 			++seq;
1823 			break;
1824 		}
1825 		tcp_eat_recv_skb(sk, skb);
1826 	}
1827 	WRITE_ONCE(tp->copied_seq, seq);
1828 
1829 	tcp_rcv_space_adjust(sk);
1830 
1831 	/* Clean up data we have read: This will do ACK frames. */
1832 	if (left != len)
1833 		tcp_cleanup_rbuf(sk, len - left);
1834 }
1835 EXPORT_SYMBOL(tcp_read_done);
1836 
tcp_peek_len(struct socket * sock)1837 int tcp_peek_len(struct socket *sock)
1838 {
1839 	return tcp_inq(sock->sk);
1840 }
1841 EXPORT_SYMBOL(tcp_peek_len);
1842 
1843 /* Make sure sk_rcvbuf is big enough to satisfy SO_RCVLOWAT hint */
tcp_set_rcvlowat(struct sock * sk,int val)1844 int tcp_set_rcvlowat(struct sock *sk, int val)
1845 {
1846 	int cap;
1847 
1848 	if (sk->sk_userlocks & SOCK_RCVBUF_LOCK)
1849 		cap = sk->sk_rcvbuf >> 1;
1850 	else
1851 		cap = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2]) >> 1;
1852 	val = min(val, cap);
1853 	WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
1854 
1855 	/* Check if we need to signal EPOLLIN right now */
1856 	tcp_data_ready(sk);
1857 
1858 	if (sk->sk_userlocks & SOCK_RCVBUF_LOCK)
1859 		return 0;
1860 
1861 	val <<= 1;
1862 	if (val > sk->sk_rcvbuf) {
1863 		WRITE_ONCE(sk->sk_rcvbuf, val);
1864 		tcp_sk(sk)->window_clamp = tcp_win_from_space(sk, val);
1865 	}
1866 	return 0;
1867 }
1868 EXPORT_SYMBOL(tcp_set_rcvlowat);
1869 
tcp_update_recv_tstamps(struct sk_buff * skb,struct scm_timestamping_internal * tss)1870 void tcp_update_recv_tstamps(struct sk_buff *skb,
1871 			     struct scm_timestamping_internal *tss)
1872 {
1873 	if (skb->tstamp)
1874 		tss->ts[0] = ktime_to_timespec64(skb->tstamp);
1875 	else
1876 		tss->ts[0] = (struct timespec64) {0};
1877 
1878 	if (skb_hwtstamps(skb)->hwtstamp)
1879 		tss->ts[2] = ktime_to_timespec64(skb_hwtstamps(skb)->hwtstamp);
1880 	else
1881 		tss->ts[2] = (struct timespec64) {0};
1882 }
1883 
1884 #ifdef CONFIG_MMU
1885 static const struct vm_operations_struct tcp_vm_ops = {
1886 };
1887 
tcp_mmap(struct file * file,struct socket * sock,struct vm_area_struct * vma)1888 int tcp_mmap(struct file *file, struct socket *sock,
1889 	     struct vm_area_struct *vma)
1890 {
1891 	if (vma->vm_flags & (VM_WRITE | VM_EXEC))
1892 		return -EPERM;
1893 	vma->vm_flags &= ~(VM_MAYWRITE | VM_MAYEXEC);
1894 
1895 	/* Instruct vm_insert_page() to not mmap_read_lock(mm) */
1896 	vma->vm_flags |= VM_MIXEDMAP;
1897 
1898 	vma->vm_ops = &tcp_vm_ops;
1899 	return 0;
1900 }
1901 EXPORT_SYMBOL(tcp_mmap);
1902 
skb_advance_to_frag(struct sk_buff * skb,u32 offset_skb,u32 * offset_frag)1903 static skb_frag_t *skb_advance_to_frag(struct sk_buff *skb, u32 offset_skb,
1904 				       u32 *offset_frag)
1905 {
1906 	skb_frag_t *frag;
1907 
1908 	if (unlikely(offset_skb >= skb->len))
1909 		return NULL;
1910 
1911 	offset_skb -= skb_headlen(skb);
1912 	if ((int)offset_skb < 0 || skb_has_frag_list(skb))
1913 		return NULL;
1914 
1915 	frag = skb_shinfo(skb)->frags;
1916 	while (offset_skb) {
1917 		if (skb_frag_size(frag) > offset_skb) {
1918 			*offset_frag = offset_skb;
1919 			return frag;
1920 		}
1921 		offset_skb -= skb_frag_size(frag);
1922 		++frag;
1923 	}
1924 	*offset_frag = 0;
1925 	return frag;
1926 }
1927 
can_map_frag(const skb_frag_t * frag)1928 static bool can_map_frag(const skb_frag_t *frag)
1929 {
1930 	return skb_frag_size(frag) == PAGE_SIZE && !skb_frag_off(frag);
1931 }
1932 
find_next_mappable_frag(const skb_frag_t * frag,int remaining_in_skb)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 
tcp_zerocopy_set_hint_for_skb(struct sock * sk,struct tcp_zerocopy_receive * zc,struct sk_buff * skb,u32 offset)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);
receive_fallback_to_copy(struct sock * sk,struct tcp_zerocopy_receive * zc,int inq,struct scm_timestamping_internal * tss)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 	struct iovec iov;
1995 	int err;
1996 
1997 	zc->length = 0;
1998 	zc->recv_skip_hint = 0;
1999 
2000 	if (copy_address != zc->copybuf_address)
2001 		return -EINVAL;
2002 
2003 	err = import_single_range(READ, (void __user *)copy_address,
2004 				  inq, &iov, &msg.msg_iter);
2005 	if (err)
2006 		return err;
2007 
2008 	err = tcp_recvmsg_locked(sk, &msg, inq, MSG_DONTWAIT,
2009 				 tss, &zc->msg_flags);
2010 	if (err < 0)
2011 		return err;
2012 
2013 	zc->copybuf_len = err;
2014 	if (likely(zc->copybuf_len)) {
2015 		struct sk_buff *skb;
2016 		u32 offset;
2017 
2018 		skb = tcp_recv_skb(sk, tcp_sk(sk)->copied_seq, &offset);
2019 		if (skb)
2020 			tcp_zerocopy_set_hint_for_skb(sk, zc, skb, offset);
2021 	}
2022 	return 0;
2023 }
2024 
tcp_copy_straggler_data(struct tcp_zerocopy_receive * zc,struct sk_buff * skb,u32 copylen,u32 * offset,u32 * seq)2025 static int tcp_copy_straggler_data(struct tcp_zerocopy_receive *zc,
2026 				   struct sk_buff *skb, u32 copylen,
2027 				   u32 *offset, u32 *seq)
2028 {
2029 	unsigned long copy_address = (unsigned long)zc->copybuf_address;
2030 	struct msghdr msg = {};
2031 	struct iovec iov;
2032 	int err;
2033 
2034 	if (copy_address != zc->copybuf_address)
2035 		return -EINVAL;
2036 
2037 	err = import_single_range(READ, (void __user *)copy_address,
2038 				  copylen, &iov, &msg.msg_iter);
2039 	if (err)
2040 		return err;
2041 	err = skb_copy_datagram_msg(skb, *offset, &msg, copylen);
2042 	if (err)
2043 		return err;
2044 	zc->recv_skip_hint -= copylen;
2045 	*offset += copylen;
2046 	*seq += copylen;
2047 	return (__s32)copylen;
2048 }
2049 
tcp_zc_handle_leftover(struct tcp_zerocopy_receive * zc,struct sock * sk,struct sk_buff * skb,u32 * seq,s32 copybuf_len,struct scm_timestamping_internal * tss)2050 static int tcp_zc_handle_leftover(struct tcp_zerocopy_receive *zc,
2051 				  struct sock *sk,
2052 				  struct sk_buff *skb,
2053 				  u32 *seq,
2054 				  s32 copybuf_len,
2055 				  struct scm_timestamping_internal *tss)
2056 {
2057 	u32 offset, copylen = min_t(u32, copybuf_len, zc->recv_skip_hint);
2058 
2059 	if (!copylen)
2060 		return 0;
2061 	/* skb is null if inq < PAGE_SIZE. */
2062 	if (skb) {
2063 		offset = *seq - TCP_SKB_CB(skb)->seq;
2064 	} else {
2065 		skb = tcp_recv_skb(sk, *seq, &offset);
2066 		if (TCP_SKB_CB(skb)->has_rxtstamp) {
2067 			tcp_update_recv_tstamps(skb, tss);
2068 			zc->msg_flags |= TCP_CMSG_TS;
2069 		}
2070 	}
2071 
2072 	zc->copybuf_len = tcp_copy_straggler_data(zc, skb, copylen, &offset,
2073 						  seq);
2074 	return zc->copybuf_len < 0 ? 0 : copylen;
2075 }
2076 
tcp_zerocopy_vm_insert_batch_error(struct vm_area_struct * vma,struct page ** pending_pages,unsigned long pages_remaining,unsigned long * address,u32 * length,u32 * seq,struct tcp_zerocopy_receive * zc,u32 total_bytes_to_map,int err)2077 static int tcp_zerocopy_vm_insert_batch_error(struct vm_area_struct *vma,
2078 					      struct page **pending_pages,
2079 					      unsigned long pages_remaining,
2080 					      unsigned long *address,
2081 					      u32 *length,
2082 					      u32 *seq,
2083 					      struct tcp_zerocopy_receive *zc,
2084 					      u32 total_bytes_to_map,
2085 					      int err)
2086 {
2087 	/* At least one page did not map. Try zapping if we skipped earlier. */
2088 	if (err == -EBUSY &&
2089 	    zc->flags & TCP_RECEIVE_ZEROCOPY_FLAG_TLB_CLEAN_HINT) {
2090 		u32 maybe_zap_len;
2091 
2092 		maybe_zap_len = total_bytes_to_map -  /* All bytes to map */
2093 				*length + /* Mapped or pending */
2094 				(pages_remaining * PAGE_SIZE); /* Failed map. */
2095 		zap_page_range(vma, *address, maybe_zap_len);
2096 		err = 0;
2097 	}
2098 
2099 	if (!err) {
2100 		unsigned long leftover_pages = pages_remaining;
2101 		int bytes_mapped;
2102 
2103 		/* We called zap_page_range, try to reinsert. */
2104 		err = vm_insert_pages(vma, *address,
2105 				      pending_pages,
2106 				      &pages_remaining);
2107 		bytes_mapped = PAGE_SIZE * (leftover_pages - pages_remaining);
2108 		*seq += bytes_mapped;
2109 		*address += bytes_mapped;
2110 	}
2111 	if (err) {
2112 		/* Either we were unable to zap, OR we zapped, retried an
2113 		 * insert, and still had an issue. Either ways, pages_remaining
2114 		 * is the number of pages we were unable to map, and we unroll
2115 		 * some state we speculatively touched before.
2116 		 */
2117 		const int bytes_not_mapped = PAGE_SIZE * pages_remaining;
2118 
2119 		*length -= bytes_not_mapped;
2120 		zc->recv_skip_hint += bytes_not_mapped;
2121 	}
2122 	return err;
2123 }
2124 
tcp_zerocopy_vm_insert_batch(struct vm_area_struct * vma,struct page ** pages,unsigned int pages_to_map,unsigned long * address,u32 * length,u32 * seq,struct tcp_zerocopy_receive * zc,u32 total_bytes_to_map)2125 static int tcp_zerocopy_vm_insert_batch(struct vm_area_struct *vma,
2126 					struct page **pages,
2127 					unsigned int pages_to_map,
2128 					unsigned long *address,
2129 					u32 *length,
2130 					u32 *seq,
2131 					struct tcp_zerocopy_receive *zc,
2132 					u32 total_bytes_to_map)
2133 {
2134 	unsigned long pages_remaining = pages_to_map;
2135 	unsigned int pages_mapped;
2136 	unsigned int bytes_mapped;
2137 	int err;
2138 
2139 	err = vm_insert_pages(vma, *address, pages, &pages_remaining);
2140 	pages_mapped = pages_to_map - (unsigned int)pages_remaining;
2141 	bytes_mapped = PAGE_SIZE * pages_mapped;
2142 	/* Even if vm_insert_pages fails, it may have partially succeeded in
2143 	 * mapping (some but not all of the pages).
2144 	 */
2145 	*seq += bytes_mapped;
2146 	*address += bytes_mapped;
2147 
2148 	if (likely(!err))
2149 		return 0;
2150 
2151 	/* Error: maybe zap and retry + rollback state for failed inserts. */
2152 	return tcp_zerocopy_vm_insert_batch_error(vma, pages + pages_mapped,
2153 		pages_remaining, address, length, seq, zc, total_bytes_to_map,
2154 		err);
2155 }
2156 
2157 #define TCP_VALID_ZC_MSG_FLAGS   (TCP_CMSG_TS)
tcp_zc_finalize_rx_tstamp(struct sock * sk,struct tcp_zerocopy_receive * zc,struct scm_timestamping_internal * tss)2158 static void tcp_zc_finalize_rx_tstamp(struct sock *sk,
2159 				      struct tcp_zerocopy_receive *zc,
2160 				      struct scm_timestamping_internal *tss)
2161 {
2162 	unsigned long msg_control_addr;
2163 	struct msghdr cmsg_dummy;
2164 
2165 	msg_control_addr = (unsigned long)zc->msg_control;
2166 	cmsg_dummy.msg_control = (void *)msg_control_addr;
2167 	cmsg_dummy.msg_controllen =
2168 		(__kernel_size_t)zc->msg_controllen;
2169 	cmsg_dummy.msg_flags = in_compat_syscall()
2170 		? MSG_CMSG_COMPAT : 0;
2171 	cmsg_dummy.msg_control_is_user = true;
2172 	zc->msg_flags = 0;
2173 	if (zc->msg_control == msg_control_addr &&
2174 	    zc->msg_controllen == cmsg_dummy.msg_controllen) {
2175 		tcp_recv_timestamp(&cmsg_dummy, sk, tss);
2176 		zc->msg_control = (__u64)
2177 			((uintptr_t)cmsg_dummy.msg_control);
2178 		zc->msg_controllen =
2179 			(__u64)cmsg_dummy.msg_controllen;
2180 		zc->msg_flags = (__u32)cmsg_dummy.msg_flags;
2181 	}
2182 }
2183 
2184 #define TCP_ZEROCOPY_PAGE_BATCH_SIZE 32
tcp_zerocopy_receive(struct sock * sk,struct tcp_zerocopy_receive * zc,struct scm_timestamping_internal * tss)2185 static int tcp_zerocopy_receive(struct sock *sk,
2186 				struct tcp_zerocopy_receive *zc,
2187 				struct scm_timestamping_internal *tss)
2188 {
2189 	u32 length = 0, offset, vma_len, avail_len, copylen = 0;
2190 	unsigned long address = (unsigned long)zc->address;
2191 	struct page *pages[TCP_ZEROCOPY_PAGE_BATCH_SIZE];
2192 	s32 copybuf_len = zc->copybuf_len;
2193 	struct tcp_sock *tp = tcp_sk(sk);
2194 	const skb_frag_t *frags = NULL;
2195 	unsigned int pages_to_map = 0;
2196 	struct vm_area_struct *vma;
2197 	struct sk_buff *skb = NULL;
2198 	u32 seq = tp->copied_seq;
2199 	u32 total_bytes_to_map;
2200 	int inq = tcp_inq(sk);
2201 	int ret;
2202 
2203 	zc->copybuf_len = 0;
2204 	zc->msg_flags = 0;
2205 
2206 	if (address & (PAGE_SIZE - 1) || address != zc->address)
2207 		return -EINVAL;
2208 
2209 	if (sk->sk_state == TCP_LISTEN)
2210 		return -ENOTCONN;
2211 
2212 	sock_rps_record_flow(sk);
2213 
2214 	if (inq && inq <= copybuf_len)
2215 		return receive_fallback_to_copy(sk, zc, inq, tss);
2216 
2217 	if (inq < PAGE_SIZE) {
2218 		zc->length = 0;
2219 		zc->recv_skip_hint = inq;
2220 		if (!inq && sock_flag(sk, SOCK_DONE))
2221 			return -EIO;
2222 		return 0;
2223 	}
2224 
2225 	mmap_read_lock(current->mm);
2226 
2227 	vma = vma_lookup(current->mm, address);
2228 	if (!vma || vma->vm_ops != &tcp_vm_ops) {
2229 		mmap_read_unlock(current->mm);
2230 		return -EINVAL;
2231 	}
2232 	vma_len = min_t(unsigned long, zc->length, vma->vm_end - address);
2233 	avail_len = min_t(u32, vma_len, inq);
2234 	total_bytes_to_map = avail_len & ~(PAGE_SIZE - 1);
2235 	if (total_bytes_to_map) {
2236 		if (!(zc->flags & TCP_RECEIVE_ZEROCOPY_FLAG_TLB_CLEAN_HINT))
2237 			zap_page_range(vma, address, total_bytes_to_map);
2238 		zc->length = total_bytes_to_map;
2239 		zc->recv_skip_hint = 0;
2240 	} else {
2241 		zc->length = avail_len;
2242 		zc->recv_skip_hint = avail_len;
2243 	}
2244 	ret = 0;
2245 	while (length + PAGE_SIZE <= zc->length) {
2246 		int mappable_offset;
2247 		struct page *page;
2248 
2249 		if (zc->recv_skip_hint < PAGE_SIZE) {
2250 			u32 offset_frag;
2251 
2252 			if (skb) {
2253 				if (zc->recv_skip_hint > 0)
2254 					break;
2255 				skb = skb->next;
2256 				offset = seq - TCP_SKB_CB(skb)->seq;
2257 			} else {
2258 				skb = tcp_recv_skb(sk, seq, &offset);
2259 			}
2260 
2261 			if (TCP_SKB_CB(skb)->has_rxtstamp) {
2262 				tcp_update_recv_tstamps(skb, tss);
2263 				zc->msg_flags |= TCP_CMSG_TS;
2264 			}
2265 			zc->recv_skip_hint = skb->len - offset;
2266 			frags = skb_advance_to_frag(skb, offset, &offset_frag);
2267 			if (!frags || offset_frag)
2268 				break;
2269 		}
2270 
2271 		mappable_offset = find_next_mappable_frag(frags,
2272 							  zc->recv_skip_hint);
2273 		if (mappable_offset) {
2274 			zc->recv_skip_hint = mappable_offset;
2275 			break;
2276 		}
2277 		page = skb_frag_page(frags);
2278 		prefetchw(page);
2279 		pages[pages_to_map++] = page;
2280 		length += PAGE_SIZE;
2281 		zc->recv_skip_hint -= PAGE_SIZE;
2282 		frags++;
2283 		if (pages_to_map == TCP_ZEROCOPY_PAGE_BATCH_SIZE ||
2284 		    zc->recv_skip_hint < PAGE_SIZE) {
2285 			/* Either full batch, or we're about to go to next skb
2286 			 * (and we cannot unroll failed ops across skbs).
2287 			 */
2288 			ret = tcp_zerocopy_vm_insert_batch(vma, pages,
2289 							   pages_to_map,
2290 							   &address, &length,
2291 							   &seq, zc,
2292 							   total_bytes_to_map);
2293 			if (ret)
2294 				goto out;
2295 			pages_to_map = 0;
2296 		}
2297 	}
2298 	if (pages_to_map) {
2299 		ret = tcp_zerocopy_vm_insert_batch(vma, pages, pages_to_map,
2300 						   &address, &length, &seq,
2301 						   zc, total_bytes_to_map);
2302 	}
2303 out:
2304 	mmap_read_unlock(current->mm);
2305 	/* Try to copy straggler data. */
2306 	if (!ret)
2307 		copylen = tcp_zc_handle_leftover(zc, sk, skb, &seq, copybuf_len, tss);
2308 
2309 	if (length + copylen) {
2310 		WRITE_ONCE(tp->copied_seq, seq);
2311 		tcp_rcv_space_adjust(sk);
2312 
2313 		/* Clean up data we have read: This will do ACK frames. */
2314 		tcp_recv_skb(sk, seq, &offset);
2315 		tcp_cleanup_rbuf(sk, length + copylen);
2316 		ret = 0;
2317 		if (length == zc->length)
2318 			zc->recv_skip_hint = 0;
2319 	} else {
2320 		if (!zc->recv_skip_hint && sock_flag(sk, SOCK_DONE))
2321 			ret = -EIO;
2322 	}
2323 	zc->length = length;
2324 	return ret;
2325 }
2326 #endif
2327 
2328 /* Similar to __sock_recv_timestamp, but does not require an skb */
tcp_recv_timestamp(struct msghdr * msg,const struct sock * sk,struct scm_timestamping_internal * tss)2329 void tcp_recv_timestamp(struct msghdr *msg, const struct sock *sk,
2330 			struct scm_timestamping_internal *tss)
2331 {
2332 	int new_tstamp = sock_flag(sk, SOCK_TSTAMP_NEW);
2333 	bool has_timestamping = false;
2334 
2335 	if (tss->ts[0].tv_sec || tss->ts[0].tv_nsec) {
2336 		if (sock_flag(sk, SOCK_RCVTSTAMP)) {
2337 			if (sock_flag(sk, SOCK_RCVTSTAMPNS)) {
2338 				if (new_tstamp) {
2339 					struct __kernel_timespec kts = {
2340 						.tv_sec = tss->ts[0].tv_sec,
2341 						.tv_nsec = tss->ts[0].tv_nsec,
2342 					};
2343 					put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMPNS_NEW,
2344 						 sizeof(kts), &kts);
2345 				} else {
2346 					struct __kernel_old_timespec ts_old = {
2347 						.tv_sec = tss->ts[0].tv_sec,
2348 						.tv_nsec = tss->ts[0].tv_nsec,
2349 					};
2350 					put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMPNS_OLD,
2351 						 sizeof(ts_old), &ts_old);
2352 				}
2353 			} else {
2354 				if (new_tstamp) {
2355 					struct __kernel_sock_timeval stv = {
2356 						.tv_sec = tss->ts[0].tv_sec,
2357 						.tv_usec = tss->ts[0].tv_nsec / 1000,
2358 					};
2359 					put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_NEW,
2360 						 sizeof(stv), &stv);
2361 				} else {
2362 					struct __kernel_old_timeval tv = {
2363 						.tv_sec = tss->ts[0].tv_sec,
2364 						.tv_usec = tss->ts[0].tv_nsec / 1000,
2365 					};
2366 					put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_OLD,
2367 						 sizeof(tv), &tv);
2368 				}
2369 			}
2370 		}
2371 
2372 		if (sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE)
2373 			has_timestamping = true;
2374 		else
2375 			tss->ts[0] = (struct timespec64) {0};
2376 	}
2377 
2378 	if (tss->ts[2].tv_sec || tss->ts[2].tv_nsec) {
2379 		if (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE)
2380 			has_timestamping = true;
2381 		else
2382 			tss->ts[2] = (struct timespec64) {0};
2383 	}
2384 
2385 	if (has_timestamping) {
2386 		tss->ts[1] = (struct timespec64) {0};
2387 		if (sock_flag(sk, SOCK_TSTAMP_NEW))
2388 			put_cmsg_scm_timestamping64(msg, tss);
2389 		else
2390 			put_cmsg_scm_timestamping(msg, tss);
2391 	}
2392 }
2393 
tcp_inq_hint(struct sock * sk)2394 static int tcp_inq_hint(struct sock *sk)
2395 {
2396 	const struct tcp_sock *tp = tcp_sk(sk);
2397 	u32 copied_seq = READ_ONCE(tp->copied_seq);
2398 	u32 rcv_nxt = READ_ONCE(tp->rcv_nxt);
2399 	int inq;
2400 
2401 	inq = rcv_nxt - copied_seq;
2402 	if (unlikely(inq < 0 || copied_seq != READ_ONCE(tp->copied_seq))) {
2403 		lock_sock(sk);
2404 		inq = tp->rcv_nxt - tp->copied_seq;
2405 		release_sock(sk);
2406 	}
2407 	/* After receiving a FIN, tell the user-space to continue reading
2408 	 * by returning a non-zero inq.
2409 	 */
2410 	if (inq == 0 && sock_flag(sk, SOCK_DONE))
2411 		inq = 1;
2412 	return inq;
2413 }
2414 
2415 /*
2416  *	This routine copies from a sock struct into the user buffer.
2417  *
2418  *	Technical note: in 2.3 we work on _locked_ socket, so that
2419  *	tricks with *seq access order and skb->users are not required.
2420  *	Probably, code can be easily improved even more.
2421  */
2422 
tcp_recvmsg_locked(struct sock * sk,struct msghdr * msg,size_t len,int flags,struct scm_timestamping_internal * tss,int * cmsg_flags)2423 static int tcp_recvmsg_locked(struct sock *sk, struct msghdr *msg, size_t len,
2424 			      int flags, struct scm_timestamping_internal *tss,
2425 			      int *cmsg_flags)
2426 {
2427 	struct tcp_sock *tp = tcp_sk(sk);
2428 	int copied = 0;
2429 	u32 peek_seq;
2430 	u32 *seq;
2431 	unsigned long used;
2432 	int err;
2433 	int target;		/* Read at least this many bytes */
2434 	long timeo;
2435 	struct sk_buff *skb, *last;
2436 	u32 urg_hole = 0;
2437 
2438 	err = -ENOTCONN;
2439 	if (sk->sk_state == TCP_LISTEN)
2440 		goto out;
2441 
2442 	if (tp->recvmsg_inq) {
2443 		*cmsg_flags = TCP_CMSG_INQ;
2444 		msg->msg_get_inq = 1;
2445 	}
2446 	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2447 
2448 	/* Urgent data needs to be handled specially. */
2449 	if (flags & MSG_OOB)
2450 		goto recv_urg;
2451 
2452 	if (unlikely(tp->repair)) {
2453 		err = -EPERM;
2454 		if (!(flags & MSG_PEEK))
2455 			goto out;
2456 
2457 		if (tp->repair_queue == TCP_SEND_QUEUE)
2458 			goto recv_sndq;
2459 
2460 		err = -EINVAL;
2461 		if (tp->repair_queue == TCP_NO_QUEUE)
2462 			goto out;
2463 
2464 		/* 'common' recv queue MSG_PEEK-ing */
2465 	}
2466 
2467 	seq = &tp->copied_seq;
2468 	if (flags & MSG_PEEK) {
2469 		peek_seq = tp->copied_seq;
2470 		seq = &peek_seq;
2471 	}
2472 
2473 	target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
2474 
2475 	do {
2476 		u32 offset;
2477 
2478 		/* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */
2479 		if (unlikely(tp->urg_data) && tp->urg_seq == *seq) {
2480 			if (copied)
2481 				break;
2482 			if (signal_pending(current)) {
2483 				copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
2484 				break;
2485 			}
2486 		}
2487 
2488 		/* Next get a buffer. */
2489 
2490 		last = skb_peek_tail(&sk->sk_receive_queue);
2491 		skb_queue_walk(&sk->sk_receive_queue, skb) {
2492 			last = skb;
2493 			/* Now that we have two receive queues this
2494 			 * shouldn't happen.
2495 			 */
2496 			if (WARN(before(*seq, TCP_SKB_CB(skb)->seq),
2497 				 "TCP recvmsg seq # bug: copied %X, seq %X, rcvnxt %X, fl %X\n",
2498 				 *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt,
2499 				 flags))
2500 				break;
2501 
2502 			offset = *seq - TCP_SKB_CB(skb)->seq;
2503 			if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
2504 				pr_err_once("%s: found a SYN, please report !\n", __func__);
2505 				offset--;
2506 			}
2507 			if (offset < skb->len)
2508 				goto found_ok_skb;
2509 			if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
2510 				goto found_fin_ok;
2511 			WARN(!(flags & MSG_PEEK),
2512 			     "TCP recvmsg seq # bug 2: copied %X, seq %X, rcvnxt %X, fl %X\n",
2513 			     *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags);
2514 		}
2515 
2516 		/* Well, if we have backlog, try to process it now yet. */
2517 
2518 		if (copied >= target && !READ_ONCE(sk->sk_backlog.tail))
2519 			break;
2520 
2521 		if (copied) {
2522 			if (!timeo ||
2523 			    sk->sk_err ||
2524 			    sk->sk_state == TCP_CLOSE ||
2525 			    (sk->sk_shutdown & RCV_SHUTDOWN) ||
2526 			    signal_pending(current))
2527 				break;
2528 		} else {
2529 			if (sock_flag(sk, SOCK_DONE))
2530 				break;
2531 
2532 			if (sk->sk_err) {
2533 				copied = sock_error(sk);
2534 				break;
2535 			}
2536 
2537 			if (sk->sk_shutdown & RCV_SHUTDOWN)
2538 				break;
2539 
2540 			if (sk->sk_state == TCP_CLOSE) {
2541 				/* This occurs when user tries to read
2542 				 * from never connected socket.
2543 				 */
2544 				copied = -ENOTCONN;
2545 				break;
2546 			}
2547 
2548 			if (!timeo) {
2549 				copied = -EAGAIN;
2550 				break;
2551 			}
2552 
2553 			if (signal_pending(current)) {
2554 				copied = sock_intr_errno(timeo);
2555 				break;
2556 			}
2557 		}
2558 
2559 		if (copied >= target) {
2560 			/* Do not sleep, just process backlog. */
2561 			__sk_flush_backlog(sk);
2562 		} else {
2563 			tcp_cleanup_rbuf(sk, copied);
2564 			sk_wait_data(sk, &timeo, last);
2565 		}
2566 
2567 		if ((flags & MSG_PEEK) &&
2568 		    (peek_seq - copied - urg_hole != tp->copied_seq)) {
2569 			net_dbg_ratelimited("TCP(%s:%d): Application bug, race in MSG_PEEK\n",
2570 					    current->comm,
2571 					    task_pid_nr(current));
2572 			peek_seq = tp->copied_seq;
2573 		}
2574 		continue;
2575 
2576 found_ok_skb:
2577 		/* Ok so how much can we use? */
2578 		used = skb->len - offset;
2579 		if (len < used)
2580 			used = len;
2581 
2582 		/* Do we have urgent data here? */
2583 		if (unlikely(tp->urg_data)) {
2584 			u32 urg_offset = tp->urg_seq - *seq;
2585 			if (urg_offset < used) {
2586 				if (!urg_offset) {
2587 					if (!sock_flag(sk, SOCK_URGINLINE)) {
2588 						WRITE_ONCE(*seq, *seq + 1);
2589 						urg_hole++;
2590 						offset++;
2591 						used--;
2592 						if (!used)
2593 							goto skip_copy;
2594 					}
2595 				} else
2596 					used = urg_offset;
2597 			}
2598 		}
2599 
2600 		if (!(flags & MSG_TRUNC)) {
2601 			err = skb_copy_datagram_msg(skb, offset, msg, used);
2602 			if (err) {
2603 				/* Exception. Bailout! */
2604 				if (!copied)
2605 					copied = -EFAULT;
2606 				break;
2607 			}
2608 		}
2609 
2610 		WRITE_ONCE(*seq, *seq + used);
2611 		copied += used;
2612 		len -= used;
2613 
2614 		tcp_rcv_space_adjust(sk);
2615 
2616 skip_copy:
2617 		if (unlikely(tp->urg_data) && after(tp->copied_seq, tp->urg_seq)) {
2618 			WRITE_ONCE(tp->urg_data, 0);
2619 			tcp_fast_path_check(sk);
2620 		}
2621 
2622 		if (TCP_SKB_CB(skb)->has_rxtstamp) {
2623 			tcp_update_recv_tstamps(skb, tss);
2624 			*cmsg_flags |= TCP_CMSG_TS;
2625 		}
2626 
2627 		if (used + offset < skb->len)
2628 			continue;
2629 
2630 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
2631 			goto found_fin_ok;
2632 		if (!(flags & MSG_PEEK))
2633 			tcp_eat_recv_skb(sk, skb);
2634 		continue;
2635 
2636 found_fin_ok:
2637 		/* Process the FIN. */
2638 		WRITE_ONCE(*seq, *seq + 1);
2639 		if (!(flags & MSG_PEEK))
2640 			tcp_eat_recv_skb(sk, skb);
2641 		break;
2642 	} while (len > 0);
2643 
2644 	/* According to UNIX98, msg_name/msg_namelen are ignored
2645 	 * on connected socket. I was just happy when found this 8) --ANK
2646 	 */
2647 
2648 	/* Clean up data we have read: This will do ACK frames. */
2649 	tcp_cleanup_rbuf(sk, copied);
2650 	return copied;
2651 
2652 out:
2653 	return err;
2654 
2655 recv_urg:
2656 	err = tcp_recv_urg(sk, msg, len, flags);
2657 	goto out;
2658 
2659 recv_sndq:
2660 	err = tcp_peek_sndq(sk, msg, len);
2661 	goto out;
2662 }
2663 
tcp_recvmsg(struct sock * sk,struct msghdr * msg,size_t len,int flags,int * addr_len)2664 int tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags,
2665 		int *addr_len)
2666 {
2667 	int cmsg_flags = 0, ret;
2668 	struct scm_timestamping_internal tss;
2669 
2670 	if (unlikely(flags & MSG_ERRQUEUE))
2671 		return inet_recv_error(sk, msg, len, addr_len);
2672 
2673 	if (sk_can_busy_loop(sk) &&
2674 	    skb_queue_empty_lockless(&sk->sk_receive_queue) &&
2675 	    sk->sk_state == TCP_ESTABLISHED)
2676 		sk_busy_loop(sk, flags & MSG_DONTWAIT);
2677 
2678 	lock_sock(sk);
2679 	ret = tcp_recvmsg_locked(sk, msg, len, flags, &tss, &cmsg_flags);
2680 	release_sock(sk);
2681 
2682 	if ((cmsg_flags || msg->msg_get_inq) && ret >= 0) {
2683 		if (cmsg_flags & TCP_CMSG_TS)
2684 			tcp_recv_timestamp(msg, sk, &tss);
2685 		if (msg->msg_get_inq) {
2686 			msg->msg_inq = tcp_inq_hint(sk);
2687 			if (cmsg_flags & TCP_CMSG_INQ)
2688 				put_cmsg(msg, SOL_TCP, TCP_CM_INQ,
2689 					 sizeof(msg->msg_inq), &msg->msg_inq);
2690 		}
2691 	}
2692 	return ret;
2693 }
2694 EXPORT_SYMBOL(tcp_recvmsg);
2695 
tcp_set_state(struct sock * sk,int state)2696 void tcp_set_state(struct sock *sk, int state)
2697 {
2698 	int oldstate = sk->sk_state;
2699 
2700 	/* We defined a new enum for TCP states that are exported in BPF
2701 	 * so as not force the internal TCP states to be frozen. The
2702 	 * following checks will detect if an internal state value ever
2703 	 * differs from the BPF value. If this ever happens, then we will
2704 	 * need to remap the internal value to the BPF value before calling
2705 	 * tcp_call_bpf_2arg.
2706 	 */
2707 	BUILD_BUG_ON((int)BPF_TCP_ESTABLISHED != (int)TCP_ESTABLISHED);
2708 	BUILD_BUG_ON((int)BPF_TCP_SYN_SENT != (int)TCP_SYN_SENT);
2709 	BUILD_BUG_ON((int)BPF_TCP_SYN_RECV != (int)TCP_SYN_RECV);
2710 	BUILD_BUG_ON((int)BPF_TCP_FIN_WAIT1 != (int)TCP_FIN_WAIT1);
2711 	BUILD_BUG_ON((int)BPF_TCP_FIN_WAIT2 != (int)TCP_FIN_WAIT2);
2712 	BUILD_BUG_ON((int)BPF_TCP_TIME_WAIT != (int)TCP_TIME_WAIT);
2713 	BUILD_BUG_ON((int)BPF_TCP_CLOSE != (int)TCP_CLOSE);
2714 	BUILD_BUG_ON((int)BPF_TCP_CLOSE_WAIT != (int)TCP_CLOSE_WAIT);
2715 	BUILD_BUG_ON((int)BPF_TCP_LAST_ACK != (int)TCP_LAST_ACK);
2716 	BUILD_BUG_ON((int)BPF_TCP_LISTEN != (int)TCP_LISTEN);
2717 	BUILD_BUG_ON((int)BPF_TCP_CLOSING != (int)TCP_CLOSING);
2718 	BUILD_BUG_ON((int)BPF_TCP_NEW_SYN_RECV != (int)TCP_NEW_SYN_RECV);
2719 	BUILD_BUG_ON((int)BPF_TCP_MAX_STATES != (int)TCP_MAX_STATES);
2720 
2721 	/* bpf uapi header bpf.h defines an anonymous enum with values
2722 	 * BPF_TCP_* used by bpf programs. Currently gcc built vmlinux
2723 	 * is able to emit this enum in DWARF due to the above BUILD_BUG_ON.
2724 	 * But clang built vmlinux does not have this enum in DWARF
2725 	 * since clang removes the above code before generating IR/debuginfo.
2726 	 * Let us explicitly emit the type debuginfo to ensure the
2727 	 * above-mentioned anonymous enum in the vmlinux DWARF and hence BTF
2728 	 * regardless of which compiler is used.
2729 	 */
2730 	BTF_TYPE_EMIT_ENUM(BPF_TCP_ESTABLISHED);
2731 
2732 	if (BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), BPF_SOCK_OPS_STATE_CB_FLAG))
2733 		tcp_call_bpf_2arg(sk, BPF_SOCK_OPS_STATE_CB, oldstate, state);
2734 
2735 	switch (state) {
2736 	case TCP_ESTABLISHED:
2737 		if (oldstate != TCP_ESTABLISHED)
2738 			TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
2739 		break;
2740 
2741 	case TCP_CLOSE:
2742 		if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED)
2743 			TCP_INC_STATS(sock_net(sk), TCP_MIB_ESTABRESETS);
2744 
2745 		sk->sk_prot->unhash(sk);
2746 		if (inet_csk(sk)->icsk_bind_hash &&
2747 		    !(sk->sk_userlocks & SOCK_BINDPORT_LOCK))
2748 			inet_put_port(sk);
2749 		fallthrough;
2750 	default:
2751 		if (oldstate == TCP_ESTABLISHED)
2752 			TCP_DEC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
2753 	}
2754 
2755 	/* Change state AFTER socket is unhashed to avoid closed
2756 	 * socket sitting in hash tables.
2757 	 */
2758 	inet_sk_state_store(sk, state);
2759 }
2760 EXPORT_SYMBOL_GPL(tcp_set_state);
2761 
2762 /*
2763  *	State processing on a close. This implements the state shift for
2764  *	sending our FIN frame. Note that we only send a FIN for some
2765  *	states. A shutdown() may have already sent the FIN, or we may be
2766  *	closed.
2767  */
2768 
2769 static const unsigned char new_state[16] = {
2770   /* current state:        new state:      action:	*/
2771   [0 /* (Invalid) */]	= TCP_CLOSE,
2772   [TCP_ESTABLISHED]	= TCP_FIN_WAIT1 | TCP_ACTION_FIN,
2773   [TCP_SYN_SENT]	= TCP_CLOSE,
2774   [TCP_SYN_RECV]	= TCP_FIN_WAIT1 | TCP_ACTION_FIN,
2775   [TCP_FIN_WAIT1]	= TCP_FIN_WAIT1,
2776   [TCP_FIN_WAIT2]	= TCP_FIN_WAIT2,
2777   [TCP_TIME_WAIT]	= TCP_CLOSE,
2778   [TCP_CLOSE]		= TCP_CLOSE,
2779   [TCP_CLOSE_WAIT]	= TCP_LAST_ACK  | TCP_ACTION_FIN,
2780   [TCP_LAST_ACK]	= TCP_LAST_ACK,
2781   [TCP_LISTEN]		= TCP_CLOSE,
2782   [TCP_CLOSING]		= TCP_CLOSING,
2783   [TCP_NEW_SYN_RECV]	= TCP_CLOSE,	/* should not happen ! */
2784 };
2785 
tcp_close_state(struct sock * sk)2786 static int tcp_close_state(struct sock *sk)
2787 {
2788 	int next = (int)new_state[sk->sk_state];
2789 	int ns = next & TCP_STATE_MASK;
2790 
2791 	tcp_set_state(sk, ns);
2792 
2793 	return next & TCP_ACTION_FIN;
2794 }
2795 
2796 /*
2797  *	Shutdown the sending side of a connection. Much like close except
2798  *	that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD).
2799  */
2800 
tcp_shutdown(struct sock * sk,int how)2801 void tcp_shutdown(struct sock *sk, int how)
2802 {
2803 	/*	We need to grab some memory, and put together a FIN,
2804 	 *	and then put it into the queue to be sent.
2805 	 *		Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92.
2806 	 */
2807 	if (!(how & SEND_SHUTDOWN))
2808 		return;
2809 
2810 	/* If we've already sent a FIN, or it's a closed state, skip this. */
2811 	if ((1 << sk->sk_state) &
2812 	    (TCPF_ESTABLISHED | TCPF_SYN_SENT |
2813 	     TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) {
2814 		/* Clear out any half completed packets.  FIN if needed. */
2815 		if (tcp_close_state(sk))
2816 			tcp_send_fin(sk);
2817 	}
2818 }
2819 EXPORT_SYMBOL(tcp_shutdown);
2820 
tcp_orphan_count_sum(void)2821 int tcp_orphan_count_sum(void)
2822 {
2823 	int i, total = 0;
2824 
2825 	for_each_possible_cpu(i)
2826 		total += per_cpu(tcp_orphan_count, i);
2827 
2828 	return max(total, 0);
2829 }
2830 
2831 static int tcp_orphan_cache;
2832 static struct timer_list tcp_orphan_timer;
2833 #define TCP_ORPHAN_TIMER_PERIOD msecs_to_jiffies(100)
2834 
tcp_orphan_update(struct timer_list * unused)2835 static void tcp_orphan_update(struct timer_list *unused)
2836 {
2837 	WRITE_ONCE(tcp_orphan_cache, tcp_orphan_count_sum());
2838 	mod_timer(&tcp_orphan_timer, jiffies + TCP_ORPHAN_TIMER_PERIOD);
2839 }
2840 
tcp_too_many_orphans(int shift)2841 static bool tcp_too_many_orphans(int shift)
2842 {
2843 	return READ_ONCE(tcp_orphan_cache) << shift >
2844 		READ_ONCE(sysctl_tcp_max_orphans);
2845 }
2846 
tcp_check_oom(struct sock * sk,int shift)2847 bool tcp_check_oom(struct sock *sk, int shift)
2848 {
2849 	bool too_many_orphans, out_of_socket_memory;
2850 
2851 	too_many_orphans = tcp_too_many_orphans(shift);
2852 	out_of_socket_memory = tcp_out_of_memory(sk);
2853 
2854 	if (too_many_orphans)
2855 		net_info_ratelimited("too many orphaned sockets\n");
2856 	if (out_of_socket_memory)
2857 		net_info_ratelimited("out of memory -- consider tuning tcp_mem\n");
2858 	return too_many_orphans || out_of_socket_memory;
2859 }
2860 
__tcp_close(struct sock * sk,long timeout)2861 void __tcp_close(struct sock *sk, long timeout)
2862 {
2863 	struct sk_buff *skb;
2864 	int data_was_unread = 0;
2865 	int state;
2866 
2867 	sk->sk_shutdown = SHUTDOWN_MASK;
2868 
2869 	if (sk->sk_state == TCP_LISTEN) {
2870 		tcp_set_state(sk, TCP_CLOSE);
2871 
2872 		/* Special case. */
2873 		inet_csk_listen_stop(sk);
2874 
2875 		goto adjudge_to_death;
2876 	}
2877 
2878 	/*  We need to flush the recv. buffs.  We do this only on the
2879 	 *  descriptor close, not protocol-sourced closes, because the
2880 	 *  reader process may not have drained the data yet!
2881 	 */
2882 	while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
2883 		u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq;
2884 
2885 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
2886 			len--;
2887 		data_was_unread += len;
2888 		__kfree_skb(skb);
2889 	}
2890 
2891 	/* If socket has been already reset (e.g. in tcp_reset()) - kill it. */
2892 	if (sk->sk_state == TCP_CLOSE)
2893 		goto adjudge_to_death;
2894 
2895 	/* As outlined in RFC 2525, section 2.17, we send a RST here because
2896 	 * data was lost. To witness the awful effects of the old behavior of
2897 	 * always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk
2898 	 * GET in an FTP client, suspend the process, wait for the client to
2899 	 * advertise a zero window, then kill -9 the FTP client, wheee...
2900 	 * Note: timeout is always zero in such a case.
2901 	 */
2902 	if (unlikely(tcp_sk(sk)->repair)) {
2903 		sk->sk_prot->disconnect(sk, 0);
2904 	} else if (data_was_unread) {
2905 		/* Unread data was tossed, zap the connection. */
2906 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE);
2907 		tcp_set_state(sk, TCP_CLOSE);
2908 		tcp_send_active_reset(sk, sk->sk_allocation);
2909 	} else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
2910 		/* Check zero linger _after_ checking for unread data. */
2911 		sk->sk_prot->disconnect(sk, 0);
2912 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
2913 	} else if (tcp_close_state(sk)) {
2914 		/* We FIN if the application ate all the data before
2915 		 * zapping the connection.
2916 		 */
2917 
2918 		/* RED-PEN. Formally speaking, we have broken TCP state
2919 		 * machine. State transitions:
2920 		 *
2921 		 * TCP_ESTABLISHED -> TCP_FIN_WAIT1
2922 		 * TCP_SYN_RECV	-> TCP_FIN_WAIT1 (forget it, it's impossible)
2923 		 * TCP_CLOSE_WAIT -> TCP_LAST_ACK
2924 		 *
2925 		 * are legal only when FIN has been sent (i.e. in window),
2926 		 * rather than queued out of window. Purists blame.
2927 		 *
2928 		 * F.e. "RFC state" is ESTABLISHED,
2929 		 * if Linux state is FIN-WAIT-1, but FIN is still not sent.
2930 		 *
2931 		 * The visible declinations are that sometimes
2932 		 * we enter time-wait state, when it is not required really
2933 		 * (harmless), do not send active resets, when they are
2934 		 * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when
2935 		 * they look as CLOSING or LAST_ACK for Linux)
2936 		 * Probably, I missed some more holelets.
2937 		 * 						--ANK
2938 		 * XXX (TFO) - To start off we don't support SYN+ACK+FIN
2939 		 * in a single packet! (May consider it later but will
2940 		 * probably need API support or TCP_CORK SYN-ACK until
2941 		 * data is written and socket is closed.)
2942 		 */
2943 		tcp_send_fin(sk);
2944 	}
2945 
2946 	sk_stream_wait_close(sk, timeout);
2947 
2948 adjudge_to_death:
2949 	state = sk->sk_state;
2950 	sock_hold(sk);
2951 	sock_orphan(sk);
2952 
2953 	local_bh_disable();
2954 	bh_lock_sock(sk);
2955 	/* remove backlog if any, without releasing ownership. */
2956 	__release_sock(sk);
2957 
2958 	this_cpu_inc(tcp_orphan_count);
2959 
2960 	/* Have we already been destroyed by a softirq or backlog? */
2961 	if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE)
2962 		goto out;
2963 
2964 	/*	This is a (useful) BSD violating of the RFC. There is a
2965 	 *	problem with TCP as specified in that the other end could
2966 	 *	keep a socket open forever with no application left this end.
2967 	 *	We use a 1 minute timeout (about the same as BSD) then kill
2968 	 *	our end. If they send after that then tough - BUT: long enough
2969 	 *	that we won't make the old 4*rto = almost no time - whoops
2970 	 *	reset mistake.
2971 	 *
2972 	 *	Nope, it was not mistake. It is really desired behaviour
2973 	 *	f.e. on http servers, when such sockets are useless, but
2974 	 *	consume significant resources. Let's do it with special
2975 	 *	linger2	option.					--ANK
2976 	 */
2977 
2978 	if (sk->sk_state == TCP_FIN_WAIT2) {
2979 		struct tcp_sock *tp = tcp_sk(sk);
2980 		if (tp->linger2 < 0) {
2981 			tcp_set_state(sk, TCP_CLOSE);
2982 			tcp_send_active_reset(sk, GFP_ATOMIC);
2983 			__NET_INC_STATS(sock_net(sk),
2984 					LINUX_MIB_TCPABORTONLINGER);
2985 		} else {
2986 			const int tmo = tcp_fin_time(sk);
2987 
2988 			if (tmo > TCP_TIMEWAIT_LEN) {
2989 				inet_csk_reset_keepalive_timer(sk,
2990 						tmo - TCP_TIMEWAIT_LEN);
2991 			} else {
2992 				tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
2993 				goto out;
2994 			}
2995 		}
2996 	}
2997 	if (sk->sk_state != TCP_CLOSE) {
2998 		if (tcp_check_oom(sk, 0)) {
2999 			tcp_set_state(sk, TCP_CLOSE);
3000 			tcp_send_active_reset(sk, GFP_ATOMIC);
3001 			__NET_INC_STATS(sock_net(sk),
3002 					LINUX_MIB_TCPABORTONMEMORY);
3003 		} else if (!check_net(sock_net(sk))) {
3004 			/* Not possible to send reset; just close */
3005 			tcp_set_state(sk, TCP_CLOSE);
3006 		}
3007 	}
3008 
3009 	if (sk->sk_state == TCP_CLOSE) {
3010 		struct request_sock *req;
3011 
3012 		req = rcu_dereference_protected(tcp_sk(sk)->fastopen_rsk,
3013 						lockdep_sock_is_held(sk));
3014 		/* We could get here with a non-NULL req if the socket is
3015 		 * aborted (e.g., closed with unread data) before 3WHS
3016 		 * finishes.
3017 		 */
3018 		if (req)
3019 			reqsk_fastopen_remove(sk, req, false);
3020 		inet_csk_destroy_sock(sk);
3021 	}
3022 	/* Otherwise, socket is reprieved until protocol close. */
3023 
3024 out:
3025 	bh_unlock_sock(sk);
3026 	local_bh_enable();
3027 }
3028 
tcp_close(struct sock * sk,long timeout)3029 void tcp_close(struct sock *sk, long timeout)
3030 {
3031 	lock_sock(sk);
3032 	__tcp_close(sk, timeout);
3033 	release_sock(sk);
3034 	sock_put(sk);
3035 }
3036 EXPORT_SYMBOL(tcp_close);
3037 
3038 /* These states need RST on ABORT according to RFC793 */
3039 
tcp_need_reset(int state)3040 static inline bool tcp_need_reset(int state)
3041 {
3042 	return (1 << state) &
3043 	       (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 |
3044 		TCPF_FIN_WAIT2 | TCPF_SYN_RECV);
3045 }
3046 
tcp_rtx_queue_purge(struct sock * sk)3047 static void tcp_rtx_queue_purge(struct sock *sk)
3048 {
3049 	struct rb_node *p = rb_first(&sk->tcp_rtx_queue);
3050 
3051 	tcp_sk(sk)->highest_sack = NULL;
3052 	while (p) {
3053 		struct sk_buff *skb = rb_to_skb(p);
3054 
3055 		p = rb_next(p);
3056 		/* Since we are deleting whole queue, no need to
3057 		 * list_del(&skb->tcp_tsorted_anchor)
3058 		 */
3059 		tcp_rtx_queue_unlink(skb, sk);
3060 		tcp_wmem_free_skb(sk, skb);
3061 	}
3062 }
3063 
tcp_write_queue_purge(struct sock * sk)3064 void tcp_write_queue_purge(struct sock *sk)
3065 {
3066 	struct sk_buff *skb;
3067 
3068 	tcp_chrono_stop(sk, TCP_CHRONO_BUSY);
3069 	while ((skb = __skb_dequeue(&sk->sk_write_queue)) != NULL) {
3070 		tcp_skb_tsorted_anchor_cleanup(skb);
3071 		tcp_wmem_free_skb(sk, skb);
3072 	}
3073 	tcp_rtx_queue_purge(sk);
3074 	INIT_LIST_HEAD(&tcp_sk(sk)->tsorted_sent_queue);
3075 	tcp_clear_all_retrans_hints(tcp_sk(sk));
3076 	tcp_sk(sk)->packets_out = 0;
3077 	inet_csk(sk)->icsk_backoff = 0;
3078 }
3079 
tcp_disconnect(struct sock * sk,int flags)3080 int tcp_disconnect(struct sock *sk, int flags)
3081 {
3082 	struct inet_sock *inet = inet_sk(sk);
3083 	struct inet_connection_sock *icsk = inet_csk(sk);
3084 	struct tcp_sock *tp = tcp_sk(sk);
3085 	int old_state = sk->sk_state;
3086 	u32 seq;
3087 
3088 	if (old_state != TCP_CLOSE)
3089 		tcp_set_state(sk, TCP_CLOSE);
3090 
3091 	/* ABORT function of RFC793 */
3092 	if (old_state == TCP_LISTEN) {
3093 		inet_csk_listen_stop(sk);
3094 	} else if (unlikely(tp->repair)) {
3095 		sk->sk_err = ECONNABORTED;
3096 	} else if (tcp_need_reset(old_state) ||
3097 		   (tp->snd_nxt != tp->write_seq &&
3098 		    (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {
3099 		/* The last check adjusts for discrepancy of Linux wrt. RFC
3100 		 * states
3101 		 */
3102 		tcp_send_active_reset(sk, gfp_any());
3103 		sk->sk_err = ECONNRESET;
3104 	} else if (old_state == TCP_SYN_SENT)
3105 		sk->sk_err = ECONNRESET;
3106 
3107 	tcp_clear_xmit_timers(sk);
3108 	__skb_queue_purge(&sk->sk_receive_queue);
3109 	WRITE_ONCE(tp->copied_seq, tp->rcv_nxt);
3110 	WRITE_ONCE(tp->urg_data, 0);
3111 	tcp_write_queue_purge(sk);
3112 	tcp_fastopen_active_disable_ofo_check(sk);
3113 	skb_rbtree_purge(&tp->out_of_order_queue);
3114 
3115 	inet->inet_dport = 0;
3116 
3117 	inet_bhash2_reset_saddr(sk);
3118 
3119 	sk->sk_shutdown = 0;
3120 	sock_reset_flag(sk, SOCK_DONE);
3121 	tp->srtt_us = 0;
3122 	tp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT);
3123 	tp->rcv_rtt_last_tsecr = 0;
3124 
3125 	seq = tp->write_seq + tp->max_window + 2;
3126 	if (!seq)
3127 		seq = 1;
3128 	WRITE_ONCE(tp->write_seq, seq);
3129 
3130 	icsk->icsk_backoff = 0;
3131 	icsk->icsk_probes_out = 0;
3132 	icsk->icsk_probes_tstamp = 0;
3133 	icsk->icsk_rto = TCP_TIMEOUT_INIT;
3134 	icsk->icsk_rto_min = TCP_RTO_MIN;
3135 	icsk->icsk_delack_max = TCP_DELACK_MAX;
3136 	tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
3137 	tcp_snd_cwnd_set(tp, TCP_INIT_CWND);
3138 	tp->snd_cwnd_cnt = 0;
3139 	tp->is_cwnd_limited = 0;
3140 	tp->max_packets_out = 0;
3141 	tp->window_clamp = 0;
3142 	tp->delivered = 0;
3143 	tp->delivered_ce = 0;
3144 	if (icsk->icsk_ca_ops->release)
3145 		icsk->icsk_ca_ops->release(sk);
3146 	memset(icsk->icsk_ca_priv, 0, sizeof(icsk->icsk_ca_priv));
3147 	icsk->icsk_ca_initialized = 0;
3148 	tcp_set_ca_state(sk, TCP_CA_Open);
3149 	tp->is_sack_reneg = 0;
3150 	tcp_clear_retrans(tp);
3151 	tp->total_retrans = 0;
3152 	inet_csk_delack_init(sk);
3153 	/* Initialize rcv_mss to TCP_MIN_MSS to avoid division by 0
3154 	 * issue in __tcp_select_window()
3155 	 */
3156 	icsk->icsk_ack.rcv_mss = TCP_MIN_MSS;
3157 	memset(&tp->rx_opt, 0, sizeof(tp->rx_opt));
3158 	__sk_dst_reset(sk);
3159 	dst_release(xchg((__force struct dst_entry **)&sk->sk_rx_dst, NULL));
3160 	tcp_saved_syn_free(tp);
3161 	tp->compressed_ack = 0;
3162 	tp->segs_in = 0;
3163 	tp->segs_out = 0;
3164 	tp->bytes_sent = 0;
3165 	tp->bytes_acked = 0;
3166 	tp->bytes_received = 0;
3167 	tp->bytes_retrans = 0;
3168 	tp->data_segs_in = 0;
3169 	tp->data_segs_out = 0;
3170 	tp->duplicate_sack[0].start_seq = 0;
3171 	tp->duplicate_sack[0].end_seq = 0;
3172 	tp->dsack_dups = 0;
3173 	tp->reord_seen = 0;
3174 	tp->retrans_out = 0;
3175 	tp->sacked_out = 0;
3176 	tp->tlp_high_seq = 0;
3177 	tp->last_oow_ack_time = 0;
3178 	/* There's a bubble in the pipe until at least the first ACK. */
3179 	tp->app_limited = ~0U;
3180 	tp->rack.mstamp = 0;
3181 	tp->rack.advanced = 0;
3182 	tp->rack.reo_wnd_steps = 1;
3183 	tp->rack.last_delivered = 0;
3184 	tp->rack.reo_wnd_persist = 0;
3185 	tp->rack.dsack_seen = 0;
3186 	tp->syn_data_acked = 0;
3187 	tp->rx_opt.saw_tstamp = 0;
3188 	tp->rx_opt.dsack = 0;
3189 	tp->rx_opt.num_sacks = 0;
3190 	tp->rcv_ooopack = 0;
3191 
3192 
3193 	/* Clean up fastopen related fields */
3194 	tcp_free_fastopen_req(tp);
3195 	inet->defer_connect = 0;
3196 	tp->fastopen_client_fail = 0;
3197 
3198 	WARN_ON(inet->inet_num && !icsk->icsk_bind_hash);
3199 
3200 	if (sk->sk_frag.page) {
3201 		put_page(sk->sk_frag.page);
3202 		sk->sk_frag.page = NULL;
3203 		sk->sk_frag.offset = 0;
3204 	}
3205 	sk_error_report(sk);
3206 	return 0;
3207 }
3208 EXPORT_SYMBOL(tcp_disconnect);
3209 
tcp_can_repair_sock(const struct sock * sk)3210 static inline bool tcp_can_repair_sock(const struct sock *sk)
3211 {
3212 	return sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN) &&
3213 		(sk->sk_state != TCP_LISTEN);
3214 }
3215 
tcp_repair_set_window(struct tcp_sock * tp,sockptr_t optbuf,int len)3216 static int tcp_repair_set_window(struct tcp_sock *tp, sockptr_t optbuf, int len)
3217 {
3218 	struct tcp_repair_window opt;
3219 
3220 	if (!tp->repair)
3221 		return -EPERM;
3222 
3223 	if (len != sizeof(opt))
3224 		return -EINVAL;
3225 
3226 	if (copy_from_sockptr(&opt, optbuf, sizeof(opt)))
3227 		return -EFAULT;
3228 
3229 	if (opt.max_window < opt.snd_wnd)
3230 		return -EINVAL;
3231 
3232 	if (after(opt.snd_wl1, tp->rcv_nxt + opt.rcv_wnd))
3233 		return -EINVAL;
3234 
3235 	if (after(opt.rcv_wup, tp->rcv_nxt))
3236 		return -EINVAL;
3237 
3238 	tp->snd_wl1	= opt.snd_wl1;
3239 	tp->snd_wnd	= opt.snd_wnd;
3240 	tp->max_window	= opt.max_window;
3241 
3242 	tp->rcv_wnd	= opt.rcv_wnd;
3243 	tp->rcv_wup	= opt.rcv_wup;
3244 
3245 	return 0;
3246 }
3247 
tcp_repair_options_est(struct sock * sk,sockptr_t optbuf,unsigned int len)3248 static int tcp_repair_options_est(struct sock *sk, sockptr_t optbuf,
3249 		unsigned int len)
3250 {
3251 	struct tcp_sock *tp = tcp_sk(sk);
3252 	struct tcp_repair_opt opt;
3253 	size_t offset = 0;
3254 
3255 	while (len >= sizeof(opt)) {
3256 		if (copy_from_sockptr_offset(&opt, optbuf, offset, sizeof(opt)))
3257 			return -EFAULT;
3258 
3259 		offset += sizeof(opt);
3260 		len -= sizeof(opt);
3261 
3262 		switch (opt.opt_code) {
3263 		case TCPOPT_MSS:
3264 			tp->rx_opt.mss_clamp = opt.opt_val;
3265 			tcp_mtup_init(sk);
3266 			break;
3267 		case TCPOPT_WINDOW:
3268 			{
3269 				u16 snd_wscale = opt.opt_val & 0xFFFF;
3270 				u16 rcv_wscale = opt.opt_val >> 16;
3271 
3272 				if (snd_wscale > TCP_MAX_WSCALE || rcv_wscale > TCP_MAX_WSCALE)
3273 					return -EFBIG;
3274 
3275 				tp->rx_opt.snd_wscale = snd_wscale;
3276 				tp->rx_opt.rcv_wscale = rcv_wscale;
3277 				tp->rx_opt.wscale_ok = 1;
3278 			}
3279 			break;
3280 		case TCPOPT_SACK_PERM:
3281 			if (opt.opt_val != 0)
3282 				return -EINVAL;
3283 
3284 			tp->rx_opt.sack_ok |= TCP_SACK_SEEN;
3285 			break;
3286 		case TCPOPT_TIMESTAMP:
3287 			if (opt.opt_val != 0)
3288 				return -EINVAL;
3289 
3290 			tp->rx_opt.tstamp_ok = 1;
3291 			break;
3292 		}
3293 	}
3294 
3295 	return 0;
3296 }
3297 
3298 DEFINE_STATIC_KEY_FALSE(tcp_tx_delay_enabled);
3299 EXPORT_SYMBOL(tcp_tx_delay_enabled);
3300 
tcp_enable_tx_delay(void)3301 static void tcp_enable_tx_delay(void)
3302 {
3303 	if (!static_branch_unlikely(&tcp_tx_delay_enabled)) {
3304 		static int __tcp_tx_delay_enabled = 0;
3305 
3306 		if (cmpxchg(&__tcp_tx_delay_enabled, 0, 1) == 0) {
3307 			static_branch_enable(&tcp_tx_delay_enabled);
3308 			pr_info("TCP_TX_DELAY enabled\n");
3309 		}
3310 	}
3311 }
3312 
3313 /* When set indicates to always queue non-full frames.  Later the user clears
3314  * this option and we transmit any pending partial frames in the queue.  This is
3315  * meant to be used alongside sendfile() to get properly filled frames when the
3316  * user (for example) must write out headers with a write() call first and then
3317  * use sendfile to send out the data parts.
3318  *
3319  * TCP_CORK can be set together with TCP_NODELAY and it is stronger than
3320  * TCP_NODELAY.
3321  */
__tcp_sock_set_cork(struct sock * sk,bool on)3322 void __tcp_sock_set_cork(struct sock *sk, bool on)
3323 {
3324 	struct tcp_sock *tp = tcp_sk(sk);
3325 
3326 	if (on) {
3327 		tp->nonagle |= TCP_NAGLE_CORK;
3328 	} else {
3329 		tp->nonagle &= ~TCP_NAGLE_CORK;
3330 		if (tp->nonagle & TCP_NAGLE_OFF)
3331 			tp->nonagle |= TCP_NAGLE_PUSH;
3332 		tcp_push_pending_frames(sk);
3333 	}
3334 }
3335 
tcp_sock_set_cork(struct sock * sk,bool on)3336 void tcp_sock_set_cork(struct sock *sk, bool on)
3337 {
3338 	lock_sock(sk);
3339 	__tcp_sock_set_cork(sk, on);
3340 	release_sock(sk);
3341 }
3342 EXPORT_SYMBOL(tcp_sock_set_cork);
3343 
3344 /* TCP_NODELAY is weaker than TCP_CORK, so that this option on corked socket is
3345  * remembered, but it is not activated until cork is cleared.
3346  *
3347  * However, when TCP_NODELAY is set we make an explicit push, which overrides
3348  * even TCP_CORK for currently queued segments.
3349  */
__tcp_sock_set_nodelay(struct sock * sk,bool on)3350 void __tcp_sock_set_nodelay(struct sock *sk, bool on)
3351 {
3352 	if (on) {
3353 		tcp_sk(sk)->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH;
3354 		tcp_push_pending_frames(sk);
3355 	} else {
3356 		tcp_sk(sk)->nonagle &= ~TCP_NAGLE_OFF;
3357 	}
3358 }
3359 
tcp_sock_set_nodelay(struct sock * sk)3360 void tcp_sock_set_nodelay(struct sock *sk)
3361 {
3362 	lock_sock(sk);
3363 	__tcp_sock_set_nodelay(sk, true);
3364 	release_sock(sk);
3365 }
3366 EXPORT_SYMBOL(tcp_sock_set_nodelay);
3367 
__tcp_sock_set_quickack(struct sock * sk,int val)3368 static void __tcp_sock_set_quickack(struct sock *sk, int val)
3369 {
3370 	if (!val) {
3371 		inet_csk_enter_pingpong_mode(sk);
3372 		return;
3373 	}
3374 
3375 	inet_csk_exit_pingpong_mode(sk);
3376 	if ((1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) &&
3377 	    inet_csk_ack_scheduled(sk)) {
3378 		inet_csk(sk)->icsk_ack.pending |= ICSK_ACK_PUSHED;
3379 		tcp_cleanup_rbuf(sk, 1);
3380 		if (!(val & 1))
3381 			inet_csk_enter_pingpong_mode(sk);
3382 	}
3383 }
3384 
tcp_sock_set_quickack(struct sock * sk,int val)3385 void tcp_sock_set_quickack(struct sock *sk, int val)
3386 {
3387 	lock_sock(sk);
3388 	__tcp_sock_set_quickack(sk, val);
3389 	release_sock(sk);
3390 }
3391 EXPORT_SYMBOL(tcp_sock_set_quickack);
3392 
tcp_sock_set_syncnt(struct sock * sk,int val)3393 int tcp_sock_set_syncnt(struct sock *sk, int val)
3394 {
3395 	if (val < 1 || val > MAX_TCP_SYNCNT)
3396 		return -EINVAL;
3397 
3398 	lock_sock(sk);
3399 	inet_csk(sk)->icsk_syn_retries = val;
3400 	release_sock(sk);
3401 	return 0;
3402 }
3403 EXPORT_SYMBOL(tcp_sock_set_syncnt);
3404 
tcp_sock_set_user_timeout(struct sock * sk,u32 val)3405 void tcp_sock_set_user_timeout(struct sock *sk, u32 val)
3406 {
3407 	lock_sock(sk);
3408 	inet_csk(sk)->icsk_user_timeout = val;
3409 	release_sock(sk);
3410 }
3411 EXPORT_SYMBOL(tcp_sock_set_user_timeout);
3412 
tcp_sock_set_keepidle_locked(struct sock * sk,int val)3413 int tcp_sock_set_keepidle_locked(struct sock *sk, int val)
3414 {
3415 	struct tcp_sock *tp = tcp_sk(sk);
3416 
3417 	if (val < 1 || val > MAX_TCP_KEEPIDLE)
3418 		return -EINVAL;
3419 
3420 	tp->keepalive_time = val * HZ;
3421 	if (sock_flag(sk, SOCK_KEEPOPEN) &&
3422 	    !((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) {
3423 		u32 elapsed = keepalive_time_elapsed(tp);
3424 
3425 		if (tp->keepalive_time > elapsed)
3426 			elapsed = tp->keepalive_time - elapsed;
3427 		else
3428 			elapsed = 0;
3429 		inet_csk_reset_keepalive_timer(sk, elapsed);
3430 	}
3431 
3432 	return 0;
3433 }
3434 
tcp_sock_set_keepidle(struct sock * sk,int val)3435 int tcp_sock_set_keepidle(struct sock *sk, int val)
3436 {
3437 	int err;
3438 
3439 	lock_sock(sk);
3440 	err = tcp_sock_set_keepidle_locked(sk, val);
3441 	release_sock(sk);
3442 	return err;
3443 }
3444 EXPORT_SYMBOL(tcp_sock_set_keepidle);
3445 
tcp_sock_set_keepintvl(struct sock * sk,int val)3446 int tcp_sock_set_keepintvl(struct sock *sk, int val)
3447 {
3448 	if (val < 1 || val > MAX_TCP_KEEPINTVL)
3449 		return -EINVAL;
3450 
3451 	lock_sock(sk);
3452 	tcp_sk(sk)->keepalive_intvl = val * HZ;
3453 	release_sock(sk);
3454 	return 0;
3455 }
3456 EXPORT_SYMBOL(tcp_sock_set_keepintvl);
3457 
tcp_sock_set_keepcnt(struct sock * sk,int val)3458 int tcp_sock_set_keepcnt(struct sock *sk, int val)
3459 {
3460 	if (val < 1 || val > MAX_TCP_KEEPCNT)
3461 		return -EINVAL;
3462 
3463 	lock_sock(sk);
3464 	tcp_sk(sk)->keepalive_probes = val;
3465 	release_sock(sk);
3466 	return 0;
3467 }
3468 EXPORT_SYMBOL(tcp_sock_set_keepcnt);
3469 
tcp_set_window_clamp(struct sock * sk,int val)3470 int tcp_set_window_clamp(struct sock *sk, int val)
3471 {
3472 	struct tcp_sock *tp = tcp_sk(sk);
3473 
3474 	if (!val) {
3475 		if (sk->sk_state != TCP_CLOSE)
3476 			return -EINVAL;
3477 		tp->window_clamp = 0;
3478 	} else {
3479 		tp->window_clamp = val < SOCK_MIN_RCVBUF / 2 ?
3480 			SOCK_MIN_RCVBUF / 2 : val;
3481 		tp->rcv_ssthresh = min(tp->rcv_wnd, tp->window_clamp);
3482 	}
3483 	return 0;
3484 }
3485 
3486 /*
3487  *	Socket option code for TCP.
3488  */
do_tcp_setsockopt(struct sock * sk,int level,int optname,sockptr_t optval,unsigned int optlen)3489 int do_tcp_setsockopt(struct sock *sk, int level, int optname,
3490 		      sockptr_t optval, unsigned int optlen)
3491 {
3492 	struct tcp_sock *tp = tcp_sk(sk);
3493 	struct inet_connection_sock *icsk = inet_csk(sk);
3494 	struct net *net = sock_net(sk);
3495 	int val;
3496 	int err = 0;
3497 
3498 	/* These are data/string values, all the others are ints */
3499 	switch (optname) {
3500 	case TCP_CONGESTION: {
3501 		char name[TCP_CA_NAME_MAX];
3502 
3503 		if (optlen < 1)
3504 			return -EINVAL;
3505 
3506 		val = strncpy_from_sockptr(name, optval,
3507 					min_t(long, TCP_CA_NAME_MAX-1, optlen));
3508 		if (val < 0)
3509 			return -EFAULT;
3510 		name[val] = 0;
3511 
3512 		sockopt_lock_sock(sk);
3513 		err = tcp_set_congestion_control(sk, name, !has_current_bpf_ctx(),
3514 						 sockopt_ns_capable(sock_net(sk)->user_ns,
3515 								    CAP_NET_ADMIN));
3516 		sockopt_release_sock(sk);
3517 		return err;
3518 	}
3519 	case TCP_ULP: {
3520 		char name[TCP_ULP_NAME_MAX];
3521 
3522 		if (optlen < 1)
3523 			return -EINVAL;
3524 
3525 		val = strncpy_from_sockptr(name, optval,
3526 					min_t(long, TCP_ULP_NAME_MAX - 1,
3527 					      optlen));
3528 		if (val < 0)
3529 			return -EFAULT;
3530 		name[val] = 0;
3531 
3532 		sockopt_lock_sock(sk);
3533 		err = tcp_set_ulp(sk, name);
3534 		sockopt_release_sock(sk);
3535 		return err;
3536 	}
3537 	case TCP_FASTOPEN_KEY: {
3538 		__u8 key[TCP_FASTOPEN_KEY_BUF_LENGTH];
3539 		__u8 *backup_key = NULL;
3540 
3541 		/* Allow a backup key as well to facilitate key rotation
3542 		 * First key is the active one.
3543 		 */
3544 		if (optlen != TCP_FASTOPEN_KEY_LENGTH &&
3545 		    optlen != TCP_FASTOPEN_KEY_BUF_LENGTH)
3546 			return -EINVAL;
3547 
3548 		if (copy_from_sockptr(key, optval, optlen))
3549 			return -EFAULT;
3550 
3551 		if (optlen == TCP_FASTOPEN_KEY_BUF_LENGTH)
3552 			backup_key = key + TCP_FASTOPEN_KEY_LENGTH;
3553 
3554 		return tcp_fastopen_reset_cipher(net, sk, key, backup_key);
3555 	}
3556 	default:
3557 		/* fallthru */
3558 		break;
3559 	}
3560 
3561 	if (optlen < sizeof(int))
3562 		return -EINVAL;
3563 
3564 	if (copy_from_sockptr(&val, optval, sizeof(val)))
3565 		return -EFAULT;
3566 
3567 	sockopt_lock_sock(sk);
3568 
3569 	switch (optname) {
3570 	case TCP_MAXSEG:
3571 		/* Values greater than interface MTU won't take effect. However
3572 		 * at the point when this call is done we typically don't yet
3573 		 * know which interface is going to be used
3574 		 */
3575 		if (val && (val < TCP_MIN_MSS || val > MAX_TCP_WINDOW)) {
3576 			err = -EINVAL;
3577 			break;
3578 		}
3579 		tp->rx_opt.user_mss = val;
3580 		break;
3581 
3582 	case TCP_NODELAY:
3583 		__tcp_sock_set_nodelay(sk, val);
3584 		break;
3585 
3586 	case TCP_THIN_LINEAR_TIMEOUTS:
3587 		if (val < 0 || val > 1)
3588 			err = -EINVAL;
3589 		else
3590 			tp->thin_lto = val;
3591 		break;
3592 
3593 	case TCP_THIN_DUPACK:
3594 		if (val < 0 || val > 1)
3595 			err = -EINVAL;
3596 		break;
3597 
3598 	case TCP_REPAIR:
3599 		if (!tcp_can_repair_sock(sk))
3600 			err = -EPERM;
3601 		else if (val == TCP_REPAIR_ON) {
3602 			tp->repair = 1;
3603 			sk->sk_reuse = SK_FORCE_REUSE;
3604 			tp->repair_queue = TCP_NO_QUEUE;
3605 		} else if (val == TCP_REPAIR_OFF) {
3606 			tp->repair = 0;
3607 			sk->sk_reuse = SK_NO_REUSE;
3608 			tcp_send_window_probe(sk);
3609 		} else if (val == TCP_REPAIR_OFF_NO_WP) {
3610 			tp->repair = 0;
3611 			sk->sk_reuse = SK_NO_REUSE;
3612 		} else
3613 			err = -EINVAL;
3614 
3615 		break;
3616 
3617 	case TCP_REPAIR_QUEUE:
3618 		if (!tp->repair)
3619 			err = -EPERM;
3620 		else if ((unsigned int)val < TCP_QUEUES_NR)
3621 			tp->repair_queue = val;
3622 		else
3623 			err = -EINVAL;
3624 		break;
3625 
3626 	case TCP_QUEUE_SEQ:
3627 		if (sk->sk_state != TCP_CLOSE) {
3628 			err = -EPERM;
3629 		} else if (tp->repair_queue == TCP_SEND_QUEUE) {
3630 			if (!tcp_rtx_queue_empty(sk))
3631 				err = -EPERM;
3632 			else
3633 				WRITE_ONCE(tp->write_seq, val);
3634 		} else if (tp->repair_queue == TCP_RECV_QUEUE) {
3635 			if (tp->rcv_nxt != tp->copied_seq) {
3636 				err = -EPERM;
3637 			} else {
3638 				WRITE_ONCE(tp->rcv_nxt, val);
3639 				WRITE_ONCE(tp->copied_seq, val);
3640 			}
3641 		} else {
3642 			err = -EINVAL;
3643 		}
3644 		break;
3645 
3646 	case TCP_REPAIR_OPTIONS:
3647 		if (!tp->repair)
3648 			err = -EINVAL;
3649 		else if (sk->sk_state == TCP_ESTABLISHED && !tp->bytes_sent)
3650 			err = tcp_repair_options_est(sk, optval, optlen);
3651 		else
3652 			err = -EPERM;
3653 		break;
3654 
3655 	case TCP_CORK:
3656 		__tcp_sock_set_cork(sk, val);
3657 		break;
3658 
3659 	case TCP_KEEPIDLE:
3660 		err = tcp_sock_set_keepidle_locked(sk, val);
3661 		break;
3662 	case TCP_KEEPINTVL:
3663 		if (val < 1 || val > MAX_TCP_KEEPINTVL)
3664 			err = -EINVAL;
3665 		else
3666 			tp->keepalive_intvl = val * HZ;
3667 		break;
3668 	case TCP_KEEPCNT:
3669 		if (val < 1 || val > MAX_TCP_KEEPCNT)
3670 			err = -EINVAL;
3671 		else
3672 			tp->keepalive_probes = val;
3673 		break;
3674 	case TCP_SYNCNT:
3675 		if (val < 1 || val > MAX_TCP_SYNCNT)
3676 			err = -EINVAL;
3677 		else
3678 			icsk->icsk_syn_retries = val;
3679 		break;
3680 
3681 	case TCP_SAVE_SYN:
3682 		/* 0: disable, 1: enable, 2: start from ether_header */
3683 		if (val < 0 || val > 2)
3684 			err = -EINVAL;
3685 		else
3686 			tp->save_syn = val;
3687 		break;
3688 
3689 	case TCP_LINGER2:
3690 		if (val < 0)
3691 			tp->linger2 = -1;
3692 		else if (val > TCP_FIN_TIMEOUT_MAX / HZ)
3693 			tp->linger2 = TCP_FIN_TIMEOUT_MAX;
3694 		else
3695 			tp->linger2 = val * HZ;
3696 		break;
3697 
3698 	case TCP_DEFER_ACCEPT:
3699 		/* Translate value in seconds to number of retransmits */
3700 		icsk->icsk_accept_queue.rskq_defer_accept =
3701 			secs_to_retrans(val, TCP_TIMEOUT_INIT / HZ,
3702 					TCP_RTO_MAX / HZ);
3703 		break;
3704 
3705 	case TCP_WINDOW_CLAMP:
3706 		err = tcp_set_window_clamp(sk, val);
3707 		break;
3708 
3709 	case TCP_QUICKACK:
3710 		__tcp_sock_set_quickack(sk, val);
3711 		break;
3712 
3713 #ifdef CONFIG_TCP_MD5SIG
3714 	case TCP_MD5SIG:
3715 	case TCP_MD5SIG_EXT:
3716 		err = tp->af_specific->md5_parse(sk, optname, optval, optlen);
3717 		break;
3718 #endif
3719 	case TCP_USER_TIMEOUT:
3720 		/* Cap the max time in ms TCP will retry or probe the window
3721 		 * before giving up and aborting (ETIMEDOUT) a connection.
3722 		 */
3723 		if (val < 0)
3724 			err = -EINVAL;
3725 		else
3726 			icsk->icsk_user_timeout = val;
3727 		break;
3728 
3729 	case TCP_FASTOPEN:
3730 		if (val >= 0 && ((1 << sk->sk_state) & (TCPF_CLOSE |
3731 		    TCPF_LISTEN))) {
3732 			tcp_fastopen_init_key_once(net);
3733 
3734 			fastopen_queue_tune(sk, val);
3735 		} else {
3736 			err = -EINVAL;
3737 		}
3738 		break;
3739 	case TCP_FASTOPEN_CONNECT:
3740 		if (val > 1 || val < 0) {
3741 			err = -EINVAL;
3742 		} else if (READ_ONCE(net->ipv4.sysctl_tcp_fastopen) &
3743 			   TFO_CLIENT_ENABLE) {
3744 			if (sk->sk_state == TCP_CLOSE)
3745 				tp->fastopen_connect = val;
3746 			else
3747 				err = -EINVAL;
3748 		} else {
3749 			err = -EOPNOTSUPP;
3750 		}
3751 		break;
3752 	case TCP_FASTOPEN_NO_COOKIE:
3753 		if (val > 1 || val < 0)
3754 			err = -EINVAL;
3755 		else if (!((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
3756 			err = -EINVAL;
3757 		else
3758 			tp->fastopen_no_cookie = val;
3759 		break;
3760 	case TCP_TIMESTAMP:
3761 		if (!tp->repair)
3762 			err = -EPERM;
3763 		else
3764 			tp->tsoffset = val - tcp_time_stamp_raw();
3765 		break;
3766 	case TCP_REPAIR_WINDOW:
3767 		err = tcp_repair_set_window(tp, optval, optlen);
3768 		break;
3769 	case TCP_NOTSENT_LOWAT:
3770 		tp->notsent_lowat = val;
3771 		sk->sk_write_space(sk);
3772 		break;
3773 	case TCP_INQ:
3774 		if (val > 1 || val < 0)
3775 			err = -EINVAL;
3776 		else
3777 			tp->recvmsg_inq = val;
3778 		break;
3779 	case TCP_TX_DELAY:
3780 		if (val)
3781 			tcp_enable_tx_delay();
3782 		tp->tcp_tx_delay = val;
3783 		break;
3784 	default:
3785 		err = -ENOPROTOOPT;
3786 		break;
3787 	}
3788 
3789 	sockopt_release_sock(sk);
3790 	return err;
3791 }
3792 
tcp_setsockopt(struct sock * sk,int level,int optname,sockptr_t optval,unsigned int optlen)3793 int tcp_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval,
3794 		   unsigned int optlen)
3795 {
3796 	const struct inet_connection_sock *icsk = inet_csk(sk);
3797 
3798 	if (level != SOL_TCP)
3799 		/* Paired with WRITE_ONCE() in do_ipv6_setsockopt() and tcp_v6_connect() */
3800 		return READ_ONCE(icsk->icsk_af_ops)->setsockopt(sk, level, optname,
3801 								optval, optlen);
3802 	return do_tcp_setsockopt(sk, level, optname, optval, optlen);
3803 }
3804 EXPORT_SYMBOL(tcp_setsockopt);
3805 
tcp_get_info_chrono_stats(const struct tcp_sock * tp,struct tcp_info * info)3806 static void tcp_get_info_chrono_stats(const struct tcp_sock *tp,
3807 				      struct tcp_info *info)
3808 {
3809 	u64 stats[__TCP_CHRONO_MAX], total = 0;
3810 	enum tcp_chrono i;
3811 
3812 	for (i = TCP_CHRONO_BUSY; i < __TCP_CHRONO_MAX; ++i) {
3813 		stats[i] = tp->chrono_stat[i - 1];
3814 		if (i == tp->chrono_type)
3815 			stats[i] += tcp_jiffies32 - tp->chrono_start;
3816 		stats[i] *= USEC_PER_SEC / HZ;
3817 		total += stats[i];
3818 	}
3819 
3820 	info->tcpi_busy_time = total;
3821 	info->tcpi_rwnd_limited = stats[TCP_CHRONO_RWND_LIMITED];
3822 	info->tcpi_sndbuf_limited = stats[TCP_CHRONO_SNDBUF_LIMITED];
3823 }
3824 
3825 /* Return information about state of tcp endpoint in API format. */
tcp_get_info(struct sock * sk,struct tcp_info * info)3826 void tcp_get_info(struct sock *sk, struct tcp_info *info)
3827 {
3828 	const struct tcp_sock *tp = tcp_sk(sk); /* iff sk_type == SOCK_STREAM */
3829 	const struct inet_connection_sock *icsk = inet_csk(sk);
3830 	unsigned long rate;
3831 	u32 now;
3832 	u64 rate64;
3833 	bool slow;
3834 
3835 	memset(info, 0, sizeof(*info));
3836 	if (sk->sk_type != SOCK_STREAM)
3837 		return;
3838 
3839 	info->tcpi_state = inet_sk_state_load(sk);
3840 
3841 	/* Report meaningful fields for all TCP states, including listeners */
3842 	rate = READ_ONCE(sk->sk_pacing_rate);
3843 	rate64 = (rate != ~0UL) ? rate : ~0ULL;
3844 	info->tcpi_pacing_rate = rate64;
3845 
3846 	rate = READ_ONCE(sk->sk_max_pacing_rate);
3847 	rate64 = (rate != ~0UL) ? rate : ~0ULL;
3848 	info->tcpi_max_pacing_rate = rate64;
3849 
3850 	info->tcpi_reordering = tp->reordering;
3851 	info->tcpi_snd_cwnd = tcp_snd_cwnd(tp);
3852 
3853 	if (info->tcpi_state == TCP_LISTEN) {
3854 		/* listeners aliased fields :
3855 		 * tcpi_unacked -> Number of children ready for accept()
3856 		 * tcpi_sacked  -> max backlog
3857 		 */
3858 		info->tcpi_unacked = READ_ONCE(sk->sk_ack_backlog);
3859 		info->tcpi_sacked = READ_ONCE(sk->sk_max_ack_backlog);
3860 		return;
3861 	}
3862 
3863 	slow = lock_sock_fast(sk);
3864 
3865 	info->tcpi_ca_state = icsk->icsk_ca_state;
3866 	info->tcpi_retransmits = icsk->icsk_retransmits;
3867 	info->tcpi_probes = icsk->icsk_probes_out;
3868 	info->tcpi_backoff = icsk->icsk_backoff;
3869 
3870 	if (tp->rx_opt.tstamp_ok)
3871 		info->tcpi_options |= TCPI_OPT_TIMESTAMPS;
3872 	if (tcp_is_sack(tp))
3873 		info->tcpi_options |= TCPI_OPT_SACK;
3874 	if (tp->rx_opt.wscale_ok) {
3875 		info->tcpi_options |= TCPI_OPT_WSCALE;
3876 		info->tcpi_snd_wscale = tp->rx_opt.snd_wscale;
3877 		info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale;
3878 	}
3879 
3880 	if (tp->ecn_flags & TCP_ECN_OK)
3881 		info->tcpi_options |= TCPI_OPT_ECN;
3882 	if (tp->ecn_flags & TCP_ECN_SEEN)
3883 		info->tcpi_options |= TCPI_OPT_ECN_SEEN;
3884 	if (tp->syn_data_acked)
3885 		info->tcpi_options |= TCPI_OPT_SYN_DATA;
3886 
3887 	info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto);
3888 	info->tcpi_ato = jiffies_to_usecs(icsk->icsk_ack.ato);
3889 	info->tcpi_snd_mss = tp->mss_cache;
3890 	info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss;
3891 
3892 	info->tcpi_unacked = tp->packets_out;
3893 	info->tcpi_sacked = tp->sacked_out;
3894 
3895 	info->tcpi_lost = tp->lost_out;
3896 	info->tcpi_retrans = tp->retrans_out;
3897 
3898 	now = tcp_jiffies32;
3899 	info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime);
3900 	info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime);
3901 	info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp);
3902 
3903 	info->tcpi_pmtu = icsk->icsk_pmtu_cookie;
3904 	info->tcpi_rcv_ssthresh = tp->rcv_ssthresh;
3905 	info->tcpi_rtt = tp->srtt_us >> 3;
3906 	info->tcpi_rttvar = tp->mdev_us >> 2;
3907 	info->tcpi_snd_ssthresh = tp->snd_ssthresh;
3908 	info->tcpi_advmss = tp->advmss;
3909 
3910 	info->tcpi_rcv_rtt = tp->rcv_rtt_est.rtt_us >> 3;
3911 	info->tcpi_rcv_space = tp->rcvq_space.space;
3912 
3913 	info->tcpi_total_retrans = tp->total_retrans;
3914 
3915 	info->tcpi_bytes_acked = tp->bytes_acked;
3916 	info->tcpi_bytes_received = tp->bytes_received;
3917 	info->tcpi_notsent_bytes = max_t(int, 0, tp->write_seq - tp->snd_nxt);
3918 	tcp_get_info_chrono_stats(tp, info);
3919 
3920 	info->tcpi_segs_out = tp->segs_out;
3921 
3922 	/* segs_in and data_segs_in can be updated from tcp_segs_in() from BH */
3923 	info->tcpi_segs_in = READ_ONCE(tp->segs_in);
3924 	info->tcpi_data_segs_in = READ_ONCE(tp->data_segs_in);
3925 
3926 	info->tcpi_min_rtt = tcp_min_rtt(tp);
3927 	info->tcpi_data_segs_out = tp->data_segs_out;
3928 
3929 	info->tcpi_delivery_rate_app_limited = tp->rate_app_limited ? 1 : 0;
3930 	rate64 = tcp_compute_delivery_rate(tp);
3931 	if (rate64)
3932 		info->tcpi_delivery_rate = rate64;
3933 	info->tcpi_delivered = tp->delivered;
3934 	info->tcpi_delivered_ce = tp->delivered_ce;
3935 	info->tcpi_bytes_sent = tp->bytes_sent;
3936 	info->tcpi_bytes_retrans = tp->bytes_retrans;
3937 	info->tcpi_dsack_dups = tp->dsack_dups;
3938 	info->tcpi_reord_seen = tp->reord_seen;
3939 	info->tcpi_rcv_ooopack = tp->rcv_ooopack;
3940 	info->tcpi_snd_wnd = tp->snd_wnd;
3941 	info->tcpi_fastopen_client_fail = tp->fastopen_client_fail;
3942 	unlock_sock_fast(sk, slow);
3943 }
3944 EXPORT_SYMBOL_GPL(tcp_get_info);
3945 
tcp_opt_stats_get_size(void)3946 static size_t tcp_opt_stats_get_size(void)
3947 {
3948 	return
3949 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_BUSY */
3950 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_RWND_LIMITED */
3951 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_SNDBUF_LIMITED */
3952 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_DATA_SEGS_OUT */
3953 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_TOTAL_RETRANS */
3954 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_PACING_RATE */
3955 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_DELIVERY_RATE */
3956 		nla_total_size(sizeof(u32)) + /* TCP_NLA_SND_CWND */
3957 		nla_total_size(sizeof(u32)) + /* TCP_NLA_REORDERING */
3958 		nla_total_size(sizeof(u32)) + /* TCP_NLA_MIN_RTT */
3959 		nla_total_size(sizeof(u8)) + /* TCP_NLA_RECUR_RETRANS */
3960 		nla_total_size(sizeof(u8)) + /* TCP_NLA_DELIVERY_RATE_APP_LMT */
3961 		nla_total_size(sizeof(u32)) + /* TCP_NLA_SNDQ_SIZE */
3962 		nla_total_size(sizeof(u8)) + /* TCP_NLA_CA_STATE */
3963 		nla_total_size(sizeof(u32)) + /* TCP_NLA_SND_SSTHRESH */
3964 		nla_total_size(sizeof(u32)) + /* TCP_NLA_DELIVERED */
3965 		nla_total_size(sizeof(u32)) + /* TCP_NLA_DELIVERED_CE */
3966 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_BYTES_SENT */
3967 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_BYTES_RETRANS */
3968 		nla_total_size(sizeof(u32)) + /* TCP_NLA_DSACK_DUPS */
3969 		nla_total_size(sizeof(u32)) + /* TCP_NLA_REORD_SEEN */
3970 		nla_total_size(sizeof(u32)) + /* TCP_NLA_SRTT */
3971 		nla_total_size(sizeof(u16)) + /* TCP_NLA_TIMEOUT_REHASH */
3972 		nla_total_size(sizeof(u32)) + /* TCP_NLA_BYTES_NOTSENT */
3973 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_EDT */
3974 		nla_total_size(sizeof(u8)) + /* TCP_NLA_TTL */
3975 		0;
3976 }
3977 
3978 /* Returns TTL or hop limit of an incoming packet from skb. */
tcp_skb_ttl_or_hop_limit(const struct sk_buff * skb)3979 static u8 tcp_skb_ttl_or_hop_limit(const struct sk_buff *skb)
3980 {
3981 	if (skb->protocol == htons(ETH_P_IP))
3982 		return ip_hdr(skb)->ttl;
3983 	else if (skb->protocol == htons(ETH_P_IPV6))
3984 		return ipv6_hdr(skb)->hop_limit;
3985 	else
3986 		return 0;
3987 }
3988 
tcp_get_timestamping_opt_stats(const struct sock * sk,const struct sk_buff * orig_skb,const struct sk_buff * ack_skb)3989 struct sk_buff *tcp_get_timestamping_opt_stats(const struct sock *sk,
3990 					       const struct sk_buff *orig_skb,
3991 					       const struct sk_buff *ack_skb)
3992 {
3993 	const struct tcp_sock *tp = tcp_sk(sk);
3994 	struct sk_buff *stats;
3995 	struct tcp_info info;
3996 	unsigned long rate;
3997 	u64 rate64;
3998 
3999 	stats = alloc_skb(tcp_opt_stats_get_size(), GFP_ATOMIC);
4000 	if (!stats)
4001 		return NULL;
4002 
4003 	tcp_get_info_chrono_stats(tp, &info);
4004 	nla_put_u64_64bit(stats, TCP_NLA_BUSY,
4005 			  info.tcpi_busy_time, TCP_NLA_PAD);
4006 	nla_put_u64_64bit(stats, TCP_NLA_RWND_LIMITED,
4007 			  info.tcpi_rwnd_limited, TCP_NLA_PAD);
4008 	nla_put_u64_64bit(stats, TCP_NLA_SNDBUF_LIMITED,
4009 			  info.tcpi_sndbuf_limited, TCP_NLA_PAD);
4010 	nla_put_u64_64bit(stats, TCP_NLA_DATA_SEGS_OUT,
4011 			  tp->data_segs_out, TCP_NLA_PAD);
4012 	nla_put_u64_64bit(stats, TCP_NLA_TOTAL_RETRANS,
4013 			  tp->total_retrans, TCP_NLA_PAD);
4014 
4015 	rate = READ_ONCE(sk->sk_pacing_rate);
4016 	rate64 = (rate != ~0UL) ? rate : ~0ULL;
4017 	nla_put_u64_64bit(stats, TCP_NLA_PACING_RATE, rate64, TCP_NLA_PAD);
4018 
4019 	rate64 = tcp_compute_delivery_rate(tp);
4020 	nla_put_u64_64bit(stats, TCP_NLA_DELIVERY_RATE, rate64, TCP_NLA_PAD);
4021 
4022 	nla_put_u32(stats, TCP_NLA_SND_CWND, tcp_snd_cwnd(tp));
4023 	nla_put_u32(stats, TCP_NLA_REORDERING, tp->reordering);
4024 	nla_put_u32(stats, TCP_NLA_MIN_RTT, tcp_min_rtt(tp));
4025 
4026 	nla_put_u8(stats, TCP_NLA_RECUR_RETRANS, inet_csk(sk)->icsk_retransmits);
4027 	nla_put_u8(stats, TCP_NLA_DELIVERY_RATE_APP_LMT, !!tp->rate_app_limited);
4028 	nla_put_u32(stats, TCP_NLA_SND_SSTHRESH, tp->snd_ssthresh);
4029 	nla_put_u32(stats, TCP_NLA_DELIVERED, tp->delivered);
4030 	nla_put_u32(stats, TCP_NLA_DELIVERED_CE, tp->delivered_ce);
4031 
4032 	nla_put_u32(stats, TCP_NLA_SNDQ_SIZE, tp->write_seq - tp->snd_una);
4033 	nla_put_u8(stats, TCP_NLA_CA_STATE, inet_csk(sk)->icsk_ca_state);
4034 
4035 	nla_put_u64_64bit(stats, TCP_NLA_BYTES_SENT, tp->bytes_sent,
4036 			  TCP_NLA_PAD);
4037 	nla_put_u64_64bit(stats, TCP_NLA_BYTES_RETRANS, tp->bytes_retrans,
4038 			  TCP_NLA_PAD);
4039 	nla_put_u32(stats, TCP_NLA_DSACK_DUPS, tp->dsack_dups);
4040 	nla_put_u32(stats, TCP_NLA_REORD_SEEN, tp->reord_seen);
4041 	nla_put_u32(stats, TCP_NLA_SRTT, tp->srtt_us >> 3);
4042 	nla_put_u16(stats, TCP_NLA_TIMEOUT_REHASH, tp->timeout_rehash);
4043 	nla_put_u32(stats, TCP_NLA_BYTES_NOTSENT,
4044 		    max_t(int, 0, tp->write_seq - tp->snd_nxt));
4045 	nla_put_u64_64bit(stats, TCP_NLA_EDT, orig_skb->skb_mstamp_ns,
4046 			  TCP_NLA_PAD);
4047 	if (ack_skb)
4048 		nla_put_u8(stats, TCP_NLA_TTL,
4049 			   tcp_skb_ttl_or_hop_limit(ack_skb));
4050 
4051 	return stats;
4052 }
4053 
do_tcp_getsockopt(struct sock * sk,int level,int optname,sockptr_t optval,sockptr_t optlen)4054 int do_tcp_getsockopt(struct sock *sk, int level,
4055 		      int optname, sockptr_t optval, sockptr_t optlen)
4056 {
4057 	struct inet_connection_sock *icsk = inet_csk(sk);
4058 	struct tcp_sock *tp = tcp_sk(sk);
4059 	struct net *net = sock_net(sk);
4060 	int val, len;
4061 
4062 	if (copy_from_sockptr(&len, optlen, sizeof(int)))
4063 		return -EFAULT;
4064 
4065 	len = min_t(unsigned int, len, sizeof(int));
4066 
4067 	if (len < 0)
4068 		return -EINVAL;
4069 
4070 	switch (optname) {
4071 	case TCP_MAXSEG:
4072 		val = tp->mss_cache;
4073 		if (!val && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
4074 			val = tp->rx_opt.user_mss;
4075 		if (tp->repair)
4076 			val = tp->rx_opt.mss_clamp;
4077 		break;
4078 	case TCP_NODELAY:
4079 		val = !!(tp->nonagle&TCP_NAGLE_OFF);
4080 		break;
4081 	case TCP_CORK:
4082 		val = !!(tp->nonagle&TCP_NAGLE_CORK);
4083 		break;
4084 	case TCP_KEEPIDLE:
4085 		val = keepalive_time_when(tp) / HZ;
4086 		break;
4087 	case TCP_KEEPINTVL:
4088 		val = keepalive_intvl_when(tp) / HZ;
4089 		break;
4090 	case TCP_KEEPCNT:
4091 		val = keepalive_probes(tp);
4092 		break;
4093 	case TCP_SYNCNT:
4094 		val = icsk->icsk_syn_retries ? :
4095 			READ_ONCE(net->ipv4.sysctl_tcp_syn_retries);
4096 		break;
4097 	case TCP_LINGER2:
4098 		val = tp->linger2;
4099 		if (val >= 0)
4100 			val = (val ? : READ_ONCE(net->ipv4.sysctl_tcp_fin_timeout)) / HZ;
4101 		break;
4102 	case TCP_DEFER_ACCEPT:
4103 		val = retrans_to_secs(icsk->icsk_accept_queue.rskq_defer_accept,
4104 				      TCP_TIMEOUT_INIT / HZ, TCP_RTO_MAX / HZ);
4105 		break;
4106 	case TCP_WINDOW_CLAMP:
4107 		val = tp->window_clamp;
4108 		break;
4109 	case TCP_INFO: {
4110 		struct tcp_info info;
4111 
4112 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4113 			return -EFAULT;
4114 
4115 		tcp_get_info(sk, &info);
4116 
4117 		len = min_t(unsigned int, len, sizeof(info));
4118 		if (copy_to_sockptr(optlen, &len, sizeof(int)))
4119 			return -EFAULT;
4120 		if (copy_to_sockptr(optval, &info, len))
4121 			return -EFAULT;
4122 		return 0;
4123 	}
4124 	case TCP_CC_INFO: {
4125 		const struct tcp_congestion_ops *ca_ops;
4126 		union tcp_cc_info info;
4127 		size_t sz = 0;
4128 		int attr;
4129 
4130 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4131 			return -EFAULT;
4132 
4133 		ca_ops = icsk->icsk_ca_ops;
4134 		if (ca_ops && ca_ops->get_info)
4135 			sz = ca_ops->get_info(sk, ~0U, &attr, &info);
4136 
4137 		len = min_t(unsigned int, len, sz);
4138 		if (copy_to_sockptr(optlen, &len, sizeof(int)))
4139 			return -EFAULT;
4140 		if (copy_to_sockptr(optval, &info, len))
4141 			return -EFAULT;
4142 		return 0;
4143 	}
4144 	case TCP_QUICKACK:
4145 		val = !inet_csk_in_pingpong_mode(sk);
4146 		break;
4147 
4148 	case TCP_CONGESTION:
4149 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4150 			return -EFAULT;
4151 		len = min_t(unsigned int, len, TCP_CA_NAME_MAX);
4152 		if (copy_to_sockptr(optlen, &len, sizeof(int)))
4153 			return -EFAULT;
4154 		if (copy_to_sockptr(optval, icsk->icsk_ca_ops->name, len))
4155 			return -EFAULT;
4156 		return 0;
4157 
4158 	case TCP_ULP:
4159 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4160 			return -EFAULT;
4161 		len = min_t(unsigned int, len, TCP_ULP_NAME_MAX);
4162 		if (!icsk->icsk_ulp_ops) {
4163 			len = 0;
4164 			if (copy_to_sockptr(optlen, &len, sizeof(int)))
4165 				return -EFAULT;
4166 			return 0;
4167 		}
4168 		if (copy_to_sockptr(optlen, &len, sizeof(int)))
4169 			return -EFAULT;
4170 		if (copy_to_sockptr(optval, icsk->icsk_ulp_ops->name, len))
4171 			return -EFAULT;
4172 		return 0;
4173 
4174 	case TCP_FASTOPEN_KEY: {
4175 		u64 key[TCP_FASTOPEN_KEY_BUF_LENGTH / sizeof(u64)];
4176 		unsigned int key_len;
4177 
4178 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4179 			return -EFAULT;
4180 
4181 		key_len = tcp_fastopen_get_cipher(net, icsk, key) *
4182 				TCP_FASTOPEN_KEY_LENGTH;
4183 		len = min_t(unsigned int, len, key_len);
4184 		if (copy_to_sockptr(optlen, &len, sizeof(int)))
4185 			return -EFAULT;
4186 		if (copy_to_sockptr(optval, key, len))
4187 			return -EFAULT;
4188 		return 0;
4189 	}
4190 	case TCP_THIN_LINEAR_TIMEOUTS:
4191 		val = tp->thin_lto;
4192 		break;
4193 
4194 	case TCP_THIN_DUPACK:
4195 		val = 0;
4196 		break;
4197 
4198 	case TCP_REPAIR:
4199 		val = tp->repair;
4200 		break;
4201 
4202 	case TCP_REPAIR_QUEUE:
4203 		if (tp->repair)
4204 			val = tp->repair_queue;
4205 		else
4206 			return -EINVAL;
4207 		break;
4208 
4209 	case TCP_REPAIR_WINDOW: {
4210 		struct tcp_repair_window opt;
4211 
4212 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4213 			return -EFAULT;
4214 
4215 		if (len != sizeof(opt))
4216 			return -EINVAL;
4217 
4218 		if (!tp->repair)
4219 			return -EPERM;
4220 
4221 		opt.snd_wl1	= tp->snd_wl1;
4222 		opt.snd_wnd	= tp->snd_wnd;
4223 		opt.max_window	= tp->max_window;
4224 		opt.rcv_wnd	= tp->rcv_wnd;
4225 		opt.rcv_wup	= tp->rcv_wup;
4226 
4227 		if (copy_to_sockptr(optval, &opt, len))
4228 			return -EFAULT;
4229 		return 0;
4230 	}
4231 	case TCP_QUEUE_SEQ:
4232 		if (tp->repair_queue == TCP_SEND_QUEUE)
4233 			val = tp->write_seq;
4234 		else if (tp->repair_queue == TCP_RECV_QUEUE)
4235 			val = tp->rcv_nxt;
4236 		else
4237 			return -EINVAL;
4238 		break;
4239 
4240 	case TCP_USER_TIMEOUT:
4241 		val = icsk->icsk_user_timeout;
4242 		break;
4243 
4244 	case TCP_FASTOPEN:
4245 		val = icsk->icsk_accept_queue.fastopenq.max_qlen;
4246 		break;
4247 
4248 	case TCP_FASTOPEN_CONNECT:
4249 		val = tp->fastopen_connect;
4250 		break;
4251 
4252 	case TCP_FASTOPEN_NO_COOKIE:
4253 		val = tp->fastopen_no_cookie;
4254 		break;
4255 
4256 	case TCP_TX_DELAY:
4257 		val = tp->tcp_tx_delay;
4258 		break;
4259 
4260 	case TCP_TIMESTAMP:
4261 		val = tcp_time_stamp_raw() + tp->tsoffset;
4262 		break;
4263 	case TCP_NOTSENT_LOWAT:
4264 		val = tp->notsent_lowat;
4265 		break;
4266 	case TCP_INQ:
4267 		val = tp->recvmsg_inq;
4268 		break;
4269 	case TCP_SAVE_SYN:
4270 		val = tp->save_syn;
4271 		break;
4272 	case TCP_SAVED_SYN: {
4273 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4274 			return -EFAULT;
4275 
4276 		sockopt_lock_sock(sk);
4277 		if (tp->saved_syn) {
4278 			if (len < tcp_saved_syn_len(tp->saved_syn)) {
4279 				len = tcp_saved_syn_len(tp->saved_syn);
4280 				if (copy_to_sockptr(optlen, &len, sizeof(int))) {
4281 					sockopt_release_sock(sk);
4282 					return -EFAULT;
4283 				}
4284 				sockopt_release_sock(sk);
4285 				return -EINVAL;
4286 			}
4287 			len = tcp_saved_syn_len(tp->saved_syn);
4288 			if (copy_to_sockptr(optlen, &len, sizeof(int))) {
4289 				sockopt_release_sock(sk);
4290 				return -EFAULT;
4291 			}
4292 			if (copy_to_sockptr(optval, tp->saved_syn->data, len)) {
4293 				sockopt_release_sock(sk);
4294 				return -EFAULT;
4295 			}
4296 			tcp_saved_syn_free(tp);
4297 			sockopt_release_sock(sk);
4298 		} else {
4299 			sockopt_release_sock(sk);
4300 			len = 0;
4301 			if (copy_to_sockptr(optlen, &len, sizeof(int)))
4302 				return -EFAULT;
4303 		}
4304 		return 0;
4305 	}
4306 #ifdef CONFIG_MMU
4307 	case TCP_ZEROCOPY_RECEIVE: {
4308 		struct scm_timestamping_internal tss;
4309 		struct tcp_zerocopy_receive zc = {};
4310 		int err;
4311 
4312 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4313 			return -EFAULT;
4314 		if (len < 0 ||
4315 		    len < offsetofend(struct tcp_zerocopy_receive, length))
4316 			return -EINVAL;
4317 		if (unlikely(len > sizeof(zc))) {
4318 			err = check_zeroed_sockptr(optval, sizeof(zc),
4319 						   len - sizeof(zc));
4320 			if (err < 1)
4321 				return err == 0 ? -EINVAL : err;
4322 			len = sizeof(zc);
4323 			if (copy_to_sockptr(optlen, &len, sizeof(int)))
4324 				return -EFAULT;
4325 		}
4326 		if (copy_from_sockptr(&zc, optval, len))
4327 			return -EFAULT;
4328 		if (zc.reserved)
4329 			return -EINVAL;
4330 		if (zc.msg_flags &  ~(TCP_VALID_ZC_MSG_FLAGS))
4331 			return -EINVAL;
4332 		sockopt_lock_sock(sk);
4333 		err = tcp_zerocopy_receive(sk, &zc, &tss);
4334 		err = BPF_CGROUP_RUN_PROG_GETSOCKOPT_KERN(sk, level, optname,
4335 							  &zc, &len, err);
4336 		sockopt_release_sock(sk);
4337 		if (len >= offsetofend(struct tcp_zerocopy_receive, msg_flags))
4338 			goto zerocopy_rcv_cmsg;
4339 		switch (len) {
4340 		case offsetofend(struct tcp_zerocopy_receive, msg_flags):
4341 			goto zerocopy_rcv_cmsg;
4342 		case offsetofend(struct tcp_zerocopy_receive, msg_controllen):
4343 		case offsetofend(struct tcp_zerocopy_receive, msg_control):
4344 		case offsetofend(struct tcp_zerocopy_receive, flags):
4345 		case offsetofend(struct tcp_zerocopy_receive, copybuf_len):
4346 		case offsetofend(struct tcp_zerocopy_receive, copybuf_address):
4347 		case offsetofend(struct tcp_zerocopy_receive, err):
4348 			goto zerocopy_rcv_sk_err;
4349 		case offsetofend(struct tcp_zerocopy_receive, inq):
4350 			goto zerocopy_rcv_inq;
4351 		case offsetofend(struct tcp_zerocopy_receive, length):
4352 		default:
4353 			goto zerocopy_rcv_out;
4354 		}
4355 zerocopy_rcv_cmsg:
4356 		if (zc.msg_flags & TCP_CMSG_TS)
4357 			tcp_zc_finalize_rx_tstamp(sk, &zc, &tss);
4358 		else
4359 			zc.msg_flags = 0;
4360 zerocopy_rcv_sk_err:
4361 		if (!err)
4362 			zc.err = sock_error(sk);
4363 zerocopy_rcv_inq:
4364 		zc.inq = tcp_inq_hint(sk);
4365 zerocopy_rcv_out:
4366 		if (!err && copy_to_sockptr(optval, &zc, len))
4367 			err = -EFAULT;
4368 		return err;
4369 	}
4370 #endif
4371 	default:
4372 		return -ENOPROTOOPT;
4373 	}
4374 
4375 	if (copy_to_sockptr(optlen, &len, sizeof(int)))
4376 		return -EFAULT;
4377 	if (copy_to_sockptr(optval, &val, len))
4378 		return -EFAULT;
4379 	return 0;
4380 }
4381 
tcp_bpf_bypass_getsockopt(int level,int optname)4382 bool tcp_bpf_bypass_getsockopt(int level, int optname)
4383 {
4384 	/* TCP do_tcp_getsockopt has optimized getsockopt implementation
4385 	 * to avoid extra socket lock for TCP_ZEROCOPY_RECEIVE.
4386 	 */
4387 	if (level == SOL_TCP && optname == TCP_ZEROCOPY_RECEIVE)
4388 		return true;
4389 
4390 	return false;
4391 }
4392 EXPORT_SYMBOL(tcp_bpf_bypass_getsockopt);
4393 
tcp_getsockopt(struct sock * sk,int level,int optname,char __user * optval,int __user * optlen)4394 int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval,
4395 		   int __user *optlen)
4396 {
4397 	struct inet_connection_sock *icsk = inet_csk(sk);
4398 
4399 	if (level != SOL_TCP)
4400 		/* Paired with WRITE_ONCE() in do_ipv6_setsockopt() and tcp_v6_connect() */
4401 		return READ_ONCE(icsk->icsk_af_ops)->getsockopt(sk, level, optname,
4402 								optval, optlen);
4403 	return do_tcp_getsockopt(sk, level, optname, USER_SOCKPTR(optval),
4404 				 USER_SOCKPTR(optlen));
4405 }
4406 EXPORT_SYMBOL(tcp_getsockopt);
4407 
4408 #ifdef CONFIG_TCP_MD5SIG
4409 static DEFINE_PER_CPU(struct tcp_md5sig_pool, tcp_md5sig_pool);
4410 static DEFINE_MUTEX(tcp_md5sig_mutex);
4411 static bool tcp_md5sig_pool_populated = false;
4412 
__tcp_alloc_md5sig_pool(void)4413 static void __tcp_alloc_md5sig_pool(void)
4414 {
4415 	struct crypto_ahash *hash;
4416 	int cpu;
4417 
4418 	hash = crypto_alloc_ahash("md5", 0, CRYPTO_ALG_ASYNC);
4419 	if (IS_ERR(hash))
4420 		return;
4421 
4422 	for_each_possible_cpu(cpu) {
4423 		void *scratch = per_cpu(tcp_md5sig_pool, cpu).scratch;
4424 		struct ahash_request *req;
4425 
4426 		if (!scratch) {
4427 			scratch = kmalloc_node(sizeof(union tcp_md5sum_block) +
4428 					       sizeof(struct tcphdr),
4429 					       GFP_KERNEL,
4430 					       cpu_to_node(cpu));
4431 			if (!scratch)
4432 				return;
4433 			per_cpu(tcp_md5sig_pool, cpu).scratch = scratch;
4434 		}
4435 		if (per_cpu(tcp_md5sig_pool, cpu).md5_req)
4436 			continue;
4437 
4438 		req = ahash_request_alloc(hash, GFP_KERNEL);
4439 		if (!req)
4440 			return;
4441 
4442 		ahash_request_set_callback(req, 0, NULL, NULL);
4443 
4444 		per_cpu(tcp_md5sig_pool, cpu).md5_req = req;
4445 	}
4446 	/* before setting tcp_md5sig_pool_populated, we must commit all writes
4447 	 * to memory. See smp_rmb() in tcp_get_md5sig_pool()
4448 	 */
4449 	smp_wmb();
4450 	/* Paired with READ_ONCE() from tcp_alloc_md5sig_pool()
4451 	 * and tcp_get_md5sig_pool().
4452 	*/
4453 	WRITE_ONCE(tcp_md5sig_pool_populated, true);
4454 }
4455 
tcp_alloc_md5sig_pool(void)4456 bool tcp_alloc_md5sig_pool(void)
4457 {
4458 	/* Paired with WRITE_ONCE() from __tcp_alloc_md5sig_pool() */
4459 	if (unlikely(!READ_ONCE(tcp_md5sig_pool_populated))) {
4460 		mutex_lock(&tcp_md5sig_mutex);
4461 
4462 		if (!tcp_md5sig_pool_populated) {
4463 			__tcp_alloc_md5sig_pool();
4464 			if (tcp_md5sig_pool_populated)
4465 				static_branch_inc(&tcp_md5_needed);
4466 		}
4467 
4468 		mutex_unlock(&tcp_md5sig_mutex);
4469 	}
4470 	/* Paired with WRITE_ONCE() from __tcp_alloc_md5sig_pool() */
4471 	return READ_ONCE(tcp_md5sig_pool_populated);
4472 }
4473 EXPORT_SYMBOL(tcp_alloc_md5sig_pool);
4474 
4475 
4476 /**
4477  *	tcp_get_md5sig_pool - get md5sig_pool for this user
4478  *
4479  *	We use percpu structure, so if we succeed, we exit with preemption
4480  *	and BH disabled, to make sure another thread or softirq handling
4481  *	wont try to get same context.
4482  */
tcp_get_md5sig_pool(void)4483 struct tcp_md5sig_pool *tcp_get_md5sig_pool(void)
4484 {
4485 	local_bh_disable();
4486 
4487 	/* Paired with WRITE_ONCE() from __tcp_alloc_md5sig_pool() */
4488 	if (READ_ONCE(tcp_md5sig_pool_populated)) {
4489 		/* coupled with smp_wmb() in __tcp_alloc_md5sig_pool() */
4490 		smp_rmb();
4491 		return this_cpu_ptr(&tcp_md5sig_pool);
4492 	}
4493 	local_bh_enable();
4494 	return NULL;
4495 }
4496 EXPORT_SYMBOL(tcp_get_md5sig_pool);
4497 
tcp_md5_hash_skb_data(struct tcp_md5sig_pool * hp,const struct sk_buff * skb,unsigned int header_len)4498 int tcp_md5_hash_skb_data(struct tcp_md5sig_pool *hp,
4499 			  const struct sk_buff *skb, unsigned int header_len)
4500 {
4501 	struct scatterlist sg;
4502 	const struct tcphdr *tp = tcp_hdr(skb);
4503 	struct ahash_request *req = hp->md5_req;
4504 	unsigned int i;
4505 	const unsigned int head_data_len = skb_headlen(skb) > header_len ?
4506 					   skb_headlen(skb) - header_len : 0;
4507 	const struct skb_shared_info *shi = skb_shinfo(skb);
4508 	struct sk_buff *frag_iter;
4509 
4510 	sg_init_table(&sg, 1);
4511 
4512 	sg_set_buf(&sg, ((u8 *) tp) + header_len, head_data_len);
4513 	ahash_request_set_crypt(req, &sg, NULL, head_data_len);
4514 	if (crypto_ahash_update(req))
4515 		return 1;
4516 
4517 	for (i = 0; i < shi->nr_frags; ++i) {
4518 		const skb_frag_t *f = &shi->frags[i];
4519 		unsigned int offset = skb_frag_off(f);
4520 		struct page *page = skb_frag_page(f) + (offset >> PAGE_SHIFT);
4521 
4522 		sg_set_page(&sg, page, skb_frag_size(f),
4523 			    offset_in_page(offset));
4524 		ahash_request_set_crypt(req, &sg, NULL, skb_frag_size(f));
4525 		if (crypto_ahash_update(req))
4526 			return 1;
4527 	}
4528 
4529 	skb_walk_frags(skb, frag_iter)
4530 		if (tcp_md5_hash_skb_data(hp, frag_iter, 0))
4531 			return 1;
4532 
4533 	return 0;
4534 }
4535 EXPORT_SYMBOL(tcp_md5_hash_skb_data);
4536 
tcp_md5_hash_key(struct tcp_md5sig_pool * hp,const struct tcp_md5sig_key * key)4537 int tcp_md5_hash_key(struct tcp_md5sig_pool *hp, const struct tcp_md5sig_key *key)
4538 {
4539 	u8 keylen = READ_ONCE(key->keylen); /* paired with WRITE_ONCE() in tcp_md5_do_add */
4540 	struct scatterlist sg;
4541 
4542 	sg_init_one(&sg, key->key, keylen);
4543 	ahash_request_set_crypt(hp->md5_req, &sg, NULL, keylen);
4544 
4545 	/* We use data_race() because tcp_md5_do_add() might change key->key under us */
4546 	return data_race(crypto_ahash_update(hp->md5_req));
4547 }
4548 EXPORT_SYMBOL(tcp_md5_hash_key);
4549 
4550 /* Called with rcu_read_lock() */
4551 enum skb_drop_reason
tcp_inbound_md5_hash(const struct sock * sk,const struct sk_buff * skb,const void * saddr,const void * daddr,int family,int dif,int sdif)4552 tcp_inbound_md5_hash(const struct sock *sk, const struct sk_buff *skb,
4553 		     const void *saddr, const void *daddr,
4554 		     int family, int dif, int sdif)
4555 {
4556 	/*
4557 	 * This gets called for each TCP segment that arrives
4558 	 * so we want to be efficient.
4559 	 * We have 3 drop cases:
4560 	 * o No MD5 hash and one expected.
4561 	 * o MD5 hash and we're not expecting one.
4562 	 * o MD5 hash and its wrong.
4563 	 */
4564 	const __u8 *hash_location = NULL;
4565 	struct tcp_md5sig_key *hash_expected;
4566 	const struct tcphdr *th = tcp_hdr(skb);
4567 	struct tcp_sock *tp = tcp_sk(sk);
4568 	int genhash, l3index;
4569 	u8 newhash[16];
4570 
4571 	/* sdif set, means packet ingressed via a device
4572 	 * in an L3 domain and dif is set to the l3mdev
4573 	 */
4574 	l3index = sdif ? dif : 0;
4575 
4576 	hash_expected = tcp_md5_do_lookup(sk, l3index, saddr, family);
4577 	hash_location = tcp_parse_md5sig_option(th);
4578 
4579 	/* We've parsed the options - do we have a hash? */
4580 	if (!hash_expected && !hash_location)
4581 		return SKB_NOT_DROPPED_YET;
4582 
4583 	if (hash_expected && !hash_location) {
4584 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5NOTFOUND);
4585 		return SKB_DROP_REASON_TCP_MD5NOTFOUND;
4586 	}
4587 
4588 	if (!hash_expected && hash_location) {
4589 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5UNEXPECTED);
4590 		return SKB_DROP_REASON_TCP_MD5UNEXPECTED;
4591 	}
4592 
4593 	/* Check the signature.
4594 	 * To support dual stack listeners, we need to handle
4595 	 * IPv4-mapped case.
4596 	 */
4597 	if (family == AF_INET)
4598 		genhash = tcp_v4_md5_hash_skb(newhash,
4599 					      hash_expected,
4600 					      NULL, skb);
4601 	else
4602 		genhash = tp->af_specific->calc_md5_hash(newhash,
4603 							 hash_expected,
4604 							 NULL, skb);
4605 
4606 	if (genhash || memcmp(hash_location, newhash, 16) != 0) {
4607 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5FAILURE);
4608 		if (family == AF_INET) {
4609 			net_info_ratelimited("MD5 Hash failed for (%pI4, %d)->(%pI4, %d)%s L3 index %d\n",
4610 					saddr, ntohs(th->source),
4611 					daddr, ntohs(th->dest),
4612 					genhash ? " tcp_v4_calc_md5_hash failed"
4613 					: "", l3index);
4614 		} else {
4615 			net_info_ratelimited("MD5 Hash %s for [%pI6c]:%u->[%pI6c]:%u L3 index %d\n",
4616 					genhash ? "failed" : "mismatch",
4617 					saddr, ntohs(th->source),
4618 					daddr, ntohs(th->dest), l3index);
4619 		}
4620 		return SKB_DROP_REASON_TCP_MD5FAILURE;
4621 	}
4622 	return SKB_NOT_DROPPED_YET;
4623 }
4624 EXPORT_SYMBOL(tcp_inbound_md5_hash);
4625 
4626 #endif
4627 
tcp_done(struct sock * sk)4628 void tcp_done(struct sock *sk)
4629 {
4630 	struct request_sock *req;
4631 
4632 	/* We might be called with a new socket, after
4633 	 * inet_csk_prepare_forced_close() has been called
4634 	 * so we can not use lockdep_sock_is_held(sk)
4635 	 */
4636 	req = rcu_dereference_protected(tcp_sk(sk)->fastopen_rsk, 1);
4637 
4638 	if (sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV)
4639 		TCP_INC_STATS(sock_net(sk), TCP_MIB_ATTEMPTFAILS);
4640 
4641 	tcp_set_state(sk, TCP_CLOSE);
4642 	tcp_clear_xmit_timers(sk);
4643 	if (req)
4644 		reqsk_fastopen_remove(sk, req, false);
4645 
4646 	sk->sk_shutdown = SHUTDOWN_MASK;
4647 
4648 	if (!sock_flag(sk, SOCK_DEAD))
4649 		sk->sk_state_change(sk);
4650 	else
4651 		inet_csk_destroy_sock(sk);
4652 }
4653 EXPORT_SYMBOL_GPL(tcp_done);
4654 
tcp_abort(struct sock * sk,int err)4655 int tcp_abort(struct sock *sk, int err)
4656 {
4657 	int state = inet_sk_state_load(sk);
4658 
4659 	if (state == TCP_NEW_SYN_RECV) {
4660 		struct request_sock *req = inet_reqsk(sk);
4661 
4662 		local_bh_disable();
4663 		inet_csk_reqsk_queue_drop(req->rsk_listener, req);
4664 		local_bh_enable();
4665 		return 0;
4666 	}
4667 	if (state == TCP_TIME_WAIT) {
4668 		struct inet_timewait_sock *tw = inet_twsk(sk);
4669 
4670 		refcount_inc(&tw->tw_refcnt);
4671 		local_bh_disable();
4672 		inet_twsk_deschedule_put(tw);
4673 		local_bh_enable();
4674 		return 0;
4675 	}
4676 
4677 	/* Don't race with userspace socket closes such as tcp_close. */
4678 	lock_sock(sk);
4679 
4680 	if (sk->sk_state == TCP_LISTEN) {
4681 		tcp_set_state(sk, TCP_CLOSE);
4682 		inet_csk_listen_stop(sk);
4683 	}
4684 
4685 	/* Don't race with BH socket closes such as inet_csk_listen_stop. */
4686 	local_bh_disable();
4687 	bh_lock_sock(sk);
4688 
4689 	if (!sock_flag(sk, SOCK_DEAD)) {
4690 		sk->sk_err = err;
4691 		/* This barrier is coupled with smp_rmb() in tcp_poll() */
4692 		smp_wmb();
4693 		sk_error_report(sk);
4694 		if (tcp_need_reset(sk->sk_state))
4695 			tcp_send_active_reset(sk, GFP_ATOMIC);
4696 		tcp_done(sk);
4697 	}
4698 
4699 	bh_unlock_sock(sk);
4700 	local_bh_enable();
4701 	tcp_write_queue_purge(sk);
4702 	release_sock(sk);
4703 	return 0;
4704 }
4705 EXPORT_SYMBOL_GPL(tcp_abort);
4706 
4707 extern struct tcp_congestion_ops tcp_reno;
4708 
4709 static __initdata unsigned long thash_entries;
set_thash_entries(char * str)4710 static int __init set_thash_entries(char *str)
4711 {
4712 	ssize_t ret;
4713 
4714 	if (!str)
4715 		return 0;
4716 
4717 	ret = kstrtoul(str, 0, &thash_entries);
4718 	if (ret)
4719 		return 0;
4720 
4721 	return 1;
4722 }
4723 __setup("thash_entries=", set_thash_entries);
4724 
tcp_init_mem(void)4725 static void __init tcp_init_mem(void)
4726 {
4727 	unsigned long limit = nr_free_buffer_pages() / 16;
4728 
4729 	limit = max(limit, 128UL);
4730 	sysctl_tcp_mem[0] = limit / 4 * 3;		/* 4.68 % */
4731 	sysctl_tcp_mem[1] = limit;			/* 6.25 % */
4732 	sysctl_tcp_mem[2] = sysctl_tcp_mem[0] * 2;	/* 9.37 % */
4733 }
4734 
tcp_init(void)4735 void __init tcp_init(void)
4736 {
4737 	int max_rshare, max_wshare, cnt;
4738 	unsigned long limit;
4739 	unsigned int i;
4740 
4741 	BUILD_BUG_ON(TCP_MIN_SND_MSS <= MAX_TCP_OPTION_SPACE);
4742 	BUILD_BUG_ON(sizeof(struct tcp_skb_cb) >
4743 		     sizeof_field(struct sk_buff, cb));
4744 
4745 	percpu_counter_init(&tcp_sockets_allocated, 0, GFP_KERNEL);
4746 
4747 	timer_setup(&tcp_orphan_timer, tcp_orphan_update, TIMER_DEFERRABLE);
4748 	mod_timer(&tcp_orphan_timer, jiffies + TCP_ORPHAN_TIMER_PERIOD);
4749 
4750 	inet_hashinfo2_init(&tcp_hashinfo, "tcp_listen_portaddr_hash",
4751 			    thash_entries, 21,  /* one slot per 2 MB*/
4752 			    0, 64 * 1024);
4753 	tcp_hashinfo.bind_bucket_cachep =
4754 		kmem_cache_create("tcp_bind_bucket",
4755 				  sizeof(struct inet_bind_bucket), 0,
4756 				  SLAB_HWCACHE_ALIGN | SLAB_PANIC |
4757 				  SLAB_ACCOUNT,
4758 				  NULL);
4759 	tcp_hashinfo.bind2_bucket_cachep =
4760 		kmem_cache_create("tcp_bind2_bucket",
4761 				  sizeof(struct inet_bind2_bucket), 0,
4762 				  SLAB_HWCACHE_ALIGN | SLAB_PANIC |
4763 				  SLAB_ACCOUNT,
4764 				  NULL);
4765 
4766 	/* Size and allocate the main established and bind bucket
4767 	 * hash tables.
4768 	 *
4769 	 * The methodology is similar to that of the buffer cache.
4770 	 */
4771 	tcp_hashinfo.ehash =
4772 		alloc_large_system_hash("TCP established",
4773 					sizeof(struct inet_ehash_bucket),
4774 					thash_entries,
4775 					17, /* one slot per 128 KB of memory */
4776 					0,
4777 					NULL,
4778 					&tcp_hashinfo.ehash_mask,
4779 					0,
4780 					thash_entries ? 0 : 512 * 1024);
4781 	for (i = 0; i <= tcp_hashinfo.ehash_mask; i++)
4782 		INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i);
4783 
4784 	if (inet_ehash_locks_alloc(&tcp_hashinfo))
4785 		panic("TCP: failed to alloc ehash_locks");
4786 	tcp_hashinfo.bhash =
4787 		alloc_large_system_hash("TCP bind",
4788 					2 * sizeof(struct inet_bind_hashbucket),
4789 					tcp_hashinfo.ehash_mask + 1,
4790 					17, /* one slot per 128 KB of memory */
4791 					0,
4792 					&tcp_hashinfo.bhash_size,
4793 					NULL,
4794 					0,
4795 					64 * 1024);
4796 	tcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size;
4797 	tcp_hashinfo.bhash2 = tcp_hashinfo.bhash + tcp_hashinfo.bhash_size;
4798 	for (i = 0; i < tcp_hashinfo.bhash_size; i++) {
4799 		spin_lock_init(&tcp_hashinfo.bhash[i].lock);
4800 		INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain);
4801 		spin_lock_init(&tcp_hashinfo.bhash2[i].lock);
4802 		INIT_HLIST_HEAD(&tcp_hashinfo.bhash2[i].chain);
4803 	}
4804 
4805 	tcp_hashinfo.pernet = false;
4806 
4807 	cnt = tcp_hashinfo.ehash_mask + 1;
4808 	sysctl_tcp_max_orphans = cnt / 2;
4809 
4810 	tcp_init_mem();
4811 	/* Set per-socket limits to no more than 1/128 the pressure threshold */
4812 	limit = nr_free_buffer_pages() << (PAGE_SHIFT - 7);
4813 	max_wshare = min(4UL*1024*1024, limit);
4814 	max_rshare = min(6UL*1024*1024, limit);
4815 
4816 	init_net.ipv4.sysctl_tcp_wmem[0] = PAGE_SIZE;
4817 	init_net.ipv4.sysctl_tcp_wmem[1] = 16*1024;
4818 	init_net.ipv4.sysctl_tcp_wmem[2] = max(64*1024, max_wshare);
4819 
4820 	init_net.ipv4.sysctl_tcp_rmem[0] = PAGE_SIZE;
4821 	init_net.ipv4.sysctl_tcp_rmem[1] = 131072;
4822 	init_net.ipv4.sysctl_tcp_rmem[2] = max(131072, max_rshare);
4823 
4824 	pr_info("Hash tables configured (established %u bind %u)\n",
4825 		tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size);
4826 
4827 	tcp_v4_init();
4828 	tcp_metrics_init();
4829 	BUG_ON(tcp_register_congestion_control(&tcp_reno) != 0);
4830 	tcp_tasklet_init();
4831 	mptcp_init();
4832 }
4833