blob: 74a286c2c43bb980609ea99199988f6d1cd44386 [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);
Eric Dumazet17483762008-11-25 21:16:35 -0800299
300/*
301 * Current number of TCP sockets.
302 */
303struct percpu_counter tcp_sockets_allocated;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700304EXPORT_SYMBOL(tcp_sockets_allocated);
305
306/*
Jens Axboe9c55e012007-11-06 23:30:13 -0800307 * TCP splice context
308 */
309struct tcp_splice_state {
310 struct pipe_inode_info *pipe;
311 size_t len;
312 unsigned int flags;
313};
314
315/*
Linus Torvalds1da177e2005-04-16 15:20:36 -0700316 * Pressure flag: try to collapse.
317 * Technical note: it is used by multiple contexts non atomically.
Hideo Aoki3ab224b2007-12-31 00:11:19 -0800318 * All the __sk_mem_schedule() is of this nature: accounting
Linus Torvalds1da177e2005-04-16 15:20:36 -0700319 * is strict, actions are advisory and have some latency.
320 */
Eric Dumazet4103f8c2007-03-27 13:58:31 -0700321int tcp_memory_pressure __read_mostly;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700322EXPORT_SYMBOL(tcp_memory_pressure);
323
Pavel Emelyanov5c52ba12008-07-16 20:28:10 -0700324void tcp_enter_memory_pressure(struct sock *sk)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700325{
326 if (!tcp_memory_pressure) {
Pavel Emelyanov4e673442008-07-16 20:30:14 -0700327 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURES);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700328 tcp_memory_pressure = 1;
329 }
330}
Linus Torvalds1da177e2005-04-16 15:20:36 -0700331EXPORT_SYMBOL(tcp_enter_memory_pressure);
332
Julian Anastasovb103cf32009-10-19 10:10:40 +0000333/* Convert seconds to retransmits based on initial and max timeout */
334static u8 secs_to_retrans(int seconds, int timeout, int rto_max)
335{
336 u8 res = 0;
337
338 if (seconds > 0) {
339 int period = timeout;
340
341 res = 1;
342 while (seconds > period && res < 255) {
343 res++;
344 timeout <<= 1;
345 if (timeout > rto_max)
346 timeout = rto_max;
347 period += timeout;
348 }
349 }
350 return res;
351}
352
353/* Convert retransmits to seconds based on initial and max timeout */
354static int retrans_to_secs(u8 retrans, int timeout, int rto_max)
355{
356 int period = 0;
357
358 if (retrans > 0) {
359 period = timeout;
360 while (--retrans) {
361 timeout <<= 1;
362 if (timeout > rto_max)
363 timeout = rto_max;
364 period += timeout;
365 }
366 }
367 return period;
368}
369
Linus Torvalds1da177e2005-04-16 15:20:36 -0700370/*
Linus Torvalds1da177e2005-04-16 15:20:36 -0700371 * Wait for a TCP event.
372 *
373 * Note that we don't need to lock the socket, as the upper poll layers
374 * take care of normal races (between the test and the event) and we don't
375 * go look at any of the socket buffers directly.
376 */
377unsigned int tcp_poll(struct file *file, struct socket *sock, poll_table *wait)
378{
379 unsigned int mask;
380 struct sock *sk = sock->sk;
Eric Dumazetcf533ea2011-10-21 05:22:42 -0400381 const struct tcp_sock *tp = tcp_sk(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700382
Eric Dumazetaa395142010-04-20 13:03:51 +0000383 sock_poll_wait(file, sk_sleep(sk), wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700384 if (sk->sk_state == TCP_LISTEN)
Arnaldo Carvalho de Melodc40c7b2005-08-23 21:52:58 -0700385 return inet_csk_listen_poll(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700386
387 /* Socket is not locked. We are protected from async events
Will Newton70efce22008-07-16 20:13:43 -0700388 * by poll logic and correct handling of state changes
389 * made by other threads is impossible in any case.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700390 */
391
392 mask = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700393
394 /*
395 * POLLHUP is certainly not done right. But poll() doesn't
396 * have a notion of HUP in just one direction, and for a
397 * socket the read side is more interesting.
398 *
399 * Some poll() documentation says that POLLHUP is incompatible
400 * with the POLLOUT/POLLWR flags, so somebody should check this
401 * all. But careful, it tends to be safer to return too many
402 * bits than too few, and you can easily break real applications
403 * if you don't tell them that something has hung up!
404 *
405 * Check-me.
406 *
407 * Check number 1. POLLHUP is _UNMASKABLE_ event (see UNIX98 and
408 * our fs/select.c). It means that after we received EOF,
409 * poll always returns immediately, making impossible poll() on write()
410 * in state CLOSE_WAIT. One solution is evident --- to set POLLHUP
411 * if and only if shutdown has been made in both directions.
412 * Actually, it is interesting to look how Solaris and DUX
Will Newton70efce22008-07-16 20:13:43 -0700413 * solve this dilemma. I would prefer, if POLLHUP were maskable,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700414 * then we could set it on SND_SHUTDOWN. BTW examples given
415 * in Stevens' books assume exactly this behaviour, it explains
Will Newton70efce22008-07-16 20:13:43 -0700416 * why POLLHUP is incompatible with POLLOUT. --ANK
Linus Torvalds1da177e2005-04-16 15:20:36 -0700417 *
418 * NOTE. Check for TCP_CLOSE is added. The goal is to prevent
419 * blocking on fresh not-connected or disconnected socket. --ANK
420 */
421 if (sk->sk_shutdown == SHUTDOWN_MASK || sk->sk_state == TCP_CLOSE)
422 mask |= POLLHUP;
423 if (sk->sk_shutdown & RCV_SHUTDOWN)
Davide Libenzif348d702006-03-25 03:07:39 -0800424 mask |= POLLIN | POLLRDNORM | POLLRDHUP;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700425
426 /* Connected? */
427 if ((1 << sk->sk_state) & ~(TCPF_SYN_SENT | TCPF_SYN_RECV)) {
David S. Millerc7004482008-10-06 10:43:54 -0700428 int target = sock_rcvlowat(sk, 0, INT_MAX);
429
430 if (tp->urg_seq == tp->copied_seq &&
431 !sock_flag(sk, SOCK_URGINLINE) &&
432 tp->urg_data)
Alexandra Kossovskyb634f872010-03-18 20:29:24 -0700433 target++;
David S. Millerc7004482008-10-06 10:43:54 -0700434
Linus Torvalds1da177e2005-04-16 15:20:36 -0700435 /* Potential race condition. If read of tp below will
436 * escape above sk->sk_state, we can be illegally awaken
437 * in SYN_* states. */
David S. Millerc7004482008-10-06 10:43:54 -0700438 if (tp->rcv_nxt - tp->copied_seq >= target)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700439 mask |= POLLIN | POLLRDNORM;
440
441 if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
442 if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk)) {
443 mask |= POLLOUT | POLLWRNORM;
444 } else { /* send SIGIO later */
445 set_bit(SOCK_ASYNC_NOSPACE,
446 &sk->sk_socket->flags);
447 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
448
449 /* Race breaker. If space is freed after
450 * wspace test but before the flags are set,
451 * IO signal will be lost.
452 */
453 if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk))
454 mask |= POLLOUT | POLLWRNORM;
455 }
KOSAKI Motohirod84ba632010-08-24 16:05:48 +0000456 } else
457 mask |= POLLOUT | POLLWRNORM;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700458
459 if (tp->urg_data & TCP_URG_VALID)
460 mask |= POLLPRI;
461 }
Tom Marshalla4d25802010-09-20 15:42:05 -0700462 /* This barrier is coupled with smp_wmb() in tcp_reset() */
463 smp_rmb();
464 if (sk->sk_err)
465 mask |= POLLERR;
466
Linus Torvalds1da177e2005-04-16 15:20:36 -0700467 return mask;
468}
Eric Dumazet4bc2f182010-07-09 21:22:10 +0000469EXPORT_SYMBOL(tcp_poll);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700470
471int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg)
472{
473 struct tcp_sock *tp = tcp_sk(sk);
474 int answ;
475
476 switch (cmd) {
477 case SIOCINQ:
478 if (sk->sk_state == TCP_LISTEN)
479 return -EINVAL;
480
481 lock_sock(sk);
482 if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
483 answ = 0;
484 else if (sock_flag(sk, SOCK_URGINLINE) ||
485 !tp->urg_data ||
486 before(tp->urg_seq, tp->copied_seq) ||
487 !before(tp->urg_seq, tp->rcv_nxt)) {
David S. Miller91521942009-05-28 21:35:47 -0700488
Linus Torvalds1da177e2005-04-16 15:20:36 -0700489 answ = tp->rcv_nxt - tp->copied_seq;
490
Eric Dumazet95e6a272012-10-18 09:14:12 +0000491 /* Subtract 1, if FIN was received */
492 if (answ && sock_flag(sk, SOCK_DONE))
493 answ--;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700494 } else
495 answ = tp->urg_seq - tp->copied_seq;
496 release_sock(sk);
497 break;
498 case SIOCATMARK:
499 answ = tp->urg_data && tp->urg_seq == tp->copied_seq;
500 break;
501 case SIOCOUTQ:
502 if (sk->sk_state == TCP_LISTEN)
503 return -EINVAL;
504
505 if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
506 answ = 0;
507 else
508 answ = tp->write_seq - tp->snd_una;
509 break;
Mario Schuknecht2f4e1b32011-03-09 14:08:09 -0800510 case SIOCOUTQNSD:
511 if (sk->sk_state == TCP_LISTEN)
512 return -EINVAL;
513
514 if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
515 answ = 0;
516 else
517 answ = tp->write_seq - tp->snd_nxt;
518 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700519 default:
520 return -ENOIOCTLCMD;
Stephen Hemminger3ff50b72007-04-20 17:09:22 -0700521 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700522
523 return put_user(answ, (int __user *)arg);
524}
Eric Dumazet4bc2f182010-07-09 21:22:10 +0000525EXPORT_SYMBOL(tcp_ioctl);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700526
Linus Torvalds1da177e2005-04-16 15:20:36 -0700527static inline void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb)
528{
Eric Dumazet4de075e2011-09-27 13:25:05 -0400529 TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700530 tp->pushed_seq = tp->write_seq;
531}
532
Eric Dumazetcf533ea2011-10-21 05:22:42 -0400533static inline int forced_push(const struct tcp_sock *tp)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700534{
535 return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1));
536}
537
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -0700538static inline void skb_entail(struct sock *sk, struct sk_buff *skb)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700539{
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -0700540 struct tcp_sock *tp = tcp_sk(sk);
Arnaldo Carvalho de Melo352d4802006-11-17 19:59:12 -0200541 struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
542
543 skb->csum = 0;
544 tcb->seq = tcb->end_seq = tp->write_seq;
Eric Dumazet4de075e2011-09-27 13:25:05 -0400545 tcb->tcp_flags = TCPHDR_ACK;
Arnaldo Carvalho de Melo352d4802006-11-17 19:59:12 -0200546 tcb->sacked = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700547 skb_header_release(skb);
David S. Millerfe067e82007-03-07 12:12:44 -0800548 tcp_add_write_queue_tail(sk, skb);
Hideo Aoki3ab224b2007-12-31 00:11:19 -0800549 sk->sk_wmem_queued += skb->truesize;
550 sk_mem_charge(sk, skb->truesize);
David S. Miller89ebd192005-08-23 10:13:06 -0700551 if (tp->nonagle & TCP_NAGLE_PUSH)
YOSHIFUJI Hideakie905a9e2007-02-09 23:24:47 +0900552 tp->nonagle &= ~TCP_NAGLE_PUSH;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700553}
554
Krishna Kumarafeca342009-12-10 07:16:52 +0000555static inline void tcp_mark_urg(struct tcp_sock *tp, int flags)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700556{
Ilpo Järvinen33f5f572008-10-07 14:43:06 -0700557 if (flags & MSG_OOB)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700558 tp->snd_up = tp->write_seq;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700559}
560
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -0700561static inline void tcp_push(struct sock *sk, int flags, int mss_now,
562 int nonagle)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700563{
David S. Millerfe067e82007-03-07 12:12:44 -0800564 if (tcp_send_head(sk)) {
Krishna Kumarafeca342009-12-10 07:16:52 +0000565 struct tcp_sock *tp = tcp_sk(sk);
566
Linus Torvalds1da177e2005-04-16 15:20:36 -0700567 if (!(flags & MSG_MORE) || forced_push(tp))
Krishna Kumarafeca342009-12-10 07:16:52 +0000568 tcp_mark_push(tp, tcp_write_queue_tail(sk));
569
570 tcp_mark_urg(tp, flags);
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -0700571 __tcp_push_pending_frames(sk, mss_now,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700572 (flags & MSG_MORE) ? TCP_NAGLE_CORK : nonagle);
573 }
574}
575
Adrian Bunk6ff77512007-11-06 23:32:26 -0800576static int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
577 unsigned int offset, size_t len)
Jens Axboe9c55e012007-11-06 23:30:13 -0800578{
579 struct tcp_splice_state *tss = rd_desc->arg.data;
Willy Tarreau33966dd2009-01-13 16:04:36 -0800580 int ret;
Jens Axboe9c55e012007-11-06 23:30:13 -0800581
Dimitris Michailidis9fa5fdf2009-01-26 22:15:31 -0800582 ret = skb_splice_bits(skb, offset, tss->pipe, min(rd_desc->count, len),
583 tss->flags);
Willy Tarreau33966dd2009-01-13 16:04:36 -0800584 if (ret > 0)
585 rd_desc->count -= ret;
586 return ret;
Jens Axboe9c55e012007-11-06 23:30:13 -0800587}
588
589static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss)
590{
591 /* Store TCP splice context information in read_descriptor_t. */
592 read_descriptor_t rd_desc = {
593 .arg.data = tss,
Willy Tarreau33966dd2009-01-13 16:04:36 -0800594 .count = tss->len,
Jens Axboe9c55e012007-11-06 23:30:13 -0800595 };
596
597 return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv);
598}
599
600/**
601 * tcp_splice_read - splice data from TCP socket to a pipe
602 * @sock: socket to splice from
603 * @ppos: position (not valid)
604 * @pipe: pipe to splice to
605 * @len: number of bytes to splice
606 * @flags: splice modifier flags
607 *
608 * Description:
609 * Will read pages from given socket and fill them into a pipe.
610 *
611 **/
612ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
613 struct pipe_inode_info *pipe, size_t len,
614 unsigned int flags)
615{
616 struct sock *sk = sock->sk;
617 struct tcp_splice_state tss = {
618 .pipe = pipe,
619 .len = len,
620 .flags = flags,
621 };
622 long timeo;
623 ssize_t spliced;
624 int ret;
625
Changli Gao3a047bf2010-07-12 21:00:12 +0000626 sock_rps_record_flow(sk);
Jens Axboe9c55e012007-11-06 23:30:13 -0800627 /*
628 * We can't seek on a socket input
629 */
630 if (unlikely(*ppos))
631 return -ESPIPE;
632
633 ret = spliced = 0;
634
635 lock_sock(sk);
636
Eric Dumazet42324c62009-10-01 15:26:00 -0700637 timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK);
Jens Axboe9c55e012007-11-06 23:30:13 -0800638 while (tss.len) {
639 ret = __tcp_splice_read(sk, &tss);
640 if (ret < 0)
641 break;
642 else if (!ret) {
643 if (spliced)
644 break;
Jens Axboe9c55e012007-11-06 23:30:13 -0800645 if (sock_flag(sk, SOCK_DONE))
646 break;
647 if (sk->sk_err) {
648 ret = sock_error(sk);
649 break;
650 }
651 if (sk->sk_shutdown & RCV_SHUTDOWN)
652 break;
653 if (sk->sk_state == TCP_CLOSE) {
654 /*
655 * This occurs when user tries to read
656 * from never connected socket.
657 */
658 if (!sock_flag(sk, SOCK_DONE))
659 ret = -ENOTCONN;
660 break;
661 }
662 if (!timeo) {
663 ret = -EAGAIN;
664 break;
665 }
666 sk_wait_data(sk, &timeo);
667 if (signal_pending(current)) {
668 ret = sock_intr_errno(timeo);
669 break;
670 }
671 continue;
672 }
673 tss.len -= ret;
674 spliced += ret;
675
Willy Tarreau33966dd2009-01-13 16:04:36 -0800676 if (!timeo)
677 break;
Jens Axboe9c55e012007-11-06 23:30:13 -0800678 release_sock(sk);
679 lock_sock(sk);
680
681 if (sk->sk_err || sk->sk_state == TCP_CLOSE ||
Willy Tarreau33966dd2009-01-13 16:04:36 -0800682 (sk->sk_shutdown & RCV_SHUTDOWN) ||
Jens Axboe9c55e012007-11-06 23:30:13 -0800683 signal_pending(current))
684 break;
685 }
686
687 release_sock(sk);
688
689 if (spliced)
690 return spliced;
691
692 return ret;
693}
Eric Dumazet4bc2f182010-07-09 21:22:10 +0000694EXPORT_SYMBOL(tcp_splice_read);
Jens Axboe9c55e012007-11-06 23:30:13 -0800695
Pavel Emelyanovdf97c702007-11-29 21:22:33 +1100696struct sk_buff *sk_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp)
Pavel Emelyanovf561d0f2007-11-29 20:28:50 +1100697{
698 struct sk_buff *skb;
699
700 /* The TCP header must be at least 32-bit aligned. */
701 size = ALIGN(size, 4);
702
703 skb = alloc_skb_fclone(size + sk->sk_prot->max_header, gfp);
704 if (skb) {
Hideo Aoki3ab224b2007-12-31 00:11:19 -0800705 if (sk_wmem_schedule(sk, skb->truesize)) {
Eric Dumazeta21d4572012-04-10 20:30:48 +0000706 skb_reserve(skb, sk->sk_prot->max_header);
Pavel Emelyanovf561d0f2007-11-29 20:28:50 +1100707 /*
708 * Make sure that we have exactly size bytes
709 * available to the caller, no more, no less.
710 */
Eric Dumazeta21d4572012-04-10 20:30:48 +0000711 skb->avail_size = size;
Pavel Emelyanovf561d0f2007-11-29 20:28:50 +1100712 return skb;
713 }
714 __kfree_skb(skb);
715 } else {
Pavel Emelyanov5c52ba12008-07-16 20:28:10 -0700716 sk->sk_prot->enter_memory_pressure(sk);
Pavel Emelyanovf561d0f2007-11-29 20:28:50 +1100717 sk_stream_moderate_sndbuf(sk);
718 }
719 return NULL;
720}
721
Ilpo Järvinen0c54b852009-03-14 14:23:05 +0000722static unsigned int tcp_xmit_size_goal(struct sock *sk, u32 mss_now,
723 int large_allowed)
724{
725 struct tcp_sock *tp = tcp_sk(sk);
Ilpo Järvinen2a3a0412009-03-14 22:45:16 +0000726 u32 xmit_size_goal, old_size_goal;
Ilpo Järvinen0c54b852009-03-14 14:23:05 +0000727
728 xmit_size_goal = mss_now;
729
730 if (large_allowed && sk_can_gso(sk)) {
731 xmit_size_goal = ((sk->sk_gso_max_size - 1) -
732 inet_csk(sk)->icsk_af_ops->net_header_len -
733 inet_csk(sk)->icsk_ext_hdr_len -
734 tp->tcp_header_len);
735
736 xmit_size_goal = tcp_bound_to_half_wnd(tp, xmit_size_goal);
Ilpo Järvinen2a3a0412009-03-14 22:45:16 +0000737
738 /* We try hard to avoid divides here */
739 old_size_goal = tp->xmit_size_goal_segs * mss_now;
740
741 if (likely(old_size_goal <= xmit_size_goal &&
742 old_size_goal + mss_now > xmit_size_goal)) {
743 xmit_size_goal = old_size_goal;
744 } else {
745 tp->xmit_size_goal_segs = xmit_size_goal / mss_now;
746 xmit_size_goal = tp->xmit_size_goal_segs * mss_now;
747 }
Ilpo Järvinen0c54b852009-03-14 14:23:05 +0000748 }
749
Ilpo Järvinenafece1c2009-03-14 14:23:07 +0000750 return max(xmit_size_goal, mss_now);
Ilpo Järvinen0c54b852009-03-14 14:23:05 +0000751}
752
753static int tcp_send_mss(struct sock *sk, int *size_goal, int flags)
754{
755 int mss_now;
756
757 mss_now = tcp_current_mss(sk);
758 *size_goal = tcp_xmit_size_goal(sk, mss_now, !(flags & MSG_OOB));
759
760 return mss_now;
761}
762
Linus Torvalds1da177e2005-04-16 15:20:36 -0700763static ssize_t do_tcp_sendpages(struct sock *sk, struct page **pages, int poffset,
764 size_t psize, int flags)
765{
766 struct tcp_sock *tp = tcp_sk(sk);
David S. Millerc1b4a7e2005-07-05 15:24:38 -0700767 int mss_now, size_goal;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700768 int err;
769 ssize_t copied;
770 long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
771
772 /* Wait for a connection to finish. */
773 if ((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT))
774 if ((err = sk_stream_wait_connect(sk, &timeo)) != 0)
775 goto out_err;
776
777 clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
778
Ilpo Järvinen0c54b852009-03-14 14:23:05 +0000779 mss_now = tcp_send_mss(sk, &size_goal, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700780 copied = 0;
781
782 err = -EPIPE;
783 if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
Ilpo Järvinen0d6a7752009-02-28 04:44:41 +0000784 goto out_err;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700785
786 while (psize > 0) {
David S. Millerfe067e82007-03-07 12:12:44 -0800787 struct sk_buff *skb = tcp_write_queue_tail(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700788 struct page *page = pages[poffset / PAGE_SIZE];
789 int copy, i, can_coalesce;
790 int offset = poffset % PAGE_SIZE;
791 int size = min_t(size_t, psize, PAGE_SIZE - offset);
792
David S. Millerfe067e82007-03-07 12:12:44 -0800793 if (!tcp_send_head(sk) || (copy = size_goal - skb->len) <= 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700794new_segment:
795 if (!sk_stream_memory_free(sk))
796 goto wait_for_sndbuf;
797
Pavel Emelyanovdf97c702007-11-29 21:22:33 +1100798 skb = sk_stream_alloc_skb(sk, 0, sk->sk_allocation);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700799 if (!skb)
800 goto wait_for_memory;
801
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -0700802 skb_entail(sk, skb);
David S. Millerc1b4a7e2005-07-05 15:24:38 -0700803 copy = size_goal;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700804 }
805
806 if (copy > size)
807 copy = size;
808
809 i = skb_shinfo(skb)->nr_frags;
810 can_coalesce = skb_can_coalesce(skb, i, page, offset);
811 if (!can_coalesce && i >= MAX_SKB_FRAGS) {
812 tcp_mark_push(tp, skb);
813 goto new_segment;
814 }
Hideo Aoki3ab224b2007-12-31 00:11:19 -0800815 if (!sk_wmem_schedule(sk, copy))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700816 goto wait_for_memory;
YOSHIFUJI Hideakie905a9e2007-02-09 23:24:47 +0900817
Linus Torvalds1da177e2005-04-16 15:20:36 -0700818 if (can_coalesce) {
Eric Dumazet9e903e02011-10-18 21:00:24 +0000819 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700820 } else {
821 get_page(page);
822 skb_fill_page_desc(skb, i, page, offset, copy);
823 }
824
825 skb->len += copy;
826 skb->data_len += copy;
827 skb->truesize += copy;
828 sk->sk_wmem_queued += copy;
Hideo Aoki3ab224b2007-12-31 00:11:19 -0800829 sk_mem_charge(sk, copy);
Patrick McHardy84fa7932006-08-29 16:44:56 -0700830 skb->ip_summed = CHECKSUM_PARTIAL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700831 tp->write_seq += copy;
832 TCP_SKB_CB(skb)->end_seq += copy;
Herbert Xu79671682006-06-22 02:40:14 -0700833 skb_shinfo(skb)->gso_segs = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700834
835 if (!copied)
Eric Dumazet4de075e2011-09-27 13:25:05 -0400836 TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700837
838 copied += copy;
839 poffset += copy;
840 if (!(psize -= copy))
841 goto out;
842
Herbert Xu69d15062008-03-22 15:47:05 -0700843 if (skb->len < size_goal || (flags & MSG_OOB))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700844 continue;
845
846 if (forced_push(tp)) {
847 tcp_mark_push(tp, skb);
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -0700848 __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
David S. Millerfe067e82007-03-07 12:12:44 -0800849 } else if (skb == tcp_send_head(sk))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700850 tcp_push_one(sk, mss_now);
851 continue;
852
853wait_for_sndbuf:
854 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
855wait_for_memory:
Willy Tarreaubad115c2012-05-17 11:14:14 +0000856 tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700857
858 if ((err = sk_stream_wait_memory(sk, &timeo)) != 0)
859 goto do_error;
860
Ilpo Järvinen0c54b852009-03-14 14:23:05 +0000861 mss_now = tcp_send_mss(sk, &size_goal, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700862 }
863
864out:
Eric Dumazet35f9c092012-04-05 03:05:35 +0000865 if (copied && !(flags & MSG_SENDPAGE_NOTLAST))
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -0700866 tcp_push(sk, flags, mss_now, tp->nonagle);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700867 return copied;
868
869do_error:
870 if (copied)
871 goto out;
872out_err:
873 return sk_stream_error(sk, flags, err);
874}
875
Changli Gao7ba42912010-07-10 20:41:55 +0000876int tcp_sendpage(struct sock *sk, struct page *page, int offset,
877 size_t size, int flags)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700878{
879 ssize_t res;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700880
Linus Torvalds1da177e2005-04-16 15:20:36 -0700881 if (!(sk->sk_route_caps & NETIF_F_SG) ||
Herbert Xu8648b302006-06-17 22:06:05 -0700882 !(sk->sk_route_caps & NETIF_F_ALL_CSUM))
Changli Gao7ba42912010-07-10 20:41:55 +0000883 return sock_no_sendpage(sk->sk_socket, page, offset, size,
884 flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700885
Linus Torvalds1da177e2005-04-16 15:20:36 -0700886 lock_sock(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700887 res = do_tcp_sendpages(sk, &page, offset, size, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700888 release_sock(sk);
889 return res;
890}
Eric Dumazet4bc2f182010-07-09 21:22:10 +0000891EXPORT_SYMBOL(tcp_sendpage);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700892
Eric Dumazet690e99c2011-11-28 00:27:47 +0000893static inline int select_size(const struct sock *sk, bool sg)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700894{
Eric Dumazetcf533ea2011-10-21 05:22:42 -0400895 const struct tcp_sock *tp = tcp_sk(sk);
David S. Millerc1b4a7e2005-07-05 15:24:38 -0700896 int tmp = tp->mss_cache;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700897
Krishna Kumardef87cf2009-12-10 07:16:59 +0000898 if (sg) {
Eric Dumazetf07d9602011-11-28 22:41:47 +0000899 if (sk_can_gso(sk)) {
900 /* Small frames wont use a full page:
901 * Payload will immediately follow tcp header.
902 */
903 tmp = SKB_WITH_OVERHEAD(2048 - MAX_TCP_HEADER);
904 } else {
David S. Millerb4e26f52005-07-05 15:20:27 -0700905 int pgbreak = SKB_MAX_HEAD(MAX_TCP_HEADER);
906
907 if (tmp >= pgbreak &&
908 tmp <= pgbreak + (MAX_SKB_FRAGS - 1) * PAGE_SIZE)
909 tmp = pgbreak;
910 }
911 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700912
Linus Torvalds1da177e2005-04-16 15:20:36 -0700913 return tmp;
914}
915
Changli Gao7ba42912010-07-10 20:41:55 +0000916int tcp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700917 size_t size)
918{
919 struct iovec *iov;
920 struct tcp_sock *tp = tcp_sk(sk);
921 struct sk_buff *skb;
Eric Dumazet690e99c2011-11-28 00:27:47 +0000922 int iovlen, flags, err, copied;
David S. Millerc1b4a7e2005-07-05 15:24:38 -0700923 int mss_now, size_goal;
Eric Dumazet690e99c2011-11-28 00:27:47 +0000924 bool sg;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700925 long timeo;
926
927 lock_sock(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700928
929 flags = msg->msg_flags;
930 timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
931
932 /* Wait for a connection to finish. */
933 if ((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT))
934 if ((err = sk_stream_wait_connect(sk, &timeo)) != 0)
935 goto out_err;
936
937 /* This should be in poll */
938 clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
939
Ilpo Järvinen0c54b852009-03-14 14:23:05 +0000940 mss_now = tcp_send_mss(sk, &size_goal, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700941
942 /* Ok commence sending. */
943 iovlen = msg->msg_iovlen;
944 iov = msg->msg_iov;
945 copied = 0;
946
947 err = -EPIPE;
948 if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
Ilpo Järvinen0d6a7752009-02-28 04:44:41 +0000949 goto out_err;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700950
Eric Dumazet690e99c2011-11-28 00:27:47 +0000951 sg = !!(sk->sk_route_caps & NETIF_F_SG);
Krishna Kumardef87cf2009-12-10 07:16:59 +0000952
Linus Torvalds1da177e2005-04-16 15:20:36 -0700953 while (--iovlen >= 0) {
David S. Miller01db4032010-09-27 20:24:54 -0700954 size_t seglen = iov->iov_len;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700955 unsigned char __user *from = iov->iov_base;
956
957 iov++;
958
959 while (seglen > 0) {
Herbert Xu6828b922009-06-28 18:06:41 +0000960 int copy = 0;
961 int max = size_goal;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700962
David S. Millerfe067e82007-03-07 12:12:44 -0800963 skb = tcp_write_queue_tail(sk);
Herbert Xu6828b922009-06-28 18:06:41 +0000964 if (tcp_send_head(sk)) {
965 if (skb->ip_summed == CHECKSUM_NONE)
966 max = mss_now;
967 copy = max - skb->len;
968 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700969
Herbert Xu6828b922009-06-28 18:06:41 +0000970 if (copy <= 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700971new_segment:
972 /* Allocate new segment. If the interface is SG,
973 * allocate skb fitting to single page.
974 */
975 if (!sk_stream_memory_free(sk))
976 goto wait_for_sndbuf;
977
Krishna Kumardef87cf2009-12-10 07:16:59 +0000978 skb = sk_stream_alloc_skb(sk,
979 select_size(sk, sg),
980 sk->sk_allocation);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700981 if (!skb)
982 goto wait_for_memory;
983
984 /*
985 * Check whether we can use HW checksum.
986 */
Herbert Xu8648b302006-06-17 22:06:05 -0700987 if (sk->sk_route_caps & NETIF_F_ALL_CSUM)
Patrick McHardy84fa7932006-08-29 16:44:56 -0700988 skb->ip_summed = CHECKSUM_PARTIAL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700989
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -0700990 skb_entail(sk, skb);
David S. Millerc1b4a7e2005-07-05 15:24:38 -0700991 copy = size_goal;
Herbert Xu6828b922009-06-28 18:06:41 +0000992 max = size_goal;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700993 }
994
995 /* Try to append data to the end of skb. */
996 if (copy > seglen)
997 copy = seglen;
998
999 /* Where to copy to? */
Eric Dumazeta21d4572012-04-10 20:30:48 +00001000 if (skb_availroom(skb) > 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001001 /* We have some space in skb head. Superb! */
Eric Dumazeta21d4572012-04-10 20:30:48 +00001002 copy = min_t(int, copy, skb_availroom(skb));
Tom Herbertc6e1a0d2011-04-04 22:30:30 -07001003 err = skb_add_data_nocache(sk, skb, from, copy);
1004 if (err)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001005 goto do_fault;
1006 } else {
1007 int merge = 0;
1008 int i = skb_shinfo(skb)->nr_frags;
Eric Dumazet0a5912d2011-12-05 01:07:15 +00001009 struct page *page = sk->sk_sndmsg_page;
Eric Dumazet761965e2011-12-04 07:05:17 +00001010 int off;
1011
1012 if (page && page_count(page) == 1)
Eric Dumazet0a5912d2011-12-05 01:07:15 +00001013 sk->sk_sndmsg_off = 0;
Eric Dumazet761965e2011-12-04 07:05:17 +00001014
Eric Dumazet0a5912d2011-12-05 01:07:15 +00001015 off = sk->sk_sndmsg_off;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001016
1017 if (skb_can_coalesce(skb, i, page, off) &&
1018 off != PAGE_SIZE) {
1019 /* We can extend the last page
1020 * fragment. */
1021 merge = 1;
Krishna Kumardef87cf2009-12-10 07:16:59 +00001022 } else if (i == MAX_SKB_FRAGS || !sg) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001023 /* Need to add new fragment and cannot
1024 * do this because interface is non-SG,
1025 * or because all the page slots are
1026 * busy. */
1027 tcp_mark_push(tp, skb);
1028 goto new_segment;
1029 } else if (page) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001030 if (off == PAGE_SIZE) {
1031 put_page(page);
Eric Dumazet0a5912d2011-12-05 01:07:15 +00001032 sk->sk_sndmsg_page = page = NULL;
Herbert Xufb5f5e62005-09-05 18:55:48 -07001033 off = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001034 }
Herbert Xuef015782005-09-01 17:48:59 -07001035 } else
Herbert Xufb5f5e62005-09-05 18:55:48 -07001036 off = 0;
Herbert Xuef015782005-09-01 17:48:59 -07001037
1038 if (copy > PAGE_SIZE - off)
1039 copy = PAGE_SIZE - off;
1040
Hideo Aoki3ab224b2007-12-31 00:11:19 -08001041 if (!sk_wmem_schedule(sk, copy))
Herbert Xuef015782005-09-01 17:48:59 -07001042 goto wait_for_memory;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001043
1044 if (!page) {
1045 /* Allocate new cache page. */
1046 if (!(page = sk_stream_alloc_page(sk)))
1047 goto wait_for_memory;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001048 }
1049
Linus Torvalds1da177e2005-04-16 15:20:36 -07001050 /* Time to copy data. We are close to
1051 * the end! */
Tom Herbertc6e1a0d2011-04-04 22:30:30 -07001052 err = skb_copy_to_page_nocache(sk, from, skb,
1053 page, off, copy);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001054 if (err) {
1055 /* If this page was new, give it to the
1056 * socket so it does not get leaked.
1057 */
Eric Dumazet0a5912d2011-12-05 01:07:15 +00001058 if (!sk->sk_sndmsg_page) {
1059 sk->sk_sndmsg_page = page;
1060 sk->sk_sndmsg_off = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001061 }
1062 goto do_error;
1063 }
1064
1065 /* Update the skb. */
1066 if (merge) {
Eric Dumazet9e903e02011-10-18 21:00:24 +00001067 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001068 } else {
1069 skb_fill_page_desc(skb, i, page, off, copy);
Eric Dumazet0a5912d2011-12-05 01:07:15 +00001070 if (sk->sk_sndmsg_page) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001071 get_page(page);
1072 } else if (off + copy < PAGE_SIZE) {
1073 get_page(page);
Eric Dumazet0a5912d2011-12-05 01:07:15 +00001074 sk->sk_sndmsg_page = page;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001075 }
1076 }
1077
Eric Dumazet0a5912d2011-12-05 01:07:15 +00001078 sk->sk_sndmsg_off = off + copy;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001079 }
1080
1081 if (!copied)
Eric Dumazet4de075e2011-09-27 13:25:05 -04001082 TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001083
1084 tp->write_seq += copy;
1085 TCP_SKB_CB(skb)->end_seq += copy;
Herbert Xu79671682006-06-22 02:40:14 -07001086 skb_shinfo(skb)->gso_segs = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001087
1088 from += copy;
1089 copied += copy;
1090 if ((seglen -= copy) == 0 && iovlen == 0)
1091 goto out;
1092
Herbert Xu6828b922009-06-28 18:06:41 +00001093 if (skb->len < max || (flags & MSG_OOB))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001094 continue;
1095
1096 if (forced_push(tp)) {
1097 tcp_mark_push(tp, skb);
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -07001098 __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
David S. Millerfe067e82007-03-07 12:12:44 -08001099 } else if (skb == tcp_send_head(sk))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001100 tcp_push_one(sk, mss_now);
1101 continue;
1102
1103wait_for_sndbuf:
1104 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1105wait_for_memory:
1106 if (copied)
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -07001107 tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001108
1109 if ((err = sk_stream_wait_memory(sk, &timeo)) != 0)
1110 goto do_error;
1111
Ilpo Järvinen0c54b852009-03-14 14:23:05 +00001112 mss_now = tcp_send_mss(sk, &size_goal, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001113 }
1114 }
1115
1116out:
1117 if (copied)
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -07001118 tcp_push(sk, flags, mss_now, tp->nonagle);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001119 release_sock(sk);
Mike Chan5a0b3542009-01-07 11:40:42 -08001120
1121 if (copied > 0)
1122 uid_stat_tcp_snd(current_uid(), copied);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001123 return copied;
1124
1125do_fault:
1126 if (!skb->len) {
David S. Millerfe067e82007-03-07 12:12:44 -08001127 tcp_unlink_write_queue(skb, sk);
1128 /* It is the one place in all of TCP, except connection
1129 * reset, where we can be unlinking the send_head.
1130 */
1131 tcp_check_send_head(sk, skb);
Hideo Aoki3ab224b2007-12-31 00:11:19 -08001132 sk_wmem_free_skb(sk, skb);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001133 }
1134
1135do_error:
1136 if (copied)
1137 goto out;
1138out_err:
1139 err = sk_stream_error(sk, flags, err);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001140 release_sock(sk);
1141 return err;
1142}
Eric Dumazet4bc2f182010-07-09 21:22:10 +00001143EXPORT_SYMBOL(tcp_sendmsg);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001144
1145/*
1146 * Handle reading urgent data. BSD has very simple semantics for
1147 * this, no blocking and very strange errors 8)
1148 */
1149
Rami Rosen377f0a02009-03-31 14:43:17 -07001150static int tcp_recv_urg(struct sock *sk, struct msghdr *msg, int len, int flags)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001151{
1152 struct tcp_sock *tp = tcp_sk(sk);
1153
1154 /* No URG data to read. */
1155 if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data ||
1156 tp->urg_data == TCP_URG_READ)
1157 return -EINVAL; /* Yes this is right ! */
1158
1159 if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE))
1160 return -ENOTCONN;
1161
1162 if (tp->urg_data & TCP_URG_VALID) {
1163 int err = 0;
1164 char c = tp->urg_data;
1165
1166 if (!(flags & MSG_PEEK))
1167 tp->urg_data = TCP_URG_READ;
1168
1169 /* Read urgent data. */
1170 msg->msg_flags |= MSG_OOB;
1171
1172 if (len > 0) {
1173 if (!(flags & MSG_TRUNC))
1174 err = memcpy_toiovec(msg->msg_iov, &c, 1);
1175 len = 1;
1176 } else
1177 msg->msg_flags |= MSG_TRUNC;
1178
1179 return err ? -EFAULT : len;
1180 }
1181
1182 if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN))
1183 return 0;
1184
1185 /* Fixed the recv(..., MSG_OOB) behaviour. BSD docs and
1186 * the available implementations agree in this case:
1187 * this call should never block, independent of the
1188 * blocking state of the socket.
1189 * Mike <pall@rz.uni-karlsruhe.de>
1190 */
1191 return -EAGAIN;
1192}
1193
1194/* Clean up the receive buffer for full frames taken by the user,
1195 * then send an ACK if necessary. COPIED is the number of bytes
1196 * tcp_recvmsg has given to the user so far, it speeds up the
1197 * calculation of whether or not we must ACK for the sake of
1198 * a window update.
1199 */
Chris Leech0e4b4992006-05-23 18:00:16 -07001200void tcp_cleanup_rbuf(struct sock *sk, int copied)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001201{
1202 struct tcp_sock *tp = tcp_sk(sk);
1203 int time_to_ack = 0;
1204
Linus Torvalds1da177e2005-04-16 15:20:36 -07001205 struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
1206
Ilpo Järvinend792c102009-11-13 13:56:33 -08001207 WARN(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq),
Joe Perches2af6fd82010-10-30 11:08:53 +00001208 "cleanup rbuf bug: copied %X seq %X rcvnxt %X\n",
Ilpo Järvinend792c102009-11-13 13:56:33 -08001209 tp->copied_seq, TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001210
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07001211 if (inet_csk_ack_scheduled(sk)) {
1212 const struct inet_connection_sock *icsk = inet_csk(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001213 /* Delayed ACKs frequently hit locked sockets during bulk
1214 * receive. */
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07001215 if (icsk->icsk_ack.blocked ||
Linus Torvalds1da177e2005-04-16 15:20:36 -07001216 /* Once-per-two-segments ACK was not sent by tcp_input.c */
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07001217 tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss ||
Linus Torvalds1da177e2005-04-16 15:20:36 -07001218 /*
1219 * If this read emptied read buffer, we send ACK, if
1220 * connection is not bidirectional, user drained
1221 * receive buffer and there was a small segment
1222 * in queue.
1223 */
Alexey Kuznetsov1ef96962006-09-19 12:52:50 -07001224 (copied > 0 &&
1225 ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) ||
1226 ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) &&
1227 !icsk->icsk_ack.pingpong)) &&
1228 !atomic_read(&sk->sk_rmem_alloc)))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001229 time_to_ack = 1;
1230 }
1231
1232 /* We send an ACK if we can now advertise a non-zero window
1233 * which has been raised "significantly".
1234 *
1235 * Even if window raised up to infinity, do not send window open ACK
1236 * in states, where we will not receive more. It is useless.
1237 */
1238 if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
1239 __u32 rcv_window_now = tcp_receive_window(tp);
1240
1241 /* Optimize, __tcp_select_window() is not cheap. */
1242 if (2*rcv_window_now <= tp->window_clamp) {
1243 __u32 new_window = __tcp_select_window(sk);
1244
1245 /* Send ACK now, if this read freed lots of space
1246 * in our buffer. Certainly, new_window is new window.
1247 * We can advertise it now, if it is not less than current one.
1248 * "Lots" means "at least twice" here.
1249 */
1250 if (new_window && new_window >= 2 * rcv_window_now)
1251 time_to_ack = 1;
1252 }
1253 }
1254 if (time_to_ack)
1255 tcp_send_ack(sk);
1256}
1257
1258static void tcp_prequeue_process(struct sock *sk)
1259{
1260 struct sk_buff *skb;
1261 struct tcp_sock *tp = tcp_sk(sk);
1262
Pavel Emelyanov6f67c812008-07-16 20:31:39 -07001263 NET_INC_STATS_USER(sock_net(sk), LINUX_MIB_TCPPREQUEUED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001264
1265 /* RX process wants to run with disabled BHs, though it is not
1266 * necessary */
1267 local_bh_disable();
1268 while ((skb = __skb_dequeue(&tp->ucopy.prequeue)) != NULL)
Peter Zijlstrac57943a2008-10-07 14:18:42 -07001269 sk_backlog_rcv(sk, skb);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001270 local_bh_enable();
1271
1272 /* Clear memory counter. */
1273 tp->ucopy.memory = 0;
1274}
1275
Steven J. Magnani73852e82010-03-16 05:22:44 +00001276#ifdef CONFIG_NET_DMA
1277static void tcp_service_net_dma(struct sock *sk, bool wait)
1278{
1279 dma_cookie_t done, used;
1280 dma_cookie_t last_issued;
1281 struct tcp_sock *tp = tcp_sk(sk);
1282
1283 if (!tp->ucopy.dma_chan)
1284 return;
1285
1286 last_issued = tp->ucopy.dma_cookie;
1287 dma_async_memcpy_issue_pending(tp->ucopy.dma_chan);
1288
1289 do {
1290 if (dma_async_memcpy_complete(tp->ucopy.dma_chan,
1291 last_issued, &done,
1292 &used) == DMA_SUCCESS) {
1293 /* Safe to free early-copied skbs now */
1294 __skb_queue_purge(&sk->sk_async_wait_queue);
1295 break;
1296 } else {
1297 struct sk_buff *skb;
1298 while ((skb = skb_peek(&sk->sk_async_wait_queue)) &&
1299 (dma_async_is_complete(skb->dma_cookie, done,
1300 used) == DMA_SUCCESS)) {
1301 __skb_dequeue(&sk->sk_async_wait_queue);
1302 kfree_skb(skb);
1303 }
1304 }
1305 } while (wait);
1306}
1307#endif
1308
Linus Torvalds1da177e2005-04-16 15:20:36 -07001309static inline struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off)
1310{
1311 struct sk_buff *skb;
1312 u32 offset;
1313
1314 skb_queue_walk(&sk->sk_receive_queue, skb) {
1315 offset = seq - TCP_SKB_CB(skb)->seq;
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07001316 if (tcp_hdr(skb)->syn)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001317 offset--;
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07001318 if (offset < skb->len || tcp_hdr(skb)->fin) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001319 *off = offset;
1320 return skb;
1321 }
1322 }
1323 return NULL;
1324}
1325
1326/*
1327 * This routine provides an alternative to tcp_recvmsg() for routines
1328 * that would like to handle copying from skbuffs directly in 'sendfile'
1329 * fashion.
1330 * Note:
1331 * - It is assumed that the socket was locked by the caller.
1332 * - The routine does not block.
1333 * - At present, there is no support for reading OOB data
1334 * or for 'peeking' the socket using this routine
1335 * (although both would be easy to implement).
1336 */
1337int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
1338 sk_read_actor_t recv_actor)
1339{
1340 struct sk_buff *skb;
1341 struct tcp_sock *tp = tcp_sk(sk);
1342 u32 seq = tp->copied_seq;
1343 u32 offset;
1344 int copied = 0;
1345
1346 if (sk->sk_state == TCP_LISTEN)
1347 return -ENOTCONN;
1348 while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
1349 if (offset < skb->len) {
Octavian Purdila374e7b52008-07-03 03:31:21 -07001350 int used;
1351 size_t len;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001352
1353 len = skb->len - offset;
1354 /* Stop reading if we hit a patch of urgent data */
1355 if (tp->urg_data) {
1356 u32 urg_offset = tp->urg_seq - seq;
1357 if (urg_offset < len)
1358 len = urg_offset;
1359 if (!len)
1360 break;
1361 }
1362 used = recv_actor(desc, skb, offset, len);
Jens Axboeddb61a52007-06-23 23:07:50 -07001363 if (used < 0) {
1364 if (!copied)
1365 copied = used;
1366 break;
1367 } else if (used <= len) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001368 seq += used;
1369 copied += used;
1370 offset += used;
1371 }
Octavian Purdila293ad602008-06-04 15:45:58 -07001372 /*
1373 * If recv_actor drops the lock (e.g. TCP splice
1374 * receive) the skb pointer might be invalid when
1375 * getting here: tcp_collapse might have deleted it
1376 * while aggregating skbs from the socket queue.
1377 */
1378 skb = tcp_recv_skb(sk, seq-1, &offset);
1379 if (!skb || (offset+1 != skb->len))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001380 break;
1381 }
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07001382 if (tcp_hdr(skb)->fin) {
Chris Leech624d1162006-05-23 18:01:28 -07001383 sk_eat_skb(sk, skb, 0);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001384 ++seq;
1385 break;
1386 }
Chris Leech624d1162006-05-23 18:01:28 -07001387 sk_eat_skb(sk, skb, 0);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001388 if (!desc->count)
1389 break;
Steven J. Magnanibaff42a2010-03-30 13:56:01 -07001390 tp->copied_seq = seq;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001391 }
1392 tp->copied_seq = seq;
1393
1394 tcp_rcv_space_adjust(sk);
1395
1396 /* Clean up data we have read: This will do ACK frames. */
Mike Chan5a0b3542009-01-07 11:40:42 -08001397 if (copied > 0) {
Chris Leech0e4b4992006-05-23 18:00:16 -07001398 tcp_cleanup_rbuf(sk, copied);
Mike Chan5a0b3542009-01-07 11:40:42 -08001399 uid_stat_tcp_rcv(current_uid(), copied);
1400 }
1401
Linus Torvalds1da177e2005-04-16 15:20:36 -07001402 return copied;
1403}
Eric Dumazet4bc2f182010-07-09 21:22:10 +00001404EXPORT_SYMBOL(tcp_read_sock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001405
1406/*
1407 * This routine copies from a sock struct into the user buffer.
1408 *
1409 * Technical note: in 2.3 we work on _locked_ socket, so that
1410 * tricks with *seq access order and skb->users are not required.
1411 * Probably, code can be easily improved even more.
1412 */
1413
1414int tcp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
1415 size_t len, int nonblock, int flags, int *addr_len)
1416{
1417 struct tcp_sock *tp = tcp_sk(sk);
1418 int copied = 0;
1419 u32 peek_seq;
1420 u32 *seq;
1421 unsigned long used;
1422 int err;
1423 int target; /* Read at least this many bytes */
1424 long timeo;
1425 struct task_struct *user_recv = NULL;
Chris Leech1a2449a2006-05-23 18:05:53 -07001426 int copied_early = 0;
Chris Leech2b1244a2007-03-08 09:57:36 -08001427 struct sk_buff *skb;
Ilpo Järvinen77527312009-05-10 20:32:34 +00001428 u32 urg_hole = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001429
1430 lock_sock(sk);
1431
Linus Torvalds1da177e2005-04-16 15:20:36 -07001432 err = -ENOTCONN;
1433 if (sk->sk_state == TCP_LISTEN)
1434 goto out;
1435
1436 timeo = sock_rcvtimeo(sk, nonblock);
1437
1438 /* Urgent data needs to be handled specially. */
1439 if (flags & MSG_OOB)
1440 goto recv_urg;
1441
1442 seq = &tp->copied_seq;
1443 if (flags & MSG_PEEK) {
1444 peek_seq = tp->copied_seq;
1445 seq = &peek_seq;
1446 }
1447
1448 target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
1449
Chris Leech1a2449a2006-05-23 18:05:53 -07001450#ifdef CONFIG_NET_DMA
1451 tp->ucopy.dma_chan = NULL;
1452 preempt_disable();
Chris Leech2b1244a2007-03-08 09:57:36 -08001453 skb = skb_peek_tail(&sk->sk_receive_queue);
Andrew Mortone00c5d82007-03-08 09:57:36 -08001454 {
1455 int available = 0;
1456
1457 if (skb)
1458 available = TCP_SKB_CB(skb)->seq + skb->len - (*seq);
1459 if ((available < target) &&
1460 (len > sysctl_tcp_dma_copybreak) && !(flags & MSG_PEEK) &&
1461 !sysctl_tcp_low_latency &&
Dave Jianga2bd1142012-04-04 16:10:46 -07001462 net_dma_find_channel()) {
Andrew Mortone00c5d82007-03-08 09:57:36 -08001463 preempt_enable_no_resched();
1464 tp->ucopy.pinned_list =
1465 dma_pin_iovec_pages(msg->msg_iov, len);
1466 } else {
1467 preempt_enable_no_resched();
1468 }
1469 }
Chris Leech1a2449a2006-05-23 18:05:53 -07001470#endif
1471
Linus Torvalds1da177e2005-04-16 15:20:36 -07001472 do {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001473 u32 offset;
1474
1475 /* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */
1476 if (tp->urg_data && tp->urg_seq == *seq) {
1477 if (copied)
1478 break;
1479 if (signal_pending(current)) {
1480 copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
1481 break;
1482 }
1483 }
1484
1485 /* Next get a buffer. */
1486
David S. Miller91521942009-05-28 21:35:47 -07001487 skb_queue_walk(&sk->sk_receive_queue, skb) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001488 /* Now that we have two receive queues this
1489 * shouldn't happen.
1490 */
Ilpo Järvinend792c102009-11-13 13:56:33 -08001491 if (WARN(before(*seq, TCP_SKB_CB(skb)->seq),
Joe Perches2af6fd82010-10-30 11:08:53 +00001492 "recvmsg bug: copied %X seq %X rcvnxt %X fl %X\n",
1493 *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt,
1494 flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001495 break;
Ilpo Järvinend792c102009-11-13 13:56:33 -08001496
Linus Torvalds1da177e2005-04-16 15:20:36 -07001497 offset = *seq - TCP_SKB_CB(skb)->seq;
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07001498 if (tcp_hdr(skb)->syn)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001499 offset--;
1500 if (offset < skb->len)
1501 goto found_ok_skb;
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07001502 if (tcp_hdr(skb)->fin)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001503 goto found_fin_ok;
Joe Perches2af6fd82010-10-30 11:08:53 +00001504 WARN(!(flags & MSG_PEEK),
1505 "recvmsg bug 2: copied %X seq %X rcvnxt %X fl %X\n",
1506 *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags);
David S. Miller91521942009-05-28 21:35:47 -07001507 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001508
1509 /* Well, if we have backlog, try to process it now yet. */
1510
1511 if (copied >= target && !sk->sk_backlog.tail)
1512 break;
1513
1514 if (copied) {
1515 if (sk->sk_err ||
1516 sk->sk_state == TCP_CLOSE ||
1517 (sk->sk_shutdown & RCV_SHUTDOWN) ||
1518 !timeo ||
David S. Miller518a09e2008-11-05 03:36:01 -08001519 signal_pending(current))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001520 break;
1521 } else {
1522 if (sock_flag(sk, SOCK_DONE))
1523 break;
1524
1525 if (sk->sk_err) {
1526 copied = sock_error(sk);
1527 break;
1528 }
1529
1530 if (sk->sk_shutdown & RCV_SHUTDOWN)
1531 break;
1532
1533 if (sk->sk_state == TCP_CLOSE) {
1534 if (!sock_flag(sk, SOCK_DONE)) {
1535 /* This occurs when user tries to read
1536 * from never connected socket.
1537 */
1538 copied = -ENOTCONN;
1539 break;
1540 }
1541 break;
1542 }
1543
1544 if (!timeo) {
1545 copied = -EAGAIN;
1546 break;
1547 }
1548
1549 if (signal_pending(current)) {
1550 copied = sock_intr_errno(timeo);
1551 break;
1552 }
1553 }
1554
Chris Leech0e4b4992006-05-23 18:00:16 -07001555 tcp_cleanup_rbuf(sk, copied);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001556
David S. Miller7df55122005-06-18 23:01:10 -07001557 if (!sysctl_tcp_low_latency && tp->ucopy.task == user_recv) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001558 /* Install new reader */
1559 if (!user_recv && !(flags & (MSG_TRUNC | MSG_PEEK))) {
1560 user_recv = current;
1561 tp->ucopy.task = user_recv;
1562 tp->ucopy.iov = msg->msg_iov;
1563 }
1564
1565 tp->ucopy.len = len;
1566
Ilpo Järvinen547b7922008-07-25 21:43:18 -07001567 WARN_ON(tp->copied_seq != tp->rcv_nxt &&
1568 !(flags & (MSG_PEEK | MSG_TRUNC)));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001569
1570 /* Ugly... If prequeue is not empty, we have to
1571 * process it before releasing socket, otherwise
1572 * order will be broken at second iteration.
1573 * More elegant solution is required!!!
1574 *
1575 * Look: we have the following (pseudo)queues:
1576 *
1577 * 1. packets in flight
1578 * 2. backlog
1579 * 3. prequeue
1580 * 4. receive_queue
1581 *
1582 * Each queue can be processed only if the next ones
1583 * are empty. At this point we have empty receive_queue.
1584 * But prequeue _can_ be not empty after 2nd iteration,
1585 * when we jumped to start of loop because backlog
1586 * processing added something to receive_queue.
1587 * We cannot release_sock(), because backlog contains
1588 * packets arrived _after_ prequeued ones.
1589 *
1590 * Shortly, algorithm is clear --- to process all
1591 * the queues in order. We could make it more directly,
1592 * requeueing packets from backlog to prequeue, if
1593 * is not empty. It is more elegant, but eats cycles,
1594 * unfortunately.
1595 */
David S. Millerb03efcf2005-07-08 14:57:23 -07001596 if (!skb_queue_empty(&tp->ucopy.prequeue))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001597 goto do_prequeue;
1598
1599 /* __ Set realtime policy in scheduler __ */
1600 }
1601
Steven J. Magnani73852e82010-03-16 05:22:44 +00001602#ifdef CONFIG_NET_DMA
1603 if (tp->ucopy.dma_chan)
1604 dma_async_memcpy_issue_pending(tp->ucopy.dma_chan);
1605#endif
Linus Torvalds1da177e2005-04-16 15:20:36 -07001606 if (copied >= target) {
1607 /* Do not sleep, just process backlog. */
1608 release_sock(sk);
1609 lock_sock(sk);
1610 } else
1611 sk_wait_data(sk, &timeo);
1612
Chris Leech1a2449a2006-05-23 18:05:53 -07001613#ifdef CONFIG_NET_DMA
Steven J. Magnani73852e82010-03-16 05:22:44 +00001614 tcp_service_net_dma(sk, false); /* Don't block */
Chris Leech1a2449a2006-05-23 18:05:53 -07001615 tp->ucopy.wakeup = 0;
1616#endif
1617
Linus Torvalds1da177e2005-04-16 15:20:36 -07001618 if (user_recv) {
1619 int chunk;
1620
1621 /* __ Restore normal policy in scheduler __ */
1622
1623 if ((chunk = len - tp->ucopy.len) != 0) {
Pavel Emelyanoved880982008-07-16 20:32:45 -07001624 NET_ADD_STATS_USER(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMBACKLOG, chunk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001625 len -= chunk;
1626 copied += chunk;
1627 }
1628
1629 if (tp->rcv_nxt == tp->copied_seq &&
David S. Millerb03efcf2005-07-08 14:57:23 -07001630 !skb_queue_empty(&tp->ucopy.prequeue)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001631do_prequeue:
1632 tcp_prequeue_process(sk);
1633
1634 if ((chunk = len - tp->ucopy.len) != 0) {
Pavel Emelyanoved880982008-07-16 20:32:45 -07001635 NET_ADD_STATS_USER(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001636 len -= chunk;
1637 copied += chunk;
1638 }
1639 }
1640 }
Ilpo Järvinen77527312009-05-10 20:32:34 +00001641 if ((flags & MSG_PEEK) &&
1642 (peek_seq - copied - urg_hole != tp->copied_seq)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001643 if (net_ratelimit())
1644 printk(KERN_DEBUG "TCP(%s:%d): Application bug, race in MSG_PEEK.\n",
Pavel Emelyanovba25f9d2007-10-18 23:40:40 -07001645 current->comm, task_pid_nr(current));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001646 peek_seq = tp->copied_seq;
1647 }
1648 continue;
1649
1650 found_ok_skb:
1651 /* Ok so how much can we use? */
1652 used = skb->len - offset;
1653 if (len < used)
1654 used = len;
1655
1656 /* Do we have urgent data here? */
1657 if (tp->urg_data) {
1658 u32 urg_offset = tp->urg_seq - *seq;
1659 if (urg_offset < used) {
1660 if (!urg_offset) {
1661 if (!sock_flag(sk, SOCK_URGINLINE)) {
1662 ++*seq;
Ilpo Järvinen77527312009-05-10 20:32:34 +00001663 urg_hole++;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001664 offset++;
1665 used--;
1666 if (!used)
1667 goto skip_copy;
1668 }
1669 } else
1670 used = urg_offset;
1671 }
1672 }
1673
1674 if (!(flags & MSG_TRUNC)) {
Chris Leech1a2449a2006-05-23 18:05:53 -07001675#ifdef CONFIG_NET_DMA
1676 if (!tp->ucopy.dma_chan && tp->ucopy.pinned_list)
Dave Jianga2bd1142012-04-04 16:10:46 -07001677 tp->ucopy.dma_chan = net_dma_find_channel();
Chris Leech1a2449a2006-05-23 18:05:53 -07001678
1679 if (tp->ucopy.dma_chan) {
1680 tp->ucopy.dma_cookie = dma_skb_copy_datagram_iovec(
1681 tp->ucopy.dma_chan, skb, offset,
1682 msg->msg_iov, used,
1683 tp->ucopy.pinned_list);
1684
1685 if (tp->ucopy.dma_cookie < 0) {
1686
Joe Perchesafd465032012-03-12 07:03:32 +00001687 pr_alert("%s: dma_cookie < 0\n",
1688 __func__);
Chris Leech1a2449a2006-05-23 18:05:53 -07001689
1690 /* Exception. Bailout! */
1691 if (!copied)
1692 copied = -EFAULT;
1693 break;
1694 }
Steven J. Magnani73852e82010-03-16 05:22:44 +00001695
1696 dma_async_memcpy_issue_pending(tp->ucopy.dma_chan);
1697
Chris Leech1a2449a2006-05-23 18:05:53 -07001698 if ((offset + used) == skb->len)
1699 copied_early = 1;
1700
1701 } else
1702#endif
1703 {
1704 err = skb_copy_datagram_iovec(skb, offset,
1705 msg->msg_iov, used);
1706 if (err) {
1707 /* Exception. Bailout! */
1708 if (!copied)
1709 copied = -EFAULT;
1710 break;
1711 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001712 }
1713 }
1714
1715 *seq += used;
1716 copied += used;
1717 len -= used;
1718
1719 tcp_rcv_space_adjust(sk);
1720
1721skip_copy:
1722 if (tp->urg_data && after(tp->copied_seq, tp->urg_seq)) {
1723 tp->urg_data = 0;
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -07001724 tcp_fast_path_check(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001725 }
1726 if (used + offset < skb->len)
1727 continue;
1728
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07001729 if (tcp_hdr(skb)->fin)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001730 goto found_fin_ok;
Chris Leech1a2449a2006-05-23 18:05:53 -07001731 if (!(flags & MSG_PEEK)) {
1732 sk_eat_skb(sk, skb, copied_early);
1733 copied_early = 0;
1734 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001735 continue;
1736
1737 found_fin_ok:
1738 /* Process the FIN. */
1739 ++*seq;
Chris Leech1a2449a2006-05-23 18:05:53 -07001740 if (!(flags & MSG_PEEK)) {
1741 sk_eat_skb(sk, skb, copied_early);
1742 copied_early = 0;
1743 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001744 break;
1745 } while (len > 0);
1746
1747 if (user_recv) {
David S. Millerb03efcf2005-07-08 14:57:23 -07001748 if (!skb_queue_empty(&tp->ucopy.prequeue)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001749 int chunk;
1750
1751 tp->ucopy.len = copied > 0 ? len : 0;
1752
1753 tcp_prequeue_process(sk);
1754
1755 if (copied > 0 && (chunk = len - tp->ucopy.len) != 0) {
Pavel Emelyanoved880982008-07-16 20:32:45 -07001756 NET_ADD_STATS_USER(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001757 len -= chunk;
1758 copied += chunk;
1759 }
1760 }
1761
1762 tp->ucopy.task = NULL;
1763 tp->ucopy.len = 0;
1764 }
1765
Chris Leech1a2449a2006-05-23 18:05:53 -07001766#ifdef CONFIG_NET_DMA
Steven J. Magnani73852e82010-03-16 05:22:44 +00001767 tcp_service_net_dma(sk, true); /* Wait for queue to drain */
1768 tp->ucopy.dma_chan = NULL;
Chris Leech1a2449a2006-05-23 18:05:53 -07001769
Chris Leech1a2449a2006-05-23 18:05:53 -07001770 if (tp->ucopy.pinned_list) {
1771 dma_unpin_iovec_pages(tp->ucopy.pinned_list);
1772 tp->ucopy.pinned_list = NULL;
1773 }
1774#endif
1775
Linus Torvalds1da177e2005-04-16 15:20:36 -07001776 /* According to UNIX98, msg_name/msg_namelen are ignored
1777 * on connected socket. I was just happy when found this 8) --ANK
1778 */
1779
1780 /* Clean up data we have read: This will do ACK frames. */
Chris Leech0e4b4992006-05-23 18:00:16 -07001781 tcp_cleanup_rbuf(sk, copied);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001782
Linus Torvalds1da177e2005-04-16 15:20:36 -07001783 release_sock(sk);
Mike Chan5a0b3542009-01-07 11:40:42 -08001784
1785 if (copied > 0)
1786 uid_stat_tcp_rcv(current_uid(), copied);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001787 return copied;
1788
1789out:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001790 release_sock(sk);
1791 return err;
1792
1793recv_urg:
Rami Rosen377f0a02009-03-31 14:43:17 -07001794 err = tcp_recv_urg(sk, msg, len, flags);
Mike Chan5a0b3542009-01-07 11:40:42 -08001795 if (err > 0)
1796 uid_stat_tcp_rcv(current_uid(), err);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001797 goto out;
1798}
Eric Dumazet4bc2f182010-07-09 21:22:10 +00001799EXPORT_SYMBOL(tcp_recvmsg);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001800
Ilpo Järvinen490d5042008-01-12 03:17:20 -08001801void tcp_set_state(struct sock *sk, int state)
1802{
1803 int oldstate = sk->sk_state;
1804
1805 switch (state) {
1806 case TCP_ESTABLISHED:
1807 if (oldstate != TCP_ESTABLISHED)
Pavel Emelyanov81cc8a72008-07-16 20:22:04 -07001808 TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
Ilpo Järvinen490d5042008-01-12 03:17:20 -08001809 break;
1810
1811 case TCP_CLOSE:
1812 if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED)
Pavel Emelyanov81cc8a72008-07-16 20:22:04 -07001813 TCP_INC_STATS(sock_net(sk), TCP_MIB_ESTABRESETS);
Ilpo Järvinen490d5042008-01-12 03:17:20 -08001814
1815 sk->sk_prot->unhash(sk);
1816 if (inet_csk(sk)->icsk_bind_hash &&
1817 !(sk->sk_userlocks & SOCK_BINDPORT_LOCK))
Arnaldo Carvalho de Meloab1e0a12008-02-03 04:06:04 -08001818 inet_put_port(sk);
Ilpo Järvinen490d5042008-01-12 03:17:20 -08001819 /* fall through */
1820 default:
Jianjun Kong5a5f3a82008-11-03 00:24:34 -08001821 if (oldstate == TCP_ESTABLISHED)
Pavel Emelyanov74688e42008-07-16 20:22:46 -07001822 TCP_DEC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
Ilpo Järvinen490d5042008-01-12 03:17:20 -08001823 }
1824
1825 /* Change state AFTER socket is unhashed to avoid closed
1826 * socket sitting in hash tables.
1827 */
1828 sk->sk_state = state;
1829
1830#ifdef STATE_TRACE
Jianjun Kong5a5f3a82008-11-03 00:24:34 -08001831 SOCK_DEBUG(sk, "TCP sk=%p, State %s -> %s\n", sk, statename[oldstate], statename[state]);
Ilpo Järvinen490d5042008-01-12 03:17:20 -08001832#endif
1833}
1834EXPORT_SYMBOL_GPL(tcp_set_state);
1835
Linus Torvalds1da177e2005-04-16 15:20:36 -07001836/*
1837 * State processing on a close. This implements the state shift for
1838 * sending our FIN frame. Note that we only send a FIN for some
1839 * states. A shutdown() may have already sent the FIN, or we may be
1840 * closed.
1841 */
1842
Arjan van de Ven9b5b5cf2005-11-29 16:21:38 -08001843static const unsigned char new_state[16] = {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001844 /* current state: new state: action: */
1845 /* (Invalid) */ TCP_CLOSE,
1846 /* TCP_ESTABLISHED */ TCP_FIN_WAIT1 | TCP_ACTION_FIN,
1847 /* TCP_SYN_SENT */ TCP_CLOSE,
1848 /* TCP_SYN_RECV */ TCP_FIN_WAIT1 | TCP_ACTION_FIN,
1849 /* TCP_FIN_WAIT1 */ TCP_FIN_WAIT1,
1850 /* TCP_FIN_WAIT2 */ TCP_FIN_WAIT2,
1851 /* TCP_TIME_WAIT */ TCP_CLOSE,
1852 /* TCP_CLOSE */ TCP_CLOSE,
1853 /* TCP_CLOSE_WAIT */ TCP_LAST_ACK | TCP_ACTION_FIN,
1854 /* TCP_LAST_ACK */ TCP_LAST_ACK,
1855 /* TCP_LISTEN */ TCP_CLOSE,
1856 /* TCP_CLOSING */ TCP_CLOSING,
1857};
1858
1859static int tcp_close_state(struct sock *sk)
1860{
1861 int next = (int)new_state[sk->sk_state];
1862 int ns = next & TCP_STATE_MASK;
1863
1864 tcp_set_state(sk, ns);
1865
1866 return next & TCP_ACTION_FIN;
1867}
1868
1869/*
1870 * Shutdown the sending side of a connection. Much like close except
Satoru SATOH1f29b052008-04-21 02:27:58 -07001871 * that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD).
Linus Torvalds1da177e2005-04-16 15:20:36 -07001872 */
1873
1874void tcp_shutdown(struct sock *sk, int how)
1875{
1876 /* We need to grab some memory, and put together a FIN,
1877 * and then put it into the queue to be sent.
1878 * Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92.
1879 */
1880 if (!(how & SEND_SHUTDOWN))
1881 return;
1882
1883 /* If we've already sent a FIN, or it's a closed state, skip this. */
1884 if ((1 << sk->sk_state) &
1885 (TCPF_ESTABLISHED | TCPF_SYN_SENT |
1886 TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) {
1887 /* Clear out any half completed packets. FIN if needed. */
1888 if (tcp_close_state(sk))
1889 tcp_send_fin(sk);
1890 }
1891}
Eric Dumazet4bc2f182010-07-09 21:22:10 +00001892EXPORT_SYMBOL(tcp_shutdown);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001893
Arun Sharmaefcdbf22012-01-30 14:16:06 -08001894bool tcp_check_oom(struct sock *sk, int shift)
1895{
1896 bool too_many_orphans, out_of_socket_memory;
1897
1898 too_many_orphans = tcp_too_many_orphans(sk, shift);
1899 out_of_socket_memory = tcp_out_of_memory(sk);
1900
1901 if (too_many_orphans && net_ratelimit())
Joe Perchesafd465032012-03-12 07:03:32 +00001902 pr_info("too many orphaned sockets\n");
Arun Sharmaefcdbf22012-01-30 14:16:06 -08001903 if (out_of_socket_memory && net_ratelimit())
Joe Perchesafd465032012-03-12 07:03:32 +00001904 pr_info("out of memory -- consider tuning tcp_mem\n");
Arun Sharmaefcdbf22012-01-30 14:16:06 -08001905 return too_many_orphans || out_of_socket_memory;
1906}
1907
Linus Torvalds1da177e2005-04-16 15:20:36 -07001908void tcp_close(struct sock *sk, long timeout)
1909{
1910 struct sk_buff *skb;
1911 int data_was_unread = 0;
Herbert Xu75c2d9072006-05-03 23:31:35 -07001912 int state;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001913
1914 lock_sock(sk);
1915 sk->sk_shutdown = SHUTDOWN_MASK;
1916
1917 if (sk->sk_state == TCP_LISTEN) {
1918 tcp_set_state(sk, TCP_CLOSE);
1919
1920 /* Special case. */
Arnaldo Carvalho de Melo0a5578c2005-08-09 20:11:41 -07001921 inet_csk_listen_stop(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001922
1923 goto adjudge_to_death;
1924 }
1925
1926 /* We need to flush the recv. buffs. We do this only on the
1927 * descriptor close, not protocol-sourced closes, because the
1928 * reader process may not have drained the data yet!
1929 */
1930 while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
1931 u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq -
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07001932 tcp_hdr(skb)->fin;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001933 data_was_unread += len;
1934 __kfree_skb(skb);
1935 }
1936
Hideo Aoki3ab224b2007-12-31 00:11:19 -08001937 sk_mem_reclaim(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001938
Konstantin Khorenko565b7b22010-06-24 21:54:58 -07001939 /* If socket has been already reset (e.g. in tcp_reset()) - kill it. */
1940 if (sk->sk_state == TCP_CLOSE)
1941 goto adjudge_to_death;
1942
Gerrit Renker65bb7232007-04-28 21:21:46 -07001943 /* As outlined in RFC 2525, section 2.17, we send a RST here because
1944 * data was lost. To witness the awful effects of the old behavior of
1945 * always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk
1946 * GET in an FTP client, suspend the process, wait for the client to
1947 * advertise a zero window, then kill -9 the FTP client, wheee...
1948 * Note: timeout is always zero in such a case.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001949 */
1950 if (data_was_unread) {
1951 /* Unread data was tossed, zap the connection. */
Pavel Emelyanov6f67c812008-07-16 20:31:39 -07001952 NET_INC_STATS_USER(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001953 tcp_set_state(sk, TCP_CLOSE);
Wu Fengguangaa133072009-09-02 23:45:45 -07001954 tcp_send_active_reset(sk, sk->sk_allocation);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001955 } else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
1956 /* Check zero linger _after_ checking for unread data. */
1957 sk->sk_prot->disconnect(sk, 0);
Pavel Emelyanov6f67c812008-07-16 20:31:39 -07001958 NET_INC_STATS_USER(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001959 } else if (tcp_close_state(sk)) {
1960 /* We FIN if the application ate all the data before
1961 * zapping the connection.
1962 */
1963
1964 /* RED-PEN. Formally speaking, we have broken TCP state
1965 * machine. State transitions:
1966 *
1967 * TCP_ESTABLISHED -> TCP_FIN_WAIT1
1968 * TCP_SYN_RECV -> TCP_FIN_WAIT1 (forget it, it's impossible)
1969 * TCP_CLOSE_WAIT -> TCP_LAST_ACK
1970 *
1971 * are legal only when FIN has been sent (i.e. in window),
1972 * rather than queued out of window. Purists blame.
1973 *
1974 * F.e. "RFC state" is ESTABLISHED,
1975 * if Linux state is FIN-WAIT-1, but FIN is still not sent.
1976 *
1977 * The visible declinations are that sometimes
1978 * we enter time-wait state, when it is not required really
1979 * (harmless), do not send active resets, when they are
1980 * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when
1981 * they look as CLOSING or LAST_ACK for Linux)
1982 * Probably, I missed some more holelets.
1983 * --ANK
1984 */
1985 tcp_send_fin(sk);
1986 }
1987
1988 sk_stream_wait_close(sk, timeout);
1989
1990adjudge_to_death:
Herbert Xu75c2d9072006-05-03 23:31:35 -07001991 state = sk->sk_state;
1992 sock_hold(sk);
1993 sock_orphan(sk);
Herbert Xu75c2d9072006-05-03 23:31:35 -07001994
Linus Torvalds1da177e2005-04-16 15:20:36 -07001995 /* It is the last release_sock in its life. It will remove backlog. */
1996 release_sock(sk);
1997
1998
1999 /* Now socket is owned by kernel and we acquire BH lock
2000 to finish close. No need to check for user refs.
2001 */
2002 local_bh_disable();
2003 bh_lock_sock(sk);
Ilpo Järvinen547b7922008-07-25 21:43:18 -07002004 WARN_ON(sock_owned_by_user(sk));
Linus Torvalds1da177e2005-04-16 15:20:36 -07002005
Herbert Xueb4dea52008-12-29 23:04:08 -08002006 percpu_counter_inc(sk->sk_prot->orphan_count);
2007
Herbert Xu75c2d9072006-05-03 23:31:35 -07002008 /* Have we already been destroyed by a softirq or backlog? */
2009 if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE)
2010 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002011
2012 /* This is a (useful) BSD violating of the RFC. There is a
2013 * problem with TCP as specified in that the other end could
2014 * keep a socket open forever with no application left this end.
2015 * We use a 3 minute timeout (about the same as BSD) then kill
2016 * our end. If they send after that then tough - BUT: long enough
2017 * that we won't make the old 4*rto = almost no time - whoops
2018 * reset mistake.
2019 *
2020 * Nope, it was not mistake. It is really desired behaviour
2021 * f.e. on http servers, when such sockets are useless, but
2022 * consume significant resources. Let's do it with special
2023 * linger2 option. --ANK
2024 */
2025
2026 if (sk->sk_state == TCP_FIN_WAIT2) {
2027 struct tcp_sock *tp = tcp_sk(sk);
2028 if (tp->linger2 < 0) {
2029 tcp_set_state(sk, TCP_CLOSE);
2030 tcp_send_active_reset(sk, GFP_ATOMIC);
Pavel Emelyanovde0744a2008-07-16 20:31:16 -07002031 NET_INC_STATS_BH(sock_net(sk),
2032 LINUX_MIB_TCPABORTONLINGER);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002033 } else {
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002034 const int tmo = tcp_fin_time(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002035
2036 if (tmo > TCP_TIMEWAIT_LEN) {
David S. Miller52499af2006-07-31 22:32:09 -07002037 inet_csk_reset_keepalive_timer(sk,
2038 tmo - TCP_TIMEWAIT_LEN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002039 } else {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002040 tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
2041 goto out;
2042 }
2043 }
2044 }
2045 if (sk->sk_state != TCP_CLOSE) {
Hideo Aoki3ab224b2007-12-31 00:11:19 -08002046 sk_mem_reclaim(sk);
Arun Sharmaefcdbf22012-01-30 14:16:06 -08002047 if (tcp_check_oom(sk, 0)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002048 tcp_set_state(sk, TCP_CLOSE);
2049 tcp_send_active_reset(sk, GFP_ATOMIC);
Pavel Emelyanovde0744a2008-07-16 20:31:16 -07002050 NET_INC_STATS_BH(sock_net(sk),
2051 LINUX_MIB_TCPABORTONMEMORY);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002052 }
2053 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002054
2055 if (sk->sk_state == TCP_CLOSE)
Arnaldo Carvalho de Melo0a5578c2005-08-09 20:11:41 -07002056 inet_csk_destroy_sock(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002057 /* Otherwise, socket is reprieved until protocol close. */
2058
2059out:
2060 bh_unlock_sock(sk);
2061 local_bh_enable();
2062 sock_put(sk);
2063}
Eric Dumazet4bc2f182010-07-09 21:22:10 +00002064EXPORT_SYMBOL(tcp_close);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002065
2066/* These states need RST on ABORT according to RFC793 */
2067
2068static inline int tcp_need_reset(int state)
2069{
2070 return (1 << state) &
2071 (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 |
2072 TCPF_FIN_WAIT2 | TCPF_SYN_RECV);
2073}
2074
2075int tcp_disconnect(struct sock *sk, int flags)
2076{
2077 struct inet_sock *inet = inet_sk(sk);
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002078 struct inet_connection_sock *icsk = inet_csk(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002079 struct tcp_sock *tp = tcp_sk(sk);
2080 int err = 0;
2081 int old_state = sk->sk_state;
2082
2083 if (old_state != TCP_CLOSE)
2084 tcp_set_state(sk, TCP_CLOSE);
2085
2086 /* ABORT function of RFC793 */
2087 if (old_state == TCP_LISTEN) {
Arnaldo Carvalho de Melo0a5578c2005-08-09 20:11:41 -07002088 inet_csk_listen_stop(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002089 } else if (tcp_need_reset(old_state) ||
2090 (tp->snd_nxt != tp->write_seq &&
2091 (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {
Stephen Hemmingercaa20d9a2005-11-10 17:13:47 -08002092 /* The last check adjusts for discrepancy of Linux wrt. RFC
Linus Torvalds1da177e2005-04-16 15:20:36 -07002093 * states
2094 */
2095 tcp_send_active_reset(sk, gfp_any());
2096 sk->sk_err = ECONNRESET;
2097 } else if (old_state == TCP_SYN_SENT)
2098 sk->sk_err = ECONNRESET;
2099
2100 tcp_clear_xmit_timers(sk);
2101 __skb_queue_purge(&sk->sk_receive_queue);
David S. Millerfe067e82007-03-07 12:12:44 -08002102 tcp_write_queue_purge(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002103 __skb_queue_purge(&tp->out_of_order_queue);
Chris Leech1a2449a2006-05-23 18:05:53 -07002104#ifdef CONFIG_NET_DMA
2105 __skb_queue_purge(&sk->sk_async_wait_queue);
2106#endif
Linus Torvalds1da177e2005-04-16 15:20:36 -07002107
Eric Dumazetc720c7e2009-10-15 06:30:45 +00002108 inet->inet_dport = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002109
2110 if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
2111 inet_reset_saddr(sk);
2112
2113 sk->sk_shutdown = 0;
2114 sock_reset_flag(sk, SOCK_DONE);
2115 tp->srtt = 0;
2116 if ((tp->write_seq += tp->max_window + 2) == 0)
2117 tp->write_seq = 1;
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002118 icsk->icsk_backoff = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002119 tp->snd_cwnd = 2;
Arnaldo Carvalho de Melo6687e982005-08-10 04:03:31 -03002120 icsk->icsk_probes_out = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002121 tp->packets_out = 0;
Ilpo Järvinen0b6a05c2009-09-15 01:30:10 -07002122 tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002123 tp->snd_cwnd_cnt = 0;
Stephen Hemminger9772efb2005-11-10 17:09:53 -08002124 tp->bytes_acked = 0;
Eric Dumazet1fdf4752009-11-30 12:53:30 -08002125 tp->window_clamp = 0;
Arnaldo Carvalho de Melo6687e982005-08-10 04:03:31 -03002126 tcp_set_ca_state(sk, TCP_CA_Open);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002127 tcp_clear_retrans(tp);
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002128 inet_csk_delack_init(sk);
David S. Millerfe067e82007-03-07 12:12:44 -08002129 tcp_init_send_head(sk);
Srinivas Ajib40b4f72007-05-03 17:32:28 -07002130 memset(&tp->rx_opt, 0, sizeof(tp->rx_opt));
Linus Torvalds1da177e2005-04-16 15:20:36 -07002131 __sk_dst_reset(sk);
2132
Eric Dumazetc720c7e2009-10-15 06:30:45 +00002133 WARN_ON(inet->inet_num && !icsk->icsk_bind_hash);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002134
2135 sk->sk_error_report(sk);
2136 return err;
2137}
Eric Dumazet4bc2f182010-07-09 21:22:10 +00002138EXPORT_SYMBOL(tcp_disconnect);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002139
2140/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07002141 * Socket option code for TCP.
2142 */
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002143static int do_tcp_setsockopt(struct sock *sk, int level,
David S. Millerb7058842009-09-30 16:12:20 -07002144 int optname, char __user *optval, unsigned int optlen)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002145{
2146 struct tcp_sock *tp = tcp_sk(sk);
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002147 struct inet_connection_sock *icsk = inet_csk(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002148 int val;
2149 int err = 0;
2150
William Allen Simpsone56fb502009-12-02 18:19:30 +00002151 /* These are data/string values, all the others are ints */
2152 switch (optname) {
2153 case TCP_CONGESTION: {
Stephen Hemminger5f8ef482005-06-23 20:37:36 -07002154 char name[TCP_CA_NAME_MAX];
2155
2156 if (optlen < 1)
2157 return -EINVAL;
2158
2159 val = strncpy_from_user(name, optval,
Andrew Morton4fdb78d2009-10-01 15:02:20 -07002160 min_t(long, TCP_CA_NAME_MAX-1, optlen));
Stephen Hemminger5f8ef482005-06-23 20:37:36 -07002161 if (val < 0)
2162 return -EFAULT;
2163 name[val] = 0;
2164
2165 lock_sock(sk);
Arnaldo Carvalho de Melo6687e982005-08-10 04:03:31 -03002166 err = tcp_set_congestion_control(sk, name);
Stephen Hemminger5f8ef482005-06-23 20:37:36 -07002167 release_sock(sk);
2168 return err;
2169 }
William Allen Simpsone56fb502009-12-02 18:19:30 +00002170 case TCP_COOKIE_TRANSACTIONS: {
2171 struct tcp_cookie_transactions ctd;
2172 struct tcp_cookie_values *cvp = NULL;
2173
2174 if (sizeof(ctd) > optlen)
2175 return -EINVAL;
2176 if (copy_from_user(&ctd, optval, sizeof(ctd)))
2177 return -EFAULT;
2178
2179 if (ctd.tcpct_used > sizeof(ctd.tcpct_value) ||
2180 ctd.tcpct_s_data_desired > TCP_MSS_DESIRED)
2181 return -EINVAL;
2182
2183 if (ctd.tcpct_cookie_desired == 0) {
2184 /* default to global value */
2185 } else if ((0x1 & ctd.tcpct_cookie_desired) ||
2186 ctd.tcpct_cookie_desired > TCP_COOKIE_MAX ||
2187 ctd.tcpct_cookie_desired < TCP_COOKIE_MIN) {
2188 return -EINVAL;
2189 }
2190
2191 if (TCP_COOKIE_OUT_NEVER & ctd.tcpct_flags) {
2192 /* Supercedes all other values */
2193 lock_sock(sk);
2194 if (tp->cookie_values != NULL) {
2195 kref_put(&tp->cookie_values->kref,
2196 tcp_cookie_values_release);
2197 tp->cookie_values = NULL;
2198 }
2199 tp->rx_opt.cookie_in_always = 0; /* false */
2200 tp->rx_opt.cookie_out_never = 1; /* true */
2201 release_sock(sk);
2202 return err;
2203 }
2204
2205 /* Allocate ancillary memory before locking.
2206 */
2207 if (ctd.tcpct_used > 0 ||
2208 (tp->cookie_values == NULL &&
2209 (sysctl_tcp_cookie_size > 0 ||
2210 ctd.tcpct_cookie_desired > 0 ||
2211 ctd.tcpct_s_data_desired > 0))) {
2212 cvp = kzalloc(sizeof(*cvp) + ctd.tcpct_used,
2213 GFP_KERNEL);
2214 if (cvp == NULL)
2215 return -ENOMEM;
Dmitry Popova3bdb542010-07-29 01:59:36 +00002216
2217 kref_init(&cvp->kref);
William Allen Simpsone56fb502009-12-02 18:19:30 +00002218 }
2219 lock_sock(sk);
2220 tp->rx_opt.cookie_in_always =
2221 (TCP_COOKIE_IN_ALWAYS & ctd.tcpct_flags);
2222 tp->rx_opt.cookie_out_never = 0; /* false */
2223
2224 if (tp->cookie_values != NULL) {
2225 if (cvp != NULL) {
2226 /* Changed values are recorded by a changed
2227 * pointer, ensuring the cookie will differ,
2228 * without separately hashing each value later.
2229 */
2230 kref_put(&tp->cookie_values->kref,
2231 tcp_cookie_values_release);
William Allen Simpsone56fb502009-12-02 18:19:30 +00002232 } else {
2233 cvp = tp->cookie_values;
2234 }
2235 }
Dmitry Popova3bdb542010-07-29 01:59:36 +00002236
William Allen Simpsone56fb502009-12-02 18:19:30 +00002237 if (cvp != NULL) {
2238 cvp->cookie_desired = ctd.tcpct_cookie_desired;
2239
2240 if (ctd.tcpct_used > 0) {
2241 memcpy(cvp->s_data_payload, ctd.tcpct_value,
2242 ctd.tcpct_used);
2243 cvp->s_data_desired = ctd.tcpct_used;
2244 cvp->s_data_constant = 1; /* true */
2245 } else {
2246 /* No constant payload data. */
2247 cvp->s_data_desired = ctd.tcpct_s_data_desired;
2248 cvp->s_data_constant = 0; /* false */
2249 }
Dmitry Popova3bdb542010-07-29 01:59:36 +00002250
2251 tp->cookie_values = cvp;
William Allen Simpsone56fb502009-12-02 18:19:30 +00002252 }
2253 release_sock(sk);
2254 return err;
2255 }
2256 default:
2257 /* fallthru */
2258 break;
Joe Perchesccbd6a52010-05-14 10:58:26 +00002259 }
Stephen Hemminger5f8ef482005-06-23 20:37:36 -07002260
Linus Torvalds1da177e2005-04-16 15:20:36 -07002261 if (optlen < sizeof(int))
2262 return -EINVAL;
2263
2264 if (get_user(val, (int __user *)optval))
2265 return -EFAULT;
2266
2267 lock_sock(sk);
2268
2269 switch (optname) {
2270 case TCP_MAXSEG:
2271 /* Values greater than interface MTU won't take effect. However
2272 * at the point when this call is done we typically don't yet
2273 * know which interface is going to be used */
David S. Millerc39508d2010-11-24 11:47:22 -08002274 if (val < TCP_MIN_MSS || val > MAX_TCP_WINDOW) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002275 err = -EINVAL;
2276 break;
2277 }
2278 tp->rx_opt.user_mss = val;
2279 break;
2280
2281 case TCP_NODELAY:
2282 if (val) {
2283 /* TCP_NODELAY is weaker than TCP_CORK, so that
2284 * this option on corked socket is remembered, but
2285 * it is not activated until cork is cleared.
2286 *
2287 * However, when TCP_NODELAY is set we make
2288 * an explicit push, which overrides even TCP_CORK
2289 * for currently queued segments.
2290 */
2291 tp->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH;
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -07002292 tcp_push_pending_frames(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002293 } else {
2294 tp->nonagle &= ~TCP_NAGLE_OFF;
2295 }
2296 break;
2297
Andreas Petlund36e31b02010-02-18 02:47:01 +00002298 case TCP_THIN_LINEAR_TIMEOUTS:
2299 if (val < 0 || val > 1)
2300 err = -EINVAL;
2301 else
2302 tp->thin_lto = val;
2303 break;
2304
Andreas Petlund7e380172010-02-18 04:48:19 +00002305 case TCP_THIN_DUPACK:
2306 if (val < 0 || val > 1)
2307 err = -EINVAL;
2308 else
2309 tp->thin_dupack = val;
2310 break;
2311
Linus Torvalds1da177e2005-04-16 15:20:36 -07002312 case TCP_CORK:
2313 /* When set indicates to always queue non-full frames.
2314 * Later the user clears this option and we transmit
2315 * any pending partial frames in the queue. This is
2316 * meant to be used alongside sendfile() to get properly
2317 * filled frames when the user (for example) must write
2318 * out headers with a write() call first and then use
2319 * sendfile to send out the data parts.
2320 *
2321 * TCP_CORK can be set together with TCP_NODELAY and it is
2322 * stronger than TCP_NODELAY.
2323 */
2324 if (val) {
2325 tp->nonagle |= TCP_NAGLE_CORK;
2326 } else {
2327 tp->nonagle &= ~TCP_NAGLE_CORK;
2328 if (tp->nonagle&TCP_NAGLE_OFF)
2329 tp->nonagle |= TCP_NAGLE_PUSH;
Ilpo Järvinen9e412ba2007-04-20 22:18:02 -07002330 tcp_push_pending_frames(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002331 }
2332 break;
2333
2334 case TCP_KEEPIDLE:
2335 if (val < 1 || val > MAX_TCP_KEEPIDLE)
2336 err = -EINVAL;
2337 else {
2338 tp->keepalive_time = val * HZ;
2339 if (sock_flag(sk, SOCK_KEEPOPEN) &&
2340 !((1 << sk->sk_state) &
2341 (TCPF_CLOSE | TCPF_LISTEN))) {
Flavio Leitner6c37e5d2010-04-26 18:33:27 +00002342 u32 elapsed = keepalive_time_elapsed(tp);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002343 if (tp->keepalive_time > elapsed)
2344 elapsed = tp->keepalive_time - elapsed;
2345 else
2346 elapsed = 0;
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002347 inet_csk_reset_keepalive_timer(sk, elapsed);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002348 }
2349 }
2350 break;
2351 case TCP_KEEPINTVL:
2352 if (val < 1 || val > MAX_TCP_KEEPINTVL)
2353 err = -EINVAL;
2354 else
2355 tp->keepalive_intvl = val * HZ;
2356 break;
2357 case TCP_KEEPCNT:
2358 if (val < 1 || val > MAX_TCP_KEEPCNT)
2359 err = -EINVAL;
2360 else
2361 tp->keepalive_probes = val;
2362 break;
2363 case TCP_SYNCNT:
2364 if (val < 1 || val > MAX_TCP_SYNCNT)
2365 err = -EINVAL;
2366 else
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002367 icsk->icsk_syn_retries = val;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002368 break;
2369
2370 case TCP_LINGER2:
2371 if (val < 0)
2372 tp->linger2 = -1;
2373 else if (val > sysctl_tcp_fin_timeout / HZ)
2374 tp->linger2 = 0;
2375 else
2376 tp->linger2 = val * HZ;
2377 break;
2378
2379 case TCP_DEFER_ACCEPT:
Julian Anastasovb103cf32009-10-19 10:10:40 +00002380 /* Translate value in seconds to number of retransmits */
2381 icsk->icsk_accept_queue.rskq_defer_accept =
2382 secs_to_retrans(val, TCP_TIMEOUT_INIT / HZ,
2383 TCP_RTO_MAX / HZ);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002384 break;
2385
2386 case TCP_WINDOW_CLAMP:
2387 if (!val) {
2388 if (sk->sk_state != TCP_CLOSE) {
2389 err = -EINVAL;
2390 break;
2391 }
2392 tp->window_clamp = 0;
2393 } else
2394 tp->window_clamp = val < SOCK_MIN_RCVBUF / 2 ?
2395 SOCK_MIN_RCVBUF / 2 : val;
2396 break;
2397
2398 case TCP_QUICKACK:
2399 if (!val) {
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002400 icsk->icsk_ack.pingpong = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002401 } else {
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002402 icsk->icsk_ack.pingpong = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002403 if ((1 << sk->sk_state) &
2404 (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) &&
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002405 inet_csk_ack_scheduled(sk)) {
2406 icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
Chris Leech0e4b4992006-05-23 18:00:16 -07002407 tcp_cleanup_rbuf(sk, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002408 if (!(val & 1))
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002409 icsk->icsk_ack.pingpong = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002410 }
2411 }
2412 break;
2413
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002414#ifdef CONFIG_TCP_MD5SIG
2415 case TCP_MD5SIG:
2416 /* Read the IP->Key mappings from userspace */
2417 err = tp->af_specific->md5_parse(sk, optval, optlen);
2418 break;
2419#endif
Jerry Chudca43c72010-08-27 19:13:28 +00002420 case TCP_USER_TIMEOUT:
2421 /* Cap the max timeout in ms TCP will retry/retrans
2422 * before giving up and aborting (ETIMEDOUT) a connection.
2423 */
2424 icsk->icsk_user_timeout = msecs_to_jiffies(val);
2425 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002426 default:
2427 err = -ENOPROTOOPT;
2428 break;
Stephen Hemminger3ff50b72007-04-20 17:09:22 -07002429 }
2430
Linus Torvalds1da177e2005-04-16 15:20:36 -07002431 release_sock(sk);
2432 return err;
2433}
2434
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002435int tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval,
David S. Millerb7058842009-09-30 16:12:20 -07002436 unsigned int optlen)
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002437{
Eric Dumazetcf533ea2011-10-21 05:22:42 -04002438 const struct inet_connection_sock *icsk = inet_csk(sk);
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002439
2440 if (level != SOL_TCP)
2441 return icsk->icsk_af_ops->setsockopt(sk, level, optname,
2442 optval, optlen);
2443 return do_tcp_setsockopt(sk, level, optname, optval, optlen);
2444}
Eric Dumazet4bc2f182010-07-09 21:22:10 +00002445EXPORT_SYMBOL(tcp_setsockopt);
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002446
2447#ifdef CONFIG_COMPAT
Arnaldo Carvalho de Melo543d9cf2006-03-20 22:48:35 -08002448int compat_tcp_setsockopt(struct sock *sk, int level, int optname,
David S. Millerb7058842009-09-30 16:12:20 -07002449 char __user *optval, unsigned int optlen)
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002450{
Arnaldo Carvalho de Melodec73ff2006-03-20 22:46:16 -08002451 if (level != SOL_TCP)
2452 return inet_csk_compat_setsockopt(sk, level, optname,
2453 optval, optlen);
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002454 return do_tcp_setsockopt(sk, level, optname, optval, optlen);
2455}
Arnaldo Carvalho de Melo543d9cf2006-03-20 22:48:35 -08002456EXPORT_SYMBOL(compat_tcp_setsockopt);
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002457#endif
2458
Linus Torvalds1da177e2005-04-16 15:20:36 -07002459/* Return information about state of tcp endpoint in API format. */
Eric Dumazetcf533ea2011-10-21 05:22:42 -04002460void tcp_get_info(const struct sock *sk, struct tcp_info *info)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002461{
Eric Dumazetcf533ea2011-10-21 05:22:42 -04002462 const struct tcp_sock *tp = tcp_sk(sk);
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002463 const struct inet_connection_sock *icsk = inet_csk(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002464 u32 now = tcp_time_stamp;
2465
2466 memset(info, 0, sizeof(*info));
2467
2468 info->tcpi_state = sk->sk_state;
Arnaldo Carvalho de Melo6687e982005-08-10 04:03:31 -03002469 info->tcpi_ca_state = icsk->icsk_ca_state;
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002470 info->tcpi_retransmits = icsk->icsk_retransmits;
Arnaldo Carvalho de Melo6687e982005-08-10 04:03:31 -03002471 info->tcpi_probes = icsk->icsk_probes_out;
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002472 info->tcpi_backoff = icsk->icsk_backoff;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002473
2474 if (tp->rx_opt.tstamp_ok)
2475 info->tcpi_options |= TCPI_OPT_TIMESTAMPS;
Ilpo Järvinene60402d2007-08-09 15:14:46 +03002476 if (tcp_is_sack(tp))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002477 info->tcpi_options |= TCPI_OPT_SACK;
2478 if (tp->rx_opt.wscale_ok) {
2479 info->tcpi_options |= TCPI_OPT_WSCALE;
2480 info->tcpi_snd_wscale = tp->rx_opt.snd_wscale;
2481 info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale;
YOSHIFUJI Hideakie905a9e2007-02-09 23:24:47 +09002482 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002483
Eric Dumazetb5c56932011-10-03 14:01:21 -04002484 if (tp->ecn_flags & TCP_ECN_OK)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002485 info->tcpi_options |= TCPI_OPT_ECN;
Eric Dumazetb5c56932011-10-03 14:01:21 -04002486 if (tp->ecn_flags & TCP_ECN_SEEN)
2487 info->tcpi_options |= TCPI_OPT_ECN_SEEN;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002488
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002489 info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto);
2490 info->tcpi_ato = jiffies_to_usecs(icsk->icsk_ack.ato);
David S. Millerc1b4a7e2005-07-05 15:24:38 -07002491 info->tcpi_snd_mss = tp->mss_cache;
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002492 info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002493
Rick Jones5ee3afb2007-09-18 13:26:31 -07002494 if (sk->sk_state == TCP_LISTEN) {
2495 info->tcpi_unacked = sk->sk_ack_backlog;
2496 info->tcpi_sacked = sk->sk_max_ack_backlog;
2497 } else {
2498 info->tcpi_unacked = tp->packets_out;
2499 info->tcpi_sacked = tp->sacked_out;
2500 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002501 info->tcpi_lost = tp->lost_out;
2502 info->tcpi_retrans = tp->retrans_out;
2503 info->tcpi_fackets = tp->fackets_out;
2504
2505 info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime);
Arnaldo Carvalho de Melo463c84b2005-08-09 20:10:42 -07002506 info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002507 info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp);
2508
Arnaldo Carvalho de Melod83d8462005-12-13 23:26:10 -08002509 info->tcpi_pmtu = icsk->icsk_pmtu_cookie;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002510 info->tcpi_rcv_ssthresh = tp->rcv_ssthresh;
2511 info->tcpi_rtt = jiffies_to_usecs(tp->srtt)>>3;
2512 info->tcpi_rttvar = jiffies_to_usecs(tp->mdev)>>2;
2513 info->tcpi_snd_ssthresh = tp->snd_ssthresh;
2514 info->tcpi_snd_cwnd = tp->snd_cwnd;
2515 info->tcpi_advmss = tp->advmss;
2516 info->tcpi_reordering = tp->reordering;
2517
2518 info->tcpi_rcv_rtt = jiffies_to_usecs(tp->rcv_rtt_est.rtt)>>3;
2519 info->tcpi_rcv_space = tp->rcvq_space.space;
2520
2521 info->tcpi_total_retrans = tp->total_retrans;
Chinh Tranbbebbfe2011-10-26 16:14:15 -07002522
Steve Mucklef132c6c2012-06-06 18:30:57 -07002523 if (sk->sk_socket) {
Chinh Tranbbebbfe2011-10-26 16:14:15 -07002524 struct file *filep = sk->sk_socket->file;
Steve Mucklef132c6c2012-06-06 18:30:57 -07002525 if (filep)
Chinh Tranbbebbfe2011-10-26 16:14:15 -07002526 info->tcpi_count = atomic_read(&filep->f_count);
2527 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002528}
Linus Torvalds1da177e2005-04-16 15:20:36 -07002529EXPORT_SYMBOL_GPL(tcp_get_info);
2530
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002531static int do_tcp_getsockopt(struct sock *sk, int level,
2532 int optname, char __user *optval, int __user *optlen)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002533{
Arnaldo Carvalho de Melo295f7322005-08-09 20:11:56 -07002534 struct inet_connection_sock *icsk = inet_csk(sk);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002535 struct tcp_sock *tp = tcp_sk(sk);
2536 int val, len;
2537
Linus Torvalds1da177e2005-04-16 15:20:36 -07002538 if (get_user(len, optlen))
2539 return -EFAULT;
2540
2541 len = min_t(unsigned int, len, sizeof(int));
2542
2543 if (len < 0)
2544 return -EINVAL;
2545
2546 switch (optname) {
2547 case TCP_MAXSEG:
David S. Millerc1b4a7e2005-07-05 15:24:38 -07002548 val = tp->mss_cache;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002549 if (!val && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
2550 val = tp->rx_opt.user_mss;
2551 break;
2552 case TCP_NODELAY:
2553 val = !!(tp->nonagle&TCP_NAGLE_OFF);
2554 break;
2555 case TCP_CORK:
2556 val = !!(tp->nonagle&TCP_NAGLE_CORK);
2557 break;
2558 case TCP_KEEPIDLE:
Eric Dumazetdf19a622009-08-28 23:48:54 -07002559 val = keepalive_time_when(tp) / HZ;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002560 break;
2561 case TCP_KEEPINTVL:
Eric Dumazetdf19a622009-08-28 23:48:54 -07002562 val = keepalive_intvl_when(tp) / HZ;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002563 break;
2564 case TCP_KEEPCNT:
Eric Dumazetdf19a622009-08-28 23:48:54 -07002565 val = keepalive_probes(tp);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002566 break;
2567 case TCP_SYNCNT:
Arnaldo Carvalho de Melo295f7322005-08-09 20:11:56 -07002568 val = icsk->icsk_syn_retries ? : sysctl_tcp_syn_retries;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002569 break;
2570 case TCP_LINGER2:
2571 val = tp->linger2;
2572 if (val >= 0)
2573 val = (val ? : sysctl_tcp_fin_timeout) / HZ;
2574 break;
2575 case TCP_DEFER_ACCEPT:
Julian Anastasovb103cf32009-10-19 10:10:40 +00002576 val = retrans_to_secs(icsk->icsk_accept_queue.rskq_defer_accept,
2577 TCP_TIMEOUT_INIT / HZ, TCP_RTO_MAX / HZ);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002578 break;
2579 case TCP_WINDOW_CLAMP:
2580 val = tp->window_clamp;
2581 break;
2582 case TCP_INFO: {
2583 struct tcp_info info;
2584
2585 if (get_user(len, optlen))
2586 return -EFAULT;
2587
2588 tcp_get_info(sk, &info);
2589
2590 len = min_t(unsigned int, len, sizeof(info));
2591 if (put_user(len, optlen))
2592 return -EFAULT;
2593 if (copy_to_user(optval, &info, len))
2594 return -EFAULT;
2595 return 0;
2596 }
2597 case TCP_QUICKACK:
Arnaldo Carvalho de Melo295f7322005-08-09 20:11:56 -07002598 val = !icsk->icsk_ack.pingpong;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002599 break;
Stephen Hemminger5f8ef482005-06-23 20:37:36 -07002600
2601 case TCP_CONGESTION:
2602 if (get_user(len, optlen))
2603 return -EFAULT;
2604 len = min_t(unsigned int, len, TCP_CA_NAME_MAX);
2605 if (put_user(len, optlen))
2606 return -EFAULT;
Arnaldo Carvalho de Melo6687e982005-08-10 04:03:31 -03002607 if (copy_to_user(optval, icsk->icsk_ca_ops->name, len))
Stephen Hemminger5f8ef482005-06-23 20:37:36 -07002608 return -EFAULT;
2609 return 0;
William Allen Simpsone56fb502009-12-02 18:19:30 +00002610
2611 case TCP_COOKIE_TRANSACTIONS: {
2612 struct tcp_cookie_transactions ctd;
2613 struct tcp_cookie_values *cvp = tp->cookie_values;
2614
2615 if (get_user(len, optlen))
2616 return -EFAULT;
2617 if (len < sizeof(ctd))
2618 return -EINVAL;
2619
2620 memset(&ctd, 0, sizeof(ctd));
2621 ctd.tcpct_flags = (tp->rx_opt.cookie_in_always ?
2622 TCP_COOKIE_IN_ALWAYS : 0)
2623 | (tp->rx_opt.cookie_out_never ?
2624 TCP_COOKIE_OUT_NEVER : 0);
2625
2626 if (cvp != NULL) {
2627 ctd.tcpct_flags |= (cvp->s_data_in ?
2628 TCP_S_DATA_IN : 0)
2629 | (cvp->s_data_out ?
2630 TCP_S_DATA_OUT : 0);
2631
2632 ctd.tcpct_cookie_desired = cvp->cookie_desired;
2633 ctd.tcpct_s_data_desired = cvp->s_data_desired;
2634
William Allen Simpsone56fb502009-12-02 18:19:30 +00002635 memcpy(&ctd.tcpct_value[0], &cvp->cookie_pair[0],
2636 cvp->cookie_pair_size);
2637 ctd.tcpct_used = cvp->cookie_pair_size;
2638 }
2639
2640 if (put_user(sizeof(ctd), optlen))
2641 return -EFAULT;
2642 if (copy_to_user(optval, &ctd, sizeof(ctd)))
2643 return -EFAULT;
2644 return 0;
2645 }
Josh Hunt3c0fef02010-07-30 13:49:35 +00002646 case TCP_THIN_LINEAR_TIMEOUTS:
2647 val = tp->thin_lto;
2648 break;
2649 case TCP_THIN_DUPACK:
2650 val = tp->thin_dupack;
2651 break;
Jerry Chudca43c72010-08-27 19:13:28 +00002652
2653 case TCP_USER_TIMEOUT:
2654 val = jiffies_to_msecs(icsk->icsk_user_timeout);
2655 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002656 default:
2657 return -ENOPROTOOPT;
Stephen Hemminger3ff50b72007-04-20 17:09:22 -07002658 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002659
2660 if (put_user(len, optlen))
2661 return -EFAULT;
2662 if (copy_to_user(optval, &val, len))
2663 return -EFAULT;
2664 return 0;
2665}
2666
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002667int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval,
2668 int __user *optlen)
2669{
2670 struct inet_connection_sock *icsk = inet_csk(sk);
2671
2672 if (level != SOL_TCP)
2673 return icsk->icsk_af_ops->getsockopt(sk, level, optname,
2674 optval, optlen);
2675 return do_tcp_getsockopt(sk, level, optname, optval, optlen);
2676}
Eric Dumazet4bc2f182010-07-09 21:22:10 +00002677EXPORT_SYMBOL(tcp_getsockopt);
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002678
2679#ifdef CONFIG_COMPAT
Arnaldo Carvalho de Melo543d9cf2006-03-20 22:48:35 -08002680int compat_tcp_getsockopt(struct sock *sk, int level, int optname,
2681 char __user *optval, int __user *optlen)
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002682{
Arnaldo Carvalho de Melodec73ff2006-03-20 22:46:16 -08002683 if (level != SOL_TCP)
2684 return inet_csk_compat_getsockopt(sk, level, optname,
2685 optval, optlen);
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002686 return do_tcp_getsockopt(sk, level, optname, optval, optlen);
2687}
Arnaldo Carvalho de Melo543d9cf2006-03-20 22:48:35 -08002688EXPORT_SYMBOL(compat_tcp_getsockopt);
Dmitry Mishin3fdadf72006-03-20 22:45:21 -08002689#endif
Linus Torvalds1da177e2005-04-16 15:20:36 -07002690
Michał Mirosławc8f44af2011-11-15 15:29:55 +00002691struct sk_buff *tcp_tso_segment(struct sk_buff *skb,
2692 netdev_features_t features)
Herbert Xuf4c50d92006-06-22 03:02:40 -07002693{
2694 struct sk_buff *segs = ERR_PTR(-EINVAL);
2695 struct tcphdr *th;
2696 unsigned thlen;
2697 unsigned int seq;
Al Virod3bc23e2006-11-14 21:24:49 -08002698 __be32 delta;
Herbert Xuf4c50d92006-06-22 03:02:40 -07002699 unsigned int oldlen;
Herbert Xu4e704ee2009-01-14 20:41:12 -08002700 unsigned int mss;
Herbert Xuf4c50d92006-06-22 03:02:40 -07002701
2702 if (!pskb_may_pull(skb, sizeof(*th)))
2703 goto out;
2704
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07002705 th = tcp_hdr(skb);
Herbert Xuf4c50d92006-06-22 03:02:40 -07002706 thlen = th->doff * 4;
2707 if (thlen < sizeof(*th))
2708 goto out;
2709
2710 if (!pskb_may_pull(skb, thlen))
2711 goto out;
2712
Herbert Xu0718bcc2006-06-25 23:55:46 -07002713 oldlen = (u16)~skb->len;
Herbert Xuf4c50d92006-06-22 03:02:40 -07002714 __skb_pull(skb, thlen);
2715
Herbert Xu4e704ee2009-01-14 20:41:12 -08002716 mss = skb_shinfo(skb)->gso_size;
2717 if (unlikely(skb->len <= mss))
2718 goto out;
2719
Herbert Xu3820c3f2006-06-29 20:11:25 -07002720 if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) {
2721 /* Packet is from an untrusted source, reset gso_segs. */
Herbert Xubbcf4672006-07-03 19:38:35 -07002722 int type = skb_shinfo(skb)->gso_type;
Herbert Xu3820c3f2006-06-29 20:11:25 -07002723
Herbert Xubbcf4672006-07-03 19:38:35 -07002724 if (unlikely(type &
2725 ~(SKB_GSO_TCPV4 |
2726 SKB_GSO_DODGY |
2727 SKB_GSO_TCP_ECN |
2728 SKB_GSO_TCPV6 |
2729 0) ||
2730 !(type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))))
2731 goto out;
2732
Ilpo Järvinen172589c2007-08-28 15:50:33 -07002733 skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss);
Herbert Xu3820c3f2006-06-29 20:11:25 -07002734
2735 segs = NULL;
2736 goto out;
2737 }
2738
Herbert Xu576a30e2006-06-27 13:22:38 -07002739 segs = skb_segment(skb, features);
Herbert Xuf4c50d92006-06-22 03:02:40 -07002740 if (IS_ERR(segs))
2741 goto out;
2742
Herbert Xu4e704ee2009-01-14 20:41:12 -08002743 delta = htonl(oldlen + (thlen + mss));
Herbert Xuf4c50d92006-06-22 03:02:40 -07002744
2745 skb = segs;
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07002746 th = tcp_hdr(skb);
Herbert Xuf4c50d92006-06-22 03:02:40 -07002747 seq = ntohl(th->seq);
2748
2749 do {
2750 th->fin = th->psh = 0;
2751
Al Virod3bc23e2006-11-14 21:24:49 -08002752 th->check = ~csum_fold((__force __wsum)((__force u32)th->check +
2753 (__force u32)delta));
Patrick McHardy84fa7932006-08-29 16:44:56 -07002754 if (skb->ip_summed != CHECKSUM_PARTIAL)
Arnaldo Carvalho de Melo9c702202007-04-25 18:04:18 -07002755 th->check =
2756 csum_fold(csum_partial(skb_transport_header(skb),
2757 thlen, skb->csum));
Herbert Xuf4c50d92006-06-22 03:02:40 -07002758
Herbert Xu4e704ee2009-01-14 20:41:12 -08002759 seq += mss;
Herbert Xuf4c50d92006-06-22 03:02:40 -07002760 skb = skb->next;
Arnaldo Carvalho de Meloaa8223c2007-04-10 21:04:22 -07002761 th = tcp_hdr(skb);
Herbert Xuf4c50d92006-06-22 03:02:40 -07002762
2763 th->seq = htonl(seq);
2764 th->cwr = 0;
2765 } while (skb->next);
2766
Arnaldo Carvalho de Melo27a884d2007-04-19 20:29:13 -07002767 delta = htonl(oldlen + (skb->tail - skb->transport_header) +
Arnaldo Carvalho de Melo9c702202007-04-25 18:04:18 -07002768 skb->data_len);
Al Virod3bc23e2006-11-14 21:24:49 -08002769 th->check = ~csum_fold((__force __wsum)((__force u32)th->check +
2770 (__force u32)delta));
Patrick McHardy84fa7932006-08-29 16:44:56 -07002771 if (skb->ip_summed != CHECKSUM_PARTIAL)
Arnaldo Carvalho de Melo9c702202007-04-25 18:04:18 -07002772 th->check = csum_fold(csum_partial(skb_transport_header(skb),
2773 thlen, skb->csum));
Herbert Xuf4c50d92006-06-22 03:02:40 -07002774
2775out:
2776 return segs;
2777}
Herbert Xuadcfc7d2006-06-30 13:36:15 -07002778EXPORT_SYMBOL(tcp_tso_segment);
Herbert Xuf4c50d92006-06-22 03:02:40 -07002779
Herbert Xubf296b12008-12-15 23:43:36 -08002780struct sk_buff **tcp_gro_receive(struct sk_buff **head, struct sk_buff *skb)
2781{
2782 struct sk_buff **pp = NULL;
2783 struct sk_buff *p;
2784 struct tcphdr *th;
2785 struct tcphdr *th2;
Herbert Xua0a69a02009-04-17 02:34:38 -07002786 unsigned int len;
Herbert Xubf296b12008-12-15 23:43:36 -08002787 unsigned int thlen;
Eric Dumazet0eae88f2010-04-20 19:06:52 -07002788 __be32 flags;
Herbert Xubf296b12008-12-15 23:43:36 -08002789 unsigned int mss = 1;
Herbert Xua5b1cf22009-05-26 18:50:28 +00002790 unsigned int hlen;
2791 unsigned int off;
Herbert Xubf296b12008-12-15 23:43:36 -08002792 int flush = 1;
Herbert Xuaa6320d2009-02-08 18:00:40 +00002793 int i;
Herbert Xubf296b12008-12-15 23:43:36 -08002794
Herbert Xua5b1cf22009-05-26 18:50:28 +00002795 off = skb_gro_offset(skb);
2796 hlen = off + sizeof(*th);
2797 th = skb_gro_header_fast(skb, off);
2798 if (skb_gro_header_hard(skb, hlen)) {
2799 th = skb_gro_header_slow(skb, hlen, off);
2800 if (unlikely(!th))
2801 goto out;
2802 }
Herbert Xubf296b12008-12-15 23:43:36 -08002803
Herbert Xubf296b12008-12-15 23:43:36 -08002804 thlen = th->doff * 4;
2805 if (thlen < sizeof(*th))
2806 goto out;
2807
Herbert Xua5b1cf22009-05-26 18:50:28 +00002808 hlen = off + thlen;
2809 if (skb_gro_header_hard(skb, hlen)) {
2810 th = skb_gro_header_slow(skb, hlen, off);
2811 if (unlikely(!th))
2812 goto out;
2813 }
Herbert Xubf296b12008-12-15 23:43:36 -08002814
Herbert Xu86911732009-01-29 14:19:50 +00002815 skb_gro_pull(skb, thlen);
Herbert Xubf296b12008-12-15 23:43:36 -08002816
Herbert Xua0a69a02009-04-17 02:34:38 -07002817 len = skb_gro_len(skb);
Herbert Xubf296b12008-12-15 23:43:36 -08002818 flags = tcp_flag_word(th);
2819
2820 for (; (p = *head); head = &p->next) {
2821 if (!NAPI_GRO_CB(p)->same_flow)
2822 continue;
2823
2824 th2 = tcp_hdr(p);
2825
Herbert Xu745898e2009-05-26 18:50:24 +00002826 if (*(u32 *)&th->source ^ *(u32 *)&th2->source) {
Herbert Xubf296b12008-12-15 23:43:36 -08002827 NAPI_GRO_CB(p)->same_flow = 0;
2828 continue;
2829 }
2830
2831 goto found;
2832 }
2833
2834 goto out_check_final;
2835
2836found:
2837 flush = NAPI_GRO_CB(p)->flush;
Eric Dumazet0eae88f2010-04-20 19:06:52 -07002838 flush |= (__force int)(flags & TCP_FLAG_CWR);
2839 flush |= (__force int)((flags ^ tcp_flag_word(th2)) &
2840 ~(TCP_FLAG_CWR | TCP_FLAG_FIN | TCP_FLAG_PSH));
2841 flush |= (__force int)(th->ack_seq ^ th2->ack_seq);
Herbert Xua2a804c2009-05-26 18:50:34 +00002842 for (i = sizeof(*th); i < thlen; i += 4)
Herbert Xuaa6320d2009-02-08 18:00:40 +00002843 flush |= *(u32 *)((u8 *)th + i) ^
2844 *(u32 *)((u8 *)th2 + i);
Herbert Xubf296b12008-12-15 23:43:36 -08002845
Herbert Xub5302562009-01-04 16:13:19 -08002846 mss = skb_shinfo(p)->gso_size;
Herbert Xubf296b12008-12-15 23:43:36 -08002847
Herbert Xu30a3ae32009-05-26 18:50:26 +00002848 flush |= (len - 1) >= mss;
Herbert Xuaa6320d2009-02-08 18:00:40 +00002849 flush |= (ntohl(th2->seq) + skb_gro_len(p)) ^ ntohl(th->seq);
Herbert Xubf296b12008-12-15 23:43:36 -08002850
2851 if (flush || skb_gro_receive(head, skb)) {
2852 mss = 1;
2853 goto out_check_final;
2854 }
2855
2856 p = *head;
2857 th2 = tcp_hdr(p);
2858 tcp_flag_word(th2) |= flags & (TCP_FLAG_FIN | TCP_FLAG_PSH);
2859
2860out_check_final:
Herbert Xua0a69a02009-04-17 02:34:38 -07002861 flush = len < mss;
Eric Dumazet0eae88f2010-04-20 19:06:52 -07002862 flush |= (__force int)(flags & (TCP_FLAG_URG | TCP_FLAG_PSH |
2863 TCP_FLAG_RST | TCP_FLAG_SYN |
2864 TCP_FLAG_FIN));
Herbert Xubf296b12008-12-15 23:43:36 -08002865
2866 if (p && (!NAPI_GRO_CB(skb)->same_flow || flush))
2867 pp = head;
2868
2869out:
2870 NAPI_GRO_CB(skb)->flush |= flush;
2871
2872 return pp;
2873}
Herbert Xu684f2172009-01-08 10:41:23 -08002874EXPORT_SYMBOL(tcp_gro_receive);
Herbert Xubf296b12008-12-15 23:43:36 -08002875
2876int tcp_gro_complete(struct sk_buff *skb)
2877{
2878 struct tcphdr *th = tcp_hdr(skb);
2879
2880 skb->csum_start = skb_transport_header(skb) - skb->head;
2881 skb->csum_offset = offsetof(struct tcphdr, check);
2882 skb->ip_summed = CHECKSUM_PARTIAL;
2883
Herbert Xubf296b12008-12-15 23:43:36 -08002884 skb_shinfo(skb)->gso_segs = NAPI_GRO_CB(skb)->count;
2885
2886 if (th->cwr)
2887 skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
2888
2889 return 0;
2890}
Herbert Xu684f2172009-01-08 10:41:23 -08002891EXPORT_SYMBOL(tcp_gro_complete);
Herbert Xubf296b12008-12-15 23:43:36 -08002892
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002893#ifdef CONFIG_TCP_MD5SIG
2894static unsigned long tcp_md5sig_users;
Eric Dumazet765cf992011-09-12 20:28:37 +00002895static struct tcp_md5sig_pool __percpu *tcp_md5sig_pool;
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002896static DEFINE_SPINLOCK(tcp_md5sig_pool_lock);
2897
Eric Dumazet765cf992011-09-12 20:28:37 +00002898static void __tcp_free_md5sig_pool(struct tcp_md5sig_pool __percpu *pool)
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002899{
2900 int cpu;
Eric Dumazet765cf992011-09-12 20:28:37 +00002901
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002902 for_each_possible_cpu(cpu) {
Eric Dumazet765cf992011-09-12 20:28:37 +00002903 struct tcp_md5sig_pool *p = per_cpu_ptr(pool, cpu);
2904
2905 if (p->md5_desc.tfm)
2906 crypto_free_hash(p->md5_desc.tfm);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002907 }
2908 free_percpu(pool);
2909}
2910
2911void tcp_free_md5sig_pool(void)
2912{
Eric Dumazet765cf992011-09-12 20:28:37 +00002913 struct tcp_md5sig_pool __percpu *pool = NULL;
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002914
David S. Miller2c4f6212007-02-20 23:51:47 -08002915 spin_lock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002916 if (--tcp_md5sig_users == 0) {
2917 pool = tcp_md5sig_pool;
2918 tcp_md5sig_pool = NULL;
2919 }
David S. Miller2c4f6212007-02-20 23:51:47 -08002920 spin_unlock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002921 if (pool)
2922 __tcp_free_md5sig_pool(pool);
2923}
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002924EXPORT_SYMBOL(tcp_free_md5sig_pool);
2925
Eric Dumazet765cf992011-09-12 20:28:37 +00002926static struct tcp_md5sig_pool __percpu *
Tejun Heo7d720c32010-02-16 15:20:26 +00002927__tcp_alloc_md5sig_pool(struct sock *sk)
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002928{
2929 int cpu;
Eric Dumazet765cf992011-09-12 20:28:37 +00002930 struct tcp_md5sig_pool __percpu *pool;
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002931
Eric Dumazet765cf992011-09-12 20:28:37 +00002932 pool = alloc_percpu(struct tcp_md5sig_pool);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002933 if (!pool)
2934 return NULL;
2935
2936 for_each_possible_cpu(cpu) {
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002937 struct crypto_hash *hash;
2938
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002939 hash = crypto_alloc_hash("md5", 0, CRYPTO_ALG_ASYNC);
2940 if (!hash || IS_ERR(hash))
2941 goto out_free;
2942
Eric Dumazet765cf992011-09-12 20:28:37 +00002943 per_cpu_ptr(pool, cpu)->md5_desc.tfm = hash;
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002944 }
2945 return pool;
2946out_free:
2947 __tcp_free_md5sig_pool(pool);
2948 return NULL;
2949}
2950
Eric Dumazet765cf992011-09-12 20:28:37 +00002951struct tcp_md5sig_pool __percpu *tcp_alloc_md5sig_pool(struct sock *sk)
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002952{
Eric Dumazet765cf992011-09-12 20:28:37 +00002953 struct tcp_md5sig_pool __percpu *pool;
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002954 int alloc = 0;
2955
2956retry:
David S. Miller2c4f6212007-02-20 23:51:47 -08002957 spin_lock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002958 pool = tcp_md5sig_pool;
2959 if (tcp_md5sig_users++ == 0) {
2960 alloc = 1;
David S. Miller2c4f6212007-02-20 23:51:47 -08002961 spin_unlock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002962 } else if (!pool) {
2963 tcp_md5sig_users--;
David S. Miller2c4f6212007-02-20 23:51:47 -08002964 spin_unlock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002965 cpu_relax();
2966 goto retry;
2967 } else
David S. Miller2c4f6212007-02-20 23:51:47 -08002968 spin_unlock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002969
2970 if (alloc) {
2971 /* we cannot hold spinlock here because this may sleep. */
Eric Dumazet765cf992011-09-12 20:28:37 +00002972 struct tcp_md5sig_pool __percpu *p;
Tejun Heo7d720c32010-02-16 15:20:26 +00002973
2974 p = __tcp_alloc_md5sig_pool(sk);
David S. Miller2c4f6212007-02-20 23:51:47 -08002975 spin_lock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002976 if (!p) {
2977 tcp_md5sig_users--;
David S. Miller2c4f6212007-02-20 23:51:47 -08002978 spin_unlock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002979 return NULL;
2980 }
2981 pool = tcp_md5sig_pool;
2982 if (pool) {
2983 /* oops, it has already been assigned. */
David S. Miller2c4f6212007-02-20 23:51:47 -08002984 spin_unlock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002985 __tcp_free_md5sig_pool(p);
2986 } else {
2987 tcp_md5sig_pool = pool = p;
David S. Miller2c4f6212007-02-20 23:51:47 -08002988 spin_unlock_bh(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002989 }
2990 }
2991 return pool;
2992}
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08002993EXPORT_SYMBOL(tcp_alloc_md5sig_pool);
2994
Eric Dumazet35790c02010-05-16 00:34:04 -07002995
2996/**
2997 * tcp_get_md5sig_pool - get md5sig_pool for this user
2998 *
2999 * We use percpu structure, so if we succeed, we exit with preemption
3000 * and BH disabled, to make sure another thread or softirq handling
3001 * wont try to get same context.
3002 */
3003struct tcp_md5sig_pool *tcp_get_md5sig_pool(void)
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08003004{
Eric Dumazet765cf992011-09-12 20:28:37 +00003005 struct tcp_md5sig_pool __percpu *p;
Eric Dumazet35790c02010-05-16 00:34:04 -07003006
3007 local_bh_disable();
3008
3009 spin_lock(&tcp_md5sig_pool_lock);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08003010 p = tcp_md5sig_pool;
3011 if (p)
3012 tcp_md5sig_users++;
Eric Dumazet35790c02010-05-16 00:34:04 -07003013 spin_unlock(&tcp_md5sig_pool_lock);
3014
3015 if (p)
Eric Dumazet765cf992011-09-12 20:28:37 +00003016 return this_cpu_ptr(p);
Eric Dumazet35790c02010-05-16 00:34:04 -07003017
3018 local_bh_enable();
3019 return NULL;
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08003020}
Eric Dumazet35790c02010-05-16 00:34:04 -07003021EXPORT_SYMBOL(tcp_get_md5sig_pool);
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08003022
Eric Dumazet35790c02010-05-16 00:34:04 -07003023void tcp_put_md5sig_pool(void)
David S. Miller6931ba72006-12-13 16:25:44 -08003024{
Eric Dumazet35790c02010-05-16 00:34:04 -07003025 local_bh_enable();
David S. Miller6931ba72006-12-13 16:25:44 -08003026 tcp_free_md5sig_pool();
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08003027}
Eric Dumazet35790c02010-05-16 00:34:04 -07003028EXPORT_SYMBOL(tcp_put_md5sig_pool);
Adam Langley49a72df2008-07-19 00:01:42 -07003029
3030int tcp_md5_hash_header(struct tcp_md5sig_pool *hp,
Eric Dumazetca35a0e2011-10-24 01:52:35 -04003031 const struct tcphdr *th)
Adam Langley49a72df2008-07-19 00:01:42 -07003032{
3033 struct scatterlist sg;
Eric Dumazetca35a0e2011-10-24 01:52:35 -04003034 struct tcphdr hdr;
Adam Langley49a72df2008-07-19 00:01:42 -07003035 int err;
3036
Eric Dumazetca35a0e2011-10-24 01:52:35 -04003037 /* We are not allowed to change tcphdr, make a local copy */
3038 memcpy(&hdr, th, sizeof(hdr));
3039 hdr.check = 0;
3040
Adam Langley49a72df2008-07-19 00:01:42 -07003041 /* options aren't included in the hash */
Eric Dumazetca35a0e2011-10-24 01:52:35 -04003042 sg_init_one(&sg, &hdr, sizeof(hdr));
3043 err = crypto_hash_update(&hp->md5_desc, &sg, sizeof(hdr));
Adam Langley49a72df2008-07-19 00:01:42 -07003044 return err;
3045}
Adam Langley49a72df2008-07-19 00:01:42 -07003046EXPORT_SYMBOL(tcp_md5_hash_header);
3047
3048int tcp_md5_hash_skb_data(struct tcp_md5sig_pool *hp,
Eric Dumazetcf533ea2011-10-21 05:22:42 -04003049 const struct sk_buff *skb, unsigned int header_len)
Adam Langley49a72df2008-07-19 00:01:42 -07003050{
3051 struct scatterlist sg;
3052 const struct tcphdr *tp = tcp_hdr(skb);
3053 struct hash_desc *desc = &hp->md5_desc;
3054 unsigned i;
3055 const unsigned head_data_len = skb_headlen(skb) > header_len ?
3056 skb_headlen(skb) - header_len : 0;
3057 const struct skb_shared_info *shi = skb_shinfo(skb);
Eric Dumazetd7fd1b572010-05-17 20:40:51 +00003058 struct sk_buff *frag_iter;
Adam Langley49a72df2008-07-19 00:01:42 -07003059
3060 sg_init_table(&sg, 1);
3061
3062 sg_set_buf(&sg, ((u8 *) tp) + header_len, head_data_len);
3063 if (crypto_hash_update(desc, &sg, head_data_len))
3064 return 1;
3065
3066 for (i = 0; i < shi->nr_frags; ++i) {
3067 const struct skb_frag_struct *f = &shi->frags[i];
Ian Campbellaff65da2011-08-22 23:44:59 +00003068 struct page *page = skb_frag_page(f);
Eric Dumazet9e903e02011-10-18 21:00:24 +00003069 sg_set_page(&sg, page, skb_frag_size(f), f->page_offset);
3070 if (crypto_hash_update(desc, &sg, skb_frag_size(f)))
Adam Langley49a72df2008-07-19 00:01:42 -07003071 return 1;
3072 }
3073
Eric Dumazetd7fd1b572010-05-17 20:40:51 +00003074 skb_walk_frags(skb, frag_iter)
3075 if (tcp_md5_hash_skb_data(hp, frag_iter, 0))
3076 return 1;
3077
Adam Langley49a72df2008-07-19 00:01:42 -07003078 return 0;
3079}
Adam Langley49a72df2008-07-19 00:01:42 -07003080EXPORT_SYMBOL(tcp_md5_hash_skb_data);
3081
Eric Dumazetcf533ea2011-10-21 05:22:42 -04003082int tcp_md5_hash_key(struct tcp_md5sig_pool *hp, const struct tcp_md5sig_key *key)
Adam Langley49a72df2008-07-19 00:01:42 -07003083{
3084 struct scatterlist sg;
3085
3086 sg_init_one(&sg, key->key, key->keylen);
3087 return crypto_hash_update(&hp->md5_desc, &sg, key->keylen);
3088}
Adam Langley49a72df2008-07-19 00:01:42 -07003089EXPORT_SYMBOL(tcp_md5_hash_key);
3090
YOSHIFUJI Hideakicfb6eeb2006-11-14 19:07:45 -08003091#endif
3092
William Allen Simpsonda5c78c2009-12-02 18:12:09 +00003093/**
3094 * Each Responder maintains up to two secret values concurrently for
3095 * efficient secret rollover. Each secret value has 4 states:
3096 *
3097 * Generating. (tcp_secret_generating != tcp_secret_primary)
3098 * Generates new Responder-Cookies, but not yet used for primary
3099 * verification. This is a short-term state, typically lasting only
3100 * one round trip time (RTT).
3101 *
3102 * Primary. (tcp_secret_generating == tcp_secret_primary)
3103 * Used both for generation and primary verification.
3104 *
3105 * Retiring. (tcp_secret_retiring != tcp_secret_secondary)
3106 * Used for verification, until the first failure that can be
3107 * verified by the newer Generating secret. At that time, this
3108 * cookie's state is changed to Secondary, and the Generating
3109 * cookie's state is changed to Primary. This is a short-term state,
3110 * typically lasting only one round trip time (RTT).
3111 *
3112 * Secondary. (tcp_secret_retiring == tcp_secret_secondary)
3113 * Used for secondary verification, after primary verification
3114 * failures. This state lasts no more than twice the Maximum Segment
3115 * Lifetime (2MSL). Then, the secret is discarded.
3116 */
3117struct tcp_cookie_secret {
3118 /* The secret is divided into two parts. The digest part is the
3119 * equivalent of previously hashing a secret and saving the state,
3120 * and serves as an initialization vector (IV). The message part
3121 * serves as the trailing secret.
3122 */
3123 u32 secrets[COOKIE_WORKSPACE_WORDS];
3124 unsigned long expires;
3125};
3126
3127#define TCP_SECRET_1MSL (HZ * TCP_PAWS_MSL)
3128#define TCP_SECRET_2MSL (HZ * TCP_PAWS_MSL * 2)
3129#define TCP_SECRET_LIFE (HZ * 600)
3130
3131static struct tcp_cookie_secret tcp_secret_one;
3132static struct tcp_cookie_secret tcp_secret_two;
3133
3134/* Essentially a circular list, without dynamic allocation. */
3135static struct tcp_cookie_secret *tcp_secret_generating;
3136static struct tcp_cookie_secret *tcp_secret_primary;
3137static struct tcp_cookie_secret *tcp_secret_retiring;
3138static struct tcp_cookie_secret *tcp_secret_secondary;
3139
3140static DEFINE_SPINLOCK(tcp_secret_locker);
3141
3142/* Select a pseudo-random word in the cookie workspace.
3143 */
3144static inline u32 tcp_cookie_work(const u32 *ws, const int n)
3145{
3146 return ws[COOKIE_DIGEST_WORDS + ((COOKIE_MESSAGE_WORDS-1) & ws[n])];
3147}
3148
3149/* Fill bakery[COOKIE_WORKSPACE_WORDS] with generator, updating as needed.
3150 * Called in softirq context.
3151 * Returns: 0 for success.
3152 */
3153int tcp_cookie_generator(u32 *bakery)
3154{
3155 unsigned long jiffy = jiffies;
3156
3157 if (unlikely(time_after_eq(jiffy, tcp_secret_generating->expires))) {
3158 spin_lock_bh(&tcp_secret_locker);
3159 if (!time_after_eq(jiffy, tcp_secret_generating->expires)) {
3160 /* refreshed by another */
3161 memcpy(bakery,
3162 &tcp_secret_generating->secrets[0],
3163 COOKIE_WORKSPACE_WORDS);
3164 } else {
3165 /* still needs refreshing */
3166 get_random_bytes(bakery, COOKIE_WORKSPACE_WORDS);
3167
3168 /* The first time, paranoia assumes that the
3169 * randomization function isn't as strong. But,
3170 * this secret initialization is delayed until
3171 * the last possible moment (packet arrival).
3172 * Although that time is observable, it is
3173 * unpredictably variable. Mash in the most
3174 * volatile clock bits available, and expire the
3175 * secret extra quickly.
3176 */
3177 if (unlikely(tcp_secret_primary->expires ==
3178 tcp_secret_secondary->expires)) {
3179 struct timespec tv;
3180
3181 getnstimeofday(&tv);
3182 bakery[COOKIE_DIGEST_WORDS+0] ^=
3183 (u32)tv.tv_nsec;
3184
3185 tcp_secret_secondary->expires = jiffy
3186 + TCP_SECRET_1MSL
3187 + (0x0f & tcp_cookie_work(bakery, 0));
3188 } else {
3189 tcp_secret_secondary->expires = jiffy
3190 + TCP_SECRET_LIFE
3191 + (0xff & tcp_cookie_work(bakery, 1));
3192 tcp_secret_primary->expires = jiffy
3193 + TCP_SECRET_2MSL
3194 + (0x1f & tcp_cookie_work(bakery, 2));
3195 }
3196 memcpy(&tcp_secret_secondary->secrets[0],
3197 bakery, COOKIE_WORKSPACE_WORDS);
3198
3199 rcu_assign_pointer(tcp_secret_generating,
3200 tcp_secret_secondary);
3201 rcu_assign_pointer(tcp_secret_retiring,
3202 tcp_secret_primary);
3203 /*
3204 * Neither call_rcu() nor synchronize_rcu() needed.
3205 * Retiring data is not freed. It is replaced after
3206 * further (locked) pointer updates, and a quiet time
3207 * (minimum 1MSL, maximum LIFE - 2MSL).
3208 */
3209 }
3210 spin_unlock_bh(&tcp_secret_locker);
3211 } else {
3212 rcu_read_lock_bh();
3213 memcpy(bakery,
3214 &rcu_dereference(tcp_secret_generating)->secrets[0],
3215 COOKIE_WORKSPACE_WORDS);
3216 rcu_read_unlock_bh();
3217 }
3218 return 0;
3219}
3220EXPORT_SYMBOL(tcp_cookie_generator);
3221
Andi Kleen4ac02ba2007-04-20 17:11:46 -07003222void tcp_done(struct sock *sk)
3223{
Jianjun Kong5a5f3a82008-11-03 00:24:34 -08003224 if (sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV)
Pavel Emelyanov63231bd2008-07-16 20:22:25 -07003225 TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_ATTEMPTFAILS);
Andi Kleen4ac02ba2007-04-20 17:11:46 -07003226
3227 tcp_set_state(sk, TCP_CLOSE);
3228 tcp_clear_xmit_timers(sk);
3229
3230 sk->sk_shutdown = SHUTDOWN_MASK;
3231
3232 if (!sock_flag(sk, SOCK_DEAD))
3233 sk->sk_state_change(sk);
3234 else
3235 inet_csk_destroy_sock(sk);
3236}
3237EXPORT_SYMBOL_GPL(tcp_done);
3238
Stephen Hemminger5f8ef482005-06-23 20:37:36 -07003239extern struct tcp_congestion_ops tcp_reno;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003240
3241static __initdata unsigned long thash_entries;
3242static int __init set_thash_entries(char *str)
3243{
3244 if (!str)
3245 return 0;
3246 thash_entries = simple_strtoul(str, &str, 0);
3247 return 1;
3248}
3249__setup("thash_entries=", set_thash_entries);
3250
Glauber Costa4acb4192012-01-30 01:20:17 +00003251void tcp_init_mem(struct net *net)
3252{
Glauber Costa4acb4192012-01-30 01:20:17 +00003253 unsigned long limit = nr_free_buffer_pages() / 8;
3254 limit = max(limit, 128UL);
3255 net->ipv4.sysctl_tcp_mem[0] = limit / 4 * 3;
3256 net->ipv4.sysctl_tcp_mem[1] = limit;
3257 net->ipv4.sysctl_tcp_mem[2] = net->ipv4.sysctl_tcp_mem[0] * 2;
3258}
3259
Linus Torvalds1da177e2005-04-16 15:20:36 -07003260void __init tcp_init(void)
3261{
3262 struct sk_buff *skb = NULL;
Eric Dumazetf03d78d2011-07-07 00:27:05 -07003263 unsigned long limit;
Eric Dumazetb49960a2012-05-02 02:28:41 +00003264 int max_rshare, max_wshare, cnt;
Dimitri Sivanich074b8512012-02-08 12:39:07 -08003265 unsigned int i;
William Allen Simpsonda5c78c2009-12-02 18:12:09 +00003266 unsigned long jiffy = jiffies;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003267
Pavel Emelyanov1f9e6362007-12-11 02:12:04 -08003268 BUILD_BUG_ON(sizeof(struct tcp_skb_cb) > sizeof(skb->cb));
Linus Torvalds1da177e2005-04-16 15:20:36 -07003269
Eric Dumazet17483762008-11-25 21:16:35 -08003270 percpu_counter_init(&tcp_sockets_allocated, 0);
Eric Dumazetdd24c002008-11-25 21:17:14 -08003271 percpu_counter_init(&tcp_orphan_count, 0);
Arnaldo Carvalho de Melo6e04e022005-08-09 20:07:35 -07003272 tcp_hashinfo.bind_bucket_cachep =
3273 kmem_cache_create("tcp_bind_bucket",
3274 sizeof(struct inet_bind_bucket), 0,
Paul Mundt20c2df82007-07-20 10:11:58 +09003275 SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003276
Linus Torvalds1da177e2005-04-16 15:20:36 -07003277 /* Size and allocate the main established and bind bucket
3278 * hash tables.
3279 *
3280 * The methodology is similar to that of the buffer cache.
3281 */
Arnaldo Carvalho de Melo6e04e022005-08-09 20:07:35 -07003282 tcp_hashinfo.ehash =
Linus Torvalds1da177e2005-04-16 15:20:36 -07003283 alloc_large_system_hash("TCP established",
Arnaldo Carvalho de Melo0f7ff922005-08-09 19:59:44 -07003284 sizeof(struct inet_ehash_bucket),
Linus Torvalds1da177e2005-04-16 15:20:36 -07003285 thash_entries,
Jan Beulich44813742009-09-21 17:03:05 -07003286 (totalram_pages >= 128 * 1024) ?
Mike Stroyan18955cf2005-11-29 16:12:55 -08003287 13 : 15,
John Heffner9e950ef2006-11-06 23:10:51 -08003288 0,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003289 NULL,
Eric Dumazetf373b532009-10-09 00:16:19 +00003290 &tcp_hashinfo.ehash_mask,
Jean Delvare0ccfe612007-10-30 00:59:25 -07003291 thash_entries ? 0 : 512 * 1024);
Eric Dumazetf373b532009-10-09 00:16:19 +00003292 for (i = 0; i <= tcp_hashinfo.ehash_mask; i++) {
Eric Dumazet3ab5aee2008-11-16 19:40:17 -08003293 INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i);
3294 INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].twchain, i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003295 }
Eric Dumazet230140c2007-11-07 02:40:20 -08003296 if (inet_ehash_locks_alloc(&tcp_hashinfo))
3297 panic("TCP: failed to alloc ehash_locks");
Arnaldo Carvalho de Melo6e04e022005-08-09 20:07:35 -07003298 tcp_hashinfo.bhash =
Linus Torvalds1da177e2005-04-16 15:20:36 -07003299 alloc_large_system_hash("TCP bind",
Arnaldo Carvalho de Melo0f7ff922005-08-09 19:59:44 -07003300 sizeof(struct inet_bind_hashbucket),
Eric Dumazetf373b532009-10-09 00:16:19 +00003301 tcp_hashinfo.ehash_mask + 1,
Jan Beulich44813742009-09-21 17:03:05 -07003302 (totalram_pages >= 128 * 1024) ?
Mike Stroyan18955cf2005-11-29 16:12:55 -08003303 13 : 15,
John Heffner9e950ef2006-11-06 23:10:51 -08003304 0,
Arnaldo Carvalho de Melo6e04e022005-08-09 20:07:35 -07003305 &tcp_hashinfo.bhash_size,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003306 NULL,
3307 64 * 1024);
Dimitri Sivanich074b8512012-02-08 12:39:07 -08003308 tcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size;
Arnaldo Carvalho de Melo6e04e022005-08-09 20:07:35 -07003309 for (i = 0; i < tcp_hashinfo.bhash_size; i++) {
3310 spin_lock_init(&tcp_hashinfo.bhash[i].lock);
3311 INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003312 }
3313
Eric Dumazetc5ed63d2010-08-25 23:02:17 -07003314
3315 cnt = tcp_hashinfo.ehash_mask + 1;
3316
3317 tcp_death_row.sysctl_max_tw_buckets = cnt / 2;
3318 sysctl_tcp_max_orphans = cnt / 2;
3319 sysctl_max_syn_backlog = max(128, cnt / 256);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003320
Glauber Costa4acb4192012-01-30 01:20:17 +00003321 tcp_init_mem(&init_net);
Jason Wangc43b8742012-02-02 00:07:00 +00003322 /* Set per-socket limits to no more than 1/128 the pressure threshold */
Eric Dumazet5fb84b12012-04-10 00:56:42 +00003323 limit = nr_free_buffer_pages() << (PAGE_SHIFT - 7);
Eric Dumazetb49960a2012-05-02 02:28:41 +00003324 max_wshare = min(4UL*1024*1024, limit);
3325 max_rshare = min(6UL*1024*1024, limit);
John Heffner7b4f4b52006-03-25 01:34:07 -08003326
Hideo Aoki3ab224b2007-12-31 00:11:19 -08003327 sysctl_tcp_wmem[0] = SK_MEM_QUANTUM;
John Heffner7b4f4b52006-03-25 01:34:07 -08003328 sysctl_tcp_wmem[1] = 16*1024;
Eric Dumazetb49960a2012-05-02 02:28:41 +00003329 sysctl_tcp_wmem[2] = max(64*1024, max_wshare);
John Heffner7b4f4b52006-03-25 01:34:07 -08003330
Hideo Aoki3ab224b2007-12-31 00:11:19 -08003331 sysctl_tcp_rmem[0] = SK_MEM_QUANTUM;
John Heffner7b4f4b52006-03-25 01:34:07 -08003332 sysctl_tcp_rmem[1] = 87380;
Eric Dumazetb49960a2012-05-02 02:28:41 +00003333 sysctl_tcp_rmem[2] = max(87380, max_rshare);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003334
Joe Perchesafd465032012-03-12 07:03:32 +00003335 pr_info("Hash tables configured (established %u bind %u)\n",
Joe Perches058bd4d2012-03-11 18:36:11 +00003336 tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size);
Stephen Hemminger317a76f2005-06-23 12:19:55 -07003337
3338 tcp_register_congestion_control(&tcp_reno);
William Allen Simpsonda5c78c2009-12-02 18:12:09 +00003339
3340 memset(&tcp_secret_one.secrets[0], 0, sizeof(tcp_secret_one.secrets));
3341 memset(&tcp_secret_two.secrets[0], 0, sizeof(tcp_secret_two.secrets));
3342 tcp_secret_one.expires = jiffy; /* past due */
3343 tcp_secret_two.expires = jiffy; /* past due */
3344 tcp_secret_generating = &tcp_secret_one;
3345 tcp_secret_primary = &tcp_secret_one;
3346 tcp_secret_retiring = &tcp_secret_two;
3347 tcp_secret_secondary = &tcp_secret_two;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003348}
Robert Love2365d052008-05-12 17:08:29 -04003349
3350static int tcp_is_local(struct net *net, __be32 addr) {
3351 struct rtable *rt;
3352 struct flowi4 fl4 = { .daddr = addr };
3353 rt = ip_route_output_key(net, &fl4);
3354 if (IS_ERR_OR_NULL(rt))
3355 return 0;
3356 return rt->dst.dev && (rt->dst.dev->flags & IFF_LOOPBACK);
3357}
3358
3359#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3360static int tcp_is_local6(struct net *net, struct in6_addr *addr) {
3361 struct rt6_info *rt6 = rt6_lookup(net, addr, addr, 0, 0);
3362 return rt6 && rt6->dst.dev && (rt6->dst.dev->flags & IFF_LOOPBACK);
3363}
3364#endif
3365
3366/*
3367 * tcp_nuke_addr - destroy all sockets on the given local address
3368 * if local address is the unspecified address (0.0.0.0 or ::), destroy all
3369 * sockets with local addresses that are not configured.
3370 */
3371int tcp_nuke_addr(struct net *net, struct sockaddr *addr)
3372{
3373 int family = addr->sa_family;
3374 unsigned int bucket;
3375
Bryan Huntsman3f2bc4d2011-08-16 17:27:22 -07003376 struct in_addr *in = NULL;
Robert Love2365d052008-05-12 17:08:29 -04003377#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
Bryan Huntsman3f2bc4d2011-08-16 17:27:22 -07003378 struct in6_addr *in6 = NULL;
Robert Love2365d052008-05-12 17:08:29 -04003379#endif
3380 if (family == AF_INET) {
3381 in = &((struct sockaddr_in *)addr)->sin_addr;
3382#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3383 } else if (family == AF_INET6) {
3384 in6 = &((struct sockaddr_in6 *)addr)->sin6_addr;
3385#endif
3386 } else {
3387 return -EAFNOSUPPORT;
3388 }
3389
3390 for (bucket = 0; bucket < tcp_hashinfo.ehash_mask; bucket++) {
3391 struct hlist_nulls_node *node;
3392 struct sock *sk;
3393 spinlock_t *lock = inet_ehash_lockp(&tcp_hashinfo, bucket);
3394
3395restart:
3396 spin_lock_bh(lock);
3397 sk_nulls_for_each(sk, node, &tcp_hashinfo.ehash[bucket].chain) {
3398 struct inet_sock *inet = inet_sk(sk);
3399
3400 if (sysctl_ip_dynaddr && sk->sk_state == TCP_SYN_SENT)
3401 continue;
3402 if (sock_flag(sk, SOCK_DEAD))
3403 continue;
3404
3405 if (family == AF_INET) {
3406 __be32 s4 = inet->inet_rcv_saddr;
3407 if (s4 == LOOPBACK4_IPV6)
3408 continue;
3409
3410 if (in->s_addr != s4 &&
3411 !(in->s_addr == INADDR_ANY &&
3412 !tcp_is_local(net, s4)))
3413 continue;
3414 }
3415
3416#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3417 if (family == AF_INET6) {
3418 struct in6_addr *s6;
3419 if (!inet->pinet6)
3420 continue;
3421
3422 s6 = &inet->pinet6->rcv_saddr;
3423 if (ipv6_addr_type(s6) == IPV6_ADDR_MAPPED)
3424 continue;
3425
3426 if (!ipv6_addr_equal(in6, s6) &&
3427 !(ipv6_addr_equal(in6, &in6addr_any) &&
3428 !tcp_is_local6(net, s6)))
3429 continue;
3430 }
3431#endif
3432
3433 sock_hold(sk);
3434 spin_unlock_bh(lock);
3435
3436 local_bh_disable();
3437 bh_lock_sock(sk);
3438 sk->sk_err = ETIMEDOUT;
3439 sk->sk_error_report(sk);
3440
3441 tcp_done(sk);
3442 bh_unlock_sock(sk);
3443 local_bh_enable();
3444 sock_put(sk);
3445
3446 goto restart;
3447 }
3448 spin_unlock_bh(lock);
3449 }
3450
3451 return 0;
3452}