blob: b2458f26d5562d59f9bdd600dd80e9d4a1c7bec6 [file] [log] [blame]
Linus Torvalds1da177e2005-04-16 15:20:36 -07001/*
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 *
Jesper Juhl02c30a82005-05-05 16:16:16 -07008 * Authors: Ross Biro
Linus Torvalds1da177e2005-04-16 15:20:36 -07009 * 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
Joe Perchesafd465032012-03-12 07:03:32 +0000248#define pr_fmt(fmt) "TCP: " fmt
249
Ilpo Järvinen172589c2007-08-28 15:50:33 -0700250#include <linux/kernel.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700251#include <linux/module.h>
252#include <linux/types.h>
253#include <linux/fcntl.h>
254#include <linux/poll.h>
255#include <linux/init.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700256#include <linux/fs.h>
Jens Axboe9c55e012007-11-06 23:30:13 -0800257#include <linux/skbuff.h>
Andrew Morton81b23b42008-07-03 03:22:02 -0700258#include <linux/scatterlist.h>
Jens Axboe9c55e012007-11-06 23:30:13 -0800259#include <linux/splice.h>
260#include <linux/net.h>
261#include <linux/socket.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700262#include <linux/random.h>
263#include <linux/bootmem.h>
Miquel van Smoorenburg57413eb2008-06-27 17:23:57 -0700264#include <linux/highmem.h>
265#include <linux/swap.h>
David S. Millerb8059ea2006-03-25 01:36:56 -0800266#include <linux/cache.h>
Herbert Xuf4c50d92006-06-22 03:02:40 -0700267#include <linux/err.h>
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -0800268#include <linux/crypto.h>
William Allen Simpsonda5c78c2009-12-02 18:12:09 +0000269#include <linux/time.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +0900270#include <linux/slab.h>
Mike Chan5a0b3542009-01-07 11:40:42 -0800271#include <linux/uid_stat.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700272
273#include <net/icmp.h>
274#include <net/tcp.h>
275#include <net/xfrm.h>
276#include <net/ip.h>
Robert Love2365d052008-05-12 17:08:29 -0400277#include <net/ip6_route.h>
278#include <net/ipv6.h>
279#include <net/transp_v6.h>
Chris Leech1a2449a2006-05-23 18:05:53 -0700280#include <net/netdma.h>
Jens Axboe9c55e012007-11-06 23:30:13 -0800281#include <net/sock.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700282
283#include <asm/uaccess.h>
284#include <asm/ioctls.h>
285
Brian Haleyab32ea52006-09-22 14:15:41 -0700286int sysctl_tcp_fin_timeout __read_mostly = TCP_FIN_TIMEOUT;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700287
Eric Dumazetdd24c002008-11-25 21:17:14 -0800288struct percpu_counter tcp_orphan_count;
Arnaldo Carvalho de Melo0a5578c2005-08-09 20:11:41 -0700289EXPORT_SYMBOL_GPL(tcp_orphan_count);
290
David S. Millerb8059ea2006-03-25 01:36:56 -0800291int sysctl_tcp_wmem[3] __read_mostly;
292int sysctl_tcp_rmem[3] __read_mostly;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700293
Linus Torvalds1da177e2005-04-16 15:20:36 -0700294EXPORT_SYMBOL(sysctl_tcp_rmem);
295EXPORT_SYMBOL(sysctl_tcp_wmem);
296
Eric Dumazet8d987e52010-11-09 23:24:26 +0000297atomic_long_t tcp_memory_allocated; /* Current allocated memory. */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700298EXPORT_SYMBOL(tcp_memory_allocated);
Mahesh A Saptasagar7f285eb2014-02-11 13:39:05 +0530299int sysctl_tcp_delack_seg __read_mostly = TCP_DELACK_SEG;
300EXPORT_SYMBOL(sysctl_tcp_delack_seg);
301
302int sysctl_tcp_use_userconfig __read_mostly;
303EXPORT_SYMBOL(sysctl_tcp_use_userconfig);
Eric Dumazet17483762008-11-25 21:16:35 -0800304
305/*
306 * Current number of TCP sockets.
307 */
308struct percpu_counter tcp_sockets_allocated;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700309EXPORT_SYMBOL(tcp_sockets_allocated);
310
311/*
Jens Axboe9c55e012007-11-06 23:30:13 -0800312 * TCP splice context
313 */
314struct tcp_splice_state {
315 struct pipe_inode_info *pipe;
316 size_t len;
317 unsigned int flags;
318};
319
320/*
Linus Torvalds1da177e2005-04-16 15:20:36 -0700321 * Pressure flag: try to collapse.
322 * Technical note: it is used by multiple contexts non atomically.
Hideo Aoki3ab224b2007-12-31 00:11:19 -0800323 * All the __sk_mem_schedule() is of this nature: accounting
Linus Torvalds1da177e2005-04-16 15:20:36 -0700324 * is strict, actions are advisory and have some latency.
325 */
Eric Dumazet4103f8c2007-03-27 13:58:31 -0700326int tcp_memory_pressure __read_mostly;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700327EXPORT_SYMBOL(tcp_memory_pressure);
328
Pavel Emelyanov5c52ba12008-07-16 20:28:10 -0700329void tcp_enter_memory_pressure(struct sock *sk)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700330{
331 if (!tcp_memory_pressure) {
Pavel Emelyanov4e673442008-07-16 20:30:14 -0700332 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURES);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700333 tcp_memory_pressure = 1;
334 }
335}
Linus Torvalds1da177e2005-04-16 15:20:36 -0700336EXPORT_SYMBOL(tcp_enter_memory_pressure);
337
Julian Anastasovb103cf32009-10-19 10:10:40 +0000338/* Convert seconds to retransmits based on initial and max timeout */
339static u8 secs_to_retrans(int seconds, int timeout, int rto_max)
340{
341 u8 res = 0;
342
343 if (seconds > 0) {
344 int period = timeout;
345
346 res = 1;
347 while (seconds > period && res < 255) {
348 res++;
349 timeout <<= 1;
350 if (timeout > rto_max)
351 timeout = rto_max;
352 period += timeout;
353 }
354 }
355 return res;
356}
357
358/* Convert retransmits to seconds based on initial and max timeout */
359static int retrans_to_secs(u8 retrans, int timeout, int rto_max)
360{
361 int period = 0;
362
363 if (retrans > 0) {
364 period = timeout;
365 while (--retrans) {
366 timeout <<= 1;
367 if (timeout > rto_max)
368 timeout = rto_max;
369 period += timeout;
370 }
371 }
372 return period;
373}
374
Linus Torvalds1da177e2005-04-16 15:20:36 -0700375/*
Linus Torvalds1da177e2005-04-16 15:20:36 -0700376 * Wait for a TCP event.
377 *
378 * Note that we don't need to lock the socket, as the upper poll layers
379 * take care of normal races (between the test and the event) and we don't
380 * go look at any of the socket buffers directly.
381 */
382unsigned int tcp_poll(struct file *file, struct socket *sock, poll_table *wait)
383{
384 unsigned int mask;
385 struct sock *sk = sock->sk;
Eric Dumazetcf533ea2011-10-21 05:22:42 -0400386 const struct tcp_sock *tp = tcp_sk(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700387
Eric Dumazetaa395142010-04-20 13:03:51 +0000388 sock_poll_wait(file, sk_sleep(sk), wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700389 if (sk->sk_state == TCP_LISTEN)
Arnaldo Carvalho de Melodc40c7b2005-08-23 21:52:58 -0700390 return inet_csk_listen_poll(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700391
392 /* Socket is not locked. We are protected from async events
Will Newton70efce22008-07-16 20:13:43 -0700393 * by poll logic and correct handling of state changes
394 * made by other threads is impossible in any case.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700395 */
396
397 mask = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700398
399 /*
400 * POLLHUP is certainly not done right. But poll() doesn't
401 * have a notion of HUP in just one direction, and for a
402 * socket the read side is more interesting.
403 *
404 * Some poll() documentation says that POLLHUP is incompatible
405 * with the POLLOUT/POLLWR flags, so somebody should check this
406 * all. But careful, it tends to be safer to return too many
407 * bits than too few, and you can easily break real applications
408 * if you don't tell them that something has hung up!
409 *
410 * Check-me.
411 *
412 * Check number 1. POLLHUP is _UNMASKABLE_ event (see UNIX98 and
413 * our fs/select.c). It means that after we received EOF,
414 * poll always returns immediately, making impossible poll() on write()
415 * in state CLOSE_WAIT. One solution is evident --- to set POLLHUP
416 * if and only if shutdown has been made in both directions.
417 * Actually, it is interesting to look how Solaris and DUX
Will Newton70efce22008-07-16 20:13:43 -0700418 * solve this dilemma. I would prefer, if POLLHUP were maskable,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700419 * then we could set it on SND_SHUTDOWN. BTW examples given
420 * in Stevens' books assume exactly this behaviour, it explains
Will Newton70efce22008-07-16 20:13:43 -0700421 * why POLLHUP is incompatible with POLLOUT. --ANK
Linus Torvalds1da177e2005-04-16 15:20:36 -0700422 *
423 * NOTE. Check for TCP_CLOSE is added. The goal is to prevent
424 * blocking on fresh not-connected or disconnected socket. --ANK
425 */
426 if (sk->sk_shutdown == SHUTDOWN_MASK || sk->sk_state == TCP_CLOSE)
427 mask |= POLLHUP;
428 if (sk->sk_shutdown & RCV_SHUTDOWN)
Davide Libenzif348d702006-03-25 03:07:39 -0800429 mask |= POLLIN | POLLRDNORM | POLLRDHUP;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700430
431 /* Connected? */
432 if ((1 << sk->sk_state) & ~(TCPF_SYN_SENT | TCPF_SYN_RECV)) {
David S. Millerc7004482008-10-06 10:43:54 -0700433 int target = sock_rcvlowat(sk, 0, INT_MAX);
434
435 if (tp->urg_seq == tp->copied_seq &&
436 !sock_flag(sk, SOCK_URGINLINE) &&
437 tp->urg_data)
Alexandra Kossovskyb634f872010-03-18 20:29:24 -0700438 target++;
David S. Millerc7004482008-10-06 10:43:54 -0700439
Linus Torvalds1da177e2005-04-16 15:20:36 -0700440 /* Potential race condition. If read of tp below will
441 * escape above sk->sk_state, we can be illegally awaken
442 * in SYN_* states. */
David S. Millerc7004482008-10-06 10:43:54 -0700443 if (tp->rcv_nxt - tp->copied_seq >= target)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700444 mask |= POLLIN | POLLRDNORM;
445
446 if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
447 if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk)) {
448 mask |= POLLOUT | POLLWRNORM;
449 } else { /* send SIGIO later */
450 set_bit(SOCK_ASYNC_NOSPACE,
451 &sk->sk_socket->flags);
452 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
453
454 /* Race breaker. If space is freed after
455 * wspace test but before the flags are set,
456 * IO signal will be lost.
457 */
458 if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk))
459 mask |= POLLOUT | POLLWRNORM;
460 }
KOSAKI Motohirod84ba632010-08-24 16:05:48 +0000461 } else
462 mask |= POLLOUT | POLLWRNORM;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700463
464 if (tp->urg_data & TCP_URG_VALID)
465 mask |= POLLPRI;
466 }
Tom Marshalla4d25802010-09-20 15:42:05 -0700467 /* This barrier is coupled with smp_wmb() in tcp_reset() */
468 smp_rmb();
469 if (sk->sk_err)
470 mask |= POLLERR;
471
Linus Torvalds1da177e2005-04-16 15:20:36 -0700472 return mask;
473}
Eric Dumazet4bc2f182010-07-09 21:22:10 +0000474EXPORT_SYMBOL(tcp_poll);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700475
476int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg)
477{
478 struct tcp_sock *tp = tcp_sk(sk);
479 int answ;
480
481 switch (cmd) {
482 case SIOCINQ:
483 if (sk->sk_state == TCP_LISTEN)
484 return -EINVAL;
485
486 lock_sock(sk);
487 if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
488 answ = 0;
489 else if (sock_flag(sk, SOCK_URGINLINE) ||
490 !tp->urg_data ||
491 before(tp->urg_seq, tp->copied_seq) ||
492 !before(tp->urg_seq, tp->rcv_nxt)) {
David S. Miller91521942009-05-28 21:35:47 -0700493
Linus Torvalds1da177e2005-04-16 15:20:36 -0700494 answ = tp->rcv_nxt - tp->copied_seq;
495
Eric Dumazet95e6a272012-10-18 09:14:12 +0000496 /* Subtract 1, if FIN was received */
497 if (answ && sock_flag(sk, SOCK_DONE))
498 answ--;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700499 } else
500 answ = tp->urg_seq - tp->copied_seq;
501 release_sock(sk);
502 break;
503 case SIOCATMARK:
504 answ = tp->urg_data && tp->urg_seq == tp->copied_seq;
505 break;
506 case SIOCOUTQ:
507 if (sk->sk_state == TCP_LISTEN)
508 return -EINVAL;
509
510 if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
511 answ = 0;
512 else
513 answ = tp->write_seq - tp->snd_una;
514 break;
Mario Schuknecht2f4e1b32011-03-09 14:08:09 -0800515 case SIOCOUTQNSD:
516 if (sk->sk_state == TCP_LISTEN)
517 return -EINVAL;
518
519 if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
520 answ = 0;
521 else
522 answ = tp->write_seq - tp->snd_nxt;
523 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700524 default:
525 return -ENOIOCTLCMD;
Stephen Hemminger3ff50b72007-04-20 17:09:22 -0700526 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700527
528 return put_user(answ, (int __user *)arg);
529}
Eric Dumazet4bc2f182010-07-09 21:22:10 +0000530EXPORT_SYMBOL(tcp_ioctl);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700531
Linus Torvalds1da177e2005-04-16 15:20:36 -0700532static inline void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb)
533{
Eric Dumazet4de075e2011-09-27 13:25:05 -0400534 TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700535 tp->pushed_seq = tp->write_seq;
536}
537
Eric Dumazetcf533ea2011-10-21 05:22:42 -0400538static inline int forced_push(const struct tcp_sock *tp)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700539{
540 return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1));
541}
542
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -0700543static inline void skb_entail(struct sock *sk, struct sk_buff *skb)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700544{
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -0700545 struct tcp_sock *tp = tcp_sk(sk);
Arnaldo Carvalho de Melo352d4802006-11-17 19:59:12 -0200546 struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
547
548 skb->csum = 0;
549 tcb->seq = tcb->end_seq = tp->write_seq;
Eric Dumazet4de075e2011-09-27 13:25:05 -0400550 tcb->tcp_flags = TCPHDR_ACK;
Arnaldo Carvalho de Melo352d4802006-11-17 19:59:12 -0200551 tcb->sacked = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700552 skb_header_release(skb);
David S. Millerfe067e82007-03-07 12:12:44 -0800553 tcp_add_write_queue_tail(sk, skb);
Hideo Aoki3ab224b2007-12-31 00:11:19 -0800554 sk->sk_wmem_queued += skb->truesize;
555 sk_mem_charge(sk, skb->truesize);
David S. Miller89ebd192005-08-23 10:13:06 -0700556 if (tp->nonagle & TCP_NAGLE_PUSH)
YOSHIFUJI Hideakie905a9e2007-02-09 23:24:47 +0900557 tp->nonagle &= ~TCP_NAGLE_PUSH;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700558}
559
Krishna Kumarafeca342009-12-10 07:16:52 +0000560static inline void tcp_mark_urg(struct tcp_sock *tp, int flags)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700561{
Ilpo Järvinen33f5f572008-10-07 14:43:06 -0700562 if (flags & MSG_OOB)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700563 tp->snd_up = tp->write_seq;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700564}
565
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -0700566static inline void tcp_push(struct sock *sk, int flags, int mss_now,
567 int nonagle)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700568{
David S. Millerfe067e82007-03-07 12:12:44 -0800569 if (tcp_send_head(sk)) {
Krishna Kumarafeca342009-12-10 07:16:52 +0000570 struct tcp_sock *tp = tcp_sk(sk);
571
Linus Torvalds1da177e2005-04-16 15:20:36 -0700572 if (!(flags & MSG_MORE) || forced_push(tp))
Krishna Kumarafeca342009-12-10 07:16:52 +0000573 tcp_mark_push(tp, tcp_write_queue_tail(sk));
574
575 tcp_mark_urg(tp, flags);
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -0700576 __tcp_push_pending_frames(sk, mss_now,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700577 (flags & MSG_MORE) ? TCP_NAGLE_CORK : nonagle);
578 }
579}
580
Adrian Bunk6ff77512007-11-06 23:32:26 -0800581static int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
582 unsigned int offset, size_t len)
Jens Axboe9c55e012007-11-06 23:30:13 -0800583{
584 struct tcp_splice_state *tss = rd_desc->arg.data;
Willy Tarreau33966dd2009-01-13 16:04:36 -0800585 int ret;
Jens Axboe9c55e012007-11-06 23:30:13 -0800586
Dimitris Michailidis9fa5fdf2009-01-26 22:15:31 -0800587 ret = skb_splice_bits(skb, offset, tss->pipe, min(rd_desc->count, len),
588 tss->flags);
Willy Tarreau33966dd2009-01-13 16:04:36 -0800589 if (ret > 0)
590 rd_desc->count -= ret;
591 return ret;
Jens Axboe9c55e012007-11-06 23:30:13 -0800592}
593
594static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss)
595{
596 /* Store TCP splice context information in read_descriptor_t. */
597 read_descriptor_t rd_desc = {
598 .arg.data = tss,
Willy Tarreau33966dd2009-01-13 16:04:36 -0800599 .count = tss->len,
Jens Axboe9c55e012007-11-06 23:30:13 -0800600 };
601
602 return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv);
603}
604
605/**
606 * tcp_splice_read - splice data from TCP socket to a pipe
607 * @sock: socket to splice from
608 * @ppos: position (not valid)
609 * @pipe: pipe to splice to
610 * @len: number of bytes to splice
611 * @flags: splice modifier flags
612 *
613 * Description:
614 * Will read pages from given socket and fill them into a pipe.
615 *
616 **/
617ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
618 struct pipe_inode_info *pipe, size_t len,
619 unsigned int flags)
620{
621 struct sock *sk = sock->sk;
622 struct tcp_splice_state tss = {
623 .pipe = pipe,
624 .len = len,
625 .flags = flags,
626 };
627 long timeo;
628 ssize_t spliced;
629 int ret;
630
Changli Gao3a047bf2010-07-12 21:00:12 +0000631 sock_rps_record_flow(sk);
Jens Axboe9c55e012007-11-06 23:30:13 -0800632 /*
633 * We can't seek on a socket input
634 */
635 if (unlikely(*ppos))
636 return -ESPIPE;
637
638 ret = spliced = 0;
639
640 lock_sock(sk);
641
Eric Dumazet42324c62009-10-01 15:26:00 -0700642 timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK);
Jens Axboe9c55e012007-11-06 23:30:13 -0800643 while (tss.len) {
644 ret = __tcp_splice_read(sk, &tss);
645 if (ret < 0)
646 break;
647 else if (!ret) {
648 if (spliced)
649 break;
Jens Axboe9c55e012007-11-06 23:30:13 -0800650 if (sock_flag(sk, SOCK_DONE))
651 break;
652 if (sk->sk_err) {
653 ret = sock_error(sk);
654 break;
655 }
656 if (sk->sk_shutdown & RCV_SHUTDOWN)
657 break;
658 if (sk->sk_state == TCP_CLOSE) {
659 /*
660 * This occurs when user tries to read
661 * from never connected socket.
662 */
663 if (!sock_flag(sk, SOCK_DONE))
664 ret = -ENOTCONN;
665 break;
666 }
667 if (!timeo) {
668 ret = -EAGAIN;
669 break;
670 }
671 sk_wait_data(sk, &timeo);
672 if (signal_pending(current)) {
673 ret = sock_intr_errno(timeo);
674 break;
675 }
676 continue;
677 }
678 tss.len -= ret;
679 spliced += ret;
680
Willy Tarreau33966dd2009-01-13 16:04:36 -0800681 if (!timeo)
682 break;
Jens Axboe9c55e012007-11-06 23:30:13 -0800683 release_sock(sk);
684 lock_sock(sk);
685
686 if (sk->sk_err || sk->sk_state == TCP_CLOSE ||
Willy Tarreau33966dd2009-01-13 16:04:36 -0800687 (sk->sk_shutdown & RCV_SHUTDOWN) ||
Jens Axboe9c55e012007-11-06 23:30:13 -0800688 signal_pending(current))
689 break;
690 }
691
692 release_sock(sk);
693
694 if (spliced)
695 return spliced;
696
697 return ret;
698}
Eric Dumazet4bc2f182010-07-09 21:22:10 +0000699EXPORT_SYMBOL(tcp_splice_read);
Jens Axboe9c55e012007-11-06 23:30:13 -0800700
Pavel Emelyanovdf97c702007-11-29 21:22:33 +1100701struct sk_buff *sk_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp)
Pavel Emelyanovf561d0f2007-11-29 20:28:50 +1100702{
703 struct sk_buff *skb;
704
705 /* The TCP header must be at least 32-bit aligned. */
706 size = ALIGN(size, 4);
707
708 skb = alloc_skb_fclone(size + sk->sk_prot->max_header, gfp);
709 if (skb) {
Hideo Aoki3ab224b2007-12-31 00:11:19 -0800710 if (sk_wmem_schedule(sk, skb->truesize)) {
Eric Dumazeta21d4572012-04-10 20:30:48 +0000711 skb_reserve(skb, sk->sk_prot->max_header);
Pavel Emelyanovf561d0f2007-11-29 20:28:50 +1100712 /*
713 * Make sure that we have exactly size bytes
714 * available to the caller, no more, no less.
715 */
Eric Dumazeta21d4572012-04-10 20:30:48 +0000716 skb->avail_size = size;
Pavel Emelyanovf561d0f2007-11-29 20:28:50 +1100717 return skb;
718 }
719 __kfree_skb(skb);
720 } else {
Pavel Emelyanov5c52ba12008-07-16 20:28:10 -0700721 sk->sk_prot->enter_memory_pressure(sk);
Pavel Emelyanovf561d0f2007-11-29 20:28:50 +1100722 sk_stream_moderate_sndbuf(sk);
723 }
724 return NULL;
725}
726
Ilpo Järvinen0c54b852009-03-14 14:23:05 +0000727static unsigned int tcp_xmit_size_goal(struct sock *sk, u32 mss_now,
728 int large_allowed)
729{
730 struct tcp_sock *tp = tcp_sk(sk);
Ilpo Järvinen2a3a0412009-03-14 22:45:16 +0000731 u32 xmit_size_goal, old_size_goal;
Ilpo Järvinen0c54b852009-03-14 14:23:05 +0000732
733 xmit_size_goal = mss_now;
734
735 if (large_allowed && sk_can_gso(sk)) {
736 xmit_size_goal = ((sk->sk_gso_max_size - 1) -
737 inet_csk(sk)->icsk_af_ops->net_header_len -
738 inet_csk(sk)->icsk_ext_hdr_len -
739 tp->tcp_header_len);
740
741 xmit_size_goal = tcp_bound_to_half_wnd(tp, xmit_size_goal);
Ilpo Järvinen2a3a0412009-03-14 22:45:16 +0000742
743 /* We try hard to avoid divides here */
744 old_size_goal = tp->xmit_size_goal_segs * mss_now;
745
746 if (likely(old_size_goal <= xmit_size_goal &&
747 old_size_goal + mss_now > xmit_size_goal)) {
748 xmit_size_goal = old_size_goal;
749 } else {
750 tp->xmit_size_goal_segs = xmit_size_goal / mss_now;
751 xmit_size_goal = tp->xmit_size_goal_segs * mss_now;
752 }
Ilpo Järvinen0c54b852009-03-14 14:23:05 +0000753 }
754
Ilpo Järvinenafece1c2009-03-14 14:23:07 +0000755 return max(xmit_size_goal, mss_now);
Ilpo Järvinen0c54b852009-03-14 14:23:05 +0000756}
757
758static int tcp_send_mss(struct sock *sk, int *size_goal, int flags)
759{
760 int mss_now;
761
762 mss_now = tcp_current_mss(sk);
763 *size_goal = tcp_xmit_size_goal(sk, mss_now, !(flags & MSG_OOB));
764
765 return mss_now;
766}
767
Linus Torvalds1da177e2005-04-16 15:20:36 -0700768static ssize_t do_tcp_sendpages(struct sock *sk, struct page **pages, int poffset,
769 size_t psize, int flags)
770{
771 struct tcp_sock *tp = tcp_sk(sk);
David S. Millerc1b4a7e2005-07-05 15:24:38 -0700772 int mss_now, size_goal;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700773 int err;
774 ssize_t copied;
775 long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
776
777 /* Wait for a connection to finish. */
778 if ((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT))
779 if ((err = sk_stream_wait_connect(sk, &timeo)) != 0)
780 goto out_err;
781
782 clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
783
Ilpo Järvinen0c54b852009-03-14 14:23:05 +0000784 mss_now = tcp_send_mss(sk, &size_goal, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700785 copied = 0;
786
787 err = -EPIPE;
788 if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
Ilpo Järvinen0d6a7752009-02-28 04:44:41 +0000789 goto out_err;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700790
791 while (psize > 0) {
David S. Millerfe067e82007-03-07 12:12:44 -0800792 struct sk_buff *skb = tcp_write_queue_tail(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700793 struct page *page = pages[poffset / PAGE_SIZE];
794 int copy, i, can_coalesce;
795 int offset = poffset % PAGE_SIZE;
796 int size = min_t(size_t, psize, PAGE_SIZE - offset);
797
David S. Millerfe067e82007-03-07 12:12:44 -0800798 if (!tcp_send_head(sk) || (copy = size_goal - skb->len) <= 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700799new_segment:
800 if (!sk_stream_memory_free(sk))
801 goto wait_for_sndbuf;
802
Pavel Emelyanovdf97c702007-11-29 21:22:33 +1100803 skb = sk_stream_alloc_skb(sk, 0, sk->sk_allocation);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700804 if (!skb)
805 goto wait_for_memory;
806
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -0700807 skb_entail(sk, skb);
David S. Millerc1b4a7e2005-07-05 15:24:38 -0700808 copy = size_goal;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700809 }
810
811 if (copy > size)
812 copy = size;
813
814 i = skb_shinfo(skb)->nr_frags;
815 can_coalesce = skb_can_coalesce(skb, i, page, offset);
816 if (!can_coalesce && i >= MAX_SKB_FRAGS) {
817 tcp_mark_push(tp, skb);
818 goto new_segment;
819 }
Hideo Aoki3ab224b2007-12-31 00:11:19 -0800820 if (!sk_wmem_schedule(sk, copy))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700821 goto wait_for_memory;
YOSHIFUJI Hideakie905a9e2007-02-09 23:24:47 +0900822
Linus Torvalds1da177e2005-04-16 15:20:36 -0700823 if (can_coalesce) {
Eric Dumazet9e903e02011-10-18 21:00:24 +0000824 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700825 } else {
826 get_page(page);
827 skb_fill_page_desc(skb, i, page, offset, copy);
828 }
829
830 skb->len += copy;
831 skb->data_len += copy;
832 skb->truesize += copy;
833 sk->sk_wmem_queued += copy;
Hideo Aoki3ab224b2007-12-31 00:11:19 -0800834 sk_mem_charge(sk, copy);
Patrick McHardy84fa7932006-08-29 16:44:56 -0700835 skb->ip_summed = CHECKSUM_PARTIAL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700836 tp->write_seq += copy;
837 TCP_SKB_CB(skb)->end_seq += copy;
Herbert Xu79671682006-06-22 02:40:14 -0700838 skb_shinfo(skb)->gso_segs = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700839
840 if (!copied)
Eric Dumazet4de075e2011-09-27 13:25:05 -0400841 TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700842
843 copied += copy;
844 poffset += copy;
845 if (!(psize -= copy))
846 goto out;
847
Herbert Xu69d15062008-03-22 15:47:05 -0700848 if (skb->len < size_goal || (flags & MSG_OOB))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700849 continue;
850
851 if (forced_push(tp)) {
852 tcp_mark_push(tp, skb);
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -0700853 __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
David S. Millerfe067e82007-03-07 12:12:44 -0800854 } else if (skb == tcp_send_head(sk))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700855 tcp_push_one(sk, mss_now);
856 continue;
857
858wait_for_sndbuf:
859 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
860wait_for_memory:
Willy Tarreaubad115c2012-05-17 11:14:14 +0000861 tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700862
863 if ((err = sk_stream_wait_memory(sk, &timeo)) != 0)
864 goto do_error;
865
Ilpo Järvinen0c54b852009-03-14 14:23:05 +0000866 mss_now = tcp_send_mss(sk, &size_goal, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700867 }
868
869out:
Eric Dumazet35f9c092012-04-05 03:05:35 +0000870 if (copied && !(flags & MSG_SENDPAGE_NOTLAST))
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -0700871 tcp_push(sk, flags, mss_now, tp->nonagle);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700872 return copied;
873
874do_error:
875 if (copied)
876 goto out;
877out_err:
878 return sk_stream_error(sk, flags, err);
879}
880
Changli Gao7ba42912010-07-10 20:41:55 +0000881int tcp_sendpage(struct sock *sk, struct page *page, int offset,
882 size_t size, int flags)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700883{
884 ssize_t res;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700885
Linus Torvalds1da177e2005-04-16 15:20:36 -0700886 if (!(sk->sk_route_caps & NETIF_F_SG) ||
Herbert Xu8648b302006-06-17 22:06:05 -0700887 !(sk->sk_route_caps & NETIF_F_ALL_CSUM))
Changli Gao7ba42912010-07-10 20:41:55 +0000888 return sock_no_sendpage(sk->sk_socket, page, offset, size,
889 flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700890
Linus Torvalds1da177e2005-04-16 15:20:36 -0700891 lock_sock(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700892 res = do_tcp_sendpages(sk, &page, offset, size, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700893 release_sock(sk);
894 return res;
895}
Eric Dumazet4bc2f182010-07-09 21:22:10 +0000896EXPORT_SYMBOL(tcp_sendpage);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700897
Eric Dumazet690e99c2011-11-28 00:27:47 +0000898static inline int select_size(const struct sock *sk, bool sg)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700899{
Eric Dumazetcf533ea2011-10-21 05:22:42 -0400900 const struct tcp_sock *tp = tcp_sk(sk);
David S. Millerc1b4a7e2005-07-05 15:24:38 -0700901 int tmp = tp->mss_cache;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700902
Krishna Kumardef87cf2009-12-10 07:16:59 +0000903 if (sg) {
Eric Dumazetf07d9602011-11-28 22:41:47 +0000904 if (sk_can_gso(sk)) {
905 /* Small frames wont use a full page:
906 * Payload will immediately follow tcp header.
907 */
908 tmp = SKB_WITH_OVERHEAD(2048 - MAX_TCP_HEADER);
909 } else {
David S. Millerb4e26f52005-07-05 15:20:27 -0700910 int pgbreak = SKB_MAX_HEAD(MAX_TCP_HEADER);
911
912 if (tmp >= pgbreak &&
913 tmp <= pgbreak + (MAX_SKB_FRAGS - 1) * PAGE_SIZE)
914 tmp = pgbreak;
915 }
916 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700917
Linus Torvalds1da177e2005-04-16 15:20:36 -0700918 return tmp;
919}
920
Changli Gao7ba42912010-07-10 20:41:55 +0000921int tcp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700922 size_t size)
923{
924 struct iovec *iov;
925 struct tcp_sock *tp = tcp_sk(sk);
926 struct sk_buff *skb;
Eric Dumazet690e99c2011-11-28 00:27:47 +0000927 int iovlen, flags, err, copied;
David S. Millerc1b4a7e2005-07-05 15:24:38 -0700928 int mss_now, size_goal;
Eric Dumazet690e99c2011-11-28 00:27:47 +0000929 bool sg;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700930 long timeo;
931
932 lock_sock(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700933
934 flags = msg->msg_flags;
935 timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
936
937 /* Wait for a connection to finish. */
938 if ((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT))
939 if ((err = sk_stream_wait_connect(sk, &timeo)) != 0)
940 goto out_err;
941
942 /* This should be in poll */
943 clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
944
Ilpo Järvinen0c54b852009-03-14 14:23:05 +0000945 mss_now = tcp_send_mss(sk, &size_goal, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700946
947 /* Ok commence sending. */
948 iovlen = msg->msg_iovlen;
949 iov = msg->msg_iov;
950 copied = 0;
951
952 err = -EPIPE;
953 if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
Ilpo Järvinen0d6a7752009-02-28 04:44:41 +0000954 goto out_err;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700955
Eric Dumazet690e99c2011-11-28 00:27:47 +0000956 sg = !!(sk->sk_route_caps & NETIF_F_SG);
Krishna Kumardef87cf2009-12-10 07:16:59 +0000957
Linus Torvalds1da177e2005-04-16 15:20:36 -0700958 while (--iovlen >= 0) {
David S. Miller01db4032010-09-27 20:24:54 -0700959 size_t seglen = iov->iov_len;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700960 unsigned char __user *from = iov->iov_base;
961
962 iov++;
963
964 while (seglen > 0) {
Herbert Xu6828b922009-06-28 18:06:41 +0000965 int copy = 0;
966 int max = size_goal;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700967
David S. Millerfe067e82007-03-07 12:12:44 -0800968 skb = tcp_write_queue_tail(sk);
Herbert Xu6828b922009-06-28 18:06:41 +0000969 if (tcp_send_head(sk)) {
970 if (skb->ip_summed == CHECKSUM_NONE)
971 max = mss_now;
972 copy = max - skb->len;
973 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700974
Herbert Xu6828b922009-06-28 18:06:41 +0000975 if (copy <= 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700976new_segment:
977 /* Allocate new segment. If the interface is SG,
978 * allocate skb fitting to single page.
979 */
980 if (!sk_stream_memory_free(sk))
981 goto wait_for_sndbuf;
982
Krishna Kumardef87cf2009-12-10 07:16:59 +0000983 skb = sk_stream_alloc_skb(sk,
984 select_size(sk, sg),
985 sk->sk_allocation);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700986 if (!skb)
987 goto wait_for_memory;
988
989 /*
990 * Check whether we can use HW checksum.
991 */
Herbert Xu8648b302006-06-17 22:06:05 -0700992 if (sk->sk_route_caps & NETIF_F_ALL_CSUM)
Patrick McHardy84fa7932006-08-29 16:44:56 -0700993 skb->ip_summed = CHECKSUM_PARTIAL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700994
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -0700995 skb_entail(sk, skb);
David S. Millerc1b4a7e2005-07-05 15:24:38 -0700996 copy = size_goal;
Herbert Xu6828b922009-06-28 18:06:41 +0000997 max = size_goal;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700998 }
999
1000 /* Try to append data to the end of skb. */
1001 if (copy > seglen)
1002 copy = seglen;
1003
1004 /* Where to copy to? */
Eric Dumazeta21d4572012-04-10 20:30:48 +00001005 if (skb_availroom(skb) > 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001006 /* We have some space in skb head. Superb! */
Eric Dumazeta21d4572012-04-10 20:30:48 +00001007 copy = min_t(int, copy, skb_availroom(skb));
Tom Herbertc6e1a0d2011-04-04 22:30:30 -07001008 err = skb_add_data_nocache(sk, skb, from, copy);
1009 if (err)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001010 goto do_fault;
1011 } else {
1012 int merge = 0;
1013 int i = skb_shinfo(skb)->nr_frags;
Eric Dumazet0a5912d2011-12-05 01:07:15 +00001014 struct page *page = sk->sk_sndmsg_page;
Eric Dumazet761965e2011-12-04 07:05:17 +00001015 int off;
1016
1017 if (page && page_count(page) == 1)
Eric Dumazet0a5912d2011-12-05 01:07:15 +00001018 sk->sk_sndmsg_off = 0;
Eric Dumazet761965e2011-12-04 07:05:17 +00001019
Eric Dumazet0a5912d2011-12-05 01:07:15 +00001020 off = sk->sk_sndmsg_off;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001021
1022 if (skb_can_coalesce(skb, i, page, off) &&
1023 off != PAGE_SIZE) {
1024 /* We can extend the last page
1025 * fragment. */
1026 merge = 1;
Krishna Kumardef87cf2009-12-10 07:16:59 +00001027 } else if (i == MAX_SKB_FRAGS || !sg) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001028 /* Need to add new fragment and cannot
1029 * do this because interface is non-SG,
1030 * or because all the page slots are
1031 * busy. */
1032 tcp_mark_push(tp, skb);
1033 goto new_segment;
1034 } else if (page) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001035 if (off == PAGE_SIZE) {
1036 put_page(page);
Eric Dumazet0a5912d2011-12-05 01:07:15 +00001037 sk->sk_sndmsg_page = page = NULL;
Herbert Xufb5f5e62005-09-05 18:55:48 -07001038 off = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001039 }
Herbert Xuef015782005-09-01 17:48:59 -07001040 } else
Herbert Xufb5f5e62005-09-05 18:55:48 -07001041 off = 0;
Herbert Xuef015782005-09-01 17:48:59 -07001042
1043 if (copy > PAGE_SIZE - off)
1044 copy = PAGE_SIZE - off;
1045
Hideo Aoki3ab224b2007-12-31 00:11:19 -08001046 if (!sk_wmem_schedule(sk, copy))
Herbert Xuef015782005-09-01 17:48:59 -07001047 goto wait_for_memory;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001048
1049 if (!page) {
1050 /* Allocate new cache page. */
1051 if (!(page = sk_stream_alloc_page(sk)))
1052 goto wait_for_memory;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001053 }
1054
Linus Torvalds1da177e2005-04-16 15:20:36 -07001055 /* Time to copy data. We are close to
1056 * the end! */
Tom Herbertc6e1a0d2011-04-04 22:30:30 -07001057 err = skb_copy_to_page_nocache(sk, from, skb,
1058 page, off, copy);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001059 if (err) {
1060 /* If this page was new, give it to the
1061 * socket so it does not get leaked.
1062 */
Eric Dumazet0a5912d2011-12-05 01:07:15 +00001063 if (!sk->sk_sndmsg_page) {
1064 sk->sk_sndmsg_page = page;
1065 sk->sk_sndmsg_off = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001066 }
1067 goto do_error;
1068 }
1069
1070 /* Update the skb. */
1071 if (merge) {
Eric Dumazet9e903e02011-10-18 21:00:24 +00001072 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001073 } else {
1074 skb_fill_page_desc(skb, i, page, off, copy);
Eric Dumazet0a5912d2011-12-05 01:07:15 +00001075 if (sk->sk_sndmsg_page) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001076 get_page(page);
1077 } else if (off + copy < PAGE_SIZE) {
1078 get_page(page);
Eric Dumazet0a5912d2011-12-05 01:07:15 +00001079 sk->sk_sndmsg_page = page;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001080 }
1081 }
1082
Eric Dumazet0a5912d2011-12-05 01:07:15 +00001083 sk->sk_sndmsg_off = off + copy;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001084 }
1085
1086 if (!copied)
Eric Dumazet4de075e2011-09-27 13:25:05 -04001087 TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001088
1089 tp->write_seq += copy;
1090 TCP_SKB_CB(skb)->end_seq += copy;
Herbert Xu79671682006-06-22 02:40:14 -07001091 skb_shinfo(skb)->gso_segs = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001092
1093 from += copy;
1094 copied += copy;
1095 if ((seglen -= copy) == 0 && iovlen == 0)
1096 goto out;
1097
Herbert Xu6828b922009-06-28 18:06:41 +00001098 if (skb->len < max || (flags & MSG_OOB))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001099 continue;
1100
1101 if (forced_push(tp)) {
1102 tcp_mark_push(tp, skb);
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -07001103 __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
David S. Millerfe067e82007-03-07 12:12:44 -08001104 } else if (skb == tcp_send_head(sk))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001105 tcp_push_one(sk, mss_now);
1106 continue;
1107
1108wait_for_sndbuf:
1109 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1110wait_for_memory:
1111 if (copied)
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -07001112 tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001113
1114 if ((err = sk_stream_wait_memory(sk, &timeo)) != 0)
1115 goto do_error;
1116
Ilpo Järvinen0c54b852009-03-14 14:23:05 +00001117 mss_now = tcp_send_mss(sk, &size_goal, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001118 }
1119 }
1120
1121out:
1122 if (copied)
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -07001123 tcp_push(sk, flags, mss_now, tp->nonagle);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001124 release_sock(sk);
Mike Chan5a0b3542009-01-07 11:40:42 -08001125
1126 if (copied > 0)
1127 uid_stat_tcp_snd(current_uid(), copied);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001128 return copied;
1129
1130do_fault:
1131 if (!skb->len) {
David S. Millerfe067e82007-03-07 12:12:44 -08001132 tcp_unlink_write_queue(skb, sk);
1133 /* It is the one place in all of TCP, except connection
1134 * reset, where we can be unlinking the send_head.
1135 */
1136 tcp_check_send_head(sk, skb);
Hideo Aoki3ab224b2007-12-31 00:11:19 -08001137 sk_wmem_free_skb(sk, skb);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001138 }
1139
1140do_error:
1141 if (copied)
1142 goto out;
1143out_err:
1144 err = sk_stream_error(sk, flags, err);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001145 release_sock(sk);
1146 return err;
1147}
Eric Dumazet4bc2f182010-07-09 21:22:10 +00001148EXPORT_SYMBOL(tcp_sendmsg);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001149
1150/*
1151 * Handle reading urgent data. BSD has very simple semantics for
1152 * this, no blocking and very strange errors 8)
1153 */
1154
Rami Rosen377f0a02009-03-31 14:43:17 -07001155static int tcp_recv_urg(struct sock *sk, struct msghdr *msg, int len, int flags)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001156{
1157 struct tcp_sock *tp = tcp_sk(sk);
1158
1159 /* No URG data to read. */
1160 if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data ||
1161 tp->urg_data == TCP_URG_READ)
1162 return -EINVAL; /* Yes this is right ! */
1163
1164 if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE))
1165 return -ENOTCONN;
1166
1167 if (tp->urg_data & TCP_URG_VALID) {
1168 int err = 0;
1169 char c = tp->urg_data;
1170
1171 if (!(flags & MSG_PEEK))
1172 tp->urg_data = TCP_URG_READ;
1173
1174 /* Read urgent data. */
1175 msg->msg_flags |= MSG_OOB;
1176
1177 if (len > 0) {
1178 if (!(flags & MSG_TRUNC))
1179 err = memcpy_toiovec(msg->msg_iov, &c, 1);
1180 len = 1;
1181 } else
1182 msg->msg_flags |= MSG_TRUNC;
1183
1184 return err ? -EFAULT : len;
1185 }
1186
1187 if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN))
1188 return 0;
1189
1190 /* Fixed the recv(..., MSG_OOB) behaviour. BSD docs and
1191 * the available implementations agree in this case:
1192 * this call should never block, independent of the
1193 * blocking state of the socket.
1194 * Mike <pall@rz.uni-karlsruhe.de>
1195 */
1196 return -EAGAIN;
1197}
1198
1199/* Clean up the receive buffer for full frames taken by the user,
1200 * then send an ACK if necessary. COPIED is the number of bytes
1201 * tcp_recvmsg has given to the user so far, it speeds up the
1202 * calculation of whether or not we must ACK for the sake of
1203 * a window update.
1204 */
Chris Leech0e4b4992006-05-23 18:00:16 -07001205void tcp_cleanup_rbuf(struct sock *sk, int copied)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001206{
1207 struct tcp_sock *tp = tcp_sk(sk);
1208 int time_to_ack = 0;
1209
Linus Torvalds1da177e2005-04-16 15:20:36 -07001210 struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
1211
Ilpo Järvinend792c102009-11-13 13:56:33 -08001212 WARN(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq),
Joe Perches2af6fd82010-10-30 11:08:53 +00001213 "cleanup rbuf bug: copied %X seq %X rcvnxt %X\n",
Ilpo Järvinend792c102009-11-13 13:56:33 -08001214 tp->copied_seq, TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001215
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07001216 if (inet_csk_ack_scheduled(sk)) {
1217 const struct inet_connection_sock *icsk = inet_csk(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001218 /* Delayed ACKs frequently hit locked sockets during bulk
1219 * receive. */
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07001220 if (icsk->icsk_ack.blocked ||
Mahesh A Saptasagar7f285eb2014-02-11 13:39:05 +05301221 /* Once-per-sysctl_tcp_delack_segments
1222 * ACK was not sent by tcp_input.c
1223 */
1224 tp->rcv_nxt - tp->rcv_wup > (icsk->icsk_ack.rcv_mss) *
1225 sysctl_tcp_delack_seg ||
Linus Torvalds1da177e2005-04-16 15:20:36 -07001226 /*
1227 * If this read emptied read buffer, we send ACK, if
1228 * connection is not bidirectional, user drained
1229 * receive buffer and there was a small segment
1230 * in queue.
1231 */
Alexey Kuznetsov1ef96962006-09-19 12:52:50 -07001232 (copied > 0 &&
1233 ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) ||
1234 ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) &&
1235 !icsk->icsk_ack.pingpong)) &&
1236 !atomic_read(&sk->sk_rmem_alloc)))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001237 time_to_ack = 1;
1238 }
1239
1240 /* We send an ACK if we can now advertise a non-zero window
1241 * which has been raised "significantly".
1242 *
1243 * Even if window raised up to infinity, do not send window open ACK
1244 * in states, where we will not receive more. It is useless.
1245 */
1246 if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
1247 __u32 rcv_window_now = tcp_receive_window(tp);
1248
1249 /* Optimize, __tcp_select_window() is not cheap. */
1250 if (2*rcv_window_now <= tp->window_clamp) {
1251 __u32 new_window = __tcp_select_window(sk);
1252
1253 /* Send ACK now, if this read freed lots of space
1254 * in our buffer. Certainly, new_window is new window.
1255 * We can advertise it now, if it is not less than current one.
1256 * "Lots" means "at least twice" here.
1257 */
1258 if (new_window && new_window >= 2 * rcv_window_now)
1259 time_to_ack = 1;
1260 }
1261 }
1262 if (time_to_ack)
1263 tcp_send_ack(sk);
1264}
1265
1266static void tcp_prequeue_process(struct sock *sk)
1267{
1268 struct sk_buff *skb;
1269 struct tcp_sock *tp = tcp_sk(sk);
1270
Pavel Emelyanov6f67c812008-07-16 20:31:39 -07001271 NET_INC_STATS_USER(sock_net(sk), LINUX_MIB_TCPPREQUEUED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001272
1273 /* RX process wants to run with disabled BHs, though it is not
1274 * necessary */
1275 local_bh_disable();
1276 while ((skb = __skb_dequeue(&tp->ucopy.prequeue)) != NULL)
Peter Zijlstrac57943a2008-10-07 14:18:42 -07001277 sk_backlog_rcv(sk, skb);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001278 local_bh_enable();
1279
1280 /* Clear memory counter. */
1281 tp->ucopy.memory = 0;
1282}
1283
Steven J. Magnani73852e82010-03-16 05:22:44 +00001284#ifdef CONFIG_NET_DMA
1285static void tcp_service_net_dma(struct sock *sk, bool wait)
1286{
1287 dma_cookie_t done, used;
1288 dma_cookie_t last_issued;
1289 struct tcp_sock *tp = tcp_sk(sk);
1290
1291 if (!tp->ucopy.dma_chan)
1292 return;
1293
1294 last_issued = tp->ucopy.dma_cookie;
1295 dma_async_memcpy_issue_pending(tp->ucopy.dma_chan);
1296
1297 do {
1298 if (dma_async_memcpy_complete(tp->ucopy.dma_chan,
1299 last_issued, &done,
1300 &used) == DMA_SUCCESS) {
1301 /* Safe to free early-copied skbs now */
1302 __skb_queue_purge(&sk->sk_async_wait_queue);
1303 break;
1304 } else {
1305 struct sk_buff *skb;
1306 while ((skb = skb_peek(&sk->sk_async_wait_queue)) &&
1307 (dma_async_is_complete(skb->dma_cookie, done,
1308 used) == DMA_SUCCESS)) {
1309 __skb_dequeue(&sk->sk_async_wait_queue);
1310 kfree_skb(skb);
1311 }
1312 }
1313 } while (wait);
1314}
1315#endif
1316
Linus Torvalds1da177e2005-04-16 15:20:36 -07001317static inline struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off)
1318{
1319 struct sk_buff *skb;
1320 u32 offset;
1321
1322 skb_queue_walk(&sk->sk_receive_queue, skb) {
1323 offset = seq - TCP_SKB_CB(skb)->seq;
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07001324 if (tcp_hdr(skb)->syn)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001325 offset--;
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07001326 if (offset < skb->len || tcp_hdr(skb)->fin) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001327 *off = offset;
1328 return skb;
1329 }
1330 }
1331 return NULL;
1332}
1333
1334/*
1335 * This routine provides an alternative to tcp_recvmsg() for routines
1336 * that would like to handle copying from skbuffs directly in 'sendfile'
1337 * fashion.
1338 * Note:
1339 * - It is assumed that the socket was locked by the caller.
1340 * - The routine does not block.
1341 * - At present, there is no support for reading OOB data
1342 * or for 'peeking' the socket using this routine
1343 * (although both would be easy to implement).
1344 */
1345int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
1346 sk_read_actor_t recv_actor)
1347{
1348 struct sk_buff *skb;
1349 struct tcp_sock *tp = tcp_sk(sk);
1350 u32 seq = tp->copied_seq;
1351 u32 offset;
1352 int copied = 0;
1353
1354 if (sk->sk_state == TCP_LISTEN)
1355 return -ENOTCONN;
1356 while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
1357 if (offset < skb->len) {
Octavian Purdila374e7b52008-07-03 03:31:21 -07001358 int used;
1359 size_t len;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001360
1361 len = skb->len - offset;
1362 /* Stop reading if we hit a patch of urgent data */
1363 if (tp->urg_data) {
1364 u32 urg_offset = tp->urg_seq - seq;
1365 if (urg_offset < len)
1366 len = urg_offset;
1367 if (!len)
1368 break;
1369 }
1370 used = recv_actor(desc, skb, offset, len);
Jens Axboeddb61a52007-06-23 23:07:50 -07001371 if (used < 0) {
1372 if (!copied)
1373 copied = used;
1374 break;
1375 } else if (used <= len) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001376 seq += used;
1377 copied += used;
1378 offset += used;
1379 }
Octavian Purdila293ad602008-06-04 15:45:58 -07001380 /*
1381 * If recv_actor drops the lock (e.g. TCP splice
1382 * receive) the skb pointer might be invalid when
1383 * getting here: tcp_collapse might have deleted it
1384 * while aggregating skbs from the socket queue.
1385 */
1386 skb = tcp_recv_skb(sk, seq-1, &offset);
1387 if (!skb || (offset+1 != skb->len))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001388 break;
1389 }
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07001390 if (tcp_hdr(skb)->fin) {
Chris Leech624d1162006-05-23 18:01:28 -07001391 sk_eat_skb(sk, skb, 0);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001392 ++seq;
1393 break;
1394 }
Chris Leech624d1162006-05-23 18:01:28 -07001395 sk_eat_skb(sk, skb, 0);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001396 if (!desc->count)
1397 break;
Steven J. Magnanibaff42a2010-03-30 13:56:01 -07001398 tp->copied_seq = seq;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001399 }
1400 tp->copied_seq = seq;
1401
1402 tcp_rcv_space_adjust(sk);
1403
1404 /* Clean up data we have read: This will do ACK frames. */
Mike Chan5a0b3542009-01-07 11:40:42 -08001405 if (copied > 0) {
Chris Leech0e4b4992006-05-23 18:00:16 -07001406 tcp_cleanup_rbuf(sk, copied);
Mike Chan5a0b3542009-01-07 11:40:42 -08001407 uid_stat_tcp_rcv(current_uid(), copied);
1408 }
1409
Linus Torvalds1da177e2005-04-16 15:20:36 -07001410 return copied;
1411}
Eric Dumazet4bc2f182010-07-09 21:22:10 +00001412EXPORT_SYMBOL(tcp_read_sock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001413
1414/*
1415 * This routine copies from a sock struct into the user buffer.
1416 *
1417 * Technical note: in 2.3 we work on _locked_ socket, so that
1418 * tricks with *seq access order and skb->users are not required.
1419 * Probably, code can be easily improved even more.
1420 */
1421
1422int tcp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
1423 size_t len, int nonblock, int flags, int *addr_len)
1424{
1425 struct tcp_sock *tp = tcp_sk(sk);
1426 int copied = 0;
1427 u32 peek_seq;
1428 u32 *seq;
1429 unsigned long used;
1430 int err;
1431 int target; /* Read at least this many bytes */
1432 long timeo;
1433 struct task_struct *user_recv = NULL;
Chris Leech1a2449a2006-05-23 18:05:53 -07001434 int copied_early = 0;
Chris Leech2b1244a2007-03-08 09:57:36 -08001435 struct sk_buff *skb;
Ilpo Järvinen77527312009-05-10 20:32:34 +00001436 u32 urg_hole = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001437
1438 lock_sock(sk);
1439
Linus Torvalds1da177e2005-04-16 15:20:36 -07001440 err = -ENOTCONN;
1441 if (sk->sk_state == TCP_LISTEN)
1442 goto out;
1443
1444 timeo = sock_rcvtimeo(sk, nonblock);
1445
1446 /* Urgent data needs to be handled specially. */
1447 if (flags & MSG_OOB)
1448 goto recv_urg;
1449
1450 seq = &tp->copied_seq;
1451 if (flags & MSG_PEEK) {
1452 peek_seq = tp->copied_seq;
1453 seq = &peek_seq;
1454 }
1455
1456 target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
1457
Chris Leech1a2449a2006-05-23 18:05:53 -07001458#ifdef CONFIG_NET_DMA
1459 tp->ucopy.dma_chan = NULL;
1460 preempt_disable();
Chris Leech2b1244a2007-03-08 09:57:36 -08001461 skb = skb_peek_tail(&sk->sk_receive_queue);
Andrew Mortone00c5d82007-03-08 09:57:36 -08001462 {
1463 int available = 0;
1464
1465 if (skb)
1466 available = TCP_SKB_CB(skb)->seq + skb->len - (*seq);
1467 if ((available < target) &&
1468 (len > sysctl_tcp_dma_copybreak) && !(flags & MSG_PEEK) &&
1469 !sysctl_tcp_low_latency &&
Dave Jianga2bd1142012-04-04 16:10:46 -07001470 net_dma_find_channel()) {
Andrew Mortone00c5d82007-03-08 09:57:36 -08001471 preempt_enable_no_resched();
1472 tp->ucopy.pinned_list =
1473 dma_pin_iovec_pages(msg->msg_iov, len);
1474 } else {
1475 preempt_enable_no_resched();
1476 }
1477 }
Chris Leech1a2449a2006-05-23 18:05:53 -07001478#endif
1479
Linus Torvalds1da177e2005-04-16 15:20:36 -07001480 do {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001481 u32 offset;
1482
1483 /* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */
1484 if (tp->urg_data && tp->urg_seq == *seq) {
1485 if (copied)
1486 break;
1487 if (signal_pending(current)) {
1488 copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
1489 break;
1490 }
1491 }
1492
1493 /* Next get a buffer. */
1494
David S. Miller91521942009-05-28 21:35:47 -07001495 skb_queue_walk(&sk->sk_receive_queue, skb) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001496 /* Now that we have two receive queues this
1497 * shouldn't happen.
1498 */
Ilpo Järvinend792c102009-11-13 13:56:33 -08001499 if (WARN(before(*seq, TCP_SKB_CB(skb)->seq),
Joe Perches2af6fd82010-10-30 11:08:53 +00001500 "recvmsg bug: copied %X seq %X rcvnxt %X fl %X\n",
1501 *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt,
1502 flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001503 break;
Ilpo Järvinend792c102009-11-13 13:56:33 -08001504
Linus Torvalds1da177e2005-04-16 15:20:36 -07001505 offset = *seq - TCP_SKB_CB(skb)->seq;
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07001506 if (tcp_hdr(skb)->syn)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001507 offset--;
1508 if (offset < skb->len)
1509 goto found_ok_skb;
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07001510 if (tcp_hdr(skb)->fin)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001511 goto found_fin_ok;
Joe Perches2af6fd82010-10-30 11:08:53 +00001512 WARN(!(flags & MSG_PEEK),
1513 "recvmsg bug 2: copied %X seq %X rcvnxt %X fl %X\n",
1514 *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags);
David S. Miller91521942009-05-28 21:35:47 -07001515 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001516
1517 /* Well, if we have backlog, try to process it now yet. */
1518
1519 if (copied >= target && !sk->sk_backlog.tail)
1520 break;
1521
1522 if (copied) {
1523 if (sk->sk_err ||
1524 sk->sk_state == TCP_CLOSE ||
1525 (sk->sk_shutdown & RCV_SHUTDOWN) ||
1526 !timeo ||
David S. Miller518a09e2008-11-05 03:36:01 -08001527 signal_pending(current))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001528 break;
1529 } else {
1530 if (sock_flag(sk, SOCK_DONE))
1531 break;
1532
1533 if (sk->sk_err) {
1534 copied = sock_error(sk);
1535 break;
1536 }
1537
1538 if (sk->sk_shutdown & RCV_SHUTDOWN)
1539 break;
1540
1541 if (sk->sk_state == TCP_CLOSE) {
1542 if (!sock_flag(sk, SOCK_DONE)) {
1543 /* This occurs when user tries to read
1544 * from never connected socket.
1545 */
1546 copied = -ENOTCONN;
1547 break;
1548 }
1549 break;
1550 }
1551
1552 if (!timeo) {
1553 copied = -EAGAIN;
1554 break;
1555 }
1556
1557 if (signal_pending(current)) {
1558 copied = sock_intr_errno(timeo);
1559 break;
1560 }
1561 }
1562
Chris Leech0e4b4992006-05-23 18:00:16 -07001563 tcp_cleanup_rbuf(sk, copied);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001564
David S. Miller7df55122005-06-18 23:01:10 -07001565 if (!sysctl_tcp_low_latency && tp->ucopy.task == user_recv) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001566 /* Install new reader */
1567 if (!user_recv && !(flags & (MSG_TRUNC | MSG_PEEK))) {
1568 user_recv = current;
1569 tp->ucopy.task = user_recv;
1570 tp->ucopy.iov = msg->msg_iov;
1571 }
1572
1573 tp->ucopy.len = len;
1574
Ilpo Järvinen547b7922008-07-25 21:43:18 -07001575 WARN_ON(tp->copied_seq != tp->rcv_nxt &&
1576 !(flags & (MSG_PEEK | MSG_TRUNC)));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001577
1578 /* Ugly... If prequeue is not empty, we have to
1579 * process it before releasing socket, otherwise
1580 * order will be broken at second iteration.
1581 * More elegant solution is required!!!
1582 *
1583 * Look: we have the following (pseudo)queues:
1584 *
1585 * 1. packets in flight
1586 * 2. backlog
1587 * 3. prequeue
1588 * 4. receive_queue
1589 *
1590 * Each queue can be processed only if the next ones
1591 * are empty. At this point we have empty receive_queue.
1592 * But prequeue _can_ be not empty after 2nd iteration,
1593 * when we jumped to start of loop because backlog
1594 * processing added something to receive_queue.
1595 * We cannot release_sock(), because backlog contains
1596 * packets arrived _after_ prequeued ones.
1597 *
1598 * Shortly, algorithm is clear --- to process all
1599 * the queues in order. We could make it more directly,
1600 * requeueing packets from backlog to prequeue, if
1601 * is not empty. It is more elegant, but eats cycles,
1602 * unfortunately.
1603 */
David S. Millerb03efcf2005-07-08 14:57:23 -07001604 if (!skb_queue_empty(&tp->ucopy.prequeue))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001605 goto do_prequeue;
1606
1607 /* __ Set realtime policy in scheduler __ */
1608 }
1609
Steven J. Magnani73852e82010-03-16 05:22:44 +00001610#ifdef CONFIG_NET_DMA
1611 if (tp->ucopy.dma_chan)
1612 dma_async_memcpy_issue_pending(tp->ucopy.dma_chan);
1613#endif
Linus Torvalds1da177e2005-04-16 15:20:36 -07001614 if (copied >= target) {
1615 /* Do not sleep, just process backlog. */
1616 release_sock(sk);
1617 lock_sock(sk);
1618 } else
1619 sk_wait_data(sk, &timeo);
1620
Chris Leech1a2449a2006-05-23 18:05:53 -07001621#ifdef CONFIG_NET_DMA
Steven J. Magnani73852e82010-03-16 05:22:44 +00001622 tcp_service_net_dma(sk, false); /* Don't block */
Chris Leech1a2449a2006-05-23 18:05:53 -07001623 tp->ucopy.wakeup = 0;
1624#endif
1625
Linus Torvalds1da177e2005-04-16 15:20:36 -07001626 if (user_recv) {
1627 int chunk;
1628
1629 /* __ Restore normal policy in scheduler __ */
1630
1631 if ((chunk = len - tp->ucopy.len) != 0) {
Pavel Emelyanoved880982008-07-16 20:32:45 -07001632 NET_ADD_STATS_USER(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMBACKLOG, chunk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001633 len -= chunk;
1634 copied += chunk;
1635 }
1636
1637 if (tp->rcv_nxt == tp->copied_seq &&
David S. Millerb03efcf2005-07-08 14:57:23 -07001638 !skb_queue_empty(&tp->ucopy.prequeue)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001639do_prequeue:
1640 tcp_prequeue_process(sk);
1641
1642 if ((chunk = len - tp->ucopy.len) != 0) {
Pavel Emelyanoved880982008-07-16 20:32:45 -07001643 NET_ADD_STATS_USER(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001644 len -= chunk;
1645 copied += chunk;
1646 }
1647 }
1648 }
Ilpo Järvinen77527312009-05-10 20:32:34 +00001649 if ((flags & MSG_PEEK) &&
1650 (peek_seq - copied - urg_hole != tp->copied_seq)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001651 if (net_ratelimit())
1652 printk(KERN_DEBUG "TCP(%s:%d): Application bug, race in MSG_PEEK.\n",
Pavel Emelyanovba25f9d2007-10-18 23:40:40 -07001653 current->comm, task_pid_nr(current));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001654 peek_seq = tp->copied_seq;
1655 }
1656 continue;
1657
1658 found_ok_skb:
1659 /* Ok so how much can we use? */
1660 used = skb->len - offset;
1661 if (len < used)
1662 used = len;
1663
1664 /* Do we have urgent data here? */
1665 if (tp->urg_data) {
1666 u32 urg_offset = tp->urg_seq - *seq;
1667 if (urg_offset < used) {
1668 if (!urg_offset) {
1669 if (!sock_flag(sk, SOCK_URGINLINE)) {
1670 ++*seq;
Ilpo Järvinen77527312009-05-10 20:32:34 +00001671 urg_hole++;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001672 offset++;
1673 used--;
1674 if (!used)
1675 goto skip_copy;
1676 }
1677 } else
1678 used = urg_offset;
1679 }
1680 }
1681
1682 if (!(flags & MSG_TRUNC)) {
Chris Leech1a2449a2006-05-23 18:05:53 -07001683#ifdef CONFIG_NET_DMA
1684 if (!tp->ucopy.dma_chan && tp->ucopy.pinned_list)
Dave Jianga2bd1142012-04-04 16:10:46 -07001685 tp->ucopy.dma_chan = net_dma_find_channel();
Chris Leech1a2449a2006-05-23 18:05:53 -07001686
1687 if (tp->ucopy.dma_chan) {
1688 tp->ucopy.dma_cookie = dma_skb_copy_datagram_iovec(
1689 tp->ucopy.dma_chan, skb, offset,
1690 msg->msg_iov, used,
1691 tp->ucopy.pinned_list);
1692
1693 if (tp->ucopy.dma_cookie < 0) {
1694
Joe Perchesafd465032012-03-12 07:03:32 +00001695 pr_alert("%s: dma_cookie < 0\n",
1696 __func__);
Chris Leech1a2449a2006-05-23 18:05:53 -07001697
1698 /* Exception. Bailout! */
1699 if (!copied)
1700 copied = -EFAULT;
1701 break;
1702 }
Steven J. Magnani73852e82010-03-16 05:22:44 +00001703
1704 dma_async_memcpy_issue_pending(tp->ucopy.dma_chan);
1705
Chris Leech1a2449a2006-05-23 18:05:53 -07001706 if ((offset + used) == skb->len)
1707 copied_early = 1;
1708
1709 } else
1710#endif
1711 {
1712 err = skb_copy_datagram_iovec(skb, offset,
1713 msg->msg_iov, used);
1714 if (err) {
1715 /* Exception. Bailout! */
1716 if (!copied)
1717 copied = -EFAULT;
1718 break;
1719 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001720 }
1721 }
1722
1723 *seq += used;
1724 copied += used;
1725 len -= used;
1726
1727 tcp_rcv_space_adjust(sk);
1728
1729skip_copy:
1730 if (tp->urg_data && after(tp->copied_seq, tp->urg_seq)) {
1731 tp->urg_data = 0;
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -07001732 tcp_fast_path_check(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001733 }
1734 if (used + offset < skb->len)
1735 continue;
1736
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07001737 if (tcp_hdr(skb)->fin)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001738 goto found_fin_ok;
Chris Leech1a2449a2006-05-23 18:05:53 -07001739 if (!(flags & MSG_PEEK)) {
1740 sk_eat_skb(sk, skb, copied_early);
1741 copied_early = 0;
1742 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001743 continue;
1744
1745 found_fin_ok:
1746 /* Process the FIN. */
1747 ++*seq;
Chris Leech1a2449a2006-05-23 18:05:53 -07001748 if (!(flags & MSG_PEEK)) {
1749 sk_eat_skb(sk, skb, copied_early);
1750 copied_early = 0;
1751 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001752 break;
1753 } while (len > 0);
1754
1755 if (user_recv) {
David S. Millerb03efcf2005-07-08 14:57:23 -07001756 if (!skb_queue_empty(&tp->ucopy.prequeue)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001757 int chunk;
1758
1759 tp->ucopy.len = copied > 0 ? len : 0;
1760
1761 tcp_prequeue_process(sk);
1762
1763 if (copied > 0 && (chunk = len - tp->ucopy.len) != 0) {
Pavel Emelyanoved880982008-07-16 20:32:45 -07001764 NET_ADD_STATS_USER(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001765 len -= chunk;
1766 copied += chunk;
1767 }
1768 }
1769
1770 tp->ucopy.task = NULL;
1771 tp->ucopy.len = 0;
1772 }
1773
Chris Leech1a2449a2006-05-23 18:05:53 -07001774#ifdef CONFIG_NET_DMA
Steven J. Magnani73852e82010-03-16 05:22:44 +00001775 tcp_service_net_dma(sk, true); /* Wait for queue to drain */
1776 tp->ucopy.dma_chan = NULL;
Chris Leech1a2449a2006-05-23 18:05:53 -07001777
Chris Leech1a2449a2006-05-23 18:05:53 -07001778 if (tp->ucopy.pinned_list) {
1779 dma_unpin_iovec_pages(tp->ucopy.pinned_list);
1780 tp->ucopy.pinned_list = NULL;
1781 }
1782#endif
1783
Linus Torvalds1da177e2005-04-16 15:20:36 -07001784 /* According to UNIX98, msg_name/msg_namelen are ignored
1785 * on connected socket. I was just happy when found this 8) --ANK
1786 */
1787
1788 /* Clean up data we have read: This will do ACK frames. */
Chris Leech0e4b4992006-05-23 18:00:16 -07001789 tcp_cleanup_rbuf(sk, copied);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001790
Linus Torvalds1da177e2005-04-16 15:20:36 -07001791 release_sock(sk);
Mike Chan5a0b3542009-01-07 11:40:42 -08001792
1793 if (copied > 0)
1794 uid_stat_tcp_rcv(current_uid(), copied);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001795 return copied;
1796
1797out:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001798 release_sock(sk);
1799 return err;
1800
1801recv_urg:
Rami Rosen377f0a02009-03-31 14:43:17 -07001802 err = tcp_recv_urg(sk, msg, len, flags);
Mike Chan5a0b3542009-01-07 11:40:42 -08001803 if (err > 0)
1804 uid_stat_tcp_rcv(current_uid(), err);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001805 goto out;
1806}
Eric Dumazet4bc2f182010-07-09 21:22:10 +00001807EXPORT_SYMBOL(tcp_recvmsg);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001808
Ilpo Järvinen490d5042008-01-12 03:17:20 -08001809void tcp_set_state(struct sock *sk, int state)
1810{
1811 int oldstate = sk->sk_state;
1812
1813 switch (state) {
1814 case TCP_ESTABLISHED:
1815 if (oldstate != TCP_ESTABLISHED)
Pavel Emelyanov81cc8a72008-07-16 20:22:04 -07001816 TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
Ilpo Järvinen490d5042008-01-12 03:17:20 -08001817 break;
1818
1819 case TCP_CLOSE:
1820 if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED)
Pavel Emelyanov81cc8a72008-07-16 20:22:04 -07001821 TCP_INC_STATS(sock_net(sk), TCP_MIB_ESTABRESETS);
Ilpo Järvinen490d5042008-01-12 03:17:20 -08001822
1823 sk->sk_prot->unhash(sk);
1824 if (inet_csk(sk)->icsk_bind_hash &&
1825 !(sk->sk_userlocks & SOCK_BINDPORT_LOCK))
Arnaldo Carvalho de Meloab1e0a12008-02-03 04:06:04 -08001826 inet_put_port(sk);
Ilpo Järvinen490d5042008-01-12 03:17:20 -08001827 /* fall through */
1828 default:
Jianjun Kong5a5f3a82008-11-03 00:24:34 -08001829 if (oldstate == TCP_ESTABLISHED)
Pavel Emelyanov74688e42008-07-16 20:22:46 -07001830 TCP_DEC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
Ilpo Järvinen490d5042008-01-12 03:17:20 -08001831 }
1832
1833 /* Change state AFTER socket is unhashed to avoid closed
1834 * socket sitting in hash tables.
1835 */
1836 sk->sk_state = state;
1837
1838#ifdef STATE_TRACE
Jianjun Kong5a5f3a82008-11-03 00:24:34 -08001839 SOCK_DEBUG(sk, "TCP sk=%p, State %s -> %s\n", sk, statename[oldstate], statename[state]);
Ilpo Järvinen490d5042008-01-12 03:17:20 -08001840#endif
1841}
1842EXPORT_SYMBOL_GPL(tcp_set_state);
1843
Linus Torvalds1da177e2005-04-16 15:20:36 -07001844/*
1845 * State processing on a close. This implements the state shift for
1846 * sending our FIN frame. Note that we only send a FIN for some
1847 * states. A shutdown() may have already sent the FIN, or we may be
1848 * closed.
1849 */
1850
Arjan van de Ven9b5b5cf2005-11-29 16:21:38 -08001851static const unsigned char new_state[16] = {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001852 /* current state: new state: action: */
1853 /* (Invalid) */ TCP_CLOSE,
1854 /* TCP_ESTABLISHED */ TCP_FIN_WAIT1 | TCP_ACTION_FIN,
1855 /* TCP_SYN_SENT */ TCP_CLOSE,
1856 /* TCP_SYN_RECV */ TCP_FIN_WAIT1 | TCP_ACTION_FIN,
1857 /* TCP_FIN_WAIT1 */ TCP_FIN_WAIT1,
1858 /* TCP_FIN_WAIT2 */ TCP_FIN_WAIT2,
1859 /* TCP_TIME_WAIT */ TCP_CLOSE,
1860 /* TCP_CLOSE */ TCP_CLOSE,
1861 /* TCP_CLOSE_WAIT */ TCP_LAST_ACK | TCP_ACTION_FIN,
1862 /* TCP_LAST_ACK */ TCP_LAST_ACK,
1863 /* TCP_LISTEN */ TCP_CLOSE,
1864 /* TCP_CLOSING */ TCP_CLOSING,
1865};
1866
1867static int tcp_close_state(struct sock *sk)
1868{
1869 int next = (int)new_state[sk->sk_state];
1870 int ns = next & TCP_STATE_MASK;
1871
1872 tcp_set_state(sk, ns);
1873
1874 return next & TCP_ACTION_FIN;
1875}
1876
1877/*
1878 * Shutdown the sending side of a connection. Much like close except
Satoru SATOH1f29b052008-04-21 02:27:58 -07001879 * that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD).
Linus Torvalds1da177e2005-04-16 15:20:36 -07001880 */
1881
1882void tcp_shutdown(struct sock *sk, int how)
1883{
1884 /* We need to grab some memory, and put together a FIN,
1885 * and then put it into the queue to be sent.
1886 * Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92.
1887 */
1888 if (!(how & SEND_SHUTDOWN))
1889 return;
1890
1891 /* If we've already sent a FIN, or it's a closed state, skip this. */
1892 if ((1 << sk->sk_state) &
1893 (TCPF_ESTABLISHED | TCPF_SYN_SENT |
1894 TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) {
1895 /* Clear out any half completed packets. FIN if needed. */
1896 if (tcp_close_state(sk))
1897 tcp_send_fin(sk);
1898 }
1899}
Eric Dumazet4bc2f182010-07-09 21:22:10 +00001900EXPORT_SYMBOL(tcp_shutdown);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001901
Arun Sharmaefcdbf22012-01-30 14:16:06 -08001902bool tcp_check_oom(struct sock *sk, int shift)
1903{
1904 bool too_many_orphans, out_of_socket_memory;
1905
1906 too_many_orphans = tcp_too_many_orphans(sk, shift);
1907 out_of_socket_memory = tcp_out_of_memory(sk);
1908
1909 if (too_many_orphans && net_ratelimit())
Joe Perchesafd465032012-03-12 07:03:32 +00001910 pr_info("too many orphaned sockets\n");
Arun Sharmaefcdbf22012-01-30 14:16:06 -08001911 if (out_of_socket_memory && net_ratelimit())
Joe Perchesafd465032012-03-12 07:03:32 +00001912 pr_info("out of memory -- consider tuning tcp_mem\n");
Arun Sharmaefcdbf22012-01-30 14:16:06 -08001913 return too_many_orphans || out_of_socket_memory;
1914}
1915
Linus Torvalds1da177e2005-04-16 15:20:36 -07001916void tcp_close(struct sock *sk, long timeout)
1917{
1918 struct sk_buff *skb;
1919 int data_was_unread = 0;
Herbert Xu75c2d9072006-05-03 23:31:35 -07001920 int state;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001921
1922 lock_sock(sk);
1923 sk->sk_shutdown = SHUTDOWN_MASK;
1924
1925 if (sk->sk_state == TCP_LISTEN) {
1926 tcp_set_state(sk, TCP_CLOSE);
1927
1928 /* Special case. */
Arnaldo Carvalho de Melo0a5578c2005-08-09 20:11:41 -07001929 inet_csk_listen_stop(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001930
1931 goto adjudge_to_death;
1932 }
1933
1934 /* We need to flush the recv. buffs. We do this only on the
1935 * descriptor close, not protocol-sourced closes, because the
1936 * reader process may not have drained the data yet!
1937 */
1938 while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
1939 u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq -
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07001940 tcp_hdr(skb)->fin;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001941 data_was_unread += len;
1942 __kfree_skb(skb);
1943 }
1944
Hideo Aoki3ab224b2007-12-31 00:11:19 -08001945 sk_mem_reclaim(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001946
Konstantin Khorenko565b7b22010-06-24 21:54:58 -07001947 /* If socket has been already reset (e.g. in tcp_reset()) - kill it. */
1948 if (sk->sk_state == TCP_CLOSE)
1949 goto adjudge_to_death;
1950
Gerrit Renker65bb7232007-04-28 21:21:46 -07001951 /* As outlined in RFC 2525, section 2.17, we send a RST here because
1952 * data was lost. To witness the awful effects of the old behavior of
1953 * always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk
1954 * GET in an FTP client, suspend the process, wait for the client to
1955 * advertise a zero window, then kill -9 the FTP client, wheee...
1956 * Note: timeout is always zero in such a case.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001957 */
1958 if (data_was_unread) {
1959 /* Unread data was tossed, zap the connection. */
Pavel Emelyanov6f67c812008-07-16 20:31:39 -07001960 NET_INC_STATS_USER(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001961 tcp_set_state(sk, TCP_CLOSE);
Wu Fengguangaa133072009-09-02 23:45:45 -07001962 tcp_send_active_reset(sk, sk->sk_allocation);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001963 } else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
1964 /* Check zero linger _after_ checking for unread data. */
1965 sk->sk_prot->disconnect(sk, 0);
Pavel Emelyanov6f67c812008-07-16 20:31:39 -07001966 NET_INC_STATS_USER(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001967 } else if (tcp_close_state(sk)) {
1968 /* We FIN if the application ate all the data before
1969 * zapping the connection.
1970 */
1971
1972 /* RED-PEN. Formally speaking, we have broken TCP state
1973 * machine. State transitions:
1974 *
1975 * TCP_ESTABLISHED -> TCP_FIN_WAIT1
1976 * TCP_SYN_RECV -> TCP_FIN_WAIT1 (forget it, it's impossible)
1977 * TCP_CLOSE_WAIT -> TCP_LAST_ACK
1978 *
1979 * are legal only when FIN has been sent (i.e. in window),
1980 * rather than queued out of window. Purists blame.
1981 *
1982 * F.e. "RFC state" is ESTABLISHED,
1983 * if Linux state is FIN-WAIT-1, but FIN is still not sent.
1984 *
1985 * The visible declinations are that sometimes
1986 * we enter time-wait state, when it is not required really
1987 * (harmless), do not send active resets, when they are
1988 * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when
1989 * they look as CLOSING or LAST_ACK for Linux)
1990 * Probably, I missed some more holelets.
1991 * --ANK
1992 */
1993 tcp_send_fin(sk);
1994 }
1995
1996 sk_stream_wait_close(sk, timeout);
1997
1998adjudge_to_death:
Herbert Xu75c2d9072006-05-03 23:31:35 -07001999 state = sk->sk_state;
2000 sock_hold(sk);
2001 sock_orphan(sk);
Herbert Xu75c2d9072006-05-03 23:31:35 -07002002
Linus Torvalds1da177e2005-04-16 15:20:36 -07002003 /* It is the last release_sock in its life. It will remove backlog. */
2004 release_sock(sk);
2005
2006
2007 /* Now socket is owned by kernel and we acquire BH lock
2008 to finish close. No need to check for user refs.
2009 */
2010 local_bh_disable();
2011 bh_lock_sock(sk);
Ilpo Järvinen547b7922008-07-25 21:43:18 -07002012 WARN_ON(sock_owned_by_user(sk));
Linus Torvalds1da177e2005-04-16 15:20:36 -07002013
Herbert Xueb4dea52008-12-29 23:04:08 -08002014 percpu_counter_inc(sk->sk_prot->orphan_count);
2015
Herbert Xu75c2d9072006-05-03 23:31:35 -07002016 /* Have we already been destroyed by a softirq or backlog? */
2017 if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE)
2018 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002019
2020 /* This is a (useful) BSD violating of the RFC. There is a
2021 * problem with TCP as specified in that the other end could
2022 * keep a socket open forever with no application left this end.
2023 * We use a 3 minute timeout (about the same as BSD) then kill
2024 * our end. If they send after that then tough - BUT: long enough
2025 * that we won't make the old 4*rto = almost no time - whoops
2026 * reset mistake.
2027 *
2028 * Nope, it was not mistake. It is really desired behaviour
2029 * f.e. on http servers, when such sockets are useless, but
2030 * consume significant resources. Let's do it with special
2031 * linger2 option. --ANK
2032 */
2033
2034 if (sk->sk_state == TCP_FIN_WAIT2) {
2035 struct tcp_sock *tp = tcp_sk(sk);
2036 if (tp->linger2 < 0) {
2037 tcp_set_state(sk, TCP_CLOSE);
2038 tcp_send_active_reset(sk, GFP_ATOMIC);
Pavel Emelyanovde0744a2008-07-16 20:31:16 -07002039 NET_INC_STATS_BH(sock_net(sk),
2040 LINUX_MIB_TCPABORTONLINGER);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002041 } else {
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002042 const int tmo = tcp_fin_time(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002043
2044 if (tmo > TCP_TIMEWAIT_LEN) {
David S. Miller52499af2006-07-31 22:32:09 -07002045 inet_csk_reset_keepalive_timer(sk,
2046 tmo - TCP_TIMEWAIT_LEN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002047 } else {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002048 tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
2049 goto out;
2050 }
2051 }
2052 }
2053 if (sk->sk_state != TCP_CLOSE) {
Hideo Aoki3ab224b2007-12-31 00:11:19 -08002054 sk_mem_reclaim(sk);
Arun Sharmaefcdbf22012-01-30 14:16:06 -08002055 if (tcp_check_oom(sk, 0)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002056 tcp_set_state(sk, TCP_CLOSE);
2057 tcp_send_active_reset(sk, GFP_ATOMIC);
Pavel Emelyanovde0744a2008-07-16 20:31:16 -07002058 NET_INC_STATS_BH(sock_net(sk),
2059 LINUX_MIB_TCPABORTONMEMORY);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002060 }
2061 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002062
2063 if (sk->sk_state == TCP_CLOSE)
Arnaldo Carvalho de Melo0a5578c2005-08-09 20:11:41 -07002064 inet_csk_destroy_sock(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002065 /* Otherwise, socket is reprieved until protocol close. */
2066
2067out:
2068 bh_unlock_sock(sk);
2069 local_bh_enable();
2070 sock_put(sk);
2071}
Eric Dumazet4bc2f182010-07-09 21:22:10 +00002072EXPORT_SYMBOL(tcp_close);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002073
2074/* These states need RST on ABORT according to RFC793 */
2075
2076static inline int tcp_need_reset(int state)
2077{
2078 return (1 << state) &
2079 (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 |
2080 TCPF_FIN_WAIT2 | TCPF_SYN_RECV);
2081}
2082
2083int tcp_disconnect(struct sock *sk, int flags)
2084{
2085 struct inet_sock *inet = inet_sk(sk);
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002086 struct inet_connection_sock *icsk = inet_csk(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002087 struct tcp_sock *tp = tcp_sk(sk);
2088 int err = 0;
2089 int old_state = sk->sk_state;
2090
2091 if (old_state != TCP_CLOSE)
2092 tcp_set_state(sk, TCP_CLOSE);
2093
2094 /* ABORT function of RFC793 */
2095 if (old_state == TCP_LISTEN) {
Arnaldo Carvalho de Melo0a5578c2005-08-09 20:11:41 -07002096 inet_csk_listen_stop(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002097 } else if (tcp_need_reset(old_state) ||
2098 (tp->snd_nxt != tp->write_seq &&
2099 (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {
Stephen Hemmingercaa20d9a2005-11-10 17:13:47 -08002100 /* The last check adjusts for discrepancy of Linux wrt. RFC
Linus Torvalds1da177e2005-04-16 15:20:36 -07002101 * states
2102 */
2103 tcp_send_active_reset(sk, gfp_any());
2104 sk->sk_err = ECONNRESET;
2105 } else if (old_state == TCP_SYN_SENT)
2106 sk->sk_err = ECONNRESET;
2107
2108 tcp_clear_xmit_timers(sk);
2109 __skb_queue_purge(&sk->sk_receive_queue);
David S. Millerfe067e82007-03-07 12:12:44 -08002110 tcp_write_queue_purge(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002111 __skb_queue_purge(&tp->out_of_order_queue);
Chris Leech1a2449a2006-05-23 18:05:53 -07002112#ifdef CONFIG_NET_DMA
2113 __skb_queue_purge(&sk->sk_async_wait_queue);
2114#endif
Linus Torvalds1da177e2005-04-16 15:20:36 -07002115
Eric Dumazetc720c7e2009-10-15 06:30:45 +00002116 inet->inet_dport = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002117
2118 if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
2119 inet_reset_saddr(sk);
2120
2121 sk->sk_shutdown = 0;
2122 sock_reset_flag(sk, SOCK_DONE);
2123 tp->srtt = 0;
2124 if ((tp->write_seq += tp->max_window + 2) == 0)
2125 tp->write_seq = 1;
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002126 icsk->icsk_backoff = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002127 tp->snd_cwnd = 2;
Arnaldo Carvalho de Melo6687e982005-08-10 04:03:31 -03002128 icsk->icsk_probes_out = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002129 tp->packets_out = 0;
Ilpo Järvinen0b6a05c2009-09-15 01:30:10 -07002130 tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002131 tp->snd_cwnd_cnt = 0;
Stephen Hemminger9772efb2005-11-10 17:09:53 -08002132 tp->bytes_acked = 0;
Eric Dumazet1fdf4752009-11-30 12:53:30 -08002133 tp->window_clamp = 0;
Arnaldo Carvalho de Melo6687e982005-08-10 04:03:31 -03002134 tcp_set_ca_state(sk, TCP_CA_Open);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002135 tcp_clear_retrans(tp);
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002136 inet_csk_delack_init(sk);
David S. Millerfe067e82007-03-07 12:12:44 -08002137 tcp_init_send_head(sk);
Srinivas Ajib40b4f72007-05-03 17:32:28 -07002138 memset(&tp->rx_opt, 0, sizeof(tp->rx_opt));
Linus Torvalds1da177e2005-04-16 15:20:36 -07002139 __sk_dst_reset(sk);
2140
Eric Dumazetc720c7e2009-10-15 06:30:45 +00002141 WARN_ON(inet->inet_num && !icsk->icsk_bind_hash);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002142
2143 sk->sk_error_report(sk);
2144 return err;
2145}
Eric Dumazet4bc2f182010-07-09 21:22:10 +00002146EXPORT_SYMBOL(tcp_disconnect);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002147
2148/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07002149 * Socket option code for TCP.
2150 */
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002151static int do_tcp_setsockopt(struct sock *sk, int level,
David S. Millerb7058842009-09-30 16:12:20 -07002152 int optname, char __user *optval, unsigned int optlen)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002153{
2154 struct tcp_sock *tp = tcp_sk(sk);
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002155 struct inet_connection_sock *icsk = inet_csk(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002156 int val;
2157 int err = 0;
2158
William Allen Simpsone56fb502009-12-02 18:19:30 +00002159 /* These are data/string values, all the others are ints */
2160 switch (optname) {
2161 case TCP_CONGESTION: {
Stephen Hemminger5f8ef482005-06-23 20:37:36 -07002162 char name[TCP_CA_NAME_MAX];
2163
2164 if (optlen < 1)
2165 return -EINVAL;
2166
2167 val = strncpy_from_user(name, optval,
Andrew Morton4fdb78d2009-10-01 15:02:20 -07002168 min_t(long, TCP_CA_NAME_MAX-1, optlen));
Stephen Hemminger5f8ef482005-06-23 20:37:36 -07002169 if (val < 0)
2170 return -EFAULT;
2171 name[val] = 0;
2172
2173 lock_sock(sk);
Arnaldo Carvalho de Melo6687e982005-08-10 04:03:31 -03002174 err = tcp_set_congestion_control(sk, name);
Stephen Hemminger5f8ef482005-06-23 20:37:36 -07002175 release_sock(sk);
2176 return err;
2177 }
William Allen Simpsone56fb502009-12-02 18:19:30 +00002178 case TCP_COOKIE_TRANSACTIONS: {
2179 struct tcp_cookie_transactions ctd;
2180 struct tcp_cookie_values *cvp = NULL;
2181
2182 if (sizeof(ctd) > optlen)
2183 return -EINVAL;
2184 if (copy_from_user(&ctd, optval, sizeof(ctd)))
2185 return -EFAULT;
2186
2187 if (ctd.tcpct_used > sizeof(ctd.tcpct_value) ||
2188 ctd.tcpct_s_data_desired > TCP_MSS_DESIRED)
2189 return -EINVAL;
2190
2191 if (ctd.tcpct_cookie_desired == 0) {
2192 /* default to global value */
2193 } else if ((0x1 & ctd.tcpct_cookie_desired) ||
2194 ctd.tcpct_cookie_desired > TCP_COOKIE_MAX ||
2195 ctd.tcpct_cookie_desired < TCP_COOKIE_MIN) {
2196 return -EINVAL;
2197 }
2198
2199 if (TCP_COOKIE_OUT_NEVER & ctd.tcpct_flags) {
2200 /* Supercedes all other values */
2201 lock_sock(sk);
2202 if (tp->cookie_values != NULL) {
2203 kref_put(&tp->cookie_values->kref,
2204 tcp_cookie_values_release);
2205 tp->cookie_values = NULL;
2206 }
2207 tp->rx_opt.cookie_in_always = 0; /* false */
2208 tp->rx_opt.cookie_out_never = 1; /* true */
2209 release_sock(sk);
2210 return err;
2211 }
2212
2213 /* Allocate ancillary memory before locking.
2214 */
2215 if (ctd.tcpct_used > 0 ||
2216 (tp->cookie_values == NULL &&
2217 (sysctl_tcp_cookie_size > 0 ||
2218 ctd.tcpct_cookie_desired > 0 ||
2219 ctd.tcpct_s_data_desired > 0))) {
2220 cvp = kzalloc(sizeof(*cvp) + ctd.tcpct_used,
2221 GFP_KERNEL);
2222 if (cvp == NULL)
2223 return -ENOMEM;
Dmitry Popova3bdb542010-07-29 01:59:36 +00002224
2225 kref_init(&cvp->kref);
William Allen Simpsone56fb502009-12-02 18:19:30 +00002226 }
2227 lock_sock(sk);
2228 tp->rx_opt.cookie_in_always =
2229 (TCP_COOKIE_IN_ALWAYS & ctd.tcpct_flags);
2230 tp->rx_opt.cookie_out_never = 0; /* false */
2231
2232 if (tp->cookie_values != NULL) {
2233 if (cvp != NULL) {
2234 /* Changed values are recorded by a changed
2235 * pointer, ensuring the cookie will differ,
2236 * without separately hashing each value later.
2237 */
2238 kref_put(&tp->cookie_values->kref,
2239 tcp_cookie_values_release);
William Allen Simpsone56fb502009-12-02 18:19:30 +00002240 } else {
2241 cvp = tp->cookie_values;
2242 }
2243 }
Dmitry Popova3bdb542010-07-29 01:59:36 +00002244
William Allen Simpsone56fb502009-12-02 18:19:30 +00002245 if (cvp != NULL) {
2246 cvp->cookie_desired = ctd.tcpct_cookie_desired;
2247
2248 if (ctd.tcpct_used > 0) {
2249 memcpy(cvp->s_data_payload, ctd.tcpct_value,
2250 ctd.tcpct_used);
2251 cvp->s_data_desired = ctd.tcpct_used;
2252 cvp->s_data_constant = 1; /* true */
2253 } else {
2254 /* No constant payload data. */
2255 cvp->s_data_desired = ctd.tcpct_s_data_desired;
2256 cvp->s_data_constant = 0; /* false */
2257 }
Dmitry Popova3bdb542010-07-29 01:59:36 +00002258
2259 tp->cookie_values = cvp;
William Allen Simpsone56fb502009-12-02 18:19:30 +00002260 }
2261 release_sock(sk);
2262 return err;
2263 }
2264 default:
2265 /* fallthru */
2266 break;
Joe Perchesccbd6a52010-05-14 10:58:26 +00002267 }
Stephen Hemminger5f8ef482005-06-23 20:37:36 -07002268
Linus Torvalds1da177e2005-04-16 15:20:36 -07002269 if (optlen < sizeof(int))
2270 return -EINVAL;
2271
2272 if (get_user(val, (int __user *)optval))
2273 return -EFAULT;
2274
2275 lock_sock(sk);
2276
2277 switch (optname) {
2278 case TCP_MAXSEG:
2279 /* Values greater than interface MTU won't take effect. However
2280 * at the point when this call is done we typically don't yet
2281 * know which interface is going to be used */
David S. Millerc39508d2010-11-24 11:47:22 -08002282 if (val < TCP_MIN_MSS || val > MAX_TCP_WINDOW) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002283 err = -EINVAL;
2284 break;
2285 }
2286 tp->rx_opt.user_mss = val;
2287 break;
2288
2289 case TCP_NODELAY:
2290 if (val) {
2291 /* TCP_NODELAY is weaker than TCP_CORK, so that
2292 * this option on corked socket is remembered, but
2293 * it is not activated until cork is cleared.
2294 *
2295 * However, when TCP_NODELAY is set we make
2296 * an explicit push, which overrides even TCP_CORK
2297 * for currently queued segments.
2298 */
2299 tp->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH;
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -07002300 tcp_push_pending_frames(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002301 } else {
2302 tp->nonagle &= ~TCP_NAGLE_OFF;
2303 }
2304 break;
2305
Andreas Petlund36e31b02010-02-18 02:47:01 +00002306 case TCP_THIN_LINEAR_TIMEOUTS:
2307 if (val < 0 || val > 1)
2308 err = -EINVAL;
2309 else
2310 tp->thin_lto = val;
2311 break;
2312
Andreas Petlund7e380172010-02-18 04:48:19 +00002313 case TCP_THIN_DUPACK:
2314 if (val < 0 || val > 1)
2315 err = -EINVAL;
2316 else
2317 tp->thin_dupack = val;
2318 break;
2319
Linus Torvalds1da177e2005-04-16 15:20:36 -07002320 case TCP_CORK:
2321 /* When set indicates to always queue non-full frames.
2322 * Later the user clears this option and we transmit
2323 * any pending partial frames in the queue. This is
2324 * meant to be used alongside sendfile() to get properly
2325 * filled frames when the user (for example) must write
2326 * out headers with a write() call first and then use
2327 * sendfile to send out the data parts.
2328 *
2329 * TCP_CORK can be set together with TCP_NODELAY and it is
2330 * stronger than TCP_NODELAY.
2331 */
2332 if (val) {
2333 tp->nonagle |= TCP_NAGLE_CORK;
2334 } else {
2335 tp->nonagle &= ~TCP_NAGLE_CORK;
2336 if (tp->nonagle&TCP_NAGLE_OFF)
2337 tp->nonagle |= TCP_NAGLE_PUSH;
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -07002338 tcp_push_pending_frames(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002339 }
2340 break;
2341
2342 case TCP_KEEPIDLE:
2343 if (val < 1 || val > MAX_TCP_KEEPIDLE)
2344 err = -EINVAL;
2345 else {
2346 tp->keepalive_time = val * HZ;
2347 if (sock_flag(sk, SOCK_KEEPOPEN) &&
2348 !((1 << sk->sk_state) &
2349 (TCPF_CLOSE | TCPF_LISTEN))) {
Flavio Leitner6c37e5d2010-04-26 18:33:27 +00002350 u32 elapsed = keepalive_time_elapsed(tp);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002351 if (tp->keepalive_time > elapsed)
2352 elapsed = tp->keepalive_time - elapsed;
2353 else
2354 elapsed = 0;
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002355 inet_csk_reset_keepalive_timer(sk, elapsed);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002356 }
2357 }
2358 break;
2359 case TCP_KEEPINTVL:
2360 if (val < 1 || val > MAX_TCP_KEEPINTVL)
2361 err = -EINVAL;
2362 else
2363 tp->keepalive_intvl = val * HZ;
2364 break;
2365 case TCP_KEEPCNT:
2366 if (val < 1 || val > MAX_TCP_KEEPCNT)
2367 err = -EINVAL;
2368 else
2369 tp->keepalive_probes = val;
2370 break;
2371 case TCP_SYNCNT:
2372 if (val < 1 || val > MAX_TCP_SYNCNT)
2373 err = -EINVAL;
2374 else
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002375 icsk->icsk_syn_retries = val;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002376 break;
2377
2378 case TCP_LINGER2:
2379 if (val < 0)
2380 tp->linger2 = -1;
2381 else if (val > sysctl_tcp_fin_timeout / HZ)
2382 tp->linger2 = 0;
2383 else
2384 tp->linger2 = val * HZ;
2385 break;
2386
2387 case TCP_DEFER_ACCEPT:
Julian Anastasovb103cf32009-10-19 10:10:40 +00002388 /* Translate value in seconds to number of retransmits */
2389 icsk->icsk_accept_queue.rskq_defer_accept =
2390 secs_to_retrans(val, TCP_TIMEOUT_INIT / HZ,
2391 TCP_RTO_MAX / HZ);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002392 break;
2393
2394 case TCP_WINDOW_CLAMP:
2395 if (!val) {
2396 if (sk->sk_state != TCP_CLOSE) {
2397 err = -EINVAL;
2398 break;
2399 }
2400 tp->window_clamp = 0;
2401 } else
2402 tp->window_clamp = val < SOCK_MIN_RCVBUF / 2 ?
2403 SOCK_MIN_RCVBUF / 2 : val;
2404 break;
2405
2406 case TCP_QUICKACK:
2407 if (!val) {
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002408 icsk->icsk_ack.pingpong = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002409 } else {
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002410 icsk->icsk_ack.pingpong = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002411 if ((1 << sk->sk_state) &
2412 (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) &&
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002413 inet_csk_ack_scheduled(sk)) {
2414 icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
Chris Leech0e4b4992006-05-23 18:00:16 -07002415 tcp_cleanup_rbuf(sk, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002416 if (!(val & 1))
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002417 icsk->icsk_ack.pingpong = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002418 }
2419 }
2420 break;
2421
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002422#ifdef CONFIG_TCP_MD5SIG
2423 case TCP_MD5SIG:
2424 /* Read the IP->Key mappings from userspace */
2425 err = tp->af_specific->md5_parse(sk, optval, optlen);
2426 break;
2427#endif
Jerry Chudca43c72010-08-27 19:13:28 +00002428 case TCP_USER_TIMEOUT:
2429 /* Cap the max timeout in ms TCP will retry/retrans
2430 * before giving up and aborting (ETIMEDOUT) a connection.
2431 */
2432 icsk->icsk_user_timeout = msecs_to_jiffies(val);
2433 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002434 default:
2435 err = -ENOPROTOOPT;
2436 break;
Stephen Hemminger3ff50b72007-04-20 17:09:22 -07002437 }
2438
Linus Torvalds1da177e2005-04-16 15:20:36 -07002439 release_sock(sk);
2440 return err;
2441}
2442
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002443int tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval,
David S. Millerb7058842009-09-30 16:12:20 -07002444 unsigned int optlen)
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002445{
Eric Dumazetcf533ea2011-10-21 05:22:42 -04002446 const struct inet_connection_sock *icsk = inet_csk(sk);
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002447
2448 if (level != SOL_TCP)
2449 return icsk->icsk_af_ops->setsockopt(sk, level, optname,
2450 optval, optlen);
2451 return do_tcp_setsockopt(sk, level, optname, optval, optlen);
2452}
Eric Dumazet4bc2f182010-07-09 21:22:10 +00002453EXPORT_SYMBOL(tcp_setsockopt);
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002454
2455#ifdef CONFIG_COMPAT
Arnaldo Carvalho de Melo543d9cf2006-03-20 22:48:35 -08002456int compat_tcp_setsockopt(struct sock *sk, int level, int optname,
David S. Millerb7058842009-09-30 16:12:20 -07002457 char __user *optval, unsigned int optlen)
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002458{
Arnaldo Carvalho de Melodec73ff2006-03-20 22:46:16 -08002459 if (level != SOL_TCP)
2460 return inet_csk_compat_setsockopt(sk, level, optname,
2461 optval, optlen);
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002462 return do_tcp_setsockopt(sk, level, optname, optval, optlen);
2463}
Arnaldo Carvalho de Melo543d9cf2006-03-20 22:48:35 -08002464EXPORT_SYMBOL(compat_tcp_setsockopt);
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002465#endif
2466
Linus Torvalds1da177e2005-04-16 15:20:36 -07002467/* Return information about state of tcp endpoint in API format. */
Eric Dumazetcf533ea2011-10-21 05:22:42 -04002468void tcp_get_info(const struct sock *sk, struct tcp_info *info)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002469{
Eric Dumazetcf533ea2011-10-21 05:22:42 -04002470 const struct tcp_sock *tp = tcp_sk(sk);
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002471 const struct inet_connection_sock *icsk = inet_csk(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002472 u32 now = tcp_time_stamp;
2473
2474 memset(info, 0, sizeof(*info));
2475
2476 info->tcpi_state = sk->sk_state;
Arnaldo Carvalho de Melo6687e982005-08-10 04:03:31 -03002477 info->tcpi_ca_state = icsk->icsk_ca_state;
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002478 info->tcpi_retransmits = icsk->icsk_retransmits;
Arnaldo Carvalho de Melo6687e982005-08-10 04:03:31 -03002479 info->tcpi_probes = icsk->icsk_probes_out;
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002480 info->tcpi_backoff = icsk->icsk_backoff;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002481
2482 if (tp->rx_opt.tstamp_ok)
2483 info->tcpi_options |= TCPI_OPT_TIMESTAMPS;
Ilpo Järvinene60402d2007-08-09 15:14:46 +03002484 if (tcp_is_sack(tp))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002485 info->tcpi_options |= TCPI_OPT_SACK;
2486 if (tp->rx_opt.wscale_ok) {
2487 info->tcpi_options |= TCPI_OPT_WSCALE;
2488 info->tcpi_snd_wscale = tp->rx_opt.snd_wscale;
2489 info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale;
YOSHIFUJI Hideakie905a9e2007-02-09 23:24:47 +09002490 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002491
Eric Dumazetb5c56932011-10-03 14:01:21 -04002492 if (tp->ecn_flags & TCP_ECN_OK)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002493 info->tcpi_options |= TCPI_OPT_ECN;
Eric Dumazetb5c56932011-10-03 14:01:21 -04002494 if (tp->ecn_flags & TCP_ECN_SEEN)
2495 info->tcpi_options |= TCPI_OPT_ECN_SEEN;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002496
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002497 info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto);
2498 info->tcpi_ato = jiffies_to_usecs(icsk->icsk_ack.ato);
David S. Millerc1b4a7e2005-07-05 15:24:38 -07002499 info->tcpi_snd_mss = tp->mss_cache;
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002500 info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002501
Rick Jones5ee3afb2007-09-18 13:26:31 -07002502 if (sk->sk_state == TCP_LISTEN) {
2503 info->tcpi_unacked = sk->sk_ack_backlog;
2504 info->tcpi_sacked = sk->sk_max_ack_backlog;
2505 } else {
2506 info->tcpi_unacked = tp->packets_out;
2507 info->tcpi_sacked = tp->sacked_out;
2508 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002509 info->tcpi_lost = tp->lost_out;
2510 info->tcpi_retrans = tp->retrans_out;
2511 info->tcpi_fackets = tp->fackets_out;
2512
2513 info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime);
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002514 info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002515 info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp);
2516
Arnaldo Carvalho de Melod83d8462005-12-13 23:26:10 -08002517 info->tcpi_pmtu = icsk->icsk_pmtu_cookie;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002518 info->tcpi_rcv_ssthresh = tp->rcv_ssthresh;
2519 info->tcpi_rtt = jiffies_to_usecs(tp->srtt)>>3;
2520 info->tcpi_rttvar = jiffies_to_usecs(tp->mdev)>>2;
2521 info->tcpi_snd_ssthresh = tp->snd_ssthresh;
2522 info->tcpi_snd_cwnd = tp->snd_cwnd;
2523 info->tcpi_advmss = tp->advmss;
2524 info->tcpi_reordering = tp->reordering;
2525
2526 info->tcpi_rcv_rtt = jiffies_to_usecs(tp->rcv_rtt_est.rtt)>>3;
2527 info->tcpi_rcv_space = tp->rcvq_space.space;
2528
2529 info->tcpi_total_retrans = tp->total_retrans;
Chinh Tranbbebbfe2011-10-26 16:14:15 -07002530
Steve Mucklef132c6c2012-06-06 18:30:57 -07002531 if (sk->sk_socket) {
Chinh Tranbbebbfe2011-10-26 16:14:15 -07002532 struct file *filep = sk->sk_socket->file;
Steve Mucklef132c6c2012-06-06 18:30:57 -07002533 if (filep)
Chinh Tranbbebbfe2011-10-26 16:14:15 -07002534 info->tcpi_count = atomic_read(&filep->f_count);
2535 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002536}
Linus Torvalds1da177e2005-04-16 15:20:36 -07002537EXPORT_SYMBOL_GPL(tcp_get_info);
2538
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002539static int do_tcp_getsockopt(struct sock *sk, int level,
2540 int optname, char __user *optval, int __user *optlen)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002541{
Arnaldo Carvalho de Melo295f7322005-08-09 20:11:56 -07002542 struct inet_connection_sock *icsk = inet_csk(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002543 struct tcp_sock *tp = tcp_sk(sk);
2544 int val, len;
2545
Linus Torvalds1da177e2005-04-16 15:20:36 -07002546 if (get_user(len, optlen))
2547 return -EFAULT;
2548
2549 len = min_t(unsigned int, len, sizeof(int));
2550
2551 if (len < 0)
2552 return -EINVAL;
2553
2554 switch (optname) {
2555 case TCP_MAXSEG:
David S. Millerc1b4a7e2005-07-05 15:24:38 -07002556 val = tp->mss_cache;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002557 if (!val && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
2558 val = tp->rx_opt.user_mss;
2559 break;
2560 case TCP_NODELAY:
2561 val = !!(tp->nonagle&TCP_NAGLE_OFF);
2562 break;
2563 case TCP_CORK:
2564 val = !!(tp->nonagle&TCP_NAGLE_CORK);
2565 break;
2566 case TCP_KEEPIDLE:
Eric Dumazetdf19a622009-08-28 23:48:54 -07002567 val = keepalive_time_when(tp) / HZ;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002568 break;
2569 case TCP_KEEPINTVL:
Eric Dumazetdf19a622009-08-28 23:48:54 -07002570 val = keepalive_intvl_when(tp) / HZ;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002571 break;
2572 case TCP_KEEPCNT:
Eric Dumazetdf19a622009-08-28 23:48:54 -07002573 val = keepalive_probes(tp);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002574 break;
2575 case TCP_SYNCNT:
Arnaldo Carvalho de Melo295f7322005-08-09 20:11:56 -07002576 val = icsk->icsk_syn_retries ? : sysctl_tcp_syn_retries;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002577 break;
2578 case TCP_LINGER2:
2579 val = tp->linger2;
2580 if (val >= 0)
2581 val = (val ? : sysctl_tcp_fin_timeout) / HZ;
2582 break;
2583 case TCP_DEFER_ACCEPT:
Julian Anastasovb103cf32009-10-19 10:10:40 +00002584 val = retrans_to_secs(icsk->icsk_accept_queue.rskq_defer_accept,
2585 TCP_TIMEOUT_INIT / HZ, TCP_RTO_MAX / HZ);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002586 break;
2587 case TCP_WINDOW_CLAMP:
2588 val = tp->window_clamp;
2589 break;
2590 case TCP_INFO: {
2591 struct tcp_info info;
2592
2593 if (get_user(len, optlen))
2594 return -EFAULT;
2595
2596 tcp_get_info(sk, &info);
2597
2598 len = min_t(unsigned int, len, sizeof(info));
2599 if (put_user(len, optlen))
2600 return -EFAULT;
2601 if (copy_to_user(optval, &info, len))
2602 return -EFAULT;
2603 return 0;
2604 }
2605 case TCP_QUICKACK:
Arnaldo Carvalho de Melo295f7322005-08-09 20:11:56 -07002606 val = !icsk->icsk_ack.pingpong;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002607 break;
Stephen Hemminger5f8ef482005-06-23 20:37:36 -07002608
2609 case TCP_CONGESTION:
2610 if (get_user(len, optlen))
2611 return -EFAULT;
2612 len = min_t(unsigned int, len, TCP_CA_NAME_MAX);
2613 if (put_user(len, optlen))
2614 return -EFAULT;
Arnaldo Carvalho de Melo6687e982005-08-10 04:03:31 -03002615 if (copy_to_user(optval, icsk->icsk_ca_ops->name, len))
Stephen Hemminger5f8ef482005-06-23 20:37:36 -07002616 return -EFAULT;
2617 return 0;
William Allen Simpsone56fb502009-12-02 18:19:30 +00002618
2619 case TCP_COOKIE_TRANSACTIONS: {
2620 struct tcp_cookie_transactions ctd;
2621 struct tcp_cookie_values *cvp = tp->cookie_values;
2622
2623 if (get_user(len, optlen))
2624 return -EFAULT;
2625 if (len < sizeof(ctd))
2626 return -EINVAL;
2627
2628 memset(&ctd, 0, sizeof(ctd));
2629 ctd.tcpct_flags = (tp->rx_opt.cookie_in_always ?
2630 TCP_COOKIE_IN_ALWAYS : 0)
2631 | (tp->rx_opt.cookie_out_never ?
2632 TCP_COOKIE_OUT_NEVER : 0);
2633
2634 if (cvp != NULL) {
2635 ctd.tcpct_flags |= (cvp->s_data_in ?
2636 TCP_S_DATA_IN : 0)
2637 | (cvp->s_data_out ?
2638 TCP_S_DATA_OUT : 0);
2639
2640 ctd.tcpct_cookie_desired = cvp->cookie_desired;
2641 ctd.tcpct_s_data_desired = cvp->s_data_desired;
2642
William Allen Simpsone56fb502009-12-02 18:19:30 +00002643 memcpy(&ctd.tcpct_value[0], &cvp->cookie_pair[0],
2644 cvp->cookie_pair_size);
2645 ctd.tcpct_used = cvp->cookie_pair_size;
2646 }
2647
2648 if (put_user(sizeof(ctd), optlen))
2649 return -EFAULT;
2650 if (copy_to_user(optval, &ctd, sizeof(ctd)))
2651 return -EFAULT;
2652 return 0;
2653 }
Josh Hunt3c0fef02010-07-30 13:49:35 +00002654 case TCP_THIN_LINEAR_TIMEOUTS:
2655 val = tp->thin_lto;
2656 break;
2657 case TCP_THIN_DUPACK:
2658 val = tp->thin_dupack;
2659 break;
Jerry Chudca43c72010-08-27 19:13:28 +00002660
2661 case TCP_USER_TIMEOUT:
2662 val = jiffies_to_msecs(icsk->icsk_user_timeout);
2663 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002664 default:
2665 return -ENOPROTOOPT;
Stephen Hemminger3ff50b72007-04-20 17:09:22 -07002666 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002667
2668 if (put_user(len, optlen))
2669 return -EFAULT;
2670 if (copy_to_user(optval, &val, len))
2671 return -EFAULT;
2672 return 0;
2673}
2674
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002675int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval,
2676 int __user *optlen)
2677{
2678 struct inet_connection_sock *icsk = inet_csk(sk);
2679
2680 if (level != SOL_TCP)
2681 return icsk->icsk_af_ops->getsockopt(sk, level, optname,
2682 optval, optlen);
2683 return do_tcp_getsockopt(sk, level, optname, optval, optlen);
2684}
Eric Dumazet4bc2f182010-07-09 21:22:10 +00002685EXPORT_SYMBOL(tcp_getsockopt);
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002686
2687#ifdef CONFIG_COMPAT
Arnaldo Carvalho de Melo543d9cf2006-03-20 22:48:35 -08002688int compat_tcp_getsockopt(struct sock *sk, int level, int optname,
2689 char __user *optval, int __user *optlen)
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002690{
Arnaldo Carvalho de Melodec73ff2006-03-20 22:46:16 -08002691 if (level != SOL_TCP)
2692 return inet_csk_compat_getsockopt(sk, level, optname,
2693 optval, optlen);
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002694 return do_tcp_getsockopt(sk, level, optname, optval, optlen);
2695}
Arnaldo Carvalho de Melo543d9cf2006-03-20 22:48:35 -08002696EXPORT_SYMBOL(compat_tcp_getsockopt);
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002697#endif
Linus Torvalds1da177e2005-04-16 15:20:36 -07002698
Michał Mirosławc8f44af2011-11-15 15:29:55 +00002699struct sk_buff *tcp_tso_segment(struct sk_buff *skb,
2700 netdev_features_t features)
Herbert Xuf4c50d92006-06-22 03:02:40 -07002701{
2702 struct sk_buff *segs = ERR_PTR(-EINVAL);
2703 struct tcphdr *th;
2704 unsigned thlen;
2705 unsigned int seq;
Al Virod3bc23e2006-11-14 21:24:49 -08002706 __be32 delta;
Herbert Xuf4c50d92006-06-22 03:02:40 -07002707 unsigned int oldlen;
Herbert Xu4e704ee2009-01-14 20:41:12 -08002708 unsigned int mss;
Herbert Xuf4c50d92006-06-22 03:02:40 -07002709
2710 if (!pskb_may_pull(skb, sizeof(*th)))
2711 goto out;
2712
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07002713 th = tcp_hdr(skb);
Herbert Xuf4c50d92006-06-22 03:02:40 -07002714 thlen = th->doff * 4;
2715 if (thlen < sizeof(*th))
2716 goto out;
2717
2718 if (!pskb_may_pull(skb, thlen))
2719 goto out;
2720
Herbert Xu0718bcc2006-06-25 23:55:46 -07002721 oldlen = (u16)~skb->len;
Herbert Xuf4c50d92006-06-22 03:02:40 -07002722 __skb_pull(skb, thlen);
2723
Herbert Xu4e704ee2009-01-14 20:41:12 -08002724 mss = skb_shinfo(skb)->gso_size;
2725 if (unlikely(skb->len <= mss))
2726 goto out;
2727
Herbert Xu3820c3f2006-06-29 20:11:25 -07002728 if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) {
2729 /* Packet is from an untrusted source, reset gso_segs. */
Herbert Xubbcf4672006-07-03 19:38:35 -07002730 int type = skb_shinfo(skb)->gso_type;
Herbert Xu3820c3f2006-06-29 20:11:25 -07002731
Herbert Xubbcf4672006-07-03 19:38:35 -07002732 if (unlikely(type &
2733 ~(SKB_GSO_TCPV4 |
2734 SKB_GSO_DODGY |
2735 SKB_GSO_TCP_ECN |
2736 SKB_GSO_TCPV6 |
2737 0) ||
2738 !(type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))))
2739 goto out;
2740
Ilpo Järvinen172589c2007-08-28 15:50:33 -07002741 skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss);
Herbert Xu3820c3f2006-06-29 20:11:25 -07002742
2743 segs = NULL;
2744 goto out;
2745 }
2746
Herbert Xu576a30e2006-06-27 13:22:38 -07002747 segs = skb_segment(skb, features);
Herbert Xuf4c50d92006-06-22 03:02:40 -07002748 if (IS_ERR(segs))
2749 goto out;
2750
Herbert Xu4e704ee2009-01-14 20:41:12 -08002751 delta = htonl(oldlen + (thlen + mss));
Herbert Xuf4c50d92006-06-22 03:02:40 -07002752
2753 skb = segs;
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07002754 th = tcp_hdr(skb);
Herbert Xuf4c50d92006-06-22 03:02:40 -07002755 seq = ntohl(th->seq);
2756
2757 do {
2758 th->fin = th->psh = 0;
2759
Al Virod3bc23e2006-11-14 21:24:49 -08002760 th->check = ~csum_fold((__force __wsum)((__force u32)th->check +
2761 (__force u32)delta));
Patrick McHardy84fa7932006-08-29 16:44:56 -07002762 if (skb->ip_summed != CHECKSUM_PARTIAL)
Arnaldo Carvalho de Melo9c702202007-04-25 18:04:18 -07002763 th->check =
2764 csum_fold(csum_partial(skb_transport_header(skb),
2765 thlen, skb->csum));
Herbert Xuf4c50d92006-06-22 03:02:40 -07002766
Herbert Xu4e704ee2009-01-14 20:41:12 -08002767 seq += mss;
Herbert Xuf4c50d92006-06-22 03:02:40 -07002768 skb = skb->next;
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07002769 th = tcp_hdr(skb);
Herbert Xuf4c50d92006-06-22 03:02:40 -07002770
2771 th->seq = htonl(seq);
2772 th->cwr = 0;
2773 } while (skb->next);
2774
Arnaldo Carvalho de Melo27a884d2007-04-19 20:29:13 -07002775 delta = htonl(oldlen + (skb->tail - skb->transport_header) +
Arnaldo Carvalho de Melo9c702202007-04-25 18:04:18 -07002776 skb->data_len);
Al Virod3bc23e2006-11-14 21:24:49 -08002777 th->check = ~csum_fold((__force __wsum)((__force u32)th->check +
2778 (__force u32)delta));
Patrick McHardy84fa7932006-08-29 16:44:56 -07002779 if (skb->ip_summed != CHECKSUM_PARTIAL)
Arnaldo Carvalho de Melo9c702202007-04-25 18:04:18 -07002780 th->check = csum_fold(csum_partial(skb_transport_header(skb),
2781 thlen, skb->csum));
Herbert Xuf4c50d92006-06-22 03:02:40 -07002782
2783out:
2784 return segs;
2785}
Herbert Xuadcfc7d2006-06-30 13:36:15 -07002786EXPORT_SYMBOL(tcp_tso_segment);
Herbert Xuf4c50d92006-06-22 03:02:40 -07002787
Herbert Xubf296b12008-12-15 23:43:36 -08002788struct sk_buff **tcp_gro_receive(struct sk_buff **head, struct sk_buff *skb)
2789{
2790 struct sk_buff **pp = NULL;
2791 struct sk_buff *p;
2792 struct tcphdr *th;
2793 struct tcphdr *th2;
Herbert Xua0a69a02009-04-17 02:34:38 -07002794 unsigned int len;
Herbert Xubf296b12008-12-15 23:43:36 -08002795 unsigned int thlen;
Eric Dumazet0eae88f2010-04-20 19:06:52 -07002796 __be32 flags;
Herbert Xubf296b12008-12-15 23:43:36 -08002797 unsigned int mss = 1;
Herbert Xua5b1cf22009-05-26 18:50:28 +00002798 unsigned int hlen;
2799 unsigned int off;
Herbert Xubf296b12008-12-15 23:43:36 -08002800 int flush = 1;
Herbert Xuaa6320d2009-02-08 18:00:40 +00002801 int i;
Herbert Xubf296b12008-12-15 23:43:36 -08002802
Herbert Xua5b1cf22009-05-26 18:50:28 +00002803 off = skb_gro_offset(skb);
2804 hlen = off + sizeof(*th);
2805 th = skb_gro_header_fast(skb, off);
2806 if (skb_gro_header_hard(skb, hlen)) {
2807 th = skb_gro_header_slow(skb, hlen, off);
2808 if (unlikely(!th))
2809 goto out;
2810 }
Herbert Xubf296b12008-12-15 23:43:36 -08002811
Herbert Xubf296b12008-12-15 23:43:36 -08002812 thlen = th->doff * 4;
2813 if (thlen < sizeof(*th))
2814 goto out;
2815
Herbert Xua5b1cf22009-05-26 18:50:28 +00002816 hlen = off + thlen;
2817 if (skb_gro_header_hard(skb, hlen)) {
2818 th = skb_gro_header_slow(skb, hlen, off);
2819 if (unlikely(!th))
2820 goto out;
2821 }
Herbert Xubf296b12008-12-15 23:43:36 -08002822
Herbert Xu86911732009-01-29 14:19:50 +00002823 skb_gro_pull(skb, thlen);
Herbert Xubf296b12008-12-15 23:43:36 -08002824
Herbert Xua0a69a02009-04-17 02:34:38 -07002825 len = skb_gro_len(skb);
Herbert Xubf296b12008-12-15 23:43:36 -08002826 flags = tcp_flag_word(th);
2827
2828 for (; (p = *head); head = &p->next) {
2829 if (!NAPI_GRO_CB(p)->same_flow)
2830 continue;
2831
2832 th2 = tcp_hdr(p);
2833
Herbert Xu745898e2009-05-26 18:50:24 +00002834 if (*(u32 *)&th->source ^ *(u32 *)&th2->source) {
Herbert Xubf296b12008-12-15 23:43:36 -08002835 NAPI_GRO_CB(p)->same_flow = 0;
2836 continue;
2837 }
2838
2839 goto found;
2840 }
2841
2842 goto out_check_final;
2843
2844found:
2845 flush = NAPI_GRO_CB(p)->flush;
Eric Dumazet0eae88f2010-04-20 19:06:52 -07002846 flush |= (__force int)(flags & TCP_FLAG_CWR);
2847 flush |= (__force int)((flags ^ tcp_flag_word(th2)) &
2848 ~(TCP_FLAG_CWR | TCP_FLAG_FIN | TCP_FLAG_PSH));
2849 flush |= (__force int)(th->ack_seq ^ th2->ack_seq);
Herbert Xua2a804c2009-05-26 18:50:34 +00002850 for (i = sizeof(*th); i < thlen; i += 4)
Herbert Xuaa6320d2009-02-08 18:00:40 +00002851 flush |= *(u32 *)((u8 *)th + i) ^
2852 *(u32 *)((u8 *)th2 + i);
Herbert Xubf296b12008-12-15 23:43:36 -08002853
Herbert Xub5302562009-01-04 16:13:19 -08002854 mss = skb_shinfo(p)->gso_size;
Herbert Xubf296b12008-12-15 23:43:36 -08002855
Herbert Xu30a3ae32009-05-26 18:50:26 +00002856 flush |= (len - 1) >= mss;
Herbert Xuaa6320d2009-02-08 18:00:40 +00002857 flush |= (ntohl(th2->seq) + skb_gro_len(p)) ^ ntohl(th->seq);
Herbert Xubf296b12008-12-15 23:43:36 -08002858
2859 if (flush || skb_gro_receive(head, skb)) {
2860 mss = 1;
2861 goto out_check_final;
2862 }
2863
2864 p = *head;
2865 th2 = tcp_hdr(p);
2866 tcp_flag_word(th2) |= flags & (TCP_FLAG_FIN | TCP_FLAG_PSH);
2867
2868out_check_final:
Herbert Xua0a69a02009-04-17 02:34:38 -07002869 flush = len < mss;
Eric Dumazet0eae88f2010-04-20 19:06:52 -07002870 flush |= (__force int)(flags & (TCP_FLAG_URG | TCP_FLAG_PSH |
2871 TCP_FLAG_RST | TCP_FLAG_SYN |
2872 TCP_FLAG_FIN));
Herbert Xubf296b12008-12-15 23:43:36 -08002873
2874 if (p && (!NAPI_GRO_CB(skb)->same_flow || flush))
2875 pp = head;
2876
2877out:
2878 NAPI_GRO_CB(skb)->flush |= flush;
2879
2880 return pp;
2881}
Herbert Xu684f2172009-01-08 10:41:23 -08002882EXPORT_SYMBOL(tcp_gro_receive);
Herbert Xubf296b12008-12-15 23:43:36 -08002883
2884int tcp_gro_complete(struct sk_buff *skb)
2885{
2886 struct tcphdr *th = tcp_hdr(skb);
2887
2888 skb->csum_start = skb_transport_header(skb) - skb->head;
2889 skb->csum_offset = offsetof(struct tcphdr, check);
2890 skb->ip_summed = CHECKSUM_PARTIAL;
2891
Herbert Xubf296b12008-12-15 23:43:36 -08002892 skb_shinfo(skb)->gso_segs = NAPI_GRO_CB(skb)->count;
2893
2894 if (th->cwr)
2895 skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
2896
2897 return 0;
2898}
Herbert Xu684f2172009-01-08 10:41:23 -08002899EXPORT_SYMBOL(tcp_gro_complete);
Herbert Xubf296b12008-12-15 23:43:36 -08002900
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002901#ifdef CONFIG_TCP_MD5SIG
2902static unsigned long tcp_md5sig_users;
Eric Dumazet765cf992011-09-12 20:28:37 +00002903static struct tcp_md5sig_pool __percpu *tcp_md5sig_pool;
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002904static DEFINE_SPINLOCK(tcp_md5sig_pool_lock);
2905
Eric Dumazet765cf992011-09-12 20:28:37 +00002906static void __tcp_free_md5sig_pool(struct tcp_md5sig_pool __percpu *pool)
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002907{
2908 int cpu;
Eric Dumazet765cf992011-09-12 20:28:37 +00002909
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002910 for_each_possible_cpu(cpu) {
Eric Dumazet765cf992011-09-12 20:28:37 +00002911 struct tcp_md5sig_pool *p = per_cpu_ptr(pool, cpu);
2912
2913 if (p->md5_desc.tfm)
2914 crypto_free_hash(p->md5_desc.tfm);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002915 }
2916 free_percpu(pool);
2917}
2918
2919void tcp_free_md5sig_pool(void)
2920{
Eric Dumazet765cf992011-09-12 20:28:37 +00002921 struct tcp_md5sig_pool __percpu *pool = NULL;
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002922
David S. Miller2c4f6212007-02-20 23:51:47 -08002923 spin_lock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002924 if (--tcp_md5sig_users == 0) {
2925 pool = tcp_md5sig_pool;
2926 tcp_md5sig_pool = NULL;
2927 }
David S. Miller2c4f6212007-02-20 23:51:47 -08002928 spin_unlock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002929 if (pool)
2930 __tcp_free_md5sig_pool(pool);
2931}
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002932EXPORT_SYMBOL(tcp_free_md5sig_pool);
2933
Eric Dumazet765cf992011-09-12 20:28:37 +00002934static struct tcp_md5sig_pool __percpu *
Tejun Heo7d720c32010-02-16 15:20:26 +00002935__tcp_alloc_md5sig_pool(struct sock *sk)
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002936{
2937 int cpu;
Eric Dumazet765cf992011-09-12 20:28:37 +00002938 struct tcp_md5sig_pool __percpu *pool;
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002939
Eric Dumazet765cf992011-09-12 20:28:37 +00002940 pool = alloc_percpu(struct tcp_md5sig_pool);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002941 if (!pool)
2942 return NULL;
2943
2944 for_each_possible_cpu(cpu) {
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002945 struct crypto_hash *hash;
2946
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002947 hash = crypto_alloc_hash("md5", 0, CRYPTO_ALG_ASYNC);
2948 if (!hash || IS_ERR(hash))
2949 goto out_free;
2950
Eric Dumazet765cf992011-09-12 20:28:37 +00002951 per_cpu_ptr(pool, cpu)->md5_desc.tfm = hash;
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002952 }
2953 return pool;
2954out_free:
2955 __tcp_free_md5sig_pool(pool);
2956 return NULL;
2957}
2958
Eric Dumazet765cf992011-09-12 20:28:37 +00002959struct tcp_md5sig_pool __percpu *tcp_alloc_md5sig_pool(struct sock *sk)
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002960{
Eric Dumazet765cf992011-09-12 20:28:37 +00002961 struct tcp_md5sig_pool __percpu *pool;
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002962 int alloc = 0;
2963
2964retry:
David S. Miller2c4f6212007-02-20 23:51:47 -08002965 spin_lock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002966 pool = tcp_md5sig_pool;
2967 if (tcp_md5sig_users++ == 0) {
2968 alloc = 1;
David S. Miller2c4f6212007-02-20 23:51:47 -08002969 spin_unlock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002970 } else if (!pool) {
2971 tcp_md5sig_users--;
David S. Miller2c4f6212007-02-20 23:51:47 -08002972 spin_unlock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002973 cpu_relax();
2974 goto retry;
2975 } else
David S. Miller2c4f6212007-02-20 23:51:47 -08002976 spin_unlock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002977
2978 if (alloc) {
2979 /* we cannot hold spinlock here because this may sleep. */
Eric Dumazet765cf992011-09-12 20:28:37 +00002980 struct tcp_md5sig_pool __percpu *p;
Tejun Heo7d720c32010-02-16 15:20:26 +00002981
2982 p = __tcp_alloc_md5sig_pool(sk);
David S. Miller2c4f6212007-02-20 23:51:47 -08002983 spin_lock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002984 if (!p) {
2985 tcp_md5sig_users--;
David S. Miller2c4f6212007-02-20 23:51:47 -08002986 spin_unlock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002987 return NULL;
2988 }
2989 pool = tcp_md5sig_pool;
2990 if (pool) {
2991 /* oops, it has already been assigned. */
David S. Miller2c4f6212007-02-20 23:51:47 -08002992 spin_unlock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002993 __tcp_free_md5sig_pool(p);
2994 } else {
2995 tcp_md5sig_pool = pool = p;
David S. Miller2c4f6212007-02-20 23:51:47 -08002996 spin_unlock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002997 }
2998 }
2999 return pool;
3000}
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08003001EXPORT_SYMBOL(tcp_alloc_md5sig_pool);
3002
Eric Dumazet35790c02010-05-16 00:34:04 -07003003
3004/**
3005 * tcp_get_md5sig_pool - get md5sig_pool for this user
3006 *
3007 * We use percpu structure, so if we succeed, we exit with preemption
3008 * and BH disabled, to make sure another thread or softirq handling
3009 * wont try to get same context.
3010 */
3011struct tcp_md5sig_pool *tcp_get_md5sig_pool(void)
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08003012{
Eric Dumazet765cf992011-09-12 20:28:37 +00003013 struct tcp_md5sig_pool __percpu *p;
Eric Dumazet35790c02010-05-16 00:34:04 -07003014
3015 local_bh_disable();
3016
3017 spin_lock(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08003018 p = tcp_md5sig_pool;
3019 if (p)
3020 tcp_md5sig_users++;
Eric Dumazet35790c02010-05-16 00:34:04 -07003021 spin_unlock(&tcp_md5sig_pool_lock);
3022
3023 if (p)
Eric Dumazet765cf992011-09-12 20:28:37 +00003024 return this_cpu_ptr(p);
Eric Dumazet35790c02010-05-16 00:34:04 -07003025
3026 local_bh_enable();
3027 return NULL;
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08003028}
Eric Dumazet35790c02010-05-16 00:34:04 -07003029EXPORT_SYMBOL(tcp_get_md5sig_pool);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08003030
Eric Dumazet35790c02010-05-16 00:34:04 -07003031void tcp_put_md5sig_pool(void)
David S. Miller6931ba72006-12-13 16:25:44 -08003032{
Eric Dumazet35790c02010-05-16 00:34:04 -07003033 local_bh_enable();
David S. Miller6931ba72006-12-13 16:25:44 -08003034 tcp_free_md5sig_pool();
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08003035}
Eric Dumazet35790c02010-05-16 00:34:04 -07003036EXPORT_SYMBOL(tcp_put_md5sig_pool);
Adam Langley49a72df2008-07-19 00:01:42 -07003037
3038int tcp_md5_hash_header(struct tcp_md5sig_pool *hp,
Eric Dumazetca35a0e2011-10-24 01:52:35 -04003039 const struct tcphdr *th)
Adam Langley49a72df2008-07-19 00:01:42 -07003040{
3041 struct scatterlist sg;
Eric Dumazetca35a0e2011-10-24 01:52:35 -04003042 struct tcphdr hdr;
Adam Langley49a72df2008-07-19 00:01:42 -07003043 int err;
3044
Eric Dumazetca35a0e2011-10-24 01:52:35 -04003045 /* We are not allowed to change tcphdr, make a local copy */
3046 memcpy(&hdr, th, sizeof(hdr));
3047 hdr.check = 0;
3048
Adam Langley49a72df2008-07-19 00:01:42 -07003049 /* options aren't included in the hash */
Eric Dumazetca35a0e2011-10-24 01:52:35 -04003050 sg_init_one(&sg, &hdr, sizeof(hdr));
3051 err = crypto_hash_update(&hp->md5_desc, &sg, sizeof(hdr));
Adam Langley49a72df2008-07-19 00:01:42 -07003052 return err;
3053}
Adam Langley49a72df2008-07-19 00:01:42 -07003054EXPORT_SYMBOL(tcp_md5_hash_header);
3055
3056int tcp_md5_hash_skb_data(struct tcp_md5sig_pool *hp,
Eric Dumazetcf533ea2011-10-21 05:22:42 -04003057 const struct sk_buff *skb, unsigned int header_len)
Adam Langley49a72df2008-07-19 00:01:42 -07003058{
3059 struct scatterlist sg;
3060 const struct tcphdr *tp = tcp_hdr(skb);
3061 struct hash_desc *desc = &hp->md5_desc;
3062 unsigned i;
3063 const unsigned head_data_len = skb_headlen(skb) > header_len ?
3064 skb_headlen(skb) - header_len : 0;
3065 const struct skb_shared_info *shi = skb_shinfo(skb);
Eric Dumazetd7fd1b572010-05-17 20:40:51 +00003066 struct sk_buff *frag_iter;
Adam Langley49a72df2008-07-19 00:01:42 -07003067
3068 sg_init_table(&sg, 1);
3069
3070 sg_set_buf(&sg, ((u8 *) tp) + header_len, head_data_len);
3071 if (crypto_hash_update(desc, &sg, head_data_len))
3072 return 1;
3073
3074 for (i = 0; i < shi->nr_frags; ++i) {
3075 const struct skb_frag_struct *f = &shi->frags[i];
Ian Campbellaff65da2011-08-22 23:44:59 +00003076 struct page *page = skb_frag_page(f);
Eric Dumazet9e903e02011-10-18 21:00:24 +00003077 sg_set_page(&sg, page, skb_frag_size(f), f->page_offset);
3078 if (crypto_hash_update(desc, &sg, skb_frag_size(f)))
Adam Langley49a72df2008-07-19 00:01:42 -07003079 return 1;
3080 }
3081
Eric Dumazetd7fd1b572010-05-17 20:40:51 +00003082 skb_walk_frags(skb, frag_iter)
3083 if (tcp_md5_hash_skb_data(hp, frag_iter, 0))
3084 return 1;
3085
Adam Langley49a72df2008-07-19 00:01:42 -07003086 return 0;
3087}
Adam Langley49a72df2008-07-19 00:01:42 -07003088EXPORT_SYMBOL(tcp_md5_hash_skb_data);
3089
Eric Dumazetcf533ea2011-10-21 05:22:42 -04003090int tcp_md5_hash_key(struct tcp_md5sig_pool *hp, const struct tcp_md5sig_key *key)
Adam Langley49a72df2008-07-19 00:01:42 -07003091{
3092 struct scatterlist sg;
3093
3094 sg_init_one(&sg, key->key, key->keylen);
3095 return crypto_hash_update(&hp->md5_desc, &sg, key->keylen);
3096}
Adam Langley49a72df2008-07-19 00:01:42 -07003097EXPORT_SYMBOL(tcp_md5_hash_key);
3098
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08003099#endif
3100
William Allen Simpsonda5c78c2009-12-02 18:12:09 +00003101/**
3102 * Each Responder maintains up to two secret values concurrently for
3103 * efficient secret rollover. Each secret value has 4 states:
3104 *
3105 * Generating. (tcp_secret_generating != tcp_secret_primary)
3106 * Generates new Responder-Cookies, but not yet used for primary
3107 * verification. This is a short-term state, typically lasting only
3108 * one round trip time (RTT).
3109 *
3110 * Primary. (tcp_secret_generating == tcp_secret_primary)
3111 * Used both for generation and primary verification.
3112 *
3113 * Retiring. (tcp_secret_retiring != tcp_secret_secondary)
3114 * Used for verification, until the first failure that can be
3115 * verified by the newer Generating secret. At that time, this
3116 * cookie's state is changed to Secondary, and the Generating
3117 * cookie's state is changed to Primary. This is a short-term state,
3118 * typically lasting only one round trip time (RTT).
3119 *
3120 * Secondary. (tcp_secret_retiring == tcp_secret_secondary)
3121 * Used for secondary verification, after primary verification
3122 * failures. This state lasts no more than twice the Maximum Segment
3123 * Lifetime (2MSL). Then, the secret is discarded.
3124 */
3125struct tcp_cookie_secret {
3126 /* The secret is divided into two parts. The digest part is the
3127 * equivalent of previously hashing a secret and saving the state,
3128 * and serves as an initialization vector (IV). The message part
3129 * serves as the trailing secret.
3130 */
3131 u32 secrets[COOKIE_WORKSPACE_WORDS];
3132 unsigned long expires;
3133};
3134
3135#define TCP_SECRET_1MSL (HZ * TCP_PAWS_MSL)
3136#define TCP_SECRET_2MSL (HZ * TCP_PAWS_MSL * 2)
3137#define TCP_SECRET_LIFE (HZ * 600)
3138
3139static struct tcp_cookie_secret tcp_secret_one;
3140static struct tcp_cookie_secret tcp_secret_two;
3141
3142/* Essentially a circular list, without dynamic allocation. */
3143static struct tcp_cookie_secret *tcp_secret_generating;
3144static struct tcp_cookie_secret *tcp_secret_primary;
3145static struct tcp_cookie_secret *tcp_secret_retiring;
3146static struct tcp_cookie_secret *tcp_secret_secondary;
3147
3148static DEFINE_SPINLOCK(tcp_secret_locker);
3149
3150/* Select a pseudo-random word in the cookie workspace.
3151 */
3152static inline u32 tcp_cookie_work(const u32 *ws, const int n)
3153{
3154 return ws[COOKIE_DIGEST_WORDS + ((COOKIE_MESSAGE_WORDS-1) & ws[n])];
3155}
3156
3157/* Fill bakery[COOKIE_WORKSPACE_WORDS] with generator, updating as needed.
3158 * Called in softirq context.
3159 * Returns: 0 for success.
3160 */
3161int tcp_cookie_generator(u32 *bakery)
3162{
3163 unsigned long jiffy = jiffies;
3164
3165 if (unlikely(time_after_eq(jiffy, tcp_secret_generating->expires))) {
3166 spin_lock_bh(&tcp_secret_locker);
3167 if (!time_after_eq(jiffy, tcp_secret_generating->expires)) {
3168 /* refreshed by another */
3169 memcpy(bakery,
3170 &tcp_secret_generating->secrets[0],
3171 COOKIE_WORKSPACE_WORDS);
3172 } else {
3173 /* still needs refreshing */
3174 get_random_bytes(bakery, COOKIE_WORKSPACE_WORDS);
3175
3176 /* The first time, paranoia assumes that the
3177 * randomization function isn't as strong. But,
3178 * this secret initialization is delayed until
3179 * the last possible moment (packet arrival).
3180 * Although that time is observable, it is
3181 * unpredictably variable. Mash in the most
3182 * volatile clock bits available, and expire the
3183 * secret extra quickly.
3184 */
3185 if (unlikely(tcp_secret_primary->expires ==
3186 tcp_secret_secondary->expires)) {
3187 struct timespec tv;
3188
3189 getnstimeofday(&tv);
3190 bakery[COOKIE_DIGEST_WORDS+0] ^=
3191 (u32)tv.tv_nsec;
3192
3193 tcp_secret_secondary->expires = jiffy
3194 + TCP_SECRET_1MSL
3195 + (0x0f & tcp_cookie_work(bakery, 0));
3196 } else {
3197 tcp_secret_secondary->expires = jiffy
3198 + TCP_SECRET_LIFE
3199 + (0xff & tcp_cookie_work(bakery, 1));
3200 tcp_secret_primary->expires = jiffy
3201 + TCP_SECRET_2MSL
3202 + (0x1f & tcp_cookie_work(bakery, 2));
3203 }
3204 memcpy(&tcp_secret_secondary->secrets[0],
3205 bakery, COOKIE_WORKSPACE_WORDS);
3206
3207 rcu_assign_pointer(tcp_secret_generating,
3208 tcp_secret_secondary);
3209 rcu_assign_pointer(tcp_secret_retiring,
3210 tcp_secret_primary);
3211 /*
3212 * Neither call_rcu() nor synchronize_rcu() needed.
3213 * Retiring data is not freed. It is replaced after
3214 * further (locked) pointer updates, and a quiet time
3215 * (minimum 1MSL, maximum LIFE - 2MSL).
3216 */
3217 }
3218 spin_unlock_bh(&tcp_secret_locker);
3219 } else {
3220 rcu_read_lock_bh();
3221 memcpy(bakery,
3222 &rcu_dereference(tcp_secret_generating)->secrets[0],
3223 COOKIE_WORKSPACE_WORDS);
3224 rcu_read_unlock_bh();
3225 }
3226 return 0;
3227}
3228EXPORT_SYMBOL(tcp_cookie_generator);
3229
Andi Kleen4ac02ba2007-04-20 17:11:46 -07003230void tcp_done(struct sock *sk)
3231{
Jianjun Kong5a5f3a82008-11-03 00:24:34 -08003232 if (sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV)
Pavel Emelyanov63231bd2008-07-16 20:22:25 -07003233 TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_ATTEMPTFAILS);
Andi Kleen4ac02ba2007-04-20 17:11:46 -07003234
3235 tcp_set_state(sk, TCP_CLOSE);
3236 tcp_clear_xmit_timers(sk);
3237
3238 sk->sk_shutdown = SHUTDOWN_MASK;
3239
3240 if (!sock_flag(sk, SOCK_DEAD))
3241 sk->sk_state_change(sk);
3242 else
3243 inet_csk_destroy_sock(sk);
3244}
3245EXPORT_SYMBOL_GPL(tcp_done);
3246
Stephen Hemminger5f8ef482005-06-23 20:37:36 -07003247extern struct tcp_congestion_ops tcp_reno;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003248
3249static __initdata unsigned long thash_entries;
3250static int __init set_thash_entries(char *str)
3251{
3252 if (!str)
3253 return 0;
3254 thash_entries = simple_strtoul(str, &str, 0);
3255 return 1;
3256}
3257__setup("thash_entries=", set_thash_entries);
3258
Glauber Costa4acb4192012-01-30 01:20:17 +00003259void tcp_init_mem(struct net *net)
3260{
Glauber Costa4acb4192012-01-30 01:20:17 +00003261 unsigned long limit = nr_free_buffer_pages() / 8;
3262 limit = max(limit, 128UL);
3263 net->ipv4.sysctl_tcp_mem[0] = limit / 4 * 3;
3264 net->ipv4.sysctl_tcp_mem[1] = limit;
3265 net->ipv4.sysctl_tcp_mem[2] = net->ipv4.sysctl_tcp_mem[0] * 2;
3266}
3267
Linus Torvalds1da177e2005-04-16 15:20:36 -07003268void __init tcp_init(void)
3269{
3270 struct sk_buff *skb = NULL;
Eric Dumazetf03d78d2011-07-07 00:27:05 -07003271 unsigned long limit;
Eric Dumazetb49960a2012-05-02 02:28:41 +00003272 int max_rshare, max_wshare, cnt;
Dimitri Sivanich074b8512012-02-08 12:39:07 -08003273 unsigned int i;
William Allen Simpsonda5c78c2009-12-02 18:12:09 +00003274 unsigned long jiffy = jiffies;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003275
Pavel Emelyanov1f9e6362007-12-11 02:12:04 -08003276 BUILD_BUG_ON(sizeof(struct tcp_skb_cb) > sizeof(skb->cb));
Linus Torvalds1da177e2005-04-16 15:20:36 -07003277
Eric Dumazet17483762008-11-25 21:16:35 -08003278 percpu_counter_init(&tcp_sockets_allocated, 0);
Eric Dumazetdd24c002008-11-25 21:17:14 -08003279 percpu_counter_init(&tcp_orphan_count, 0);
Arnaldo Carvalho de Melo6e04e022005-08-09 20:07:35 -07003280 tcp_hashinfo.bind_bucket_cachep =
3281 kmem_cache_create("tcp_bind_bucket",
3282 sizeof(struct inet_bind_bucket), 0,
Paul Mundt20c2df82007-07-20 10:11:58 +09003283 SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003284
Linus Torvalds1da177e2005-04-16 15:20:36 -07003285 /* Size and allocate the main established and bind bucket
3286 * hash tables.
3287 *
3288 * The methodology is similar to that of the buffer cache.
3289 */
Arnaldo Carvalho de Melo6e04e022005-08-09 20:07:35 -07003290 tcp_hashinfo.ehash =
Linus Torvalds1da177e2005-04-16 15:20:36 -07003291 alloc_large_system_hash("TCP established",
Arnaldo Carvalho de Melo0f7ff922005-08-09 19:59:44 -07003292 sizeof(struct inet_ehash_bucket),
Linus Torvalds1da177e2005-04-16 15:20:36 -07003293 thash_entries,
Jan Beulich44813742009-09-21 17:03:05 -07003294 (totalram_pages >= 128 * 1024) ?
Mike Stroyan18955cf2005-11-29 16:12:55 -08003295 13 : 15,
John Heffner9e950ef2006-11-06 23:10:51 -08003296 0,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003297 NULL,
Eric Dumazetf373b532009-10-09 00:16:19 +00003298 &tcp_hashinfo.ehash_mask,
Jean Delvare0ccfe612007-10-30 00:59:25 -07003299 thash_entries ? 0 : 512 * 1024);
Eric Dumazetf373b532009-10-09 00:16:19 +00003300 for (i = 0; i <= tcp_hashinfo.ehash_mask; i++) {
Eric Dumazet3ab5aee2008-11-16 19:40:17 -08003301 INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i);
3302 INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].twchain, i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003303 }
Eric Dumazet230140c2007-11-07 02:40:20 -08003304 if (inet_ehash_locks_alloc(&tcp_hashinfo))
3305 panic("TCP: failed to alloc ehash_locks");
Arnaldo Carvalho de Melo6e04e022005-08-09 20:07:35 -07003306 tcp_hashinfo.bhash =
Linus Torvalds1da177e2005-04-16 15:20:36 -07003307 alloc_large_system_hash("TCP bind",
Arnaldo Carvalho de Melo0f7ff922005-08-09 19:59:44 -07003308 sizeof(struct inet_bind_hashbucket),
Eric Dumazetf373b532009-10-09 00:16:19 +00003309 tcp_hashinfo.ehash_mask + 1,
Jan Beulich44813742009-09-21 17:03:05 -07003310 (totalram_pages >= 128 * 1024) ?
Mike Stroyan18955cf2005-11-29 16:12:55 -08003311 13 : 15,
John Heffner9e950ef2006-11-06 23:10:51 -08003312 0,
Arnaldo Carvalho de Melo6e04e022005-08-09 20:07:35 -07003313 &tcp_hashinfo.bhash_size,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003314 NULL,
3315 64 * 1024);
Dimitri Sivanich074b8512012-02-08 12:39:07 -08003316 tcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size;
Arnaldo Carvalho de Melo6e04e022005-08-09 20:07:35 -07003317 for (i = 0; i < tcp_hashinfo.bhash_size; i++) {
3318 spin_lock_init(&tcp_hashinfo.bhash[i].lock);
3319 INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003320 }
3321
Eric Dumazetc5ed63d2010-08-25 23:02:17 -07003322
3323 cnt = tcp_hashinfo.ehash_mask + 1;
3324
3325 tcp_death_row.sysctl_max_tw_buckets = cnt / 2;
3326 sysctl_tcp_max_orphans = cnt / 2;
3327 sysctl_max_syn_backlog = max(128, cnt / 256);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003328
Glauber Costa4acb4192012-01-30 01:20:17 +00003329 tcp_init_mem(&init_net);
Jason Wangc43b8742012-02-02 00:07:00 +00003330 /* Set per-socket limits to no more than 1/128 the pressure threshold */
Eric Dumazet5fb84b12012-04-10 00:56:42 +00003331 limit = nr_free_buffer_pages() << (PAGE_SHIFT - 7);
Eric Dumazetb49960a2012-05-02 02:28:41 +00003332 max_wshare = min(4UL*1024*1024, limit);
3333 max_rshare = min(6UL*1024*1024, limit);
John Heffner7b4f4b52006-03-25 01:34:07 -08003334
Hideo Aoki3ab224b2007-12-31 00:11:19 -08003335 sysctl_tcp_wmem[0] = SK_MEM_QUANTUM;
John Heffner7b4f4b52006-03-25 01:34:07 -08003336 sysctl_tcp_wmem[1] = 16*1024;
Eric Dumazetb49960a2012-05-02 02:28:41 +00003337 sysctl_tcp_wmem[2] = max(64*1024, max_wshare);
John Heffner7b4f4b52006-03-25 01:34:07 -08003338
Hideo Aoki3ab224b2007-12-31 00:11:19 -08003339 sysctl_tcp_rmem[0] = SK_MEM_QUANTUM;
John Heffner7b4f4b52006-03-25 01:34:07 -08003340 sysctl_tcp_rmem[1] = 87380;
Eric Dumazetb49960a2012-05-02 02:28:41 +00003341 sysctl_tcp_rmem[2] = max(87380, max_rshare);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003342
Joe Perchesafd465032012-03-12 07:03:32 +00003343 pr_info("Hash tables configured (established %u bind %u)\n",
Joe Perches058bd4d2012-03-11 18:36:11 +00003344 tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size);
Stephen Hemminger317a76f2005-06-23 12:19:55 -07003345
3346 tcp_register_congestion_control(&tcp_reno);
William Allen Simpsonda5c78c2009-12-02 18:12:09 +00003347
3348 memset(&tcp_secret_one.secrets[0], 0, sizeof(tcp_secret_one.secrets));
3349 memset(&tcp_secret_two.secrets[0], 0, sizeof(tcp_secret_two.secrets));
3350 tcp_secret_one.expires = jiffy; /* past due */
3351 tcp_secret_two.expires = jiffy; /* past due */
3352 tcp_secret_generating = &tcp_secret_one;
3353 tcp_secret_primary = &tcp_secret_one;
3354 tcp_secret_retiring = &tcp_secret_two;
3355 tcp_secret_secondary = &tcp_secret_two;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003356}
Robert Love2365d052008-05-12 17:08:29 -04003357
3358static int tcp_is_local(struct net *net, __be32 addr) {
3359 struct rtable *rt;
3360 struct flowi4 fl4 = { .daddr = addr };
3361 rt = ip_route_output_key(net, &fl4);
3362 if (IS_ERR_OR_NULL(rt))
3363 return 0;
3364 return rt->dst.dev && (rt->dst.dev->flags & IFF_LOOPBACK);
3365}
3366
3367#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3368static int tcp_is_local6(struct net *net, struct in6_addr *addr) {
3369 struct rt6_info *rt6 = rt6_lookup(net, addr, addr, 0, 0);
3370 return rt6 && rt6->dst.dev && (rt6->dst.dev->flags & IFF_LOOPBACK);
3371}
3372#endif
3373
3374/*
3375 * tcp_nuke_addr - destroy all sockets on the given local address
3376 * if local address is the unspecified address (0.0.0.0 or ::), destroy all
3377 * sockets with local addresses that are not configured.
3378 */
3379int tcp_nuke_addr(struct net *net, struct sockaddr *addr)
3380{
3381 int family = addr->sa_family;
3382 unsigned int bucket;
3383
Bryan Huntsman3f2bc4d2011-08-16 17:27:22 -07003384 struct in_addr *in = NULL;
Robert Love2365d052008-05-12 17:08:29 -04003385#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
Bryan Huntsman3f2bc4d2011-08-16 17:27:22 -07003386 struct in6_addr *in6 = NULL;
Robert Love2365d052008-05-12 17:08:29 -04003387#endif
3388 if (family == AF_INET) {
3389 in = &((struct sockaddr_in *)addr)->sin_addr;
3390#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3391 } else if (family == AF_INET6) {
3392 in6 = &((struct sockaddr_in6 *)addr)->sin6_addr;
3393#endif
3394 } else {
3395 return -EAFNOSUPPORT;
3396 }
3397
3398 for (bucket = 0; bucket < tcp_hashinfo.ehash_mask; bucket++) {
3399 struct hlist_nulls_node *node;
3400 struct sock *sk;
3401 spinlock_t *lock = inet_ehash_lockp(&tcp_hashinfo, bucket);
3402
3403restart:
3404 spin_lock_bh(lock);
3405 sk_nulls_for_each(sk, node, &tcp_hashinfo.ehash[bucket].chain) {
3406 struct inet_sock *inet = inet_sk(sk);
3407
3408 if (sysctl_ip_dynaddr && sk->sk_state == TCP_SYN_SENT)
3409 continue;
3410 if (sock_flag(sk, SOCK_DEAD))
3411 continue;
3412
3413 if (family == AF_INET) {
3414 __be32 s4 = inet->inet_rcv_saddr;
3415 if (s4 == LOOPBACK4_IPV6)
3416 continue;
3417
3418 if (in->s_addr != s4 &&
3419 !(in->s_addr == INADDR_ANY &&
3420 !tcp_is_local(net, s4)))
3421 continue;
3422 }
3423
3424#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3425 if (family == AF_INET6) {
3426 struct in6_addr *s6;
3427 if (!inet->pinet6)
3428 continue;
3429
3430 s6 = &inet->pinet6->rcv_saddr;
3431 if (ipv6_addr_type(s6) == IPV6_ADDR_MAPPED)
3432 continue;
3433
3434 if (!ipv6_addr_equal(in6, s6) &&
3435 !(ipv6_addr_equal(in6, &in6addr_any) &&
3436 !tcp_is_local6(net, s6)))
3437 continue;
3438 }
3439#endif
3440
3441 sock_hold(sk);
3442 spin_unlock_bh(lock);
3443
3444 local_bh_disable();
3445 bh_lock_sock(sk);
3446 sk->sk_err = ETIMEDOUT;
3447 sk->sk_error_report(sk);
3448
3449 tcp_done(sk);
3450 bh_unlock_sock(sk);
3451 local_bh_enable();
3452 sock_put(sk);
3453
3454 goto restart;
3455 }
3456 spin_unlock_bh(lock);
3457 }
3458
3459 return 0;
3460}