import PULS_20160108
[GitHub/mt8127/android_kernel_alcatel_ttab.git] / net / ipv4 / tcp.c
CommitLineData
1da177e4
LT
1/*
2 * INET An implementation of the TCP/IP protocol suite for the LINUX
3 * operating system. INET is implemented using the BSD Socket
4 * interface as the means of communication with the user level.
5 *
6 * Implementation of the Transmission Control Protocol(TCP).
7 *
02c30a84 8 * Authors: Ross Biro
1da177e4
LT
9 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
10 * Mark Evans, <evansmp@uhura.aston.ac.uk>
11 * Corey Minyard <wf-rch!minyard@relay.EU.net>
12 * Florian La Roche, <flla@stud.uni-sb.de>
13 * Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
14 * Linus Torvalds, <torvalds@cs.helsinki.fi>
15 * Alan Cox, <gw4pts@gw4pts.ampr.org>
16 * Matthew Dillon, <dillon@apollo.west.oic.com>
17 * Arnt Gulbrandsen, <agulbra@nvg.unit.no>
18 * Jorge Cwik, <jorge@laser.satlink.net>
19 *
20 * Fixes:
21 * Alan Cox : Numerous verify_area() calls
22 * Alan Cox : Set the ACK bit on a reset
23 * Alan Cox : Stopped it crashing if it closed while
24 * sk->inuse=1 and was trying to connect
25 * (tcp_err()).
26 * Alan Cox : All icmp error handling was broken
27 * pointers passed where wrong and the
28 * socket was looked up backwards. Nobody
29 * tested any icmp error code obviously.
30 * Alan Cox : tcp_err() now handled properly. It
31 * wakes people on errors. poll
32 * behaves and the icmp error race
33 * has gone by moving it into sock.c
34 * Alan Cox : tcp_send_reset() fixed to work for
35 * everything not just packets for
36 * unknown sockets.
37 * Alan Cox : tcp option processing.
38 * Alan Cox : Reset tweaked (still not 100%) [Had
39 * syn rule wrong]
40 * Herp Rosmanith : More reset fixes
41 * Alan Cox : No longer acks invalid rst frames.
42 * Acking any kind of RST is right out.
43 * Alan Cox : Sets an ignore me flag on an rst
44 * receive otherwise odd bits of prattle
45 * escape still
46 * Alan Cox : Fixed another acking RST frame bug.
47 * Should stop LAN workplace lockups.
48 * Alan Cox : Some tidyups using the new skb list
49 * facilities
50 * Alan Cox : sk->keepopen now seems to work
51 * Alan Cox : Pulls options out correctly on accepts
52 * Alan Cox : Fixed assorted sk->rqueue->next errors
53 * Alan Cox : PSH doesn't end a TCP read. Switched a
54 * bit to skb ops.
55 * Alan Cox : Tidied tcp_data to avoid a potential
56 * nasty.
57 * Alan Cox : Added some better commenting, as the
58 * tcp is hard to follow
59 * Alan Cox : Removed incorrect check for 20 * psh
60 * Michael O'Reilly : ack < copied bug fix.
61 * Johannes Stille : Misc tcp fixes (not all in yet).
62 * Alan Cox : FIN with no memory -> CRASH
63 * Alan Cox : Added socket option proto entries.
64 * Also added awareness of them to accept.
65 * Alan Cox : Added TCP options (SOL_TCP)
66 * Alan Cox : Switched wakeup calls to callbacks,
67 * so the kernel can layer network
68 * sockets.
69 * Alan Cox : Use ip_tos/ip_ttl settings.
70 * Alan Cox : Handle FIN (more) properly (we hope).
71 * Alan Cox : RST frames sent on unsynchronised
72 * state ack error.
73 * Alan Cox : Put in missing check for SYN bit.
74 * Alan Cox : Added tcp_select_window() aka NET2E
75 * window non shrink trick.
76 * Alan Cox : Added a couple of small NET2E timer
77 * fixes
78 * Charles Hedrick : TCP fixes
79 * Toomas Tamm : TCP window fixes
80 * Alan Cox : Small URG fix to rlogin ^C ack fight
81 * Charles Hedrick : Rewrote most of it to actually work
82 * Linus : Rewrote tcp_read() and URG handling
83 * completely
84 * Gerhard Koerting: Fixed some missing timer handling
85 * Matthew Dillon : Reworked TCP machine states as per RFC
86 * Gerhard Koerting: PC/TCP workarounds
87 * Adam Caldwell : Assorted timer/timing errors
88 * Matthew Dillon : Fixed another RST bug
89 * Alan Cox : Move to kernel side addressing changes.
90 * Alan Cox : Beginning work on TCP fastpathing
91 * (not yet usable)
92 * Arnt Gulbrandsen: Turbocharged tcp_check() routine.
93 * Alan Cox : TCP fast path debugging
94 * Alan Cox : Window clamping
95 * Michael Riepe : Bug in tcp_check()
96 * Matt Dillon : More TCP improvements and RST bug fixes
97 * Matt Dillon : Yet more small nasties remove from the
98 * TCP code (Be very nice to this man if
99 * tcp finally works 100%) 8)
100 * Alan Cox : BSD accept semantics.
101 * Alan Cox : Reset on closedown bug.
102 * Peter De Schrijver : ENOTCONN check missing in tcp_sendto().
103 * Michael Pall : Handle poll() after URG properly in
104 * all cases.
105 * Michael Pall : Undo the last fix in tcp_read_urg()
106 * (multi URG PUSH broke rlogin).
107 * Michael Pall : Fix the multi URG PUSH problem in
108 * tcp_readable(), poll() after URG
109 * works now.
110 * Michael Pall : recv(...,MSG_OOB) never blocks in the
111 * BSD api.
112 * Alan Cox : Changed the semantics of sk->socket to
113 * fix a race and a signal problem with
114 * accept() and async I/O.
115 * Alan Cox : Relaxed the rules on tcp_sendto().
116 * Yury Shevchuk : Really fixed accept() blocking problem.
117 * Craig I. Hagan : Allow for BSD compatible TIME_WAIT for
118 * clients/servers which listen in on
119 * fixed ports.
120 * Alan Cox : Cleaned the above up and shrank it to
121 * a sensible code size.
122 * Alan Cox : Self connect lockup fix.
123 * Alan Cox : No connect to multicast.
124 * Ross Biro : Close unaccepted children on master
125 * socket close.
126 * Alan Cox : Reset tracing code.
127 * Alan Cox : Spurious resets on shutdown.
128 * Alan Cox : Giant 15 minute/60 second timer error
129 * Alan Cox : Small whoops in polling before an
130 * accept.
131 * Alan Cox : Kept the state trace facility since
132 * it's handy for debugging.
133 * Alan Cox : More reset handler fixes.
134 * Alan Cox : Started rewriting the code based on
135 * the RFC's for other useful protocol
136 * references see: Comer, KA9Q NOS, and
137 * for a reference on the difference
138 * between specifications and how BSD
139 * works see the 4.4lite source.
140 * A.N.Kuznetsov : Don't time wait on completion of tidy
141 * close.
142 * Linus Torvalds : Fin/Shutdown & copied_seq changes.
143 * Linus Torvalds : Fixed BSD port reuse to work first syn
144 * Alan Cox : Reimplemented timers as per the RFC
145 * and using multiple timers for sanity.
146 * Alan Cox : Small bug fixes, and a lot of new
147 * comments.
148 * Alan Cox : Fixed dual reader crash by locking
149 * the buffers (much like datagram.c)
150 * Alan Cox : Fixed stuck sockets in probe. A probe
151 * now gets fed up of retrying without
152 * (even a no space) answer.
153 * Alan Cox : Extracted closing code better
154 * Alan Cox : Fixed the closing state machine to
155 * resemble the RFC.
156 * Alan Cox : More 'per spec' fixes.
157 * Jorge Cwik : Even faster checksumming.
158 * Alan Cox : tcp_data() doesn't ack illegal PSH
159 * only frames. At least one pc tcp stack
160 * generates them.
161 * Alan Cox : Cache last socket.
162 * Alan Cox : Per route irtt.
163 * Matt Day : poll()->select() match BSD precisely on error
164 * Alan Cox : New buffers
165 * Marc Tamsky : Various sk->prot->retransmits and
166 * sk->retransmits misupdating fixed.
167 * Fixed tcp_write_timeout: stuck close,
168 * and TCP syn retries gets used now.
169 * Mark Yarvis : In tcp_read_wakeup(), don't send an
170 * ack if state is TCP_CLOSED.
171 * Alan Cox : Look up device on a retransmit - routes may
172 * change. Doesn't yet cope with MSS shrink right
173 * but it's a start!
174 * Marc Tamsky : Closing in closing fixes.
175 * Mike Shaver : RFC1122 verifications.
176 * Alan Cox : rcv_saddr errors.
177 * Alan Cox : Block double connect().
178 * Alan Cox : Small hooks for enSKIP.
179 * Alexey Kuznetsov: Path MTU discovery.
180 * Alan Cox : Support soft errors.
181 * Alan Cox : Fix MTU discovery pathological case
182 * when the remote claims no mtu!
183 * Marc Tamsky : TCP_CLOSE fix.
184 * Colin (G3TNE) : Send a reset on syn ack replies in
185 * window but wrong (fixes NT lpd problems)
186 * Pedro Roque : Better TCP window handling, delayed ack.
187 * Joerg Reuter : No modification of locked buffers in
188 * tcp_do_retransmit()
189 * Eric Schenk : Changed receiver side silly window
190 * avoidance algorithm to BSD style
191 * algorithm. This doubles throughput
192 * against machines running Solaris,
193 * and seems to result in general
194 * improvement.
195 * Stefan Magdalinski : adjusted tcp_readable() to fix FIONREAD
196 * Willy Konynenberg : Transparent proxying support.
197 * Mike McLagan : Routing by source
198 * Keith Owens : Do proper merging with partial SKB's in
199 * tcp_do_sendmsg to avoid burstiness.
200 * Eric Schenk : Fix fast close down bug with
201 * shutdown() followed by close().
202 * Andi Kleen : Make poll agree with SIGIO
203 * Salvatore Sanfilippo : Support SO_LINGER with linger == 1 and
204 * lingertime == 0 (RFC 793 ABORT Call)
205 * Hirokazu Takahashi : Use copy_from_user() instead of
206 * csum_and_copy_from_user() if possible.
207 *
208 * This program is free software; you can redistribute it and/or
209 * modify it under the terms of the GNU General Public License
210 * as published by the Free Software Foundation; either version
211 * 2 of the License, or(at your option) any later version.
212 *
213 * Description of States:
214 *
215 * TCP_SYN_SENT sent a connection request, waiting for ack
216 *
217 * TCP_SYN_RECV received a connection request, sent ack,
218 * waiting for final ack in three-way handshake.
219 *
220 * TCP_ESTABLISHED connection established
221 *
222 * TCP_FIN_WAIT1 our side has shutdown, waiting to complete
223 * transmission of remaining buffered data
224 *
225 * TCP_FIN_WAIT2 all buffered data sent, waiting for remote
226 * to shutdown
227 *
228 * TCP_CLOSING both sides have shutdown but we still have
229 * data we have to finish sending
230 *
231 * TCP_TIME_WAIT timeout to catch resent junk before entering
232 * closed, can only be entered from FIN_WAIT2
233 * or CLOSING. Required because the other end
234 * may not have gotten our last ACK causing it
235 * to retransmit the data packet (which we ignore)
236 *
237 * TCP_CLOSE_WAIT remote side has shutdown and is waiting for
238 * us to finish writing our data and to shutdown
239 * (we have to close() to move on to LAST_ACK)
240 *
241 * TCP_LAST_ACK out side has shutdown after remote has
242 * shutdown. There may still be data in our
243 * buffer that we have to finish sending
244 *
245 * TCP_CLOSE socket is finished
246 */
247
afd46503
JP
248#define pr_fmt(fmt) "TCP: " fmt
249
172589cc 250#include <linux/kernel.h>
1da177e4
LT
251#include <linux/module.h>
252#include <linux/types.h>
253#include <linux/fcntl.h>
254#include <linux/poll.h>
255#include <linux/init.h>
1da177e4 256#include <linux/fs.h>
9c55e01c 257#include <linux/skbuff.h>
81b23b4a 258#include <linux/scatterlist.h>
9c55e01c
JA
259#include <linux/splice.h>
260#include <linux/net.h>
261#include <linux/socket.h>
1da177e4
LT
262#include <linux/random.h>
263#include <linux/bootmem.h>
57413ebc
MS
264#include <linux/highmem.h>
265#include <linux/swap.h>
b8059ead 266#include <linux/cache.h>
f4c50d99 267#include <linux/err.h>
cfb6eeb4 268#include <linux/crypto.h>
da5c78c8 269#include <linux/time.h>
5a0e3ad6 270#include <linux/slab.h>
6fa3eb70 271#include <linux/uid_stat.h>
1da177e4
LT
272
273#include <net/icmp.h>
cf60af03 274#include <net/inet_common.h>
1da177e4
LT
275#include <net/tcp.h>
276#include <net/xfrm.h>
277#include <net/ip.h>
6fa3eb70
S
278#include <net/ip6_route.h>
279#include <net/ipv6.h>
280#include <net/transp_v6.h>
1a2449a8 281#include <net/netdma.h>
9c55e01c 282#include <net/sock.h>
1da177e4
LT
283
284#include <asm/uaccess.h>
285#include <asm/ioctls.h>
286
ab32ea5d 287int sysctl_tcp_fin_timeout __read_mostly = TCP_FIN_TIMEOUT;
1da177e4 288
5e25ba50
ED
289int sysctl_tcp_min_tso_segs __read_mostly = 2;
290
dd24c001 291struct percpu_counter tcp_orphan_count;
0a5578cf
ACM
292EXPORT_SYMBOL_GPL(tcp_orphan_count);
293
b8059ead
DM
294int sysctl_tcp_wmem[3] __read_mostly;
295int sysctl_tcp_rmem[3] __read_mostly;
1da177e4 296
1da177e4
LT
297EXPORT_SYMBOL(sysctl_tcp_rmem);
298EXPORT_SYMBOL(sysctl_tcp_wmem);
299
8d987e5c 300atomic_long_t tcp_memory_allocated; /* Current allocated memory. */
1da177e4 301EXPORT_SYMBOL(tcp_memory_allocated);
1748376b
ED
302
303/*
304 * Current number of TCP sockets.
305 */
306struct percpu_counter tcp_sockets_allocated;
1da177e4
LT
307EXPORT_SYMBOL(tcp_sockets_allocated);
308
9c55e01c
JA
309/*
310 * TCP splice context
311 */
312struct tcp_splice_state {
313 struct pipe_inode_info *pipe;
314 size_t len;
315 unsigned int flags;
316};
317
1da177e4
LT
318/*
319 * Pressure flag: try to collapse.
320 * Technical note: it is used by multiple contexts non atomically.
3ab224be 321 * All the __sk_mem_schedule() is of this nature: accounting
1da177e4
LT
322 * is strict, actions are advisory and have some latency.
323 */
4103f8cd 324int tcp_memory_pressure __read_mostly;
1da177e4
LT
325EXPORT_SYMBOL(tcp_memory_pressure);
326
5c52ba17 327void tcp_enter_memory_pressure(struct sock *sk)
1da177e4
LT
328{
329 if (!tcp_memory_pressure) {
4e673444 330 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURES);
1da177e4
LT
331 tcp_memory_pressure = 1;
332 }
333}
1da177e4
LT
334EXPORT_SYMBOL(tcp_enter_memory_pressure);
335
b103cf34
JA
336/* Convert seconds to retransmits based on initial and max timeout */
337static u8 secs_to_retrans(int seconds, int timeout, int rto_max)
338{
339 u8 res = 0;
340
341 if (seconds > 0) {
342 int period = timeout;
343
344 res = 1;
345 while (seconds > period && res < 255) {
346 res++;
347 timeout <<= 1;
348 if (timeout > rto_max)
349 timeout = rto_max;
350 period += timeout;
351 }
352 }
353 return res;
354}
355
356/* Convert retransmits to seconds based on initial and max timeout */
357static int retrans_to_secs(u8 retrans, int timeout, int rto_max)
358{
359 int period = 0;
360
361 if (retrans > 0) {
362 period = timeout;
363 while (--retrans) {
364 timeout <<= 1;
365 if (timeout > rto_max)
366 timeout = rto_max;
367 period += timeout;
368 }
369 }
370 return period;
371}
372
900f65d3
NC
373/* Address-family independent initialization for a tcp_sock.
374 *
375 * NOTE: A lot of things set to zero explicitly by call to
376 * sk_alloc() so need not be done here.
377 */
378void tcp_init_sock(struct sock *sk)
379{
380 struct inet_connection_sock *icsk = inet_csk(sk);
381 struct tcp_sock *tp = tcp_sk(sk);
382
383 skb_queue_head_init(&tp->out_of_order_queue);
384 tcp_init_xmit_timers(sk);
385 tcp_prequeue_init(tp);
46d3ceab 386 INIT_LIST_HEAD(&tp->tsq_node);
900f65d3
NC
387
388 icsk->icsk_rto = TCP_TIMEOUT_INIT;
389 tp->mdev = TCP_TIMEOUT_INIT;
390
391 /* So many TCP implementations out there (incorrectly) count the
392 * initial SYN frame in their delayed-ACK and congestion control
393 * algorithms that we must have the following bandaid to talk
394 * efficiently to them. -DaveM
395 */
396 tp->snd_cwnd = TCP_INIT_CWND;
397
398 /* See draft-stevens-tcpca-spec-01 for discussion of the
399 * initialization of these values.
400 */
401 tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
402 tp->snd_cwnd_clamp = ~0;
403 tp->mss_cache = TCP_MSS_DEFAULT;
404
405 tp->reordering = sysctl_tcp_reordering;
eed530b6 406 tcp_enable_early_retrans(tp);
900f65d3
NC
407 icsk->icsk_ca_ops = &tcp_init_congestion_ops;
408
ceaa1fef
AV
409 tp->tsoffset = 0;
410
900f65d3
NC
411 sk->sk_state = TCP_CLOSE;
412
413 sk->sk_write_space = sk_stream_write_space;
414 sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
415
416 icsk->icsk_sync_mss = tcp_sync_mss;
417
900f65d3
NC
418 /* Presumed zeroed, in order of appearance:
419 * cookie_in_always, cookie_out_never,
420 * s_data_constant, s_data_in, s_data_out
421 */
422 sk->sk_sndbuf = sysctl_tcp_wmem[1];
423 sk->sk_rcvbuf = sysctl_tcp_rmem[1];
424
425 local_bh_disable();
426 sock_update_memcg(sk);
427 sk_sockets_allocated_inc(sk);
428 local_bh_enable();
429}
430EXPORT_SYMBOL(tcp_init_sock);
431
1da177e4
LT
432/*
433 * Wait for a TCP event.
434 *
435 * Note that we don't need to lock the socket, as the upper poll layers
436 * take care of normal races (between the test and the event) and we don't
437 * go look at any of the socket buffers directly.
438 */
439unsigned int tcp_poll(struct file *file, struct socket *sock, poll_table *wait)
440{
441 unsigned int mask;
442 struct sock *sk = sock->sk;
cf533ea5 443 const struct tcp_sock *tp = tcp_sk(sk);
1da177e4 444
aa395145 445 sock_poll_wait(file, sk_sleep(sk), wait);
1da177e4 446 if (sk->sk_state == TCP_LISTEN)
dc40c7bc 447 return inet_csk_listen_poll(sk);
1da177e4
LT
448
449 /* Socket is not locked. We are protected from async events
70efce27
WN
450 * by poll logic and correct handling of state changes
451 * made by other threads is impossible in any case.
1da177e4
LT
452 */
453
454 mask = 0;
1da177e4
LT
455
456 /*
457 * POLLHUP is certainly not done right. But poll() doesn't
458 * have a notion of HUP in just one direction, and for a
459 * socket the read side is more interesting.
460 *
461 * Some poll() documentation says that POLLHUP is incompatible
462 * with the POLLOUT/POLLWR flags, so somebody should check this
463 * all. But careful, it tends to be safer to return too many
464 * bits than too few, and you can easily break real applications
465 * if you don't tell them that something has hung up!
466 *
467 * Check-me.
468 *
469 * Check number 1. POLLHUP is _UNMASKABLE_ event (see UNIX98 and
470 * our fs/select.c). It means that after we received EOF,
471 * poll always returns immediately, making impossible poll() on write()
472 * in state CLOSE_WAIT. One solution is evident --- to set POLLHUP
473 * if and only if shutdown has been made in both directions.
474 * Actually, it is interesting to look how Solaris and DUX
70efce27 475 * solve this dilemma. I would prefer, if POLLHUP were maskable,
1da177e4
LT
476 * then we could set it on SND_SHUTDOWN. BTW examples given
477 * in Stevens' books assume exactly this behaviour, it explains
70efce27 478 * why POLLHUP is incompatible with POLLOUT. --ANK
1da177e4
LT
479 *
480 * NOTE. Check for TCP_CLOSE is added. The goal is to prevent
481 * blocking on fresh not-connected or disconnected socket. --ANK
482 */
483 if (sk->sk_shutdown == SHUTDOWN_MASK || sk->sk_state == TCP_CLOSE)
484 mask |= POLLHUP;
485 if (sk->sk_shutdown & RCV_SHUTDOWN)
f348d70a 486 mask |= POLLIN | POLLRDNORM | POLLRDHUP;
1da177e4 487
8336886f
JC
488 /* Connected or passive Fast Open socket? */
489 if (sk->sk_state != TCP_SYN_SENT &&
490 (sk->sk_state != TCP_SYN_RECV || tp->fastopen_rsk != NULL)) {
c7004482
DM
491 int target = sock_rcvlowat(sk, 0, INT_MAX);
492
493 if (tp->urg_seq == tp->copied_seq &&
494 !sock_flag(sk, SOCK_URGINLINE) &&
495 tp->urg_data)
b634f875 496 target++;
c7004482 497
1da177e4
LT
498 /* Potential race condition. If read of tp below will
499 * escape above sk->sk_state, we can be illegally awaken
500 * in SYN_* states. */
c7004482 501 if (tp->rcv_nxt - tp->copied_seq >= target)
1da177e4
LT
502 mask |= POLLIN | POLLRDNORM;
503
504 if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
505 if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk)) {
506 mask |= POLLOUT | POLLWRNORM;
507 } else { /* send SIGIO later */
508 set_bit(SOCK_ASYNC_NOSPACE,
509 &sk->sk_socket->flags);
510 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
511
512 /* Race breaker. If space is freed after
513 * wspace test but before the flags are set,
514 * IO signal will be lost.
515 */
516 if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk))
517 mask |= POLLOUT | POLLWRNORM;
518 }
d84ba638
KM
519 } else
520 mask |= POLLOUT | POLLWRNORM;
1da177e4
LT
521
522 if (tp->urg_data & TCP_URG_VALID)
523 mask |= POLLPRI;
524 }
a4d25803
TM
525 /* This barrier is coupled with smp_wmb() in tcp_reset() */
526 smp_rmb();
527 if (sk->sk_err)
528 mask |= POLLERR;
529
1da177e4
LT
530 return mask;
531}
4bc2f18b 532EXPORT_SYMBOL(tcp_poll);
1da177e4
LT
533
534int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg)
535{
536 struct tcp_sock *tp = tcp_sk(sk);
537 int answ;
0e71c55c 538 bool slow;
1da177e4
LT
539
540 switch (cmd) {
541 case SIOCINQ:
542 if (sk->sk_state == TCP_LISTEN)
543 return -EINVAL;
544
0e71c55c 545 slow = lock_sock_fast(sk);
1da177e4
LT
546 if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
547 answ = 0;
548 else if (sock_flag(sk, SOCK_URGINLINE) ||
549 !tp->urg_data ||
550 before(tp->urg_seq, tp->copied_seq) ||
551 !before(tp->urg_seq, tp->rcv_nxt)) {
91521944 552
1da177e4
LT
553 answ = tp->rcv_nxt - tp->copied_seq;
554
a3374c42
ED
555 /* Subtract 1, if FIN was received */
556 if (answ && sock_flag(sk, SOCK_DONE))
557 answ--;
1da177e4
LT
558 } else
559 answ = tp->urg_seq - tp->copied_seq;
0e71c55c 560 unlock_sock_fast(sk, slow);
1da177e4
LT
561 break;
562 case SIOCATMARK:
563 answ = tp->urg_data && tp->urg_seq == tp->copied_seq;
564 break;
565 case SIOCOUTQ:
566 if (sk->sk_state == TCP_LISTEN)
567 return -EINVAL;
568
569 if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
570 answ = 0;
571 else
572 answ = tp->write_seq - tp->snd_una;
573 break;
2f4e1b39
MS
574 case SIOCOUTQNSD:
575 if (sk->sk_state == TCP_LISTEN)
576 return -EINVAL;
577
578 if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
579 answ = 0;
580 else
581 answ = tp->write_seq - tp->snd_nxt;
582 break;
6fa3eb70
S
583 /* MTK_NET_CHANGES */
584 case SIOCKILLSOCK:
585 {
586 struct uid_err uid_e;
587 if (copy_from_user(&uid_e, (char __user *)arg, sizeof(uid_e)))
588 return -EFAULT;
589 printk(KERN_WARNING "SIOCKILLSOCK uid = %d , err = %d",
590 uid_e.appuid, uid_e.errNum);
591 if (uid_e.errNum == 0)
592 {
593 // handle BR release problem
594 tcp_v4_handle_retrans_time_by_uid(uid_e);
595 }
596 else
597 {
598 tcp_v4_reset_connections_by_uid(uid_e);
599 }
600
601 return 0;
602 }
1da177e4
LT
603 default:
604 return -ENOIOCTLCMD;
3ff50b79 605 }
1da177e4
LT
606
607 return put_user(answ, (int __user *)arg);
608}
4bc2f18b 609EXPORT_SYMBOL(tcp_ioctl);
1da177e4 610
1da177e4
LT
611static inline void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb)
612{
4de075e0 613 TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH;
1da177e4
LT
614 tp->pushed_seq = tp->write_seq;
615}
616
a2a385d6 617static inline bool forced_push(const struct tcp_sock *tp)
1da177e4
LT
618{
619 return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1));
620}
621
9e412ba7 622static inline void skb_entail(struct sock *sk, struct sk_buff *skb)
1da177e4 623{
9e412ba7 624 struct tcp_sock *tp = tcp_sk(sk);
352d4800
ACM
625 struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
626
627 skb->csum = 0;
628 tcb->seq = tcb->end_seq = tp->write_seq;
4de075e0 629 tcb->tcp_flags = TCPHDR_ACK;
352d4800 630 tcb->sacked = 0;
1da177e4 631 skb_header_release(skb);
fe067e8a 632 tcp_add_write_queue_tail(sk, skb);
3ab224be
HA
633 sk->sk_wmem_queued += skb->truesize;
634 sk_mem_charge(sk, skb->truesize);
89ebd197 635 if (tp->nonagle & TCP_NAGLE_PUSH)
e905a9ed 636 tp->nonagle &= ~TCP_NAGLE_PUSH;
1da177e4
LT
637}
638
afeca340 639static inline void tcp_mark_urg(struct tcp_sock *tp, int flags)
1da177e4 640{
33f5f57e 641 if (flags & MSG_OOB)
1da177e4 642 tp->snd_up = tp->write_seq;
1da177e4
LT
643}
644
9e412ba7
IJ
645static inline void tcp_push(struct sock *sk, int flags, int mss_now,
646 int nonagle)
1da177e4 647{
fe067e8a 648 if (tcp_send_head(sk)) {
afeca340
KK
649 struct tcp_sock *tp = tcp_sk(sk);
650
1da177e4 651 if (!(flags & MSG_MORE) || forced_push(tp))
afeca340
KK
652 tcp_mark_push(tp, tcp_write_queue_tail(sk));
653
654 tcp_mark_urg(tp, flags);
9e412ba7 655 __tcp_push_pending_frames(sk, mss_now,
1da177e4
LT
656 (flags & MSG_MORE) ? TCP_NAGLE_CORK : nonagle);
657 }
658}
659
6ff7751d
AB
660static int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
661 unsigned int offset, size_t len)
9c55e01c
JA
662{
663 struct tcp_splice_state *tss = rd_desc->arg.data;
33966dd0 664 int ret;
9c55e01c 665
9fa5fdf2
DM
666 ret = skb_splice_bits(skb, offset, tss->pipe, min(rd_desc->count, len),
667 tss->flags);
33966dd0
WT
668 if (ret > 0)
669 rd_desc->count -= ret;
670 return ret;
9c55e01c
JA
671}
672
673static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss)
674{
675 /* Store TCP splice context information in read_descriptor_t. */
676 read_descriptor_t rd_desc = {
677 .arg.data = tss,
33966dd0 678 .count = tss->len,
9c55e01c
JA
679 };
680
681 return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv);
682}
683
684/**
685 * tcp_splice_read - splice data from TCP socket to a pipe
686 * @sock: socket to splice from
687 * @ppos: position (not valid)
688 * @pipe: pipe to splice to
689 * @len: number of bytes to splice
690 * @flags: splice modifier flags
691 *
692 * Description:
693 * Will read pages from given socket and fill them into a pipe.
694 *
695 **/
696ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
697 struct pipe_inode_info *pipe, size_t len,
698 unsigned int flags)
699{
700 struct sock *sk = sock->sk;
701 struct tcp_splice_state tss = {
702 .pipe = pipe,
703 .len = len,
704 .flags = flags,
705 };
706 long timeo;
707 ssize_t spliced;
708 int ret;
709
3a047bf8 710 sock_rps_record_flow(sk);
9c55e01c
JA
711 /*
712 * We can't seek on a socket input
713 */
714 if (unlikely(*ppos))
715 return -ESPIPE;
716
717 ret = spliced = 0;
718
719 lock_sock(sk);
720
42324c62 721 timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK);
9c55e01c
JA
722 while (tss.len) {
723 ret = __tcp_splice_read(sk, &tss);
724 if (ret < 0)
725 break;
726 else if (!ret) {
727 if (spliced)
728 break;
9c55e01c
JA
729 if (sock_flag(sk, SOCK_DONE))
730 break;
731 if (sk->sk_err) {
732 ret = sock_error(sk);
733 break;
734 }
735 if (sk->sk_shutdown & RCV_SHUTDOWN)
736 break;
737 if (sk->sk_state == TCP_CLOSE) {
738 /*
739 * This occurs when user tries to read
740 * from never connected socket.
741 */
742 if (!sock_flag(sk, SOCK_DONE))
743 ret = -ENOTCONN;
744 break;
745 }
746 if (!timeo) {
747 ret = -EAGAIN;
748 break;
749 }
750 sk_wait_data(sk, &timeo);
751 if (signal_pending(current)) {
752 ret = sock_intr_errno(timeo);
753 break;
754 }
755 continue;
756 }
757 tss.len -= ret;
758 spliced += ret;
759
33966dd0
WT
760 if (!timeo)
761 break;
9c55e01c
JA
762 release_sock(sk);
763 lock_sock(sk);
764
765 if (sk->sk_err || sk->sk_state == TCP_CLOSE ||
33966dd0 766 (sk->sk_shutdown & RCV_SHUTDOWN) ||
9c55e01c
JA
767 signal_pending(current))
768 break;
769 }
770
771 release_sock(sk);
772
773 if (spliced)
774 return spliced;
775
776 return ret;
777}
4bc2f18b 778EXPORT_SYMBOL(tcp_splice_read);
9c55e01c 779
df97c708 780struct sk_buff *sk_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp)
f561d0f2
PE
781{
782 struct sk_buff *skb;
783
784 /* The TCP header must be at least 32-bit aligned. */
785 size = ALIGN(size, 4);
786
787 skb = alloc_skb_fclone(size + sk->sk_prot->max_header, gfp);
788 if (skb) {
3ab224be 789 if (sk_wmem_schedule(sk, skb->truesize)) {
a21d4572 790 skb_reserve(skb, sk->sk_prot->max_header);
f561d0f2
PE
791 /*
792 * Make sure that we have exactly size bytes
793 * available to the caller, no more, no less.
794 */
16fad69c 795 skb->reserved_tailroom = skb->end - skb->tail - size;
f561d0f2
PE
796 return skb;
797 }
798 __kfree_skb(skb);
799 } else {
5c52ba17 800 sk->sk_prot->enter_memory_pressure(sk);
f561d0f2
PE
801 sk_stream_moderate_sndbuf(sk);
802 }
803 return NULL;
804}
805
0c54b85f
IJ
806static unsigned int tcp_xmit_size_goal(struct sock *sk, u32 mss_now,
807 int large_allowed)
808{
809 struct tcp_sock *tp = tcp_sk(sk);
2a3a041c 810 u32 xmit_size_goal, old_size_goal;
0c54b85f
IJ
811
812 xmit_size_goal = mss_now;
813
814 if (large_allowed && sk_can_gso(sk)) {
5e25ba50
ED
815 u32 gso_size, hlen;
816
817 /* Maybe we should/could use sk->sk_prot->max_header here ? */
818 hlen = inet_csk(sk)->icsk_af_ops->net_header_len +
819 inet_csk(sk)->icsk_ext_hdr_len +
820 tp->tcp_header_len;
821
822 /* Goal is to send at least one packet per ms,
823 * not one big TSO packet every 100 ms.
824 * This preserves ACK clocking and is consistent
825 * with tcp_tso_should_defer() heuristic.
826 */
827 gso_size = sk->sk_pacing_rate / (2 * MSEC_PER_SEC);
828 gso_size = max_t(u32, gso_size,
829 sysctl_tcp_min_tso_segs * mss_now);
830
831 xmit_size_goal = min_t(u32, gso_size,
832 sk->sk_gso_max_size - 1 - hlen);
833
0c54b85f 834 xmit_size_goal = tcp_bound_to_half_wnd(tp, xmit_size_goal);
2a3a041c
IJ
835
836 /* We try hard to avoid divides here */
837 old_size_goal = tp->xmit_size_goal_segs * mss_now;
838
839 if (likely(old_size_goal <= xmit_size_goal &&
840 old_size_goal + mss_now > xmit_size_goal)) {
841 xmit_size_goal = old_size_goal;
842 } else {
1485348d
BH
843 tp->xmit_size_goal_segs =
844 min_t(u16, xmit_size_goal / mss_now,
845 sk->sk_gso_max_segs);
2a3a041c
IJ
846 xmit_size_goal = tp->xmit_size_goal_segs * mss_now;
847 }
0c54b85f
IJ
848 }
849
afece1c6 850 return max(xmit_size_goal, mss_now);
0c54b85f
IJ
851}
852
853static int tcp_send_mss(struct sock *sk, int *size_goal, int flags)
854{
855 int mss_now;
856
857 mss_now = tcp_current_mss(sk);
858 *size_goal = tcp_xmit_size_goal(sk, mss_now, !(flags & MSG_OOB));
859
860 return mss_now;
861}
862
64022d0b
ED
863static ssize_t do_tcp_sendpages(struct sock *sk, struct page *page, int offset,
864 size_t size, int flags)
1da177e4
LT
865{
866 struct tcp_sock *tp = tcp_sk(sk);
c1b4a7e6 867 int mss_now, size_goal;
1da177e4
LT
868 int err;
869 ssize_t copied;
870 long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
871
8336886f
JC
872 /* Wait for a connection to finish. One exception is TCP Fast Open
873 * (passive side) where data is allowed to be sent before a connection
874 * is fully established.
875 */
876 if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
877 !tcp_passive_fastopen(sk)) {
1da177e4
LT
878 if ((err = sk_stream_wait_connect(sk, &timeo)) != 0)
879 goto out_err;
8336886f 880 }
1da177e4
LT
881
882 clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
883
0c54b85f 884 mss_now = tcp_send_mss(sk, &size_goal, flags);
1da177e4
LT
885 copied = 0;
886
887 err = -EPIPE;
888 if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
0d6a775e 889 goto out_err;
1da177e4 890
64022d0b 891 while (size > 0) {
fe067e8a 892 struct sk_buff *skb = tcp_write_queue_tail(sk);
38ba0a65 893 int copy, i;
38ba0a65 894 bool can_coalesce;
1da177e4 895
fe067e8a 896 if (!tcp_send_head(sk) || (copy = size_goal - skb->len) <= 0) {
1da177e4
LT
897new_segment:
898 if (!sk_stream_memory_free(sk))
899 goto wait_for_sndbuf;
900
df97c708 901 skb = sk_stream_alloc_skb(sk, 0, sk->sk_allocation);
1da177e4
LT
902 if (!skb)
903 goto wait_for_memory;
904
9e412ba7 905 skb_entail(sk, skb);
c1b4a7e6 906 copy = size_goal;
1da177e4
LT
907 }
908
909 if (copy > size)
910 copy = size;
911
912 i = skb_shinfo(skb)->nr_frags;
913 can_coalesce = skb_can_coalesce(skb, i, page, offset);
914 if (!can_coalesce && i >= MAX_SKB_FRAGS) {
915 tcp_mark_push(tp, skb);
916 goto new_segment;
917 }
3ab224be 918 if (!sk_wmem_schedule(sk, copy))
1da177e4 919 goto wait_for_memory;
e905a9ed 920
1da177e4 921 if (can_coalesce) {
9e903e08 922 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
1da177e4
LT
923 } else {
924 get_page(page);
925 skb_fill_page_desc(skb, i, page, offset, copy);
926 }
c9af6db4 927 skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
cef401de 928
1da177e4
LT
929 skb->len += copy;
930 skb->data_len += copy;
931 skb->truesize += copy;
932 sk->sk_wmem_queued += copy;
3ab224be 933 sk_mem_charge(sk, copy);
84fa7933 934 skb->ip_summed = CHECKSUM_PARTIAL;
1da177e4
LT
935 tp->write_seq += copy;
936 TCP_SKB_CB(skb)->end_seq += copy;
7967168c 937 skb_shinfo(skb)->gso_segs = 0;
1da177e4
LT
938
939 if (!copied)
4de075e0 940 TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
1da177e4
LT
941
942 copied += copy;
64022d0b
ED
943 offset += copy;
944 if (!(size -= copy))
1da177e4
LT
945 goto out;
946
69d15067 947 if (skb->len < size_goal || (flags & MSG_OOB))
1da177e4
LT
948 continue;
949
950 if (forced_push(tp)) {
951 tcp_mark_push(tp, skb);
9e412ba7 952 __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
fe067e8a 953 } else if (skb == tcp_send_head(sk))
1da177e4
LT
954 tcp_push_one(sk, mss_now);
955 continue;
956
957wait_for_sndbuf:
958 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
959wait_for_memory:
bad115cf 960 tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH);
1da177e4
LT
961
962 if ((err = sk_stream_wait_memory(sk, &timeo)) != 0)
963 goto do_error;
964
0c54b85f 965 mss_now = tcp_send_mss(sk, &size_goal, flags);
1da177e4
LT
966 }
967
968out:
35f9c09f 969 if (copied && !(flags & MSG_SENDPAGE_NOTLAST))
9e412ba7 970 tcp_push(sk, flags, mss_now, tp->nonagle);
1da177e4
LT
971 return copied;
972
973do_error:
974 if (copied)
975 goto out;
976out_err:
977 return sk_stream_error(sk, flags, err);
978}
979
7ba42910
CG
980int tcp_sendpage(struct sock *sk, struct page *page, int offset,
981 size_t size, int flags)
1da177e4
LT
982{
983 ssize_t res;
1da177e4 984
1da177e4 985 if (!(sk->sk_route_caps & NETIF_F_SG) ||
8648b305 986 !(sk->sk_route_caps & NETIF_F_ALL_CSUM))
7ba42910
CG
987 return sock_no_sendpage(sk->sk_socket, page, offset, size,
988 flags);
1da177e4 989
1da177e4 990 lock_sock(sk);
64022d0b 991 res = do_tcp_sendpages(sk, page, offset, size, flags);
1da177e4
LT
992 release_sock(sk);
993 return res;
994}
4bc2f18b 995EXPORT_SYMBOL(tcp_sendpage);
1da177e4 996
690e99c4 997static inline int select_size(const struct sock *sk, bool sg)
1da177e4 998{
cf533ea5 999 const struct tcp_sock *tp = tcp_sk(sk);
c1b4a7e6 1000 int tmp = tp->mss_cache;
1da177e4 1001
def87cf4 1002 if (sg) {
f07d960d
ED
1003 if (sk_can_gso(sk)) {
1004 /* Small frames wont use a full page:
1005 * Payload will immediately follow tcp header.
1006 */
1007 tmp = SKB_WITH_OVERHEAD(2048 - MAX_TCP_HEADER);
1008 } else {
b4e26f5e
DM
1009 int pgbreak = SKB_MAX_HEAD(MAX_TCP_HEADER);
1010
1011 if (tmp >= pgbreak &&
1012 tmp <= pgbreak + (MAX_SKB_FRAGS - 1) * PAGE_SIZE)
1013 tmp = pgbreak;
1014 }
1015 }
1da177e4 1016
1da177e4
LT
1017 return tmp;
1018}
1019
cf60af03
YC
1020void tcp_free_fastopen_req(struct tcp_sock *tp)
1021{
1022 if (tp->fastopen_req != NULL) {
1023 kfree(tp->fastopen_req);
1024 tp->fastopen_req = NULL;
1025 }
1026}
1027
fe42b170
ED
1028static int tcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg,
1029 int *copied, size_t size)
cf60af03
YC
1030{
1031 struct tcp_sock *tp = tcp_sk(sk);
1032 int err, flags;
1033
1034 if (!(sysctl_tcp_fastopen & TFO_CLIENT_ENABLE))
1035 return -EOPNOTSUPP;
1036 if (tp->fastopen_req != NULL)
1037 return -EALREADY; /* Another Fast Open is in progress */
1038
1039 tp->fastopen_req = kzalloc(sizeof(struct tcp_fastopen_request),
1040 sk->sk_allocation);
1041 if (unlikely(tp->fastopen_req == NULL))
1042 return -ENOBUFS;
1043 tp->fastopen_req->data = msg;
fe42b170 1044 tp->fastopen_req->size = size;
cf60af03
YC
1045
1046 flags = (msg->msg_flags & MSG_DONTWAIT) ? O_NONBLOCK : 0;
1047 err = __inet_stream_connect(sk->sk_socket, msg->msg_name,
1048 msg->msg_namelen, flags);
fe42b170 1049 *copied = tp->fastopen_req->copied;
cf60af03
YC
1050 tcp_free_fastopen_req(tp);
1051 return err;
1052}
1053
7ba42910 1054int tcp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
1da177e4
LT
1055 size_t size)
1056{
1057 struct iovec *iov;
1058 struct tcp_sock *tp = tcp_sk(sk);
1059 struct sk_buff *skb;
cf60af03
YC
1060 int iovlen, flags, err, copied = 0;
1061 int mss_now = 0, size_goal, copied_syn = 0, offset = 0;
690e99c4 1062 bool sg;
1da177e4
LT
1063 long timeo;
1064
1065 lock_sock(sk);
1da177e4
LT
1066
1067 flags = msg->msg_flags;
cf60af03 1068 if (flags & MSG_FASTOPEN) {
fe42b170 1069 err = tcp_sendmsg_fastopen(sk, msg, &copied_syn, size);
cf60af03
YC
1070 if (err == -EINPROGRESS && copied_syn > 0)
1071 goto out;
1072 else if (err)
1073 goto out_err;
1074 offset = copied_syn;
1075 }
1076
1da177e4
LT
1077 timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
1078
8336886f
JC
1079 /* Wait for a connection to finish. One exception is TCP Fast Open
1080 * (passive side) where data is allowed to be sent before a connection
1081 * is fully established.
1082 */
1083 if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
1084 !tcp_passive_fastopen(sk)) {
1da177e4 1085 if ((err = sk_stream_wait_connect(sk, &timeo)) != 0)
cf60af03 1086 goto do_error;
8336886f 1087 }
1da177e4 1088
c0e88ff0
PE
1089 if (unlikely(tp->repair)) {
1090 if (tp->repair_queue == TCP_RECV_QUEUE) {
1091 copied = tcp_send_rcvq(sk, msg, size);
00be0011 1092 goto out_nopush;
c0e88ff0
PE
1093 }
1094
1095 err = -EINVAL;
1096 if (tp->repair_queue == TCP_NO_QUEUE)
1097 goto out_err;
1098
1099 /* 'common' sending to sendq */
1100 }
1101
1da177e4
LT
1102 /* This should be in poll */
1103 clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
1104
0c54b85f 1105 mss_now = tcp_send_mss(sk, &size_goal, flags);
1da177e4
LT
1106
1107 /* Ok commence sending. */
1108 iovlen = msg->msg_iovlen;
1109 iov = msg->msg_iov;
1110 copied = 0;
1111
1112 err = -EPIPE;
1113 if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
0d6a775e 1114 goto out_err;
1da177e4 1115
690e99c4 1116 sg = !!(sk->sk_route_caps & NETIF_F_SG);
def87cf4 1117
1da177e4 1118 while (--iovlen >= 0) {
01db403c 1119 size_t seglen = iov->iov_len;
1da177e4
LT
1120 unsigned char __user *from = iov->iov_base;
1121
1122 iov++;
cf60af03
YC
1123 if (unlikely(offset > 0)) { /* Skip bytes copied in SYN */
1124 if (offset >= seglen) {
1125 offset -= seglen;
1126 continue;
1127 }
1128 seglen -= offset;
1129 from += offset;
1130 offset = 0;
1131 }
1da177e4
LT
1132
1133 while (seglen > 0) {
6828b92b
HX
1134 int copy = 0;
1135 int max = size_goal;
1da177e4 1136
fe067e8a 1137 skb = tcp_write_queue_tail(sk);
6828b92b
HX
1138 if (tcp_send_head(sk)) {
1139 if (skb->ip_summed == CHECKSUM_NONE)
1140 max = mss_now;
1141 copy = max - skb->len;
1142 }
1da177e4 1143
6828b92b 1144 if (copy <= 0) {
1da177e4
LT
1145new_segment:
1146 /* Allocate new segment. If the interface is SG,
1147 * allocate skb fitting to single page.
1148 */
1149 if (!sk_stream_memory_free(sk))
1150 goto wait_for_sndbuf;
1151
def87cf4
KK
1152 skb = sk_stream_alloc_skb(sk,
1153 select_size(sk, sg),
1154 sk->sk_allocation);
1da177e4
LT
1155 if (!skb)
1156 goto wait_for_memory;
1157
f3f90538
AV
1158 /*
1159 * All packets are restored as if they have
1160 * already been sent.
1161 */
1162 if (tp->repair)
1163 TCP_SKB_CB(skb)->when = tcp_time_stamp;
1164
1da177e4
LT
1165 /*
1166 * Check whether we can use HW checksum.
1167 */
8648b305 1168 if (sk->sk_route_caps & NETIF_F_ALL_CSUM)
84fa7933 1169 skb->ip_summed = CHECKSUM_PARTIAL;
1da177e4 1170
9e412ba7 1171 skb_entail(sk, skb);
c1b4a7e6 1172 copy = size_goal;
6828b92b 1173 max = size_goal;
1da177e4
LT
1174 }
1175
1176 /* Try to append data to the end of skb. */
1177 if (copy > seglen)
1178 copy = seglen;
1179
1180 /* Where to copy to? */
a21d4572 1181 if (skb_availroom(skb) > 0) {
1da177e4 1182 /* We have some space in skb head. Superb! */
a21d4572 1183 copy = min_t(int, copy, skb_availroom(skb));
c6e1a0d1
TH
1184 err = skb_add_data_nocache(sk, skb, from, copy);
1185 if (err)
1da177e4
LT
1186 goto do_fault;
1187 } else {
5640f768 1188 bool merge = true;
1da177e4 1189 int i = skb_shinfo(skb)->nr_frags;
5640f768
ED
1190 struct page_frag *pfrag = sk_page_frag(sk);
1191
1192 if (!sk_page_frag_refill(sk, pfrag))
1193 goto wait_for_memory;
1194
1195 if (!skb_can_coalesce(skb, i, pfrag->page,
1196 pfrag->offset)) {
1197 if (i == MAX_SKB_FRAGS || !sg) {
1198 tcp_mark_push(tp, skb);
1199 goto new_segment;
1da177e4 1200 }
5640f768
ED
1201 merge = false;
1202 }
ef015786 1203
5640f768 1204 copy = min_t(int, copy, pfrag->size - pfrag->offset);
ef015786 1205
3ab224be 1206 if (!sk_wmem_schedule(sk, copy))
ef015786 1207 goto wait_for_memory;
1da177e4 1208
c6e1a0d1 1209 err = skb_copy_to_page_nocache(sk, from, skb,
5640f768
ED
1210 pfrag->page,
1211 pfrag->offset,
1212 copy);
1213 if (err)
1da177e4 1214 goto do_error;
1da177e4
LT
1215
1216 /* Update the skb. */
1217 if (merge) {
9e903e08 1218 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
1da177e4 1219 } else {
5640f768
ED
1220 skb_fill_page_desc(skb, i, pfrag->page,
1221 pfrag->offset, copy);
1222 get_page(pfrag->page);
1da177e4 1223 }
5640f768 1224 pfrag->offset += copy;
1da177e4
LT
1225 }
1226
1227 if (!copied)
4de075e0 1228 TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
1da177e4
LT
1229
1230 tp->write_seq += copy;
1231 TCP_SKB_CB(skb)->end_seq += copy;
7967168c 1232 skb_shinfo(skb)->gso_segs = 0;
1da177e4
LT
1233
1234 from += copy;
1235 copied += copy;
1236 if ((seglen -= copy) == 0 && iovlen == 0)
1237 goto out;
1238
c0e88ff0 1239 if (skb->len < max || (flags & MSG_OOB) || unlikely(tp->repair))
1da177e4
LT
1240 continue;
1241
1242 if (forced_push(tp)) {
1243 tcp_mark_push(tp, skb);
9e412ba7 1244 __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
fe067e8a 1245 } else if (skb == tcp_send_head(sk))
1da177e4
LT
1246 tcp_push_one(sk, mss_now);
1247 continue;
1248
1249wait_for_sndbuf:
1250 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1251wait_for_memory:
ec342325 1252 if (copied)
9e412ba7 1253 tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH);
1da177e4
LT
1254
1255 if ((err = sk_stream_wait_memory(sk, &timeo)) != 0)
1256 goto do_error;
1257
0c54b85f 1258 mss_now = tcp_send_mss(sk, &size_goal, flags);
1da177e4
LT
1259 }
1260 }
1261
1262out:
ec342325 1263 if (copied)
9e412ba7 1264 tcp_push(sk, flags, mss_now, tp->nonagle);
00be0011 1265out_nopush:
1da177e4 1266 release_sock(sk);
6fa3eb70
S
1267
1268 if (copied + copied_syn)
1269 uid_stat_tcp_snd(current_uid(), copied + copied_syn);
cf60af03 1270 return copied + copied_syn;
1da177e4
LT
1271
1272do_fault:
1273 if (!skb->len) {
fe067e8a
DM
1274 tcp_unlink_write_queue(skb, sk);
1275 /* It is the one place in all of TCP, except connection
1276 * reset, where we can be unlinking the send_head.
1277 */
1278 tcp_check_send_head(sk, skb);
3ab224be 1279 sk_wmem_free_skb(sk, skb);
1da177e4
LT
1280 }
1281
1282do_error:
cf60af03 1283 if (copied + copied_syn)
1da177e4
LT
1284 goto out;
1285out_err:
1286 err = sk_stream_error(sk, flags, err);
1da177e4
LT
1287 release_sock(sk);
1288 return err;
1289}
4bc2f18b 1290EXPORT_SYMBOL(tcp_sendmsg);
1da177e4
LT
1291
1292/*
1293 * Handle reading urgent data. BSD has very simple semantics for
1294 * this, no blocking and very strange errors 8)
1295 */
1296
377f0a08 1297static int tcp_recv_urg(struct sock *sk, struct msghdr *msg, int len, int flags)
1da177e4
LT
1298{
1299 struct tcp_sock *tp = tcp_sk(sk);
1300
1301 /* No URG data to read. */
1302 if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data ||
1303 tp->urg_data == TCP_URG_READ)
1304 return -EINVAL; /* Yes this is right ! */
1305
1306 if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE))
1307 return -ENOTCONN;
1308
1309 if (tp->urg_data & TCP_URG_VALID) {
1310 int err = 0;
1311 char c = tp->urg_data;
1312
1313 if (!(flags & MSG_PEEK))
1314 tp->urg_data = TCP_URG_READ;
1315
1316 /* Read urgent data. */
1317 msg->msg_flags |= MSG_OOB;
1318
1319 if (len > 0) {
1320 if (!(flags & MSG_TRUNC))
1321 err = memcpy_toiovec(msg->msg_iov, &c, 1);
1322 len = 1;
1323 } else
1324 msg->msg_flags |= MSG_TRUNC;
1325
1326 return err ? -EFAULT : len;
1327 }
1328
1329 if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN))
1330 return 0;
1331
1332 /* Fixed the recv(..., MSG_OOB) behaviour. BSD docs and
1333 * the available implementations agree in this case:
1334 * this call should never block, independent of the
1335 * blocking state of the socket.
1336 * Mike <pall@rz.uni-karlsruhe.de>
1337 */
1338 return -EAGAIN;
1339}
1340
c0e88ff0
PE
1341static int tcp_peek_sndq(struct sock *sk, struct msghdr *msg, int len)
1342{
1343 struct sk_buff *skb;
1344 int copied = 0, err = 0;
1345
1346 /* XXX -- need to support SO_PEEK_OFF */
1347
1348 skb_queue_walk(&sk->sk_write_queue, skb) {
1349 err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, skb->len);
1350 if (err)
1351 break;
1352
1353 copied += skb->len;
1354 }
1355
1356 return err ?: copied;
1357}
1358
1da177e4
LT
1359/* Clean up the receive buffer for full frames taken by the user,
1360 * then send an ACK if necessary. COPIED is the number of bytes
1361 * tcp_recvmsg has given to the user so far, it speeds up the
1362 * calculation of whether or not we must ACK for the sake of
1363 * a window update.
1364 */
0e4b4992 1365void tcp_cleanup_rbuf(struct sock *sk, int copied)
1da177e4
LT
1366{
1367 struct tcp_sock *tp = tcp_sk(sk);
a2a385d6 1368 bool time_to_ack = false;
1da177e4 1369
1da177e4
LT
1370 struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
1371
d792c100 1372 WARN(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq),
2af6fd8b 1373 "cleanup rbuf bug: copied %X seq %X rcvnxt %X\n",
d792c100 1374 tp->copied_seq, TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt);
1da177e4 1375
463c84b9
ACM
1376 if (inet_csk_ack_scheduled(sk)) {
1377 const struct inet_connection_sock *icsk = inet_csk(sk);
1da177e4
LT
1378 /* Delayed ACKs frequently hit locked sockets during bulk
1379 * receive. */
463c84b9 1380 if (icsk->icsk_ack.blocked ||
1da177e4 1381 /* Once-per-two-segments ACK was not sent by tcp_input.c */
463c84b9 1382 tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss ||
1da177e4
LT
1383 /*
1384 * If this read emptied read buffer, we send ACK, if
1385 * connection is not bidirectional, user drained
1386 * receive buffer and there was a small segment
1387 * in queue.
1388 */
1ef9696c
AK
1389 (copied > 0 &&
1390 ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) ||
1391 ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) &&
1392 !icsk->icsk_ack.pingpong)) &&
1393 !atomic_read(&sk->sk_rmem_alloc)))
a2a385d6 1394 time_to_ack = true;
1da177e4
LT
1395 }
1396
1397 /* We send an ACK if we can now advertise a non-zero window
1398 * which has been raised "significantly".
1399 *
1400 * Even if window raised up to infinity, do not send window open ACK
1401 * in states, where we will not receive more. It is useless.
1402 */
1403 if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
1404 __u32 rcv_window_now = tcp_receive_window(tp);
1405
1406 /* Optimize, __tcp_select_window() is not cheap. */
1407 if (2*rcv_window_now <= tp->window_clamp) {
1408 __u32 new_window = __tcp_select_window(sk);
1409
1410 /* Send ACK now, if this read freed lots of space
1411 * in our buffer. Certainly, new_window is new window.
1412 * We can advertise it now, if it is not less than current one.
1413 * "Lots" means "at least twice" here.
1414 */
1415 if (new_window && new_window >= 2 * rcv_window_now)
a2a385d6 1416 time_to_ack = true;
1da177e4
LT
1417 }
1418 }
1419 if (time_to_ack)
1420 tcp_send_ack(sk);
1421}
1422
1423static void tcp_prequeue_process(struct sock *sk)
1424{
1425 struct sk_buff *skb;
1426 struct tcp_sock *tp = tcp_sk(sk);
1427
6f67c817 1428 NET_INC_STATS_USER(sock_net(sk), LINUX_MIB_TCPPREQUEUED);
1da177e4
LT
1429
1430 /* RX process wants to run with disabled BHs, though it is not
1431 * necessary */
1432 local_bh_disable();
1433 while ((skb = __skb_dequeue(&tp->ucopy.prequeue)) != NULL)
c57943a1 1434 sk_backlog_rcv(sk, skb);
1da177e4
LT
1435 local_bh_enable();
1436
1437 /* Clear memory counter. */
1438 tp->ucopy.memory = 0;
1439}
1440
73852e81
SM
1441#ifdef CONFIG_NET_DMA
1442static void tcp_service_net_dma(struct sock *sk, bool wait)
1443{
1444 dma_cookie_t done, used;
1445 dma_cookie_t last_issued;
1446 struct tcp_sock *tp = tcp_sk(sk);
1447
1448 if (!tp->ucopy.dma_chan)
1449 return;
1450
1451 last_issued = tp->ucopy.dma_cookie;
b9ee8683 1452 dma_async_issue_pending(tp->ucopy.dma_chan);
73852e81
SM
1453
1454 do {
e239345f 1455 if (dma_async_is_tx_complete(tp->ucopy.dma_chan,
73852e81
SM
1456 last_issued, &done,
1457 &used) == DMA_SUCCESS) {
1458 /* Safe to free early-copied skbs now */
1459 __skb_queue_purge(&sk->sk_async_wait_queue);
1460 break;
1461 } else {
1462 struct sk_buff *skb;
1463 while ((skb = skb_peek(&sk->sk_async_wait_queue)) &&
1464 (dma_async_is_complete(skb->dma_cookie, done,
1465 used) == DMA_SUCCESS)) {
1466 __skb_dequeue(&sk->sk_async_wait_queue);
1467 kfree_skb(skb);
1468 }
1469 }
1470 } while (wait);
1471}
1472#endif
1473
f26845b4 1474static struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off)
1da177e4
LT
1475{
1476 struct sk_buff *skb;
1477 u32 offset;
1478
f26845b4 1479 while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) {
1da177e4 1480 offset = seq - TCP_SKB_CB(skb)->seq;
aa8223c7 1481 if (tcp_hdr(skb)->syn)
1da177e4 1482 offset--;
aa8223c7 1483 if (offset < skb->len || tcp_hdr(skb)->fin) {
1da177e4
LT
1484 *off = offset;
1485 return skb;
1486 }
f26845b4
ED
1487 /* This looks weird, but this can happen if TCP collapsing
1488 * splitted a fat GRO packet, while we released socket lock
1489 * in skb_splice_bits()
1490 */
1491 sk_eat_skb(sk, skb, false);
1da177e4
LT
1492 }
1493 return NULL;
1494}
1495
1496/*
1497 * This routine provides an alternative to tcp_recvmsg() for routines
1498 * that would like to handle copying from skbuffs directly in 'sendfile'
1499 * fashion.
1500 * Note:
1501 * - It is assumed that the socket was locked by the caller.
1502 * - The routine does not block.
1503 * - At present, there is no support for reading OOB data
1504 * or for 'peeking' the socket using this routine
1505 * (although both would be easy to implement).
1506 */
1507int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
1508 sk_read_actor_t recv_actor)
1509{
1510 struct sk_buff *skb;
1511 struct tcp_sock *tp = tcp_sk(sk);
1512 u32 seq = tp->copied_seq;
1513 u32 offset;
1514 int copied = 0;
1515
1516 if (sk->sk_state == TCP_LISTEN)
1517 return -ENOTCONN;
1518 while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
1519 if (offset < skb->len) {
374e7b59
OP
1520 int used;
1521 size_t len;
1da177e4
LT
1522
1523 len = skb->len - offset;
1524 /* Stop reading if we hit a patch of urgent data */
1525 if (tp->urg_data) {
1526 u32 urg_offset = tp->urg_seq - seq;
1527 if (urg_offset < len)
1528 len = urg_offset;
1529 if (!len)
1530 break;
1531 }
1532 used = recv_actor(desc, skb, offset, len);
ff905b1e 1533 if (used <= 0) {
ddb61a57
JA
1534 if (!copied)
1535 copied = used;
1536 break;
1537 } else if (used <= len) {
1da177e4
LT
1538 seq += used;
1539 copied += used;
1540 offset += used;
1541 }
02275a2e 1542 /* If recv_actor drops the lock (e.g. TCP splice
293ad604
OP
1543 * receive) the skb pointer might be invalid when
1544 * getting here: tcp_collapse might have deleted it
1545 * while aggregating skbs from the socket queue.
1546 */
02275a2e
WT
1547 skb = tcp_recv_skb(sk, seq - 1, &offset);
1548 if (!skb)
1da177e4 1549 break;
02275a2e
WT
1550 /* TCP coalescing might have appended data to the skb.
1551 * Try to splice more frags
1552 */
1553 if (offset + 1 != skb->len)
1554 continue;
1da177e4 1555 }
aa8223c7 1556 if (tcp_hdr(skb)->fin) {
dc6b9b78 1557 sk_eat_skb(sk, skb, false);
1da177e4
LT
1558 ++seq;
1559 break;
1560 }
dc6b9b78 1561 sk_eat_skb(sk, skb, false);
1da177e4
LT
1562 if (!desc->count)
1563 break;
baff42ab 1564 tp->copied_seq = seq;
1da177e4
LT
1565 }
1566 tp->copied_seq = seq;
1567
1568 tcp_rcv_space_adjust(sk);
1569
1570 /* Clean up data we have read: This will do ACK frames. */
f26845b4
ED
1571 if (copied > 0) {
1572 tcp_recv_skb(sk, seq, &offset);
0e4b4992 1573 tcp_cleanup_rbuf(sk, copied);
6fa3eb70 1574 uid_stat_tcp_rcv(current_uid(), copied);
f26845b4 1575 }
1da177e4
LT
1576 return copied;
1577}
4bc2f18b 1578EXPORT_SYMBOL(tcp_read_sock);
1da177e4
LT
1579
1580/*
1581 * This routine copies from a sock struct into the user buffer.
1582 *
1583 * Technical note: in 2.3 we work on _locked_ socket, so that
1584 * tricks with *seq access order and skb->users are not required.
1585 * Probably, code can be easily improved even more.
1586 */
1587
1588int tcp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
1589 size_t len, int nonblock, int flags, int *addr_len)
1590{
1591 struct tcp_sock *tp = tcp_sk(sk);
1592 int copied = 0;
1593 u32 peek_seq;
1594 u32 *seq;
1595 unsigned long used;
1596 int err;
1597 int target; /* Read at least this many bytes */
1598 long timeo;
1599 struct task_struct *user_recv = NULL;
dc6b9b78 1600 bool copied_early = false;
2b1244a4 1601 struct sk_buff *skb;
77527313 1602 u32 urg_hole = 0;
1da177e4
LT
1603
1604 lock_sock(sk);
1605
1da177e4
LT
1606 err = -ENOTCONN;
1607 if (sk->sk_state == TCP_LISTEN)
1608 goto out;
1609
1610 timeo = sock_rcvtimeo(sk, nonblock);
1611
1612 /* Urgent data needs to be handled specially. */
1613 if (flags & MSG_OOB)
1614 goto recv_urg;
1615
c0e88ff0
PE
1616 if (unlikely(tp->repair)) {
1617 err = -EPERM;
1618 if (!(flags & MSG_PEEK))
1619 goto out;
1620
1621 if (tp->repair_queue == TCP_SEND_QUEUE)
1622 goto recv_sndq;
1623
1624 err = -EINVAL;
1625 if (tp->repair_queue == TCP_NO_QUEUE)
1626 goto out;
1627
1628 /* 'common' recv queue MSG_PEEK-ing */
1629 }
1630
1da177e4
LT
1631 seq = &tp->copied_seq;
1632 if (flags & MSG_PEEK) {
1633 peek_seq = tp->copied_seq;
1634 seq = &peek_seq;
1635 }
1636
1637 target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
1638
1a2449a8
CL
1639#ifdef CONFIG_NET_DMA
1640 tp->ucopy.dma_chan = NULL;
1641 preempt_disable();
2b1244a4 1642 skb = skb_peek_tail(&sk->sk_receive_queue);
e00c5d8b
AM
1643 {
1644 int available = 0;
1645
1646 if (skb)
1647 available = TCP_SKB_CB(skb)->seq + skb->len - (*seq);
1648 if ((available < target) &&
1649 (len > sysctl_tcp_dma_copybreak) && !(flags & MSG_PEEK) &&
1650 !sysctl_tcp_low_latency &&
a2bd1140 1651 net_dma_find_channel()) {
e00c5d8b
AM
1652 preempt_enable_no_resched();
1653 tp->ucopy.pinned_list =
1654 dma_pin_iovec_pages(msg->msg_iov, len);
1655 } else {
1656 preempt_enable_no_resched();
1657 }
1658 }
1a2449a8
CL
1659#endif
1660
1da177e4 1661 do {
1da177e4
LT
1662 u32 offset;
1663
1664 /* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */
1665 if (tp->urg_data && tp->urg_seq == *seq) {
1666 if (copied)
1667 break;
1668 if (signal_pending(current)) {
1669 copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
1670 break;
1671 }
1672 }
1673
1674 /* Next get a buffer. */
1675
91521944 1676 skb_queue_walk(&sk->sk_receive_queue, skb) {
1da177e4
LT
1677 /* Now that we have two receive queues this
1678 * shouldn't happen.
1679 */
d792c100 1680 if (WARN(before(*seq, TCP_SKB_CB(skb)->seq),
2af6fd8b
JP
1681 "recvmsg bug: copied %X seq %X rcvnxt %X fl %X\n",
1682 *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt,
1683 flags))
1da177e4 1684 break;
d792c100 1685
1da177e4 1686 offset = *seq - TCP_SKB_CB(skb)->seq;
aa8223c7 1687 if (tcp_hdr(skb)->syn)
1da177e4
LT
1688 offset--;
1689 if (offset < skb->len)
1690 goto found_ok_skb;
aa8223c7 1691 if (tcp_hdr(skb)->fin)
1da177e4 1692 goto found_fin_ok;
2af6fd8b
JP
1693 WARN(!(flags & MSG_PEEK),
1694 "recvmsg bug 2: copied %X seq %X rcvnxt %X fl %X\n",
1695 *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags);
91521944 1696 }
1da177e4
LT
1697
1698 /* Well, if we have backlog, try to process it now yet. */
1699
1700 if (copied >= target && !sk->sk_backlog.tail)
1701 break;
1702
1703 if (copied) {
1704 if (sk->sk_err ||
1705 sk->sk_state == TCP_CLOSE ||
1706 (sk->sk_shutdown & RCV_SHUTDOWN) ||
1707 !timeo ||
518a09ef 1708 signal_pending(current))
1da177e4
LT
1709 break;
1710 } else {
1711 if (sock_flag(sk, SOCK_DONE))
1712 break;
1713
1714 if (sk->sk_err) {
1715 copied = sock_error(sk);
1716 break;
1717 }
1718
1719 if (sk->sk_shutdown & RCV_SHUTDOWN)
1720 break;
1721
1722 if (sk->sk_state == TCP_CLOSE) {
1723 if (!sock_flag(sk, SOCK_DONE)) {
1724 /* This occurs when user tries to read
1725 * from never connected socket.
1726 */
1727 copied = -ENOTCONN;
1728 break;
1729 }
1730 break;
1731 }
1732
1733 if (!timeo) {
1734 copied = -EAGAIN;
1735 break;
1736 }
1737
1738 if (signal_pending(current)) {
1739 copied = sock_intr_errno(timeo);
1740 break;
1741 }
1742 }
1743
0e4b4992 1744 tcp_cleanup_rbuf(sk, copied);
1da177e4 1745
7df55125 1746 if (!sysctl_tcp_low_latency && tp->ucopy.task == user_recv) {
1da177e4
LT
1747 /* Install new reader */
1748 if (!user_recv && !(flags & (MSG_TRUNC | MSG_PEEK))) {
1749 user_recv = current;
1750 tp->ucopy.task = user_recv;
1751 tp->ucopy.iov = msg->msg_iov;
1752 }
1753
1754 tp->ucopy.len = len;
1755
547b792c
IJ
1756 WARN_ON(tp->copied_seq != tp->rcv_nxt &&
1757 !(flags & (MSG_PEEK | MSG_TRUNC)));
1da177e4
LT
1758
1759 /* Ugly... If prequeue is not empty, we have to
1760 * process it before releasing socket, otherwise
1761 * order will be broken at second iteration.
1762 * More elegant solution is required!!!
1763 *
1764 * Look: we have the following (pseudo)queues:
1765 *
1766 * 1. packets in flight
1767 * 2. backlog
1768 * 3. prequeue
1769 * 4. receive_queue
1770 *
1771 * Each queue can be processed only if the next ones
1772 * are empty. At this point we have empty receive_queue.
1773 * But prequeue _can_ be not empty after 2nd iteration,
1774 * when we jumped to start of loop because backlog
1775 * processing added something to receive_queue.
1776 * We cannot release_sock(), because backlog contains
1777 * packets arrived _after_ prequeued ones.
1778 *
1779 * Shortly, algorithm is clear --- to process all
1780 * the queues in order. We could make it more directly,
1781 * requeueing packets from backlog to prequeue, if
1782 * is not empty. It is more elegant, but eats cycles,
1783 * unfortunately.
1784 */
b03efcfb 1785 if (!skb_queue_empty(&tp->ucopy.prequeue))
1da177e4
LT
1786 goto do_prequeue;
1787
1788 /* __ Set realtime policy in scheduler __ */
1789 }
1790
73852e81 1791#ifdef CONFIG_NET_DMA
15c04175
MK
1792 if (tp->ucopy.dma_chan) {
1793 if (tp->rcv_wnd == 0 &&
1794 !skb_queue_empty(&sk->sk_async_wait_queue)) {
1795 tcp_service_net_dma(sk, true);
1796 tcp_cleanup_rbuf(sk, copied);
1797 } else
b9ee8683 1798 dma_async_issue_pending(tp->ucopy.dma_chan);
15c04175 1799 }
73852e81 1800#endif
1da177e4
LT
1801 if (copied >= target) {
1802 /* Do not sleep, just process backlog. */
1803 release_sock(sk);
1804 lock_sock(sk);
1805 } else
1806 sk_wait_data(sk, &timeo);
1807
1a2449a8 1808#ifdef CONFIG_NET_DMA
73852e81 1809 tcp_service_net_dma(sk, false); /* Don't block */
1a2449a8
CL
1810 tp->ucopy.wakeup = 0;
1811#endif
1812
1da177e4
LT
1813 if (user_recv) {
1814 int chunk;
1815
1816 /* __ Restore normal policy in scheduler __ */
1817
1818 if ((chunk = len - tp->ucopy.len) != 0) {
ed88098e 1819 NET_ADD_STATS_USER(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMBACKLOG, chunk);
1da177e4
LT
1820 len -= chunk;
1821 copied += chunk;
1822 }
1823
1824 if (tp->rcv_nxt == tp->copied_seq &&
b03efcfb 1825 !skb_queue_empty(&tp->ucopy.prequeue)) {
1da177e4
LT
1826do_prequeue:
1827 tcp_prequeue_process(sk);
1828
1829 if ((chunk = len - tp->ucopy.len) != 0) {
ed88098e 1830 NET_ADD_STATS_USER(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
1da177e4
LT
1831 len -= chunk;
1832 copied += chunk;
1833 }
1834 }
1835 }
77527313
IJ
1836 if ((flags & MSG_PEEK) &&
1837 (peek_seq - copied - urg_hole != tp->copied_seq)) {
e87cc472
JP
1838 net_dbg_ratelimited("TCP(%s:%d): Application bug, race in MSG_PEEK\n",
1839 current->comm,
1840 task_pid_nr(current));
1da177e4
LT
1841 peek_seq = tp->copied_seq;
1842 }
1843 continue;
1844
1845 found_ok_skb:
1846 /* Ok so how much can we use? */
1847 used = skb->len - offset;
1848 if (len < used)
1849 used = len;
1850
1851 /* Do we have urgent data here? */
1852 if (tp->urg_data) {
1853 u32 urg_offset = tp->urg_seq - *seq;
1854 if (urg_offset < used) {
1855 if (!urg_offset) {
1856 if (!sock_flag(sk, SOCK_URGINLINE)) {
1857 ++*seq;
77527313 1858 urg_hole++;
1da177e4
LT
1859 offset++;
1860 used--;
1861 if (!used)
1862 goto skip_copy;
1863 }
1864 } else
1865 used = urg_offset;
1866 }
1867 }
1868
1869 if (!(flags & MSG_TRUNC)) {
1a2449a8
CL
1870#ifdef CONFIG_NET_DMA
1871 if (!tp->ucopy.dma_chan && tp->ucopy.pinned_list)
a2bd1140 1872 tp->ucopy.dma_chan = net_dma_find_channel();
1a2449a8
CL
1873
1874 if (tp->ucopy.dma_chan) {
1875 tp->ucopy.dma_cookie = dma_skb_copy_datagram_iovec(
1876 tp->ucopy.dma_chan, skb, offset,
1877 msg->msg_iov, used,
1878 tp->ucopy.pinned_list);
1879
1880 if (tp->ucopy.dma_cookie < 0) {
1881
afd46503
JP
1882 pr_alert("%s: dma_cookie < 0\n",
1883 __func__);
1a2449a8
CL
1884
1885 /* Exception. Bailout! */
1886 if (!copied)
1887 copied = -EFAULT;
1888 break;
1889 }
73852e81 1890
b9ee8683 1891 dma_async_issue_pending(tp->ucopy.dma_chan);
73852e81 1892
1a2449a8 1893 if ((offset + used) == skb->len)
dc6b9b78 1894 copied_early = true;
1a2449a8
CL
1895
1896 } else
1897#endif
1898 {
1899 err = skb_copy_datagram_iovec(skb, offset,
1900 msg->msg_iov, used);
1901 if (err) {
1902 /* Exception. Bailout! */
1903 if (!copied)
1904 copied = -EFAULT;
1905 break;
1906 }
1da177e4
LT
1907 }
1908 }
1909
1910 *seq += used;
1911 copied += used;
1912 len -= used;
1913
1914 tcp_rcv_space_adjust(sk);
1915
1916skip_copy:
1917 if (tp->urg_data && after(tp->copied_seq, tp->urg_seq)) {
1918 tp->urg_data = 0;
9e412ba7 1919 tcp_fast_path_check(sk);
1da177e4
LT
1920 }
1921 if (used + offset < skb->len)
1922 continue;
1923
aa8223c7 1924 if (tcp_hdr(skb)->fin)
1da177e4 1925 goto found_fin_ok;
1a2449a8
CL
1926 if (!(flags & MSG_PEEK)) {
1927 sk_eat_skb(sk, skb, copied_early);
dc6b9b78 1928 copied_early = false;
1a2449a8 1929 }
1da177e4
LT
1930 continue;
1931
1932 found_fin_ok:
1933 /* Process the FIN. */
1934 ++*seq;
1a2449a8
CL
1935 if (!(flags & MSG_PEEK)) {
1936 sk_eat_skb(sk, skb, copied_early);
dc6b9b78 1937 copied_early = false;
1a2449a8 1938 }
1da177e4
LT
1939 break;
1940 } while (len > 0);
1941
1942 if (user_recv) {
b03efcfb 1943 if (!skb_queue_empty(&tp->ucopy.prequeue)) {
1da177e4
LT
1944 int chunk;
1945
1946 tp->ucopy.len = copied > 0 ? len : 0;
1947
1948 tcp_prequeue_process(sk);
1949
1950 if (copied > 0 && (chunk = len - tp->ucopy.len) != 0) {
ed88098e 1951 NET_ADD_STATS_USER(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
1da177e4
LT
1952 len -= chunk;
1953 copied += chunk;
1954 }
1955 }
1956
1957 tp->ucopy.task = NULL;
1958 tp->ucopy.len = 0;
1959 }
1960
1a2449a8 1961#ifdef CONFIG_NET_DMA
73852e81
SM
1962 tcp_service_net_dma(sk, true); /* Wait for queue to drain */
1963 tp->ucopy.dma_chan = NULL;
1a2449a8 1964
1a2449a8
CL
1965 if (tp->ucopy.pinned_list) {
1966 dma_unpin_iovec_pages(tp->ucopy.pinned_list);
1967 tp->ucopy.pinned_list = NULL;
1968 }
1969#endif
1970
1da177e4
LT
1971 /* According to UNIX98, msg_name/msg_namelen are ignored
1972 * on connected socket. I was just happy when found this 8) --ANK
1973 */
1974
1975 /* Clean up data we have read: This will do ACK frames. */
0e4b4992 1976 tcp_cleanup_rbuf(sk, copied);
1da177e4 1977
1da177e4 1978 release_sock(sk);
6fa3eb70
S
1979
1980 if (copied > 0)
1981 uid_stat_tcp_rcv(current_uid(), copied);
1da177e4
LT
1982 return copied;
1983
1984out:
1da177e4
LT
1985 release_sock(sk);
1986 return err;
1987
1988recv_urg:
377f0a08 1989 err = tcp_recv_urg(sk, msg, len, flags);
6fa3eb70
S
1990 if (err > 0)
1991 uid_stat_tcp_rcv(current_uid(), err);
1da177e4 1992 goto out;
c0e88ff0
PE
1993
1994recv_sndq:
1995 err = tcp_peek_sndq(sk, msg, len);
1996 goto out;
1da177e4 1997}
4bc2f18b 1998EXPORT_SYMBOL(tcp_recvmsg);
1da177e4 1999
490d5046
IJ
2000void tcp_set_state(struct sock *sk, int state)
2001{
2002 int oldstate = sk->sk_state;
2003
2004 switch (state) {
2005 case TCP_ESTABLISHED:
2006 if (oldstate != TCP_ESTABLISHED)
81cc8a75 2007 TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
490d5046
IJ
2008 break;
2009
2010 case TCP_CLOSE:
2011 if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED)
81cc8a75 2012 TCP_INC_STATS(sock_net(sk), TCP_MIB_ESTABRESETS);
490d5046
IJ
2013
2014 sk->sk_prot->unhash(sk);
2015 if (inet_csk(sk)->icsk_bind_hash &&
2016 !(sk->sk_userlocks & SOCK_BINDPORT_LOCK))
ab1e0a13 2017 inet_put_port(sk);
490d5046
IJ
2018 /* fall through */
2019 default:
5a5f3a8d 2020 if (oldstate == TCP_ESTABLISHED)
74688e48 2021 TCP_DEC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
490d5046
IJ
2022 }
2023
2024 /* Change state AFTER socket is unhashed to avoid closed
2025 * socket sitting in hash tables.
2026 */
2027 sk->sk_state = state;
2028
2029#ifdef STATE_TRACE
5a5f3a8d 2030 SOCK_DEBUG(sk, "TCP sk=%p, State %s -> %s\n", sk, statename[oldstate], statename[state]);
490d5046
IJ
2031#endif
2032}
2033EXPORT_SYMBOL_GPL(tcp_set_state);
2034
1da177e4
LT
2035/*
2036 * State processing on a close. This implements the state shift for
2037 * sending our FIN frame. Note that we only send a FIN for some
2038 * states. A shutdown() may have already sent the FIN, or we may be
2039 * closed.
2040 */
2041
9b5b5cff 2042static const unsigned char new_state[16] = {
1da177e4
LT
2043 /* current state: new state: action: */
2044 /* (Invalid) */ TCP_CLOSE,
2045 /* TCP_ESTABLISHED */ TCP_FIN_WAIT1 | TCP_ACTION_FIN,
2046 /* TCP_SYN_SENT */ TCP_CLOSE,
2047 /* TCP_SYN_RECV */ TCP_FIN_WAIT1 | TCP_ACTION_FIN,
2048 /* TCP_FIN_WAIT1 */ TCP_FIN_WAIT1,
2049 /* TCP_FIN_WAIT2 */ TCP_FIN_WAIT2,
2050 /* TCP_TIME_WAIT */ TCP_CLOSE,
2051 /* TCP_CLOSE */ TCP_CLOSE,
2052 /* TCP_CLOSE_WAIT */ TCP_LAST_ACK | TCP_ACTION_FIN,
2053 /* TCP_LAST_ACK */ TCP_LAST_ACK,
2054 /* TCP_LISTEN */ TCP_CLOSE,
2055 /* TCP_CLOSING */ TCP_CLOSING,
2056};
2057
2058static int tcp_close_state(struct sock *sk)
2059{
2060 int next = (int)new_state[sk->sk_state];
2061 int ns = next & TCP_STATE_MASK;
2062
2063 tcp_set_state(sk, ns);
2064
2065 return next & TCP_ACTION_FIN;
2066}
2067
2068/*
2069 * Shutdown the sending side of a connection. Much like close except
1f29b058 2070 * that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD).
1da177e4
LT
2071 */
2072
2073void tcp_shutdown(struct sock *sk, int how)
2074{
2075 /* We need to grab some memory, and put together a FIN,
2076 * and then put it into the queue to be sent.
2077 * Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92.
2078 */
2079 if (!(how & SEND_SHUTDOWN))
2080 return;
2081
2082 /* If we've already sent a FIN, or it's a closed state, skip this. */
2083 if ((1 << sk->sk_state) &
2084 (TCPF_ESTABLISHED | TCPF_SYN_SENT |
2085 TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) {
2086 /* Clear out any half completed packets. FIN if needed. */
2087 if (tcp_close_state(sk))
2088 tcp_send_fin(sk);
2089 }
2090}
4bc2f18b 2091EXPORT_SYMBOL(tcp_shutdown);
1da177e4 2092
efcdbf24
AS
2093bool tcp_check_oom(struct sock *sk, int shift)
2094{
2095 bool too_many_orphans, out_of_socket_memory;
2096
2097 too_many_orphans = tcp_too_many_orphans(sk, shift);
2098 out_of_socket_memory = tcp_out_of_memory(sk);
2099
e87cc472
JP
2100 if (too_many_orphans)
2101 net_info_ratelimited("too many orphaned sockets\n");
2102 if (out_of_socket_memory)
2103 net_info_ratelimited("out of memory -- consider tuning tcp_mem\n");
efcdbf24
AS
2104 return too_many_orphans || out_of_socket_memory;
2105}
2106
1da177e4
LT
2107void tcp_close(struct sock *sk, long timeout)
2108{
2109 struct sk_buff *skb;
2110 int data_was_unread = 0;
75c2d907 2111 int state;
1da177e4
LT
2112
2113 lock_sock(sk);
2114 sk->sk_shutdown = SHUTDOWN_MASK;
2115
2116 if (sk->sk_state == TCP_LISTEN) {
2117 tcp_set_state(sk, TCP_CLOSE);
2118
2119 /* Special case. */
0a5578cf 2120 inet_csk_listen_stop(sk);
1da177e4
LT
2121
2122 goto adjudge_to_death;
2123 }
2124
2125 /* We need to flush the recv. buffs. We do this only on the
2126 * descriptor close, not protocol-sourced closes, because the
2127 * reader process may not have drained the data yet!
2128 */
2129 while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
2130 u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq -
aa8223c7 2131 tcp_hdr(skb)->fin;
1da177e4
LT
2132 data_was_unread += len;
2133 __kfree_skb(skb);
2134 }
2135
3ab224be 2136 sk_mem_reclaim(sk);
1da177e4 2137
565b7b2d
KK
2138 /* If socket has been already reset (e.g. in tcp_reset()) - kill it. */
2139 if (sk->sk_state == TCP_CLOSE)
2140 goto adjudge_to_death;
2141
65bb723c
GR
2142 /* As outlined in RFC 2525, section 2.17, we send a RST here because
2143 * data was lost. To witness the awful effects of the old behavior of
2144 * always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk
2145 * GET in an FTP client, suspend the process, wait for the client to
2146 * advertise a zero window, then kill -9 the FTP client, wheee...
2147 * Note: timeout is always zero in such a case.
1da177e4 2148 */
ee995283
PE
2149 if (unlikely(tcp_sk(sk)->repair)) {
2150 sk->sk_prot->disconnect(sk, 0);
2151 } else if (data_was_unread) {
1da177e4 2152 /* Unread data was tossed, zap the connection. */
6f67c817 2153 NET_INC_STATS_USER(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE);
1da177e4 2154 tcp_set_state(sk, TCP_CLOSE);
aa133076 2155 tcp_send_active_reset(sk, sk->sk_allocation);
1da177e4
LT
2156 } else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
2157 /* Check zero linger _after_ checking for unread data. */
2158 sk->sk_prot->disconnect(sk, 0);
6f67c817 2159 NET_INC_STATS_USER(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
1da177e4
LT
2160 } else if (tcp_close_state(sk)) {
2161 /* We FIN if the application ate all the data before
2162 * zapping the connection.
2163 */
2164
2165 /* RED-PEN. Formally speaking, we have broken TCP state
2166 * machine. State transitions:
2167 *
2168 * TCP_ESTABLISHED -> TCP_FIN_WAIT1
2169 * TCP_SYN_RECV -> TCP_FIN_WAIT1 (forget it, it's impossible)
2170 * TCP_CLOSE_WAIT -> TCP_LAST_ACK
2171 *
2172 * are legal only when FIN has been sent (i.e. in window),
2173 * rather than queued out of window. Purists blame.
2174 *
2175 * F.e. "RFC state" is ESTABLISHED,
2176 * if Linux state is FIN-WAIT-1, but FIN is still not sent.
2177 *
2178 * The visible declinations are that sometimes
2179 * we enter time-wait state, when it is not required really
2180 * (harmless), do not send active resets, when they are
2181 * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when
2182 * they look as CLOSING or LAST_ACK for Linux)
2183 * Probably, I missed some more holelets.
2184 * --ANK
8336886f
JC
2185 * XXX (TFO) - To start off we don't support SYN+ACK+FIN
2186 * in a single packet! (May consider it later but will
2187 * probably need API support or TCP_CORK SYN-ACK until
2188 * data is written and socket is closed.)
1da177e4
LT
2189 */
2190 tcp_send_fin(sk);
2191 }
2192
2193 sk_stream_wait_close(sk, timeout);
2194
2195adjudge_to_death:
75c2d907
HX
2196 state = sk->sk_state;
2197 sock_hold(sk);
2198 sock_orphan(sk);
75c2d907 2199
1da177e4
LT
2200 /* It is the last release_sock in its life. It will remove backlog. */
2201 release_sock(sk);
2202
2203
2204 /* Now socket is owned by kernel and we acquire BH lock
2205 to finish close. No need to check for user refs.
2206 */
2207 local_bh_disable();
2208 bh_lock_sock(sk);
547b792c 2209 WARN_ON(sock_owned_by_user(sk));
1da177e4 2210
eb4dea58
HX
2211 percpu_counter_inc(sk->sk_prot->orphan_count);
2212
75c2d907
HX
2213 /* Have we already been destroyed by a softirq or backlog? */
2214 if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE)
2215 goto out;
1da177e4
LT
2216
2217 /* This is a (useful) BSD violating of the RFC. There is a
2218 * problem with TCP as specified in that the other end could
2219 * keep a socket open forever with no application left this end.
2220 * We use a 3 minute timeout (about the same as BSD) then kill
2221 * our end. If they send after that then tough - BUT: long enough
2222 * that we won't make the old 4*rto = almost no time - whoops
2223 * reset mistake.
2224 *
2225 * Nope, it was not mistake. It is really desired behaviour
2226 * f.e. on http servers, when such sockets are useless, but
2227 * consume significant resources. Let's do it with special
2228 * linger2 option. --ANK
2229 */
2230
2231 if (sk->sk_state == TCP_FIN_WAIT2) {
2232 struct tcp_sock *tp = tcp_sk(sk);
2233 if (tp->linger2 < 0) {
2234 tcp_set_state(sk, TCP_CLOSE);
2235 tcp_send_active_reset(sk, GFP_ATOMIC);
de0744af
PE
2236 NET_INC_STATS_BH(sock_net(sk),
2237 LINUX_MIB_TCPABORTONLINGER);
1da177e4 2238 } else {
463c84b9 2239 const int tmo = tcp_fin_time(sk);
1da177e4
LT
2240
2241 if (tmo > TCP_TIMEWAIT_LEN) {
52499afe
DM
2242 inet_csk_reset_keepalive_timer(sk,
2243 tmo - TCP_TIMEWAIT_LEN);
1da177e4 2244 } else {
1da177e4
LT
2245 tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
2246 goto out;
2247 }
2248 }
2249 }
2250 if (sk->sk_state != TCP_CLOSE) {
3ab224be 2251 sk_mem_reclaim(sk);
efcdbf24 2252 if (tcp_check_oom(sk, 0)) {
1da177e4
LT
2253 tcp_set_state(sk, TCP_CLOSE);
2254 tcp_send_active_reset(sk, GFP_ATOMIC);
de0744af
PE
2255 NET_INC_STATS_BH(sock_net(sk),
2256 LINUX_MIB_TCPABORTONMEMORY);
1da177e4
LT
2257 }
2258 }
1da177e4 2259
8336886f
JC
2260 if (sk->sk_state == TCP_CLOSE) {
2261 struct request_sock *req = tcp_sk(sk)->fastopen_rsk;
2262 /* We could get here with a non-NULL req if the socket is
2263 * aborted (e.g., closed with unread data) before 3WHS
2264 * finishes.
2265 */
2266 if (req != NULL)
2267 reqsk_fastopen_remove(sk, req, false);
0a5578cf 2268 inet_csk_destroy_sock(sk);
8336886f 2269 }
1da177e4
LT
2270 /* Otherwise, socket is reprieved until protocol close. */
2271
2272out:
2273 bh_unlock_sock(sk);
2274 local_bh_enable();
2275 sock_put(sk);
2276}
4bc2f18b 2277EXPORT_SYMBOL(tcp_close);
1da177e4
LT
2278
2279/* These states need RST on ABORT according to RFC793 */
2280
a2a385d6 2281static inline bool tcp_need_reset(int state)
1da177e4
LT
2282{
2283 return (1 << state) &
2284 (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 |
2285 TCPF_FIN_WAIT2 | TCPF_SYN_RECV);
2286}
2287
2288int tcp_disconnect(struct sock *sk, int flags)
2289{
2290 struct inet_sock *inet = inet_sk(sk);
463c84b9 2291 struct inet_connection_sock *icsk = inet_csk(sk);
1da177e4
LT
2292 struct tcp_sock *tp = tcp_sk(sk);
2293 int err = 0;
2294 int old_state = sk->sk_state;
2295
2296 if (old_state != TCP_CLOSE)
2297 tcp_set_state(sk, TCP_CLOSE);
2298
2299 /* ABORT function of RFC793 */
2300 if (old_state == TCP_LISTEN) {
0a5578cf 2301 inet_csk_listen_stop(sk);
ee995283
PE
2302 } else if (unlikely(tp->repair)) {
2303 sk->sk_err = ECONNABORTED;
1da177e4
LT
2304 } else if (tcp_need_reset(old_state) ||
2305 (tp->snd_nxt != tp->write_seq &&
2306 (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {
caa20d9a 2307 /* The last check adjusts for discrepancy of Linux wrt. RFC
1da177e4
LT
2308 * states
2309 */
2310 tcp_send_active_reset(sk, gfp_any());
2311 sk->sk_err = ECONNRESET;
2312 } else if (old_state == TCP_SYN_SENT)
2313 sk->sk_err = ECONNRESET;
2314
2315 tcp_clear_xmit_timers(sk);
2316 __skb_queue_purge(&sk->sk_receive_queue);
fe067e8a 2317 tcp_write_queue_purge(sk);
1da177e4 2318 __skb_queue_purge(&tp->out_of_order_queue);
1a2449a8
CL
2319#ifdef CONFIG_NET_DMA
2320 __skb_queue_purge(&sk->sk_async_wait_queue);
2321#endif
1da177e4 2322
c720c7e8 2323 inet->inet_dport = 0;
1da177e4
LT
2324
2325 if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
2326 inet_reset_saddr(sk);
2327
2328 sk->sk_shutdown = 0;
2329 sock_reset_flag(sk, SOCK_DONE);
2330 tp->srtt = 0;
2331 if ((tp->write_seq += tp->max_window + 2) == 0)
2332 tp->write_seq = 1;
463c84b9 2333 icsk->icsk_backoff = 0;
1da177e4 2334 tp->snd_cwnd = 2;
6687e988 2335 icsk->icsk_probes_out = 0;
1da177e4 2336 tp->packets_out = 0;
0b6a05c1 2337 tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
1da177e4 2338 tp->snd_cwnd_cnt = 0;
1fdf475a 2339 tp->window_clamp = 0;
6687e988 2340 tcp_set_ca_state(sk, TCP_CA_Open);
1da177e4 2341 tcp_clear_retrans(tp);
463c84b9 2342 inet_csk_delack_init(sk);
fe067e8a 2343 tcp_init_send_head(sk);
b40b4f79 2344 memset(&tp->rx_opt, 0, sizeof(tp->rx_opt));
1da177e4
LT
2345 __sk_dst_reset(sk);
2346
c720c7e8 2347 WARN_ON(inet->inet_num && !icsk->icsk_bind_hash);
1da177e4
LT
2348
2349 sk->sk_error_report(sk);
2350 return err;
2351}
4bc2f18b 2352EXPORT_SYMBOL(tcp_disconnect);
1da177e4 2353
bb68b647
CP
2354void tcp_sock_destruct(struct sock *sk)
2355{
2356 inet_sock_destruct(sk);
2357
2358 kfree(inet_csk(sk)->icsk_accept_queue.fastopenq);
2359}
2360
a2a385d6 2361static inline bool tcp_can_repair_sock(const struct sock *sk)
ee995283 2362{
52e804c6 2363 return ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN) &&
ee995283
PE
2364 ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_ESTABLISHED));
2365}
2366
de248a75
PE
2367static int tcp_repair_options_est(struct tcp_sock *tp,
2368 struct tcp_repair_opt __user *optbuf, unsigned int len)
b139ba4e 2369{
de248a75 2370 struct tcp_repair_opt opt;
b139ba4e 2371
de248a75
PE
2372 while (len >= sizeof(opt)) {
2373 if (copy_from_user(&opt, optbuf, sizeof(opt)))
b139ba4e
PE
2374 return -EFAULT;
2375
2376 optbuf++;
de248a75 2377 len -= sizeof(opt);
b139ba4e 2378
de248a75
PE
2379 switch (opt.opt_code) {
2380 case TCPOPT_MSS:
2381 tp->rx_opt.mss_clamp = opt.opt_val;
b139ba4e 2382 break;
de248a75 2383 case TCPOPT_WINDOW:
bc26ccd8
AV
2384 {
2385 u16 snd_wscale = opt.opt_val & 0xFFFF;
2386 u16 rcv_wscale = opt.opt_val >> 16;
2387
2388 if (snd_wscale > 14 || rcv_wscale > 14)
2389 return -EFBIG;
b139ba4e 2390
bc26ccd8
AV
2391 tp->rx_opt.snd_wscale = snd_wscale;
2392 tp->rx_opt.rcv_wscale = rcv_wscale;
2393 tp->rx_opt.wscale_ok = 1;
2394 }
b139ba4e 2395 break;
b139ba4e 2396 case TCPOPT_SACK_PERM:
de248a75
PE
2397 if (opt.opt_val != 0)
2398 return -EINVAL;
2399
b139ba4e
PE
2400 tp->rx_opt.sack_ok |= TCP_SACK_SEEN;
2401 if (sysctl_tcp_fack)
2402 tcp_enable_fack(tp);
2403 break;
2404 case TCPOPT_TIMESTAMP:
de248a75
PE
2405 if (opt.opt_val != 0)
2406 return -EINVAL;
2407
b139ba4e
PE
2408 tp->rx_opt.tstamp_ok = 1;
2409 break;
2410 }
2411 }
2412
2413 return 0;
2414}
2415
1da177e4
LT
2416/*
2417 * Socket option code for TCP.
2418 */
3fdadf7d 2419static int do_tcp_setsockopt(struct sock *sk, int level,
b7058842 2420 int optname, char __user *optval, unsigned int optlen)
1da177e4
LT
2421{
2422 struct tcp_sock *tp = tcp_sk(sk);
463c84b9 2423 struct inet_connection_sock *icsk = inet_csk(sk);
1da177e4
LT
2424 int val;
2425 int err = 0;
2426
e56fb50f
WAS
2427 /* These are data/string values, all the others are ints */
2428 switch (optname) {
2429 case TCP_CONGESTION: {
5f8ef48d
SH
2430 char name[TCP_CA_NAME_MAX];
2431
2432 if (optlen < 1)
2433 return -EINVAL;
2434
2435 val = strncpy_from_user(name, optval,
4fdb78d3 2436 min_t(long, TCP_CA_NAME_MAX-1, optlen));
5f8ef48d
SH
2437 if (val < 0)
2438 return -EFAULT;
2439 name[val] = 0;
2440
2441 lock_sock(sk);
6687e988 2442 err = tcp_set_congestion_control(sk, name);
5f8ef48d
SH
2443 release_sock(sk);
2444 return err;
2445 }
e56fb50f
WAS
2446 default:
2447 /* fallthru */
2448 break;
ccbd6a5a 2449 }
5f8ef48d 2450
1da177e4
LT
2451 if (optlen < sizeof(int))
2452 return -EINVAL;
2453
2454 if (get_user(val, (int __user *)optval))
2455 return -EFAULT;
2456
2457 lock_sock(sk);
2458
2459 switch (optname) {
2460 case TCP_MAXSEG:
2461 /* Values greater than interface MTU won't take effect. However
2462 * at the point when this call is done we typically don't yet
2463 * know which interface is going to be used */
c39508d6 2464 if (val < TCP_MIN_MSS || val > MAX_TCP_WINDOW) {
1da177e4
LT
2465 err = -EINVAL;
2466 break;
2467 }
2468 tp->rx_opt.user_mss = val;
2469 break;
2470
2471 case TCP_NODELAY:
2472 if (val) {
2473 /* TCP_NODELAY is weaker than TCP_CORK, so that
2474 * this option on corked socket is remembered, but
2475 * it is not activated until cork is cleared.
2476 *
2477 * However, when TCP_NODELAY is set we make
2478 * an explicit push, which overrides even TCP_CORK
2479 * for currently queued segments.
2480 */
2481 tp->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH;
9e412ba7 2482 tcp_push_pending_frames(sk);
1da177e4
LT
2483 } else {
2484 tp->nonagle &= ~TCP_NAGLE_OFF;
2485 }
2486 break;
2487
36e31b0a
AP
2488 case TCP_THIN_LINEAR_TIMEOUTS:
2489 if (val < 0 || val > 1)
2490 err = -EINVAL;
2491 else
2492 tp->thin_lto = val;
2493 break;
2494
7e380175
AP
2495 case TCP_THIN_DUPACK:
2496 if (val < 0 || val > 1)
2497 err = -EINVAL;
a4ae4c61 2498 else {
7e380175 2499 tp->thin_dupack = val;
eed530b6
YC
2500 if (tp->thin_dupack)
2501 tcp_disable_early_retrans(tp);
a4ae4c61 2502 }
7e380175
AP
2503 break;
2504
ee995283
PE
2505 case TCP_REPAIR:
2506 if (!tcp_can_repair_sock(sk))
2507 err = -EPERM;
2508 else if (val == 1) {
2509 tp->repair = 1;
2510 sk->sk_reuse = SK_FORCE_REUSE;
2511 tp->repair_queue = TCP_NO_QUEUE;
2512 } else if (val == 0) {
2513 tp->repair = 0;
2514 sk->sk_reuse = SK_NO_REUSE;
2515 tcp_send_window_probe(sk);
2516 } else
2517 err = -EINVAL;
2518
2519 break;
2520
2521 case TCP_REPAIR_QUEUE:
2522 if (!tp->repair)
2523 err = -EPERM;
2524 else if (val < TCP_QUEUES_NR)
2525 tp->repair_queue = val;
2526 else
2527 err = -EINVAL;
2528 break;
2529
2530 case TCP_QUEUE_SEQ:
2531 if (sk->sk_state != TCP_CLOSE)
2532 err = -EPERM;
2533 else if (tp->repair_queue == TCP_SEND_QUEUE)
2534 tp->write_seq = val;
2535 else if (tp->repair_queue == TCP_RECV_QUEUE)
2536 tp->rcv_nxt = val;
2537 else
2538 err = -EINVAL;
2539 break;
2540
b139ba4e
PE
2541 case TCP_REPAIR_OPTIONS:
2542 if (!tp->repair)
2543 err = -EINVAL;
2544 else if (sk->sk_state == TCP_ESTABLISHED)
de248a75
PE
2545 err = tcp_repair_options_est(tp,
2546 (struct tcp_repair_opt __user *)optval,
2547 optlen);
b139ba4e
PE
2548 else
2549 err = -EPERM;
2550 break;
2551
1da177e4
LT
2552 case TCP_CORK:
2553 /* When set indicates to always queue non-full frames.
2554 * Later the user clears this option and we transmit
2555 * any pending partial frames in the queue. This is
2556 * meant to be used alongside sendfile() to get properly
2557 * filled frames when the user (for example) must write
2558 * out headers with a write() call first and then use
2559 * sendfile to send out the data parts.
2560 *
2561 * TCP_CORK can be set together with TCP_NODELAY and it is
2562 * stronger than TCP_NODELAY.
2563 */
2564 if (val) {
2565 tp->nonagle |= TCP_NAGLE_CORK;
2566 } else {
2567 tp->nonagle &= ~TCP_NAGLE_CORK;
2568 if (tp->nonagle&TCP_NAGLE_OFF)
2569 tp->nonagle |= TCP_NAGLE_PUSH;
9e412ba7 2570 tcp_push_pending_frames(sk);
1da177e4
LT
2571 }
2572 break;
2573
2574 case TCP_KEEPIDLE:
2575 if (val < 1 || val > MAX_TCP_KEEPIDLE)
2576 err = -EINVAL;
2577 else {
2578 tp->keepalive_time = val * HZ;
2579 if (sock_flag(sk, SOCK_KEEPOPEN) &&
2580 !((1 << sk->sk_state) &
2581 (TCPF_CLOSE | TCPF_LISTEN))) {
6c37e5de 2582 u32 elapsed = keepalive_time_elapsed(tp);
1da177e4
LT
2583 if (tp->keepalive_time > elapsed)
2584 elapsed = tp->keepalive_time - elapsed;
2585 else
2586 elapsed = 0;
463c84b9 2587 inet_csk_reset_keepalive_timer(sk, elapsed);
1da177e4
LT
2588 }
2589 }
2590 break;
2591 case TCP_KEEPINTVL:
2592 if (val < 1 || val > MAX_TCP_KEEPINTVL)
2593 err = -EINVAL;
2594 else
2595 tp->keepalive_intvl = val * HZ;
2596 break;
2597 case TCP_KEEPCNT:
2598 if (val < 1 || val > MAX_TCP_KEEPCNT)
2599 err = -EINVAL;
2600 else
2601 tp->keepalive_probes = val;
2602 break;
2603 case TCP_SYNCNT:
2604 if (val < 1 || val > MAX_TCP_SYNCNT)
2605 err = -EINVAL;
2606 else
463c84b9 2607 icsk->icsk_syn_retries = val;
1da177e4
LT
2608 break;
2609
2610 case TCP_LINGER2:
2611 if (val < 0)
2612 tp->linger2 = -1;
2613 else if (val > sysctl_tcp_fin_timeout / HZ)
2614 tp->linger2 = 0;
2615 else
2616 tp->linger2 = val * HZ;
2617 break;
2618
2619 case TCP_DEFER_ACCEPT:
b103cf34
JA
2620 /* Translate value in seconds to number of retransmits */
2621 icsk->icsk_accept_queue.rskq_defer_accept =
2622 secs_to_retrans(val, TCP_TIMEOUT_INIT / HZ,
6fa3eb70 2623 sysctl_tcp_rto_max / HZ);
1da177e4
LT
2624 break;
2625
2626 case TCP_WINDOW_CLAMP:
2627 if (!val) {
2628 if (sk->sk_state != TCP_CLOSE) {
2629 err = -EINVAL;
2630 break;
2631 }
2632 tp->window_clamp = 0;
2633 } else
2634 tp->window_clamp = val < SOCK_MIN_RCVBUF / 2 ?
2635 SOCK_MIN_RCVBUF / 2 : val;
2636 break;
2637
2638 case TCP_QUICKACK:
2639 if (!val) {
463c84b9 2640 icsk->icsk_ack.pingpong = 1;
1da177e4 2641 } else {
463c84b9 2642 icsk->icsk_ack.pingpong = 0;
1da177e4
LT
2643 if ((1 << sk->sk_state) &
2644 (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) &&
463c84b9
ACM
2645 inet_csk_ack_scheduled(sk)) {
2646 icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
0e4b4992 2647 tcp_cleanup_rbuf(sk, 1);
1da177e4 2648 if (!(val & 1))
463c84b9 2649 icsk->icsk_ack.pingpong = 1;
1da177e4
LT
2650 }
2651 }
2652 break;
2653
cfb6eeb4
YH
2654#ifdef CONFIG_TCP_MD5SIG
2655 case TCP_MD5SIG:
2656 /* Read the IP->Key mappings from userspace */
2657 err = tp->af_specific->md5_parse(sk, optval, optlen);
2658 break;
2659#endif
dca43c75
JC
2660 case TCP_USER_TIMEOUT:
2661 /* Cap the max timeout in ms TCP will retry/retrans
2662 * before giving up and aborting (ETIMEDOUT) a connection.
2663 */
42493570
HL
2664 if (val < 0)
2665 err = -EINVAL;
2666 else
2667 icsk->icsk_user_timeout = msecs_to_jiffies(val);
dca43c75 2668 break;
8336886f
JC
2669
2670 case TCP_FASTOPEN:
2671 if (val >= 0 && ((1 << sk->sk_state) & (TCPF_CLOSE |
2672 TCPF_LISTEN)))
2673 err = fastopen_init_queue(sk, val);
2674 else
2675 err = -EINVAL;
2676 break;
93be6ce0
AV
2677 case TCP_TIMESTAMP:
2678 if (!tp->repair)
2679 err = -EPERM;
2680 else
2681 tp->tsoffset = val - tcp_time_stamp;
2682 break;
1da177e4
LT
2683 default:
2684 err = -ENOPROTOOPT;
2685 break;
3ff50b79
SH
2686 }
2687
1da177e4
LT
2688 release_sock(sk);
2689 return err;
2690}
2691
3fdadf7d 2692int tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval,
b7058842 2693 unsigned int optlen)
3fdadf7d 2694{
cf533ea5 2695 const struct inet_connection_sock *icsk = inet_csk(sk);
3fdadf7d
DM
2696
2697 if (level != SOL_TCP)
2698 return icsk->icsk_af_ops->setsockopt(sk, level, optname,
2699 optval, optlen);
2700 return do_tcp_setsockopt(sk, level, optname, optval, optlen);
2701}
4bc2f18b 2702EXPORT_SYMBOL(tcp_setsockopt);
3fdadf7d
DM
2703
2704#ifdef CONFIG_COMPAT
543d9cfe 2705int compat_tcp_setsockopt(struct sock *sk, int level, int optname,
b7058842 2706 char __user *optval, unsigned int optlen)
3fdadf7d 2707{
dec73ff0
ACM
2708 if (level != SOL_TCP)
2709 return inet_csk_compat_setsockopt(sk, level, optname,
2710 optval, optlen);
3fdadf7d
DM
2711 return do_tcp_setsockopt(sk, level, optname, optval, optlen);
2712}
543d9cfe 2713EXPORT_SYMBOL(compat_tcp_setsockopt);
3fdadf7d
DM
2714#endif
2715
1da177e4 2716/* Return information about state of tcp endpoint in API format. */
cf533ea5 2717void tcp_get_info(const struct sock *sk, struct tcp_info *info)
1da177e4 2718{
cf533ea5 2719 const struct tcp_sock *tp = tcp_sk(sk);
463c84b9 2720 const struct inet_connection_sock *icsk = inet_csk(sk);
1da177e4
LT
2721 u32 now = tcp_time_stamp;
2722
2723 memset(info, 0, sizeof(*info));
2724
2725 info->tcpi_state = sk->sk_state;
6687e988 2726 info->tcpi_ca_state = icsk->icsk_ca_state;
463c84b9 2727 info->tcpi_retransmits = icsk->icsk_retransmits;
6687e988 2728 info->tcpi_probes = icsk->icsk_probes_out;
463c84b9 2729 info->tcpi_backoff = icsk->icsk_backoff;
1da177e4
LT
2730
2731 if (tp->rx_opt.tstamp_ok)
2732 info->tcpi_options |= TCPI_OPT_TIMESTAMPS;
e60402d0 2733 if (tcp_is_sack(tp))
1da177e4
LT
2734 info->tcpi_options |= TCPI_OPT_SACK;
2735 if (tp->rx_opt.wscale_ok) {
2736 info->tcpi_options |= TCPI_OPT_WSCALE;
2737 info->tcpi_snd_wscale = tp->rx_opt.snd_wscale;
2738 info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale;
e905a9ed 2739 }
1da177e4 2740
b5c5693b 2741 if (tp->ecn_flags & TCP_ECN_OK)
1da177e4 2742 info->tcpi_options |= TCPI_OPT_ECN;
b5c5693b
ED
2743 if (tp->ecn_flags & TCP_ECN_SEEN)
2744 info->tcpi_options |= TCPI_OPT_ECN_SEEN;
6f73601e
YC
2745 if (tp->syn_data_acked)
2746 info->tcpi_options |= TCPI_OPT_SYN_DATA;
1da177e4 2747
463c84b9
ACM
2748 info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto);
2749 info->tcpi_ato = jiffies_to_usecs(icsk->icsk_ack.ato);
c1b4a7e6 2750 info->tcpi_snd_mss = tp->mss_cache;
463c84b9 2751 info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss;
1da177e4 2752
5ee3afba
RJ
2753 if (sk->sk_state == TCP_LISTEN) {
2754 info->tcpi_unacked = sk->sk_ack_backlog;
2755 info->tcpi_sacked = sk->sk_max_ack_backlog;
2756 } else {
2757 info->tcpi_unacked = tp->packets_out;
2758 info->tcpi_sacked = tp->sacked_out;
2759 }
1da177e4
LT
2760 info->tcpi_lost = tp->lost_out;
2761 info->tcpi_retrans = tp->retrans_out;
2762 info->tcpi_fackets = tp->fackets_out;
2763
2764 info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime);
463c84b9 2765 info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime);
1da177e4
LT
2766 info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp);
2767
d83d8461 2768 info->tcpi_pmtu = icsk->icsk_pmtu_cookie;
1da177e4
LT
2769 info->tcpi_rcv_ssthresh = tp->rcv_ssthresh;
2770 info->tcpi_rtt = jiffies_to_usecs(tp->srtt)>>3;
2771 info->tcpi_rttvar = jiffies_to_usecs(tp->mdev)>>2;
2772 info->tcpi_snd_ssthresh = tp->snd_ssthresh;
2773 info->tcpi_snd_cwnd = tp->snd_cwnd;
2774 info->tcpi_advmss = tp->advmss;
2775 info->tcpi_reordering = tp->reordering;
2776
2777 info->tcpi_rcv_rtt = jiffies_to_usecs(tp->rcv_rtt_est.rtt)>>3;
2778 info->tcpi_rcv_space = tp->rcvq_space.space;
2779
2780 info->tcpi_total_retrans = tp->total_retrans;
2781}
1da177e4
LT
2782EXPORT_SYMBOL_GPL(tcp_get_info);
2783
3fdadf7d
DM
2784static int do_tcp_getsockopt(struct sock *sk, int level,
2785 int optname, char __user *optval, int __user *optlen)
1da177e4 2786{
295f7324 2787 struct inet_connection_sock *icsk = inet_csk(sk);
1da177e4
LT
2788 struct tcp_sock *tp = tcp_sk(sk);
2789 int val, len;
2790
1da177e4
LT
2791 if (get_user(len, optlen))
2792 return -EFAULT;
2793
2794 len = min_t(unsigned int, len, sizeof(int));
2795
2796 if (len < 0)
2797 return -EINVAL;
2798
2799 switch (optname) {
2800 case TCP_MAXSEG:
c1b4a7e6 2801 val = tp->mss_cache;
1da177e4
LT
2802 if (!val && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
2803 val = tp->rx_opt.user_mss;
5e6a3ce6
PE
2804 if (tp->repair)
2805 val = tp->rx_opt.mss_clamp;
1da177e4
LT
2806 break;
2807 case TCP_NODELAY:
2808 val = !!(tp->nonagle&TCP_NAGLE_OFF);
2809 break;
2810 case TCP_CORK:
2811 val = !!(tp->nonagle&TCP_NAGLE_CORK);
2812 break;
2813 case TCP_KEEPIDLE:
df19a626 2814 val = keepalive_time_when(tp) / HZ;
1da177e4
LT
2815 break;
2816 case TCP_KEEPINTVL:
df19a626 2817 val = keepalive_intvl_when(tp) / HZ;
1da177e4
LT
2818 break;
2819 case TCP_KEEPCNT:
df19a626 2820 val = keepalive_probes(tp);
1da177e4
LT
2821 break;
2822 case TCP_SYNCNT:
295f7324 2823 val = icsk->icsk_syn_retries ? : sysctl_tcp_syn_retries;
1da177e4
LT
2824 break;
2825 case TCP_LINGER2:
2826 val = tp->linger2;
2827 if (val >= 0)
2828 val = (val ? : sysctl_tcp_fin_timeout) / HZ;
2829 break;
2830 case TCP_DEFER_ACCEPT:
b103cf34 2831 val = retrans_to_secs(icsk->icsk_accept_queue.rskq_defer_accept,
6fa3eb70 2832 TCP_TIMEOUT_INIT / HZ, sysctl_tcp_rto_max / HZ);
1da177e4
LT
2833 break;
2834 case TCP_WINDOW_CLAMP:
2835 val = tp->window_clamp;
2836 break;
2837 case TCP_INFO: {
2838 struct tcp_info info;
2839
2840 if (get_user(len, optlen))
2841 return -EFAULT;
2842
2843 tcp_get_info(sk, &info);
2844
2845 len = min_t(unsigned int, len, sizeof(info));
2846 if (put_user(len, optlen))
2847 return -EFAULT;
2848 if (copy_to_user(optval, &info, len))
2849 return -EFAULT;
2850 return 0;
2851 }
2852 case TCP_QUICKACK:
295f7324 2853 val = !icsk->icsk_ack.pingpong;
1da177e4 2854 break;
5f8ef48d
SH
2855
2856 case TCP_CONGESTION:
2857 if (get_user(len, optlen))
2858 return -EFAULT;
2859 len = min_t(unsigned int, len, TCP_CA_NAME_MAX);
2860 if (put_user(len, optlen))
2861 return -EFAULT;
6687e988 2862 if (copy_to_user(optval, icsk->icsk_ca_ops->name, len))
5f8ef48d
SH
2863 return -EFAULT;
2864 return 0;
e56fb50f 2865
3c0fef0b
JH
2866 case TCP_THIN_LINEAR_TIMEOUTS:
2867 val = tp->thin_lto;
2868 break;
2869 case TCP_THIN_DUPACK:
2870 val = tp->thin_dupack;
2871 break;
dca43c75 2872
ee995283
PE
2873 case TCP_REPAIR:
2874 val = tp->repair;
2875 break;
2876
2877 case TCP_REPAIR_QUEUE:
2878 if (tp->repair)
2879 val = tp->repair_queue;
2880 else
2881 return -EINVAL;
2882 break;
2883
2884 case TCP_QUEUE_SEQ:
2885 if (tp->repair_queue == TCP_SEND_QUEUE)
2886 val = tp->write_seq;
2887 else if (tp->repair_queue == TCP_RECV_QUEUE)
2888 val = tp->rcv_nxt;
2889 else
2890 return -EINVAL;
2891 break;
2892
dca43c75
JC
2893 case TCP_USER_TIMEOUT:
2894 val = jiffies_to_msecs(icsk->icsk_user_timeout);
2895 break;
93be6ce0
AV
2896 case TCP_TIMESTAMP:
2897 val = tcp_time_stamp + tp->tsoffset;
2898 break;
1da177e4
LT
2899 default:
2900 return -ENOPROTOOPT;
3ff50b79 2901 }
1da177e4
LT
2902
2903 if (put_user(len, optlen))
2904 return -EFAULT;
2905 if (copy_to_user(optval, &val, len))
2906 return -EFAULT;
2907 return 0;
2908}
2909
3fdadf7d
DM
2910int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval,
2911 int __user *optlen)
2912{
2913 struct inet_connection_sock *icsk = inet_csk(sk);
2914
2915 if (level != SOL_TCP)
2916 return icsk->icsk_af_ops->getsockopt(sk, level, optname,
2917 optval, optlen);
2918 return do_tcp_getsockopt(sk, level, optname, optval, optlen);
2919}
4bc2f18b 2920EXPORT_SYMBOL(tcp_getsockopt);
3fdadf7d
DM
2921
2922#ifdef CONFIG_COMPAT
543d9cfe
ACM
2923int compat_tcp_getsockopt(struct sock *sk, int level, int optname,
2924 char __user *optval, int __user *optlen)
3fdadf7d 2925{
dec73ff0
ACM
2926 if (level != SOL_TCP)
2927 return inet_csk_compat_getsockopt(sk, level, optname,
2928 optval, optlen);
3fdadf7d
DM
2929 return do_tcp_getsockopt(sk, level, optname, optval, optlen);
2930}
543d9cfe 2931EXPORT_SYMBOL(compat_tcp_getsockopt);
3fdadf7d 2932#endif
1da177e4 2933
c8f44aff
MM
2934struct sk_buff *tcp_tso_segment(struct sk_buff *skb,
2935 netdev_features_t features)
f4c50d99
HX
2936{
2937 struct sk_buff *segs = ERR_PTR(-EINVAL);
e8ef7eff 2938 unsigned int sum_truesize = 0;
f4c50d99 2939 struct tcphdr *th;
95c96174 2940 unsigned int thlen;
f4c50d99 2941 unsigned int seq;
d3bc23e7 2942 __be32 delta;
f4c50d99 2943 unsigned int oldlen;
4e704ee3 2944 unsigned int mss;
d6a4a104 2945 struct sk_buff *gso_skb = skb;
bece1b97 2946 __sum16 newcheck;
6ff50cd5 2947 bool ooo_okay, copy_destructor;
f4c50d99
HX
2948
2949 if (!pskb_may_pull(skb, sizeof(*th)))
2950 goto out;
2951
aa8223c7 2952 th = tcp_hdr(skb);
f4c50d99
HX
2953 thlen = th->doff * 4;
2954 if (thlen < sizeof(*th))
2955 goto out;
2956
2957 if (!pskb_may_pull(skb, thlen))
2958 goto out;
2959
0718bcc0 2960 oldlen = (u16)~skb->len;
f4c50d99
HX
2961 __skb_pull(skb, thlen);
2962
4e704ee3
HX
2963 mss = skb_shinfo(skb)->gso_size;
2964 if (unlikely(skb->len <= mss))
2965 goto out;
2966
3820c3f3
HX
2967 if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) {
2968 /* Packet is from an untrusted source, reset gso_segs. */
bbcf467d 2969 int type = skb_shinfo(skb)->gso_type;
bbcf467d
HX
2970
2971 if (unlikely(type &
2972 ~(SKB_GSO_TCPV4 |
2973 SKB_GSO_DODGY |
2974 SKB_GSO_TCP_ECN |
2975 SKB_GSO_TCPV6 |
68c33163 2976 SKB_GSO_GRE |
73136267 2977 SKB_GSO_UDP_TUNNEL |
bbcf467d
HX
2978 0) ||
2979 !(type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))))
2980 goto out;
3820c3f3 2981
172589cc 2982 skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss);
3820c3f3
HX
2983
2984 segs = NULL;
2985 goto out;
2986 }
2987
6ff50cd5
ED
2988 copy_destructor = gso_skb->destructor == tcp_wfree;
2989 ooo_okay = gso_skb->ooo_okay;
2990 /* All segments but the first should have ooo_okay cleared */
2991 skb->ooo_okay = 0;
2992
576a30eb 2993 segs = skb_segment(skb, features);
f4c50d99
HX
2994 if (IS_ERR(segs))
2995 goto out;
2996
6ff50cd5
ED
2997 /* Only first segment might have ooo_okay set */
2998 segs->ooo_okay = ooo_okay;
2999
4e704ee3 3000 delta = htonl(oldlen + (thlen + mss));
f4c50d99
HX
3001
3002 skb = segs;
aa8223c7 3003 th = tcp_hdr(skb);
f4c50d99
HX
3004 seq = ntohl(th->seq);
3005
bece1b97
ED
3006 newcheck = ~csum_fold((__force __wsum)((__force u32)th->check +
3007 (__force u32)delta));
3008
f4c50d99
HX
3009 do {
3010 th->fin = th->psh = 0;
bece1b97 3011 th->check = newcheck;
f4c50d99 3012
84fa7933 3013 if (skb->ip_summed != CHECKSUM_PARTIAL)
9c70220b
ACM
3014 th->check =
3015 csum_fold(csum_partial(skb_transport_header(skb),
3016 thlen, skb->csum));
f4c50d99 3017
4e704ee3 3018 seq += mss;
6ff50cd5
ED
3019 if (copy_destructor) {
3020 skb->destructor = gso_skb->destructor;
3021 skb->sk = gso_skb->sk;
e8ef7eff 3022 sum_truesize += skb->truesize;
6ff50cd5 3023 }
f4c50d99 3024 skb = skb->next;
aa8223c7 3025 th = tcp_hdr(skb);
f4c50d99
HX
3026
3027 th->seq = htonl(seq);
3028 th->cwr = 0;
3029 } while (skb->next);
3030
d6a4a104
ED
3031 /* Following permits TCP Small Queues to work well with GSO :
3032 * The callback to TCP stack will be called at the time last frag
3033 * is freed at TX completion, and not right now when gso_skb
3034 * is freed by GSO engine
3035 */
6ff50cd5 3036 if (copy_destructor) {
d6a4a104
ED
3037 swap(gso_skb->sk, skb->sk);
3038 swap(gso_skb->destructor, skb->destructor);
e8ef7eff
ED
3039 sum_truesize += skb->truesize;
3040 atomic_add(sum_truesize - gso_skb->truesize,
3041 &skb->sk->sk_wmem_alloc);
d6a4a104
ED
3042 }
3043
27a884dc 3044 delta = htonl(oldlen + (skb->tail - skb->transport_header) +
9c70220b 3045 skb->data_len);
d3bc23e7
AV
3046 th->check = ~csum_fold((__force __wsum)((__force u32)th->check +
3047 (__force u32)delta));
84fa7933 3048 if (skb->ip_summed != CHECKSUM_PARTIAL)
9c70220b
ACM
3049 th->check = csum_fold(csum_partial(skb_transport_header(skb),
3050 thlen, skb->csum));
f4c50d99
HX
3051
3052out:
3053 return segs;
3054}
adcfc7d0 3055EXPORT_SYMBOL(tcp_tso_segment);
f4c50d99 3056
bf296b12
HX
3057struct sk_buff **tcp_gro_receive(struct sk_buff **head, struct sk_buff *skb)
3058{
3059 struct sk_buff **pp = NULL;
3060 struct sk_buff *p;
3061 struct tcphdr *th;
3062 struct tcphdr *th2;
a0a69a01 3063 unsigned int len;
bf296b12 3064 unsigned int thlen;
0eae88f3 3065 __be32 flags;
bf296b12 3066 unsigned int mss = 1;
a5b1cf28
HX
3067 unsigned int hlen;
3068 unsigned int off;
bf296b12 3069 int flush = 1;
aa6320d3 3070 int i;
bf296b12 3071
a5b1cf28
HX
3072 off = skb_gro_offset(skb);
3073 hlen = off + sizeof(*th);
3074 th = skb_gro_header_fast(skb, off);
3075 if (skb_gro_header_hard(skb, hlen)) {
3076 th = skb_gro_header_slow(skb, hlen, off);
3077 if (unlikely(!th))
3078 goto out;
3079 }
bf296b12 3080
bf296b12
HX
3081 thlen = th->doff * 4;
3082 if (thlen < sizeof(*th))
3083 goto out;
3084
a5b1cf28
HX
3085 hlen = off + thlen;
3086 if (skb_gro_header_hard(skb, hlen)) {
3087 th = skb_gro_header_slow(skb, hlen, off);
3088 if (unlikely(!th))
3089 goto out;
3090 }
bf296b12 3091
86911732 3092 skb_gro_pull(skb, thlen);
bf296b12 3093
a0a69a01 3094 len = skb_gro_len(skb);
bf296b12
HX
3095 flags = tcp_flag_word(th);
3096
3097 for (; (p = *head); head = &p->next) {
3098 if (!NAPI_GRO_CB(p)->same_flow)
3099 continue;
3100
3101 th2 = tcp_hdr(p);
3102
745898ea 3103 if (*(u32 *)&th->source ^ *(u32 *)&th2->source) {
bf296b12
HX
3104 NAPI_GRO_CB(p)->same_flow = 0;
3105 continue;
3106 }
3107
3108 goto found;
3109 }
3110
3111 goto out_check_final;
3112
3113found:
3114 flush = NAPI_GRO_CB(p)->flush;
0eae88f3
ED
3115 flush |= (__force int)(flags & TCP_FLAG_CWR);
3116 flush |= (__force int)((flags ^ tcp_flag_word(th2)) &
3117 ~(TCP_FLAG_CWR | TCP_FLAG_FIN | TCP_FLAG_PSH));
3118 flush |= (__force int)(th->ack_seq ^ th2->ack_seq);
a2a804cd 3119 for (i = sizeof(*th); i < thlen; i += 4)
aa6320d3
HX
3120 flush |= *(u32 *)((u8 *)th + i) ^
3121 *(u32 *)((u8 *)th2 + i);
bf296b12 3122
b530256d 3123 mss = skb_shinfo(p)->gso_size;
bf296b12 3124
30a3ae30 3125 flush |= (len - 1) >= mss;
aa6320d3 3126 flush |= (ntohl(th2->seq) + skb_gro_len(p)) ^ ntohl(th->seq);
bf296b12
HX
3127
3128 if (flush || skb_gro_receive(head, skb)) {
3129 mss = 1;
3130 goto out_check_final;
3131 }
3132
3133 p = *head;
3134 th2 = tcp_hdr(p);
3135 tcp_flag_word(th2) |= flags & (TCP_FLAG_FIN | TCP_FLAG_PSH);
3136
3137out_check_final:
a0a69a01 3138 flush = len < mss;
0eae88f3
ED
3139 flush |= (__force int)(flags & (TCP_FLAG_URG | TCP_FLAG_PSH |
3140 TCP_FLAG_RST | TCP_FLAG_SYN |
3141 TCP_FLAG_FIN));
bf296b12
HX
3142
3143 if (p && (!NAPI_GRO_CB(skb)->same_flow || flush))
3144 pp = head;
3145
3146out:
3147 NAPI_GRO_CB(skb)->flush |= flush;
3148
3149 return pp;
3150}
684f2176 3151EXPORT_SYMBOL(tcp_gro_receive);
bf296b12
HX
3152
3153int tcp_gro_complete(struct sk_buff *skb)
3154{
3155 struct tcphdr *th = tcp_hdr(skb);
3156
3157 skb->csum_start = skb_transport_header(skb) - skb->head;
3158 skb->csum_offset = offsetof(struct tcphdr, check);
3159 skb->ip_summed = CHECKSUM_PARTIAL;
3160
bf296b12
HX
3161 skb_shinfo(skb)->gso_segs = NAPI_GRO_CB(skb)->count;
3162
3163 if (th->cwr)
3164 skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
3165
3166 return 0;
3167}
684f2176 3168EXPORT_SYMBOL(tcp_gro_complete);
bf296b12 3169
cfb6eeb4
YH
3170#ifdef CONFIG_TCP_MD5SIG
3171static unsigned long tcp_md5sig_users;
765cf997 3172static struct tcp_md5sig_pool __percpu *tcp_md5sig_pool;
cfb6eeb4
YH
3173static DEFINE_SPINLOCK(tcp_md5sig_pool_lock);
3174
765cf997 3175static void __tcp_free_md5sig_pool(struct tcp_md5sig_pool __percpu *pool)
cfb6eeb4
YH
3176{
3177 int cpu;
765cf997 3178
cfb6eeb4 3179 for_each_possible_cpu(cpu) {
765cf997
ED
3180 struct tcp_md5sig_pool *p = per_cpu_ptr(pool, cpu);
3181
3182 if (p->md5_desc.tfm)
3183 crypto_free_hash(p->md5_desc.tfm);
cfb6eeb4
YH
3184 }
3185 free_percpu(pool);
3186}
3187
3188void tcp_free_md5sig_pool(void)
3189{
765cf997 3190 struct tcp_md5sig_pool __percpu *pool = NULL;
cfb6eeb4 3191
2c4f6219 3192 spin_lock_bh(&tcp_md5sig_pool_lock);
cfb6eeb4
YH
3193 if (--tcp_md5sig_users == 0) {
3194 pool = tcp_md5sig_pool;
3195 tcp_md5sig_pool = NULL;
3196 }
2c4f6219 3197 spin_unlock_bh(&tcp_md5sig_pool_lock);
cfb6eeb4
YH
3198 if (pool)
3199 __tcp_free_md5sig_pool(pool);
3200}
cfb6eeb4
YH
3201EXPORT_SYMBOL(tcp_free_md5sig_pool);
3202
765cf997 3203static struct tcp_md5sig_pool __percpu *
7d720c3e 3204__tcp_alloc_md5sig_pool(struct sock *sk)
cfb6eeb4
YH
3205{
3206 int cpu;
765cf997 3207 struct tcp_md5sig_pool __percpu *pool;
cfb6eeb4 3208
765cf997 3209 pool = alloc_percpu(struct tcp_md5sig_pool);
cfb6eeb4
YH
3210 if (!pool)
3211 return NULL;
3212
3213 for_each_possible_cpu(cpu) {
cfb6eeb4
YH
3214 struct crypto_hash *hash;
3215
cfb6eeb4 3216 hash = crypto_alloc_hash("md5", 0, CRYPTO_ALG_ASYNC);
50c3a487 3217 if (IS_ERR_OR_NULL(hash))
cfb6eeb4
YH
3218 goto out_free;
3219
765cf997 3220 per_cpu_ptr(pool, cpu)->md5_desc.tfm = hash;
cfb6eeb4
YH
3221 }
3222 return pool;
3223out_free:
3224 __tcp_free_md5sig_pool(pool);
3225 return NULL;
3226}
3227
765cf997 3228struct tcp_md5sig_pool __percpu *tcp_alloc_md5sig_pool(struct sock *sk)
cfb6eeb4 3229{
765cf997 3230 struct tcp_md5sig_pool __percpu *pool;
a2a385d6 3231 bool alloc = false;
cfb6eeb4
YH
3232
3233retry:
2c4f6219 3234 spin_lock_bh(&tcp_md5sig_pool_lock);
cfb6eeb4
YH
3235 pool = tcp_md5sig_pool;
3236 if (tcp_md5sig_users++ == 0) {
a2a385d6 3237 alloc = true;
2c4f6219 3238 spin_unlock_bh(&tcp_md5sig_pool_lock);
cfb6eeb4
YH
3239 } else if (!pool) {
3240 tcp_md5sig_users--;
2c4f6219 3241 spin_unlock_bh(&tcp_md5sig_pool_lock);
cfb6eeb4
YH
3242 cpu_relax();
3243 goto retry;
3244 } else
2c4f6219 3245 spin_unlock_bh(&tcp_md5sig_pool_lock);
cfb6eeb4
YH
3246
3247 if (alloc) {
3248 /* we cannot hold spinlock here because this may sleep. */
765cf997 3249 struct tcp_md5sig_pool __percpu *p;
7d720c3e
TH
3250
3251 p = __tcp_alloc_md5sig_pool(sk);
2c4f6219 3252 spin_lock_bh(&tcp_md5sig_pool_lock);
cfb6eeb4
YH
3253 if (!p) {
3254 tcp_md5sig_users--;
2c4f6219 3255 spin_unlock_bh(&tcp_md5sig_pool_lock);
cfb6eeb4
YH
3256 return NULL;
3257 }
3258 pool = tcp_md5sig_pool;
3259 if (pool) {
3260 /* oops, it has already been assigned. */
2c4f6219 3261 spin_unlock_bh(&tcp_md5sig_pool_lock);
cfb6eeb4
YH
3262 __tcp_free_md5sig_pool(p);
3263 } else {
3264 tcp_md5sig_pool = pool = p;
2c4f6219 3265 spin_unlock_bh(&tcp_md5sig_pool_lock);
cfb6eeb4
YH
3266 }
3267 }
3268 return pool;
3269}
cfb6eeb4
YH
3270EXPORT_SYMBOL(tcp_alloc_md5sig_pool);
3271
35790c04
ED
3272
3273/**
3274 * tcp_get_md5sig_pool - get md5sig_pool for this user
3275 *
3276 * We use percpu structure, so if we succeed, we exit with preemption
3277 * and BH disabled, to make sure another thread or softirq handling
3278 * wont try to get same context.
3279 */
3280struct tcp_md5sig_pool *tcp_get_md5sig_pool(void)
cfb6eeb4 3281{
765cf997 3282 struct tcp_md5sig_pool __percpu *p;
35790c04
ED
3283
3284 local_bh_disable();
3285
3286 spin_lock(&tcp_md5sig_pool_lock);
cfb6eeb4
YH
3287 p = tcp_md5sig_pool;
3288 if (p)
3289 tcp_md5sig_users++;
35790c04
ED
3290 spin_unlock(&tcp_md5sig_pool_lock);
3291
3292 if (p)
765cf997 3293 return this_cpu_ptr(p);
cfb6eeb4 3294
35790c04
ED
3295 local_bh_enable();
3296 return NULL;
3297}
3298EXPORT_SYMBOL(tcp_get_md5sig_pool);
cfb6eeb4 3299
35790c04 3300void tcp_put_md5sig_pool(void)
6931ba7c 3301{
35790c04 3302 local_bh_enable();
6931ba7c 3303 tcp_free_md5sig_pool();
cfb6eeb4 3304}
35790c04 3305EXPORT_SYMBOL(tcp_put_md5sig_pool);
49a72dfb
AL
3306
3307int tcp_md5_hash_header(struct tcp_md5sig_pool *hp,
ca35a0ef 3308 const struct tcphdr *th)
49a72dfb
AL
3309{
3310 struct scatterlist sg;
ca35a0ef 3311 struct tcphdr hdr;
49a72dfb
AL
3312 int err;
3313
ca35a0ef
ED
3314 /* We are not allowed to change tcphdr, make a local copy */
3315 memcpy(&hdr, th, sizeof(hdr));
3316 hdr.check = 0;
3317
49a72dfb 3318 /* options aren't included in the hash */
ca35a0ef
ED
3319 sg_init_one(&sg, &hdr, sizeof(hdr));
3320 err = crypto_hash_update(&hp->md5_desc, &sg, sizeof(hdr));
49a72dfb
AL
3321 return err;
3322}
49a72dfb
AL
3323EXPORT_SYMBOL(tcp_md5_hash_header);
3324
3325int tcp_md5_hash_skb_data(struct tcp_md5sig_pool *hp,
cf533ea5 3326 const struct sk_buff *skb, unsigned int header_len)
49a72dfb
AL
3327{
3328 struct scatterlist sg;
3329 const struct tcphdr *tp = tcp_hdr(skb);
3330 struct hash_desc *desc = &hp->md5_desc;
95c96174
ED
3331 unsigned int i;
3332 const unsigned int head_data_len = skb_headlen(skb) > header_len ?
3333 skb_headlen(skb) - header_len : 0;
49a72dfb 3334 const struct skb_shared_info *shi = skb_shinfo(skb);
d7fd1b57 3335 struct sk_buff *frag_iter;
49a72dfb
AL
3336
3337 sg_init_table(&sg, 1);
3338
3339 sg_set_buf(&sg, ((u8 *) tp) + header_len, head_data_len);
3340 if (crypto_hash_update(desc, &sg, head_data_len))
3341 return 1;
3342
3343 for (i = 0; i < shi->nr_frags; ++i) {
3344 const struct skb_frag_struct *f = &shi->frags[i];
54d27fcb
ED
3345 unsigned int offset = f->page_offset;
3346 struct page *page = skb_frag_page(f) + (offset >> PAGE_SHIFT);
3347
3348 sg_set_page(&sg, page, skb_frag_size(f),
3349 offset_in_page(offset));
9e903e08 3350 if (crypto_hash_update(desc, &sg, skb_frag_size(f)))
49a72dfb
AL
3351 return 1;
3352 }
3353
d7fd1b57
ED
3354 skb_walk_frags(skb, frag_iter)
3355 if (tcp_md5_hash_skb_data(hp, frag_iter, 0))
3356 return 1;
3357
49a72dfb
AL
3358 return 0;
3359}
49a72dfb
AL
3360EXPORT_SYMBOL(tcp_md5_hash_skb_data);
3361
cf533ea5 3362int tcp_md5_hash_key(struct tcp_md5sig_pool *hp, const struct tcp_md5sig_key *key)
49a72dfb
AL
3363{
3364 struct scatterlist sg;
3365
3366 sg_init_one(&sg, key->key, key->keylen);
3367 return crypto_hash_update(&hp->md5_desc, &sg, key->keylen);
3368}
49a72dfb
AL
3369EXPORT_SYMBOL(tcp_md5_hash_key);
3370
cfb6eeb4
YH
3371#endif
3372
4ac02bab
AK
3373void tcp_done(struct sock *sk)
3374{
8336886f
JC
3375 struct request_sock *req = tcp_sk(sk)->fastopen_rsk;
3376
5a5f3a8d 3377 if (sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV)
63231bdd 3378 TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_ATTEMPTFAILS);
4ac02bab
AK
3379
3380 tcp_set_state(sk, TCP_CLOSE);
3381 tcp_clear_xmit_timers(sk);
8336886f
JC
3382 if (req != NULL)
3383 reqsk_fastopen_remove(sk, req, false);
4ac02bab
AK
3384
3385 sk->sk_shutdown = SHUTDOWN_MASK;
3386
3387 if (!sock_flag(sk, SOCK_DEAD))
3388 sk->sk_state_change(sk);
3389 else
3390 inet_csk_destroy_sock(sk);
3391}
3392EXPORT_SYMBOL_GPL(tcp_done);
3393
5f8ef48d 3394extern struct tcp_congestion_ops tcp_reno;
1da177e4
LT
3395
3396static __initdata unsigned long thash_entries;
3397static int __init set_thash_entries(char *str)
3398{
413c27d8
EZ
3399 ssize_t ret;
3400
1da177e4
LT
3401 if (!str)
3402 return 0;
413c27d8
EZ
3403
3404 ret = kstrtoul(str, 0, &thash_entries);
3405 if (ret)
3406 return 0;
3407
1da177e4
LT
3408 return 1;
3409}
3410__setup("thash_entries=", set_thash_entries);
3411
4acb4190
GC
3412void tcp_init_mem(struct net *net)
3413{
4acb4190
GC
3414 unsigned long limit = nr_free_buffer_pages() / 8;
3415 limit = max(limit, 128UL);
3416 net->ipv4.sysctl_tcp_mem[0] = limit / 4 * 3;
3417 net->ipv4.sysctl_tcp_mem[1] = limit;
3418 net->ipv4.sysctl_tcp_mem[2] = net->ipv4.sysctl_tcp_mem[0] * 2;
3419}
3420
1da177e4
LT
3421void __init tcp_init(void)
3422{
3423 struct sk_buff *skb = NULL;
f03d78db 3424 unsigned long limit;
b49960a0 3425 int max_rshare, max_wshare, cnt;
074b8517 3426 unsigned int i;
1da177e4 3427
1f9e636e 3428 BUILD_BUG_ON(sizeof(struct tcp_skb_cb) > sizeof(skb->cb));
1da177e4 3429
1748376b 3430 percpu_counter_init(&tcp_sockets_allocated, 0);
dd24c001 3431 percpu_counter_init(&tcp_orphan_count, 0);
6e04e021
ACM
3432 tcp_hashinfo.bind_bucket_cachep =
3433 kmem_cache_create("tcp_bind_bucket",
3434 sizeof(struct inet_bind_bucket), 0,
20c2df83 3435 SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
1da177e4 3436
1da177e4
LT
3437 /* Size and allocate the main established and bind bucket
3438 * hash tables.
3439 *
3440 * The methodology is similar to that of the buffer cache.
3441 */
6e04e021 3442 tcp_hashinfo.ehash =
1da177e4 3443 alloc_large_system_hash("TCP established",
0f7ff927 3444 sizeof(struct inet_ehash_bucket),
1da177e4 3445 thash_entries,
fd90b29d 3446 17, /* one slot per 128 KB of memory */
9e950efa 3447 0,
1da177e4 3448 NULL,
f373b53b 3449 &tcp_hashinfo.ehash_mask,
31fe62b9 3450 0,
0ccfe618 3451 thash_entries ? 0 : 512 * 1024);
f373b53b 3452 for (i = 0; i <= tcp_hashinfo.ehash_mask; i++) {
3ab5aee7
ED
3453 INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i);
3454 INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].twchain, i);
1da177e4 3455 }
230140cf
ED
3456 if (inet_ehash_locks_alloc(&tcp_hashinfo))
3457 panic("TCP: failed to alloc ehash_locks");
6e04e021 3458 tcp_hashinfo.bhash =
1da177e4 3459 alloc_large_system_hash("TCP bind",
0f7ff927 3460 sizeof(struct inet_bind_hashbucket),
f373b53b 3461 tcp_hashinfo.ehash_mask + 1,
fd90b29d 3462 17, /* one slot per 128 KB of memory */
9e950efa 3463 0,
6e04e021 3464 &tcp_hashinfo.bhash_size,
1da177e4 3465 NULL,
31fe62b9 3466 0,
1da177e4 3467 64 * 1024);
074b8517 3468 tcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size;
6e04e021
ACM
3469 for (i = 0; i < tcp_hashinfo.bhash_size; i++) {
3470 spin_lock_init(&tcp_hashinfo.bhash[i].lock);
3471 INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain);
1da177e4
LT
3472 }
3473
c5ed63d6
ED
3474
3475 cnt = tcp_hashinfo.ehash_mask + 1;
3476
3477 tcp_death_row.sysctl_max_tw_buckets = cnt / 2;
3478 sysctl_tcp_max_orphans = cnt / 2;
3479 sysctl_max_syn_backlog = max(128, cnt / 256);
1da177e4 3480
4acb4190 3481 tcp_init_mem(&init_net);
c43b874d 3482 /* Set per-socket limits to no more than 1/128 the pressure threshold */
5fb84b14 3483 limit = nr_free_buffer_pages() << (PAGE_SHIFT - 7);
b49960a0
ED
3484 max_wshare = min(4UL*1024*1024, limit);
3485 max_rshare = min(6UL*1024*1024, limit);
7b4f4b5e 3486
3ab224be 3487 sysctl_tcp_wmem[0] = SK_MEM_QUANTUM;
7b4f4b5e 3488 sysctl_tcp_wmem[1] = 16*1024;
b49960a0 3489 sysctl_tcp_wmem[2] = max(64*1024, max_wshare);
7b4f4b5e 3490
3ab224be 3491 sysctl_tcp_rmem[0] = SK_MEM_QUANTUM;
7b4f4b5e 3492 sysctl_tcp_rmem[1] = 87380;
b49960a0 3493 sysctl_tcp_rmem[2] = max(87380, max_rshare);
1da177e4 3494
afd46503 3495 pr_info("Hash tables configured (established %u bind %u)\n",
058bd4d2 3496 tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size);
317a76f9 3497
51c5d0c4
DM
3498 tcp_metrics_init();
3499
317a76f9 3500 tcp_register_congestion_control(&tcp_reno);
da5c78c8 3501
46d3ceab 3502 tcp_tasklet_init();
1da177e4 3503}
6fa3eb70
S
3504
3505static int tcp_is_local(struct net *net, __be32 addr) {
3506 struct rtable *rt;
3507 struct flowi4 fl4 = { .daddr = addr };
3508 rt = ip_route_output_key(net, &fl4);
3509 if (IS_ERR_OR_NULL(rt))
3510 return 0;
3511 return rt->dst.dev && (rt->dst.dev->flags & IFF_LOOPBACK);
3512}
3513
3514#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3515static int tcp_is_local6(struct net *net, struct in6_addr *addr) {
3516 struct rt6_info *rt6 = rt6_lookup(net, addr, addr, 0, 0);
3517 return rt6 && rt6->dst.dev && (rt6->dst.dev->flags & IFF_LOOPBACK);
3518}
3519#endif
3520
3521/*
3522 * tcp_nuke_addr - destroy all sockets on the given local address
3523 * if local address is the unspecified address (0.0.0.0 or ::), destroy all
3524 * sockets with local addresses that are not configured.
3525 */
3526int tcp_nuke_addr(struct net *net, struct sockaddr *addr)
3527{
3528 int family = addr->sa_family;
3529 unsigned int bucket;
3530
3531 struct in_addr *in;
3532#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3533 struct in6_addr *in6 = NULL ;
3534#endif
3535 if (family == AF_INET) {
3536 in = &((struct sockaddr_in *)addr)->sin_addr;
3537#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3538 } else if (family == AF_INET6) {
3539 in6 = &((struct sockaddr_in6 *)addr)->sin6_addr;
3540#endif
3541 } else {
3542 return -EAFNOSUPPORT;
3543 }
3544
3545 for (bucket = 0; bucket < tcp_hashinfo.ehash_mask; bucket++) {
3546 struct hlist_nulls_node *node;
3547 struct sock *sk;
3548 spinlock_t *lock = inet_ehash_lockp(&tcp_hashinfo, bucket);
3549
3550restart:
3551 spin_lock_bh(lock);
3552 sk_nulls_for_each(sk, node, &tcp_hashinfo.ehash[bucket].chain) {
3553 struct inet_sock *inet = inet_sk(sk);
3554
3555 if (sysctl_ip_dynaddr && sk->sk_state == TCP_SYN_SENT)
3556 continue;
3557 if (sock_flag(sk, SOCK_DEAD))
3558 continue;
3559
3560 if (family == AF_INET) {
3561 __be32 s4 = inet->inet_rcv_saddr;
3562 if (s4 == LOOPBACK4_IPV6)
3563 continue;
3564
3565 if (in->s_addr != s4 &&
3566 !(in->s_addr == INADDR_ANY &&
3567 !tcp_is_local(net, s4)))
3568 continue;
3569 }
3570
3571#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3572 if (family == AF_INET6) {
3573 struct in6_addr *s6;
3574 if (!inet->pinet6)
3575 continue;
3576
3577 s6 = &inet->pinet6->rcv_saddr;
3578 if (ipv6_addr_type(s6) == IPV6_ADDR_MAPPED)
3579 continue;
3580
3581 if (!ipv6_addr_equal(in6, s6) &&
3582 !(ipv6_addr_equal(in6, &in6addr_any) &&
3583 !tcp_is_local6(net, s6)))
3584 continue;
3585 }
3586#endif
3587
3588 sock_hold(sk);
3589 spin_unlock_bh(lock);
3590
3591 local_bh_disable();
3592 bh_lock_sock(sk);
3593 sk->sk_err = ETIMEDOUT;
3594 sk->sk_error_report(sk);
3595
3596 tcp_done(sk);
3597 bh_unlock_sock(sk);
3598 local_bh_enable();
3599 sock_put(sk);
3600
3601 goto restart;
3602 }
3603 spin_unlock_bh(lock);
3604 }
3605
3606 return 0;
3607}