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