PageRenderTime 70ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/net/ipv4/tcp.c

https://bitbucket.org/zarboz/ville-upstream-test-branch
C | 3316 lines | 2181 code | 457 blank | 678 comment | 513 complexity | 8f6a72668fa49c2983477163c730c075 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.0, AGPL-1.0

Large files files are truncated, but you can click here to view the full file

  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. #include <linux/kernel.h>
  248. #include <linux/module.h>
  249. #include <linux/types.h>
  250. #include <linux/fcntl.h>
  251. #include <linux/poll.h>
  252. #include <linux/init.h>
  253. #include <linux/fs.h>
  254. #include <linux/skbuff.h>
  255. #include <linux/scatterlist.h>
  256. #include <linux/splice.h>
  257. #include <linux/net.h>
  258. #include <linux/socket.h>
  259. #include <linux/random.h>
  260. #include <linux/bootmem.h>
  261. #include <linux/highmem.h>
  262. #include <linux/swap.h>
  263. #include <linux/cache.h>
  264. #include <linux/err.h>
  265. #include <linux/crypto.h>
  266. #include <linux/time.h>
  267. #include <linux/slab.h>
  268. #include <net/icmp.h>
  269. #include <net/tcp.h>
  270. #include <net/xfrm.h>
  271. #include <net/ip.h>
  272. #include <net/netdma.h>
  273. #include <net/sock.h>
  274. #include <asm/uaccess.h>
  275. #include <asm/ioctls.h>
  276. int sysctl_tcp_fin_timeout __read_mostly = TCP_FIN_TIMEOUT;
  277. struct percpu_counter tcp_orphan_count;
  278. EXPORT_SYMBOL_GPL(tcp_orphan_count);
  279. long sysctl_tcp_mem[3] __read_mostly;
  280. int sysctl_tcp_wmem[3] __read_mostly;
  281. int sysctl_tcp_rmem[3] __read_mostly;
  282. EXPORT_SYMBOL(sysctl_tcp_mem);
  283. EXPORT_SYMBOL(sysctl_tcp_rmem);
  284. EXPORT_SYMBOL(sysctl_tcp_wmem);
  285. atomic_long_t tcp_memory_allocated; /* Current allocated memory. */
  286. EXPORT_SYMBOL(tcp_memory_allocated);
  287. /*
  288. * Current number of TCP sockets.
  289. */
  290. struct percpu_counter tcp_sockets_allocated;
  291. EXPORT_SYMBOL(tcp_sockets_allocated);
  292. /*
  293. * TCP splice context
  294. */
  295. struct tcp_splice_state {
  296. struct pipe_inode_info *pipe;
  297. size_t len;
  298. unsigned int flags;
  299. };
  300. /*
  301. * Pressure flag: try to collapse.
  302. * Technical note: it is used by multiple contexts non atomically.
  303. * All the __sk_mem_schedule() is of this nature: accounting
  304. * is strict, actions are advisory and have some latency.
  305. */
  306. int tcp_memory_pressure __read_mostly;
  307. EXPORT_SYMBOL(tcp_memory_pressure);
  308. void tcp_enter_memory_pressure(struct sock *sk)
  309. {
  310. if (!tcp_memory_pressure) {
  311. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURES);
  312. tcp_memory_pressure = 1;
  313. }
  314. }
  315. EXPORT_SYMBOL(tcp_enter_memory_pressure);
  316. /* Convert seconds to retransmits based on initial and max timeout */
  317. static u8 secs_to_retrans(int seconds, int timeout, int rto_max)
  318. {
  319. u8 res = 0;
  320. if (seconds > 0) {
  321. int period = timeout;
  322. res = 1;
  323. while (seconds > period && res < 255) {
  324. res++;
  325. timeout <<= 1;
  326. if (timeout > rto_max)
  327. timeout = rto_max;
  328. period += timeout;
  329. }
  330. }
  331. return res;
  332. }
  333. /* Convert retransmits to seconds based on initial and max timeout */
  334. static int retrans_to_secs(u8 retrans, int timeout, int rto_max)
  335. {
  336. int period = 0;
  337. if (retrans > 0) {
  338. period = timeout;
  339. while (--retrans) {
  340. timeout <<= 1;
  341. if (timeout > rto_max)
  342. timeout = rto_max;
  343. period += timeout;
  344. }
  345. }
  346. return period;
  347. }
  348. /*
  349. * Wait for a TCP event.
  350. *
  351. * Note that we don't need to lock the socket, as the upper poll layers
  352. * take care of normal races (between the test and the event) and we don't
  353. * go look at any of the socket buffers directly.
  354. */
  355. unsigned int tcp_poll(struct file *file, struct socket *sock, poll_table *wait)
  356. {
  357. unsigned int mask;
  358. struct sock *sk = sock->sk;
  359. const struct tcp_sock *tp = tcp_sk(sk);
  360. sock_poll_wait(file, sk_sleep(sk), wait);
  361. if (sk->sk_state == TCP_LISTEN)
  362. return inet_csk_listen_poll(sk);
  363. /* Socket is not locked. We are protected from async events
  364. * by poll logic and correct handling of state changes
  365. * made by other threads is impossible in any case.
  366. */
  367. mask = 0;
  368. /*
  369. * POLLHUP is certainly not done right. But poll() doesn't
  370. * have a notion of HUP in just one direction, and for a
  371. * socket the read side is more interesting.
  372. *
  373. * Some poll() documentation says that POLLHUP is incompatible
  374. * with the POLLOUT/POLLWR flags, so somebody should check this
  375. * all. But careful, it tends to be safer to return too many
  376. * bits than too few, and you can easily break real applications
  377. * if you don't tell them that something has hung up!
  378. *
  379. * Check-me.
  380. *
  381. * Check number 1. POLLHUP is _UNMASKABLE_ event (see UNIX98 and
  382. * our fs/select.c). It means that after we received EOF,
  383. * poll always returns immediately, making impossible poll() on write()
  384. * in state CLOSE_WAIT. One solution is evident --- to set POLLHUP
  385. * if and only if shutdown has been made in both directions.
  386. * Actually, it is interesting to look how Solaris and DUX
  387. * solve this dilemma. I would prefer, if POLLHUP were maskable,
  388. * then we could set it on SND_SHUTDOWN. BTW examples given
  389. * in Stevens' books assume exactly this behaviour, it explains
  390. * why POLLHUP is incompatible with POLLOUT. --ANK
  391. *
  392. * NOTE. Check for TCP_CLOSE is added. The goal is to prevent
  393. * blocking on fresh not-connected or disconnected socket. --ANK
  394. */
  395. if (sk->sk_shutdown == SHUTDOWN_MASK || sk->sk_state == TCP_CLOSE)
  396. mask |= POLLHUP;
  397. if (sk->sk_shutdown & RCV_SHUTDOWN)
  398. mask |= POLLIN | POLLRDNORM | POLLRDHUP;
  399. /* Connected? */
  400. if ((1 << sk->sk_state) & ~(TCPF_SYN_SENT | TCPF_SYN_RECV)) {
  401. int target = sock_rcvlowat(sk, 0, INT_MAX);
  402. if (tp->urg_seq == tp->copied_seq &&
  403. !sock_flag(sk, SOCK_URGINLINE) &&
  404. tp->urg_data)
  405. target++;
  406. /* Potential race condition. If read of tp below will
  407. * escape above sk->sk_state, we can be illegally awaken
  408. * in SYN_* states. */
  409. if (tp->rcv_nxt - tp->copied_seq >= target)
  410. mask |= POLLIN | POLLRDNORM;
  411. if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
  412. if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk)) {
  413. mask |= POLLOUT | POLLWRNORM;
  414. } else { /* send SIGIO later */
  415. set_bit(SOCK_ASYNC_NOSPACE,
  416. &sk->sk_socket->flags);
  417. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  418. /* Race breaker. If space is freed after
  419. * wspace test but before the flags are set,
  420. * IO signal will be lost.
  421. */
  422. if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk))
  423. mask |= POLLOUT | POLLWRNORM;
  424. }
  425. } else
  426. mask |= POLLOUT | POLLWRNORM;
  427. if (tp->urg_data & TCP_URG_VALID)
  428. mask |= POLLPRI;
  429. }
  430. /* This barrier is coupled with smp_wmb() in tcp_reset() */
  431. smp_rmb();
  432. if (sk->sk_err)
  433. mask |= POLLERR;
  434. return mask;
  435. }
  436. EXPORT_SYMBOL(tcp_poll);
  437. int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg)
  438. {
  439. struct tcp_sock *tp = tcp_sk(sk);
  440. int answ;
  441. switch (cmd) {
  442. case SIOCINQ:
  443. if (sk->sk_state == TCP_LISTEN)
  444. return -EINVAL;
  445. lock_sock(sk);
  446. if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
  447. answ = 0;
  448. else if (sock_flag(sk, SOCK_URGINLINE) ||
  449. !tp->urg_data ||
  450. before(tp->urg_seq, tp->copied_seq) ||
  451. !before(tp->urg_seq, tp->rcv_nxt)) {
  452. answ = tp->rcv_nxt - tp->copied_seq;
  453. /* Subtract 1, if FIN was received */
  454. if (answ && sock_flag(sk, SOCK_DONE))
  455. answ--;
  456. } else
  457. answ = tp->urg_seq - tp->copied_seq;
  458. release_sock(sk);
  459. break;
  460. case SIOCATMARK:
  461. answ = tp->urg_data && tp->urg_seq == tp->copied_seq;
  462. break;
  463. case SIOCOUTQ:
  464. if (sk->sk_state == TCP_LISTEN)
  465. return -EINVAL;
  466. if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
  467. answ = 0;
  468. else
  469. answ = tp->write_seq - tp->snd_una;
  470. break;
  471. case SIOCOUTQNSD:
  472. if (sk->sk_state == TCP_LISTEN)
  473. return -EINVAL;
  474. if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
  475. answ = 0;
  476. else
  477. answ = tp->write_seq - tp->snd_nxt;
  478. break;
  479. default:
  480. return -ENOIOCTLCMD;
  481. }
  482. return put_user(answ, (int __user *)arg);
  483. }
  484. EXPORT_SYMBOL(tcp_ioctl);
  485. static inline void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb)
  486. {
  487. TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH;
  488. tp->pushed_seq = tp->write_seq;
  489. }
  490. static inline int forced_push(const struct tcp_sock *tp)
  491. {
  492. return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1));
  493. }
  494. static inline void skb_entail(struct sock *sk, struct sk_buff *skb)
  495. {
  496. struct tcp_sock *tp = tcp_sk(sk);
  497. struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
  498. skb->csum = 0;
  499. tcb->seq = tcb->end_seq = tp->write_seq;
  500. tcb->tcp_flags = TCPHDR_ACK;
  501. tcb->sacked = 0;
  502. skb_header_release(skb);
  503. tcp_add_write_queue_tail(sk, skb);
  504. sk->sk_wmem_queued += skb->truesize;
  505. sk_mem_charge(sk, skb->truesize);
  506. if (tp->nonagle & TCP_NAGLE_PUSH)
  507. tp->nonagle &= ~TCP_NAGLE_PUSH;
  508. }
  509. static inline void tcp_mark_urg(struct tcp_sock *tp, int flags)
  510. {
  511. if (flags & MSG_OOB)
  512. tp->snd_up = tp->write_seq;
  513. }
  514. static inline void tcp_push(struct sock *sk, int flags, int mss_now,
  515. int nonagle)
  516. {
  517. if (tcp_send_head(sk)) {
  518. struct tcp_sock *tp = tcp_sk(sk);
  519. if (!(flags & MSG_MORE) || forced_push(tp))
  520. tcp_mark_push(tp, tcp_write_queue_tail(sk));
  521. tcp_mark_urg(tp, flags);
  522. __tcp_push_pending_frames(sk, mss_now,
  523. (flags & MSG_MORE) ? TCP_NAGLE_CORK : nonagle);
  524. }
  525. }
  526. static int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
  527. unsigned int offset, size_t len)
  528. {
  529. struct tcp_splice_state *tss = rd_desc->arg.data;
  530. int ret;
  531. ret = skb_splice_bits(skb, offset, tss->pipe, min(rd_desc->count, len),
  532. tss->flags);
  533. if (ret > 0)
  534. rd_desc->count -= ret;
  535. return ret;
  536. }
  537. static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss)
  538. {
  539. /* Store TCP splice context information in read_descriptor_t. */
  540. read_descriptor_t rd_desc = {
  541. .arg.data = tss,
  542. .count = tss->len,
  543. };
  544. return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv);
  545. }
  546. /**
  547. * tcp_splice_read - splice data from TCP socket to a pipe
  548. * @sock: socket to splice from
  549. * @ppos: position (not valid)
  550. * @pipe: pipe to splice to
  551. * @len: number of bytes to splice
  552. * @flags: splice modifier flags
  553. *
  554. * Description:
  555. * Will read pages from given socket and fill them into a pipe.
  556. *
  557. **/
  558. ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
  559. struct pipe_inode_info *pipe, size_t len,
  560. unsigned int flags)
  561. {
  562. struct sock *sk = sock->sk;
  563. struct tcp_splice_state tss = {
  564. .pipe = pipe,
  565. .len = len,
  566. .flags = flags,
  567. };
  568. long timeo;
  569. ssize_t spliced;
  570. int ret;
  571. sock_rps_record_flow(sk);
  572. /*
  573. * We can't seek on a socket input
  574. */
  575. if (unlikely(*ppos))
  576. return -ESPIPE;
  577. ret = spliced = 0;
  578. lock_sock(sk);
  579. timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK);
  580. while (tss.len) {
  581. ret = __tcp_splice_read(sk, &tss);
  582. if (ret < 0)
  583. break;
  584. else if (!ret) {
  585. if (spliced)
  586. break;
  587. if (sock_flag(sk, SOCK_DONE))
  588. break;
  589. if (sk->sk_err) {
  590. ret = sock_error(sk);
  591. break;
  592. }
  593. if (sk->sk_shutdown & RCV_SHUTDOWN)
  594. break;
  595. if (sk->sk_state == TCP_CLOSE) {
  596. /*
  597. * This occurs when user tries to read
  598. * from never connected socket.
  599. */
  600. if (!sock_flag(sk, SOCK_DONE))
  601. ret = -ENOTCONN;
  602. break;
  603. }
  604. if (!timeo) {
  605. ret = -EAGAIN;
  606. break;
  607. }
  608. sk_wait_data(sk, &timeo);
  609. if (signal_pending(current)) {
  610. ret = sock_intr_errno(timeo);
  611. break;
  612. }
  613. continue;
  614. }
  615. tss.len -= ret;
  616. spliced += ret;
  617. if (!timeo)
  618. break;
  619. release_sock(sk);
  620. lock_sock(sk);
  621. if (sk->sk_err || sk->sk_state == TCP_CLOSE ||
  622. (sk->sk_shutdown & RCV_SHUTDOWN) ||
  623. signal_pending(current))
  624. break;
  625. }
  626. release_sock(sk);
  627. if (spliced)
  628. return spliced;
  629. return ret;
  630. }
  631. EXPORT_SYMBOL(tcp_splice_read);
  632. struct sk_buff *sk_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp)
  633. {
  634. struct sk_buff *skb;
  635. /* The TCP header must be at least 32-bit aligned. */
  636. size = ALIGN(size, 4);
  637. skb = alloc_skb_fclone(size + sk->sk_prot->max_header, gfp);
  638. if (skb) {
  639. if (sk_wmem_schedule(sk, skb->truesize)) {
  640. skb_reserve(skb, sk->sk_prot->max_header);
  641. /*
  642. * Make sure that we have exactly size bytes
  643. * available to the caller, no more, no less.
  644. */
  645. skb->avail_size = size;
  646. return skb;
  647. }
  648. __kfree_skb(skb);
  649. } else {
  650. sk->sk_prot->enter_memory_pressure(sk);
  651. sk_stream_moderate_sndbuf(sk);
  652. }
  653. return NULL;
  654. }
  655. static unsigned int tcp_xmit_size_goal(struct sock *sk, u32 mss_now,
  656. int large_allowed)
  657. {
  658. struct tcp_sock *tp = tcp_sk(sk);
  659. u32 xmit_size_goal, old_size_goal;
  660. xmit_size_goal = mss_now;
  661. if (large_allowed && sk_can_gso(sk)) {
  662. xmit_size_goal = ((sk->sk_gso_max_size - 1) -
  663. inet_csk(sk)->icsk_af_ops->net_header_len -
  664. inet_csk(sk)->icsk_ext_hdr_len -
  665. tp->tcp_header_len);
  666. xmit_size_goal = tcp_bound_to_half_wnd(tp, xmit_size_goal);
  667. /* We try hard to avoid divides here */
  668. old_size_goal = tp->xmit_size_goal_segs * mss_now;
  669. if (likely(old_size_goal <= xmit_size_goal &&
  670. old_size_goal + mss_now > xmit_size_goal)) {
  671. xmit_size_goal = old_size_goal;
  672. } else {
  673. tp->xmit_size_goal_segs =
  674. min_t(u16, xmit_size_goal / mss_now,
  675. sk->sk_gso_max_segs);
  676. xmit_size_goal = tp->xmit_size_goal_segs * mss_now;
  677. }
  678. }
  679. return max(xmit_size_goal, mss_now);
  680. }
  681. static int tcp_send_mss(struct sock *sk, int *size_goal, int flags)
  682. {
  683. int mss_now;
  684. mss_now = tcp_current_mss(sk);
  685. *size_goal = tcp_xmit_size_goal(sk, mss_now, !(flags & MSG_OOB));
  686. return mss_now;
  687. }
  688. static ssize_t do_tcp_sendpages(struct sock *sk, struct page **pages, int poffset,
  689. size_t psize, int flags)
  690. {
  691. struct tcp_sock *tp = tcp_sk(sk);
  692. int mss_now, size_goal;
  693. int err;
  694. ssize_t copied;
  695. long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
  696. /* Wait for a connection to finish. */
  697. if ((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT))
  698. if ((err = sk_stream_wait_connect(sk, &timeo)) != 0)
  699. goto out_err;
  700. clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
  701. mss_now = tcp_send_mss(sk, &size_goal, flags);
  702. copied = 0;
  703. err = -EPIPE;
  704. if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
  705. goto out_err;
  706. while (psize > 0) {
  707. struct sk_buff *skb = tcp_write_queue_tail(sk);
  708. struct page *page = pages[poffset / PAGE_SIZE];
  709. int copy, i, can_coalesce;
  710. int offset = poffset % PAGE_SIZE;
  711. int size = min_t(size_t, psize, PAGE_SIZE - offset);
  712. if (!tcp_send_head(sk) || (copy = size_goal - skb->len) <= 0) {
  713. new_segment:
  714. if (!sk_stream_memory_free(sk))
  715. goto wait_for_sndbuf;
  716. skb = sk_stream_alloc_skb(sk, 0, sk->sk_allocation);
  717. if (!skb)
  718. goto wait_for_memory;
  719. skb_entail(sk, skb);
  720. copy = size_goal;
  721. }
  722. if (copy > size)
  723. copy = size;
  724. i = skb_shinfo(skb)->nr_frags;
  725. can_coalesce = skb_can_coalesce(skb, i, page, offset);
  726. if (!can_coalesce && i >= MAX_SKB_FRAGS) {
  727. tcp_mark_push(tp, skb);
  728. goto new_segment;
  729. }
  730. if (!sk_wmem_schedule(sk, copy))
  731. goto wait_for_memory;
  732. if (can_coalesce) {
  733. skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
  734. } else {
  735. get_page(page);
  736. skb_fill_page_desc(skb, i, page, offset, copy);
  737. }
  738. skb->len += copy;
  739. skb->data_len += copy;
  740. skb->truesize += copy;
  741. sk->sk_wmem_queued += copy;
  742. sk_mem_charge(sk, copy);
  743. skb->ip_summed = CHECKSUM_PARTIAL;
  744. tp->write_seq += copy;
  745. TCP_SKB_CB(skb)->end_seq += copy;
  746. skb_shinfo(skb)->gso_segs = 0;
  747. if (!copied)
  748. TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
  749. copied += copy;
  750. poffset += copy;
  751. if (!(psize -= copy))
  752. goto out;
  753. if (skb->len < size_goal || (flags & MSG_OOB))
  754. continue;
  755. if (forced_push(tp)) {
  756. tcp_mark_push(tp, skb);
  757. __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
  758. } else if (skb == tcp_send_head(sk))
  759. tcp_push_one(sk, mss_now);
  760. continue;
  761. wait_for_sndbuf:
  762. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  763. wait_for_memory:
  764. tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH);
  765. if ((err = sk_stream_wait_memory(sk, &timeo)) != 0)
  766. goto do_error;
  767. mss_now = tcp_send_mss(sk, &size_goal, flags);
  768. }
  769. out:
  770. if (copied && !(flags & MSG_SENDPAGE_NOTLAST))
  771. tcp_push(sk, flags, mss_now, tp->nonagle);
  772. return copied;
  773. do_error:
  774. if (copied)
  775. goto out;
  776. out_err:
  777. return sk_stream_error(sk, flags, err);
  778. }
  779. int tcp_sendpage(struct sock *sk, struct page *page, int offset,
  780. size_t size, int flags)
  781. {
  782. ssize_t res;
  783. if (!(sk->sk_route_caps & NETIF_F_SG) ||
  784. !(sk->sk_route_caps & NETIF_F_ALL_CSUM))
  785. return sock_no_sendpage(sk->sk_socket, page, offset, size,
  786. flags);
  787. lock_sock(sk);
  788. res = do_tcp_sendpages(sk, &page, offset, size, flags);
  789. release_sock(sk);
  790. return res;
  791. }
  792. EXPORT_SYMBOL(tcp_sendpage);
  793. #define TCP_PAGE(sk) (sk->sk_sndmsg_page)
  794. #define TCP_OFF(sk) (sk->sk_sndmsg_off)
  795. static inline int select_size(const struct sock *sk, int sg)
  796. {
  797. const struct tcp_sock *tp = tcp_sk(sk);
  798. int tmp = tp->mss_cache;
  799. if (sg) {
  800. if (sk_can_gso(sk))
  801. tmp = 0;
  802. else {
  803. int pgbreak = SKB_MAX_HEAD(MAX_TCP_HEADER);
  804. if (tmp >= pgbreak &&
  805. tmp <= pgbreak + (MAX_SKB_FRAGS - 1) * PAGE_SIZE)
  806. tmp = pgbreak;
  807. }
  808. }
  809. return tmp;
  810. }
  811. int tcp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
  812. size_t size)
  813. {
  814. struct iovec *iov;
  815. struct tcp_sock *tp = tcp_sk(sk);
  816. struct sk_buff *skb;
  817. int iovlen, flags;
  818. int mss_now, size_goal;
  819. int sg, err, copied;
  820. long timeo;
  821. lock_sock(sk);
  822. flags = msg->msg_flags;
  823. timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
  824. /* Wait for a connection to finish. */
  825. if ((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT))
  826. if ((err = sk_stream_wait_connect(sk, &timeo)) != 0)
  827. goto out_err;
  828. /* This should be in poll */
  829. clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
  830. mss_now = tcp_send_mss(sk, &size_goal, flags);
  831. /* Ok commence sending. */
  832. iovlen = msg->msg_iovlen;
  833. iov = msg->msg_iov;
  834. copied = 0;
  835. err = -EPIPE;
  836. if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
  837. goto out_err;
  838. sg = sk->sk_route_caps & NETIF_F_SG;
  839. while (--iovlen >= 0) {
  840. size_t seglen = iov->iov_len;
  841. unsigned char __user *from = iov->iov_base;
  842. iov++;
  843. while (seglen > 0) {
  844. int copy = 0;
  845. int max = size_goal;
  846. skb = tcp_write_queue_tail(sk);
  847. if (tcp_send_head(sk)) {
  848. if (skb->ip_summed == CHECKSUM_NONE)
  849. max = mss_now;
  850. copy = max - skb->len;
  851. }
  852. if (copy <= 0) {
  853. new_segment:
  854. /* Allocate new segment. If the interface is SG,
  855. * allocate skb fitting to single page.
  856. */
  857. if (!sk_stream_memory_free(sk))
  858. goto wait_for_sndbuf;
  859. skb = sk_stream_alloc_skb(sk,
  860. select_size(sk, sg),
  861. sk->sk_allocation);
  862. if (!skb)
  863. goto wait_for_memory;
  864. /*
  865. * Check whether we can use HW checksum.
  866. */
  867. if (sk->sk_route_caps & NETIF_F_ALL_CSUM)
  868. skb->ip_summed = CHECKSUM_PARTIAL;
  869. skb_entail(sk, skb);
  870. copy = size_goal;
  871. max = size_goal;
  872. }
  873. /* Try to append data to the end of skb. */
  874. if (copy > seglen)
  875. copy = seglen;
  876. /* Where to copy to? */
  877. if (skb_availroom(skb) > 0) {
  878. /* We have some space in skb head. Superb! */
  879. copy = min_t(int, copy, skb_availroom(skb));
  880. err = skb_add_data_nocache(sk, skb, from, copy);
  881. if (err)
  882. goto do_fault;
  883. } else {
  884. int merge = 0;
  885. int i = skb_shinfo(skb)->nr_frags;
  886. struct page *page = TCP_PAGE(sk);
  887. int off = TCP_OFF(sk);
  888. if (skb_can_coalesce(skb, i, page, off) &&
  889. off != PAGE_SIZE) {
  890. /* We can extend the last page
  891. * fragment. */
  892. merge = 1;
  893. } else if (i == MAX_SKB_FRAGS || !sg) {
  894. /* Need to add new fragment and cannot
  895. * do this because interface is non-SG,
  896. * or because all the page slots are
  897. * busy. */
  898. tcp_mark_push(tp, skb);
  899. goto new_segment;
  900. } else if (page) {
  901. if (off == PAGE_SIZE) {
  902. put_page(page);
  903. TCP_PAGE(sk) = page = NULL;
  904. off = 0;
  905. }
  906. } else
  907. off = 0;
  908. if (copy > PAGE_SIZE - off)
  909. copy = PAGE_SIZE - off;
  910. if (!sk_wmem_schedule(sk, copy))
  911. goto wait_for_memory;
  912. if (!page) {
  913. /* Allocate new cache page. */
  914. if (!(page = sk_stream_alloc_page(sk)))
  915. goto wait_for_memory;
  916. }
  917. /* Time to copy data. We are close to
  918. * the end! */
  919. err = skb_copy_to_page_nocache(sk, from, skb,
  920. page, off, copy);
  921. if (err) {
  922. /* If this page was new, give it to the
  923. * socket so it does not get leaked.
  924. */
  925. if (!TCP_PAGE(sk)) {
  926. TCP_PAGE(sk) = page;
  927. TCP_OFF(sk) = 0;
  928. }
  929. goto do_error;
  930. }
  931. /* Update the skb. */
  932. if (merge) {
  933. skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
  934. } else {
  935. skb_fill_page_desc(skb, i, page, off, copy);
  936. if (TCP_PAGE(sk)) {
  937. get_page(page);
  938. } else if (off + copy < PAGE_SIZE) {
  939. get_page(page);
  940. TCP_PAGE(sk) = page;
  941. }
  942. }
  943. TCP_OFF(sk) = off + copy;
  944. }
  945. if (!copied)
  946. TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
  947. tp->write_seq += copy;
  948. TCP_SKB_CB(skb)->end_seq += copy;
  949. skb_shinfo(skb)->gso_segs = 0;
  950. from += copy;
  951. copied += copy;
  952. if ((seglen -= copy) == 0 && iovlen == 0)
  953. goto out;
  954. if (skb->len < max || (flags & MSG_OOB))
  955. continue;
  956. if (forced_push(tp)) {
  957. tcp_mark_push(tp, skb);
  958. __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
  959. } else if (skb == tcp_send_head(sk))
  960. tcp_push_one(sk, mss_now);
  961. continue;
  962. wait_for_sndbuf:
  963. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  964. wait_for_memory:
  965. if (copied)
  966. tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH);
  967. if ((err = sk_stream_wait_memory(sk, &timeo)) != 0)
  968. goto do_error;
  969. mss_now = tcp_send_mss(sk, &size_goal, flags);
  970. }
  971. }
  972. out:
  973. if (copied)
  974. tcp_push(sk, flags, mss_now, tp->nonagle);
  975. release_sock(sk);
  976. return copied;
  977. do_fault:
  978. if (!skb->len) {
  979. tcp_unlink_write_queue(skb, sk);
  980. /* It is the one place in all of TCP, except connection
  981. * reset, where we can be unlinking the send_head.
  982. */
  983. tcp_check_send_head(sk, skb);
  984. sk_wmem_free_skb(sk, skb);
  985. }
  986. do_error:
  987. if (copied)
  988. goto out;
  989. out_err:
  990. err = sk_stream_error(sk, flags, err);
  991. release_sock(sk);
  992. return err;
  993. }
  994. EXPORT_SYMBOL(tcp_sendmsg);
  995. /*
  996. * Handle reading urgent data. BSD has very simple semantics for
  997. * this, no blocking and very strange errors 8)
  998. */
  999. static int tcp_recv_urg(struct sock *sk, struct msghdr *msg, int len, int flags)
  1000. {
  1001. struct tcp_sock *tp = tcp_sk(sk);
  1002. /* No URG data to read. */
  1003. if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data ||
  1004. tp->urg_data == TCP_URG_READ)
  1005. return -EINVAL; /* Yes this is right ! */
  1006. if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE))
  1007. return -ENOTCONN;
  1008. if (tp->urg_data & TCP_URG_VALID) {
  1009. int err = 0;
  1010. char c = tp->urg_data;
  1011. if (!(flags & MSG_PEEK))
  1012. tp->urg_data = TCP_URG_READ;
  1013. /* Read urgent data. */
  1014. msg->msg_flags |= MSG_OOB;
  1015. if (len > 0) {
  1016. if (!(flags & MSG_TRUNC))
  1017. err = memcpy_toiovec(msg->msg_iov, &c, 1);
  1018. len = 1;
  1019. } else
  1020. msg->msg_flags |= MSG_TRUNC;
  1021. return err ? -EFAULT : len;
  1022. }
  1023. if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN))
  1024. return 0;
  1025. /* Fixed the recv(..., MSG_OOB) behaviour. BSD docs and
  1026. * the available implementations agree in this case:
  1027. * this call should never block, independent of the
  1028. * blocking state of the socket.
  1029. * Mike <pall@rz.uni-karlsruhe.de>
  1030. */
  1031. return -EAGAIN;
  1032. }
  1033. /* Clean up the receive buffer for full frames taken by the user,
  1034. * then send an ACK if necessary. COPIED is the number of bytes
  1035. * tcp_recvmsg has given to the user so far, it speeds up the
  1036. * calculation of whether or not we must ACK for the sake of
  1037. * a window update.
  1038. */
  1039. void tcp_cleanup_rbuf(struct sock *sk, int copied)
  1040. {
  1041. struct tcp_sock *tp = tcp_sk(sk);
  1042. int time_to_ack = 0;
  1043. struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
  1044. WARN(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq),
  1045. "cleanup rbuf bug: copied %X seq %X rcvnxt %X\n",
  1046. tp->copied_seq, TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt);
  1047. if (inet_csk_ack_scheduled(sk)) {
  1048. const struct inet_connection_sock *icsk = inet_csk(sk);
  1049. /* Delayed ACKs frequently hit locked sockets during bulk
  1050. * receive. */
  1051. if (icsk->icsk_ack.blocked ||
  1052. /* Once-per-two-segments ACK was not sent by tcp_input.c */
  1053. tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss ||
  1054. /*
  1055. * If this read emptied read buffer, we send ACK, if
  1056. * connection is not bidirectional, user drained
  1057. * receive buffer and there was a small segment
  1058. * in queue.
  1059. */
  1060. (copied > 0 &&
  1061. ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) ||
  1062. ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) &&
  1063. !icsk->icsk_ack.pingpong)) &&
  1064. !atomic_read(&sk->sk_rmem_alloc)))
  1065. time_to_ack = 1;
  1066. }
  1067. /* We send an ACK if we can now advertise a non-zero window
  1068. * which has been raised "significantly".
  1069. *
  1070. * Even if window raised up to infinity, do not send window open ACK
  1071. * in states, where we will not receive more. It is useless.
  1072. */
  1073. if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
  1074. __u32 rcv_window_now = tcp_receive_window(tp);
  1075. /* Optimize, __tcp_select_window() is not cheap. */
  1076. if (2*rcv_window_now <= tp->window_clamp) {
  1077. __u32 new_window = __tcp_select_window(sk);
  1078. /* Send ACK now, if this read freed lots of space
  1079. * in our buffer. Certainly, new_window is new window.
  1080. * We can advertise it now, if it is not less than current one.
  1081. * "Lots" means "at least twice" here.
  1082. */
  1083. if (new_window && new_window >= 2 * rcv_window_now)
  1084. time_to_ack = 1;
  1085. }
  1086. }
  1087. if (time_to_ack)
  1088. tcp_send_ack(sk);
  1089. }
  1090. static void tcp_prequeue_process(struct sock *sk)
  1091. {
  1092. struct sk_buff *skb;
  1093. struct tcp_sock *tp = tcp_sk(sk);
  1094. NET_INC_STATS_USER(sock_net(sk), LINUX_MIB_TCPPREQUEUED);
  1095. /* RX process wants to run with disabled BHs, though it is not
  1096. * necessary */
  1097. local_bh_disable();
  1098. while ((skb = __skb_dequeue(&tp->ucopy.prequeue)) != NULL)
  1099. sk_backlog_rcv(sk, skb);
  1100. local_bh_enable();
  1101. /* Clear memory counter. */
  1102. tp->ucopy.memory = 0;
  1103. }
  1104. #ifdef CONFIG_NET_DMA
  1105. static void tcp_service_net_dma(struct sock *sk, bool wait)
  1106. {
  1107. dma_cookie_t done, used;
  1108. dma_cookie_t last_issued;
  1109. struct tcp_sock *tp = tcp_sk(sk);
  1110. if (!tp->ucopy.dma_chan)
  1111. return;
  1112. last_issued = tp->ucopy.dma_cookie;
  1113. dma_async_memcpy_issue_pending(tp->ucopy.dma_chan);
  1114. do {
  1115. if (dma_async_memcpy_complete(tp->ucopy.dma_chan,
  1116. last_issued, &done,
  1117. &used) == DMA_SUCCESS) {
  1118. /* Safe to free early-copied skbs now */
  1119. __skb_queue_purge(&sk->sk_async_wait_queue);
  1120. break;
  1121. } else {
  1122. struct sk_buff *skb;
  1123. while ((skb = skb_peek(&sk->sk_async_wait_queue)) &&
  1124. (dma_async_is_complete(skb->dma_cookie, done,
  1125. used) == DMA_SUCCESS)) {
  1126. __skb_dequeue(&sk->sk_async_wait_queue);
  1127. kfree_skb(skb);
  1128. }
  1129. }
  1130. } while (wait);
  1131. }
  1132. #endif
  1133. static inline struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off)
  1134. {
  1135. struct sk_buff *skb;
  1136. u32 offset;
  1137. skb_queue_walk(&sk->sk_receive_queue, skb) {
  1138. offset = seq - TCP_SKB_CB(skb)->seq;
  1139. if (tcp_hdr(skb)->syn)
  1140. offset--;
  1141. if (offset < skb->len || tcp_hdr(skb)->fin) {
  1142. *off = offset;
  1143. return skb;
  1144. }
  1145. }
  1146. return NULL;
  1147. }
  1148. /*
  1149. * This routine provides an alternative to tcp_recvmsg() for routines
  1150. * that would like to handle copying from skbuffs directly in 'sendfile'
  1151. * fashion.
  1152. * Note:
  1153. * - It is assumed that the socket was locked by the caller.
  1154. * - The routine does not block.
  1155. * - At present, there is no support for reading OOB data
  1156. * or for 'peeking' the socket using this routine
  1157. * (although both would be easy to implement).
  1158. */
  1159. int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
  1160. sk_read_actor_t recv_actor)
  1161. {
  1162. struct sk_buff *skb;
  1163. struct tcp_sock *tp = tcp_sk(sk);
  1164. u32 seq = tp->copied_seq;
  1165. u32 offset;
  1166. int copied = 0;
  1167. if (sk->sk_state == TCP_LISTEN)
  1168. return -ENOTCONN;
  1169. while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
  1170. if (offset < skb->len) {
  1171. int used;
  1172. size_t len;
  1173. len = skb->len - offset;
  1174. /* Stop reading if we hit a patch of urgent data */
  1175. if (tp->urg_data) {
  1176. u32 urg_offset = tp->urg_seq - seq;
  1177. if (urg_offset < len)
  1178. len = urg_offset;
  1179. if (!len)
  1180. break;
  1181. }
  1182. used = recv_actor(desc, skb, offset, len);
  1183. if (used < 0) {
  1184. if (!copied)
  1185. copied = used;
  1186. break;
  1187. } else if (used <= len) {
  1188. seq += used;
  1189. copied += used;
  1190. offset += used;
  1191. }
  1192. /*
  1193. * If recv_actor drops the lock (e.g. TCP splice
  1194. * receive) the skb pointer might be invalid when
  1195. * getting here: tcp_collapse might have deleted it
  1196. * while aggregating skbs from the socket queue.
  1197. */
  1198. skb = tcp_recv_skb(sk, seq-1, &offset);
  1199. if (!skb || (offset+1 != skb->len))
  1200. break;
  1201. }
  1202. if (tcp_hdr(skb)->fin) {
  1203. sk_eat_skb(sk, skb, 0);
  1204. ++seq;
  1205. break;
  1206. }
  1207. sk_eat_skb(sk, skb, 0);
  1208. if (!desc->count)
  1209. break;
  1210. tp->copied_seq = seq;
  1211. }
  1212. tp->copied_seq = seq;
  1213. tcp_rcv_space_adjust(sk);
  1214. /* Clean up data we have read: This will do ACK frames. */
  1215. if (copied > 0)
  1216. tcp_cleanup_rbuf(sk, copied);
  1217. return copied;
  1218. }
  1219. EXPORT_SYMBOL(tcp_read_sock);
  1220. /*
  1221. * This routine copies from a sock struct into the user buffer.
  1222. *
  1223. * Technical note: in 2.3 we work on _locked_ socket, so that
  1224. * tricks with *seq access order and skb->users are not required.
  1225. * Probably, code can be easily improved even more.
  1226. */
  1227. int tcp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
  1228. size_t len, int nonblock, int flags, int *addr_len)
  1229. {
  1230. struct tcp_sock *tp = tcp_sk(sk);
  1231. int copied = 0;
  1232. u32 peek_seq;
  1233. u32 *seq;
  1234. unsigned long used;
  1235. int err;
  1236. int target; /* Read at least this many bytes */
  1237. long timeo;
  1238. struct task_struct *user_recv = NULL;
  1239. int copied_early = 0;
  1240. struct sk_buff *skb;
  1241. u32 urg_hole = 0;
  1242. lock_sock(sk);
  1243. err = -ENOTCONN;
  1244. if (sk->sk_state == TCP_LISTEN)
  1245. goto out;
  1246. timeo = sock_rcvtimeo(sk, nonblock);
  1247. /* Urgent data needs to be handled specially. */
  1248. if (flags & MSG_OOB)
  1249. goto recv_urg;
  1250. seq = &tp->copied_seq;
  1251. if (flags & MSG_PEEK) {
  1252. peek_seq = tp->copied_seq;
  1253. seq = &peek_seq;
  1254. }
  1255. target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
  1256. #ifdef CONFIG_NET_DMA
  1257. tp->ucopy.dma_chan = NULL;
  1258. preempt_disable();
  1259. skb = skb_peek_tail(&sk->sk_receive_queue);
  1260. {
  1261. int available = 0;
  1262. if (skb)
  1263. available = TCP_SKB_CB(skb)->seq + skb->len - (*seq);
  1264. if ((available < target) &&
  1265. (len > sysctl_tcp_dma_copybreak) && !(flags & MSG_PEEK) &&
  1266. !sysctl_tcp_low_latency &&
  1267. dma_find_channel(DMA_MEMCPY)) {
  1268. preempt_enable_no_resched();
  1269. tp->ucopy.pinned_list =
  1270. dma_pin_iovec_pages(msg->msg_iov, len);
  1271. } else {
  1272. preempt_enable_no_resched();
  1273. }
  1274. }
  1275. #endif
  1276. do {
  1277. u32 offset;
  1278. /* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */
  1279. if (tp->urg_data && tp->urg_seq == *seq) {
  1280. if (copied)
  1281. break;
  1282. if (signal_pending(current)) {
  1283. copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
  1284. break;
  1285. }
  1286. }
  1287. /* Next get a buffer. */
  1288. skb_queue_walk(&sk->sk_receive_queue, skb) {
  1289. /* Now that we have two receive queues this
  1290. * shouldn't happen.
  1291. */
  1292. if (WARN(before(*seq, TCP_SKB_CB(skb)->seq),
  1293. "recvmsg bug: copied %X seq %X rcvnxt %X fl %X\n",
  1294. *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt,
  1295. flags))
  1296. break;
  1297. offset = *seq - TCP_SKB_CB(skb)->seq;
  1298. if (tcp_hdr(skb)->syn)
  1299. offset--;
  1300. if (offset < skb->len)
  1301. goto found_ok_skb;
  1302. if (tcp_hdr(skb)->fin)
  1303. goto found_fin_ok;
  1304. WARN(!(flags & MSG_PEEK),
  1305. "recvmsg bug 2: copied %X seq %X rcvnxt %X fl %X\n",
  1306. *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags);
  1307. }
  1308. /* Well, if we have backlog, try to process it now yet. */
  1309. if (copied >= target && !sk->sk_backlog.tail)
  1310. break;
  1311. if (copied) {
  1312. if (sk->sk_err ||
  1313. sk->sk_state == TCP_CLOSE ||
  1314. (sk->sk_shutdown & RCV_SHUTDOWN) ||
  1315. !timeo ||
  1316. signal_pending(current))
  1317. break;
  1318. } else {
  1319. if (sock_flag(sk, SOCK_DONE))
  1320. break;
  1321. if (sk->sk_err) {
  1322. copied = sock_error(sk);
  1323. break;
  1324. }
  1325. if (sk->sk_shutdown & RCV_SHUTDOWN)
  1326. break;
  1327. if (sk->sk_state == TCP_CLOSE) {
  1328. if (!sock_flag(sk, SOCK_DONE)) {
  1329. /* This occurs when user tries to read
  1330. * from never connected socket.
  1331. */
  1332. copied = -ENOTCONN;
  1333. break;
  1334. }
  1335. break;
  1336. }
  1337. if (!timeo) {
  1338. copied = -EAGAIN;
  1339. break;
  1340. }
  1341. if (signal_pending(current)) {
  1342. copied = sock_intr_errno(timeo);
  1343. break;
  1344. }
  1345. }
  1346. tcp_cleanup_rbuf(sk, copied);
  1347. if (!sysctl_tcp_low_latency && tp->ucopy.task == user_recv) {
  1348. /* Install new reader */
  1349. if (!user_recv && !(flags & (MSG_TRUNC | MSG_PEEK))) {
  1350. user_recv = current;
  1351. tp->ucopy.task = user_recv;
  1352. tp->ucopy.iov = msg->msg_iov;
  1353. }
  1354. tp->ucopy.len = len;
  1355. WARN_ON(tp->copied_seq != tp->rcv_nxt &&
  1356. !(flags & (MSG_PEEK | MSG_TRUNC)));
  1357. /* Ugly... If prequeue is not empty, we have to
  1358. * process it before releasing socket, otherwise
  1359. * order will be broken at second iteration.
  1360. * More elegant solution is required!!!
  1361. *
  1362. * Look: we have the following (pseudo)queues:
  1363. *
  1364. * 1. packets in flight
  1365. * 2. backlog
  1366. * 3. prequeue
  1367. * 4. receive_queue
  1368. *
  1369. * Each queue can be processed only if the next ones
  1370. * are empty. At this point we have empty receive_queue.
  1371. * But prequeue _can_ be not empty after 2nd iteration,
  1372. * when we jumped to start of loop because backlog
  1373. * processing added something to receive_queue.
  1374. * We cannot release_sock(), because backlog contains
  1375. * packets arrived _after_ prequeued ones.
  1376. *
  1377. * Shortly, algorithm is clear --- to process all
  1378. * the queues in order. We could make it more directly,
  1379. * requeueing packets from backlog to prequeue, if
  1380. * is not empty. It is more elegant, but eats cycles,
  1381. * unfortunately.
  1382. */
  1383. if (!skb_queue_empty(&tp->ucopy.prequeue))
  1384. goto do_prequeue;
  1385. /* __ Set realtime policy in scheduler __ */
  1386. }
  1387. #ifdef CONFIG_NET_DMA
  1388. if (tp->ucopy.dma_chan) {
  1389. if (tp->rcv_wnd == 0 &&
  1390. !skb_queue_empty(&sk->sk_async_wait_queue)) {
  1391. tcp_service_net_dma(sk, true);
  1392. tcp_cleanup_rbuf(sk, copied);
  1393. } else
  1394. dma_async_memcpy_issue_pending(tp->ucopy.dma_chan);
  1395. }
  1396. #endif
  1397. if (copied >= target) {
  1398. /* Do not sleep, just process backlog. */
  1399. release_sock(sk);
  1400. lock_sock(sk);
  1401. } else
  1402. sk_wait_data(sk, &timeo);
  1403. #ifdef CONFIG_NET_DMA
  1404. tcp_service_net_dma(sk, false); /* Don't block */
  1405. tp->ucopy.wakeup = 0;
  1406. #endif
  1407. if (user_recv) {
  1408. int chunk;
  1409. /* __ Restore normal policy in scheduler __ */
  1410. if ((chunk = len - tp->ucopy.len) != 0) {
  1411. NET_ADD_STATS_USER(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMBACKLOG, chunk);
  1412. len -= chunk;
  1413. copied += chunk;
  1414. }
  1415. if (tp->rcv_nxt == tp->copied_seq &&
  1416. !skb_queue_empty(&tp->ucopy.prequeue)) {
  1417. do_prequeue:
  1418. tcp_prequeue_process(sk);
  1419. if ((chunk = len - tp->ucopy.len) != 0) {
  1420. NET_ADD_STATS_USER(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
  1421. len -= chunk;
  1422. copied += chunk;
  1423. }
  1424. }
  1425. }
  1426. if ((flags & MSG_PEEK) &&
  1427. (peek_seq - copied - urg_hole != tp->copied_seq)) {
  1428. if (net_ratelimit())
  1429. printk(KERN_DEBUG "TCP(%s:%d): Application bug, race in MSG_PEEK.\n",
  1430. current->comm, task_pid_nr(current));
  1431. peek_seq = tp->copied_seq;
  1432. }
  1433. continue;
  1434. found_ok_skb:
  1435. /* Ok so how much can we use? */
  1436. used = skb->len - offset;
  1437. if (len < used)
  1438. used = len;
  1439. /* Do we have urgent data here? */
  1440. if (tp->urg_data) {
  1441. u32 urg_offset = tp->urg_seq - *seq;
  1442. if (urg_offset < used) {
  1443. if (!urg_offset) {
  1444. if (!sock_flag(sk, SOCK_URGINLINE)) {
  1445. ++*seq;
  1446. urg_hole++;
  1447. offset++;
  1448. used--;
  1449. if (!used)
  1450. goto skip_copy;
  1451. }
  1452. } else
  1453. used = urg_offset;
  1454. }
  1455. }
  1456. if (!(flags & MSG_TRUNC)) {
  1457. #ifdef CONFIG_NET_DMA
  1458. if (!tp->ucopy.dma_chan && tp->ucopy.pinned_list)
  1459. tp->ucopy.dma_chan = dma_find_channel(DMA_MEMCPY);
  1460. if (tp->ucopy.dma_chan) {
  1461. tp->ucopy.dma_cookie = dma_skb_copy_datagram_iovec(
  1462. tp->ucopy.dma_chan, skb, offset,
  1463. msg->msg_iov, used,
  1464. tp->ucopy.pinned_list);
  1465. if (tp->ucopy.dma_cookie < 0) {
  1466. printk(KERN_ALERT "dma_cookie < 0\n");
  1467. /* Exception. Bailout! */
  1468. if (!copied)
  1469. copied = -EFAULT;
  1470. break;
  1471. }
  1472. dma_async_memcpy_issue_pending(tp->ucopy.dma_chan);
  1473. if ((offset + used) == skb->len)
  1474. copied_early = 1;
  1475. } else
  1476. #endif
  1477. {
  1478. err = skb_copy_datagram_iovec(skb, offset,
  1479. msg->msg_iov, used);
  1480. if (err) {
  1481. /* Exception. Bailout! */
  1482. if (!copied)
  1483. copied = -EFAULT;
  1484. break;
  1485. }
  1486. }
  1487. }
  1488. *seq += used;
  1489. copied += used;
  1490. len -= used;
  1491. tcp_rcv_space_adjust(sk);
  1492. skip_copy:
  1493. if (tp->urg_data && after(tp->copied_seq, tp->urg_seq)) {
  1494. tp->urg_data = 0;
  1495. tcp_fast_path_check(sk);
  1496. }
  1497. if (used + offset < skb->len)
  1498. continue;
  1499. if (tcp_hdr(skb)->fin)
  1500. goto found_fin_ok;
  1501. if (!(flags & MSG_PEEK)) {
  1502. sk_eat_skb(sk, skb, copied_early);
  1503. copied_early = 0;
  1504. }
  1505. continue;
  1506. found_fin_ok:
  1507. /* Process the FIN. */
  1508. ++*seq;
  1509. if (!(flags & MSG_PEEK)) {
  1510. sk_eat_skb(sk, skb, copied_early);
  1511. copied_early = 0;
  1512. }
  1513. break;
  1514. } while (len > 0);
  1515. if (user_recv) {
  1516. if (!skb_queue_empty(&tp->ucopy.prequeue)) {
  1517. int chunk;
  1518. tp->ucopy.len = copied > 0 ? len : 0;
  1519. tcp_prequeue_process(sk);
  1520. if (copied > 0 && (chunk = len - tp->ucopy.len) != 0) {
  1521. NET_ADD_STATS_USER(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
  1522. len -= chunk;
  1523. copied += chunk;
  1524. }
  1525. }
  1526. tp->ucopy.task = NULL;
  1527. tp->ucopy.len = 0;
  1528. }
  1529. #ifdef CONFIG_NET_DMA
  1530. tcp_service_net_dma(sk, true); /* Wait for queue to drain */
  1531. tp->ucopy.dma_chan = NULL;
  1532. if (tp->ucopy.pinned_list) {
  1533. dma_unpin_iovec_pages(tp->ucopy.pinned_list);
  1534. tp->ucopy.pinned_list = NULL;
  1535. }
  1536. #endif
  1537. /* According to UNIX98, msg_name/msg_namelen are ignored
  1538. * on connected socket. I was just happy when found this 8) --ANK
  1539. */
  1540. /* Clean up data we have read: This will do ACK frames. */
  1541. tcp_cleanup_rbuf(sk, copied);
  1542. release_sock(sk);
  1543. return copied;
  1544. out:
  1545. release_sock(sk);
  1546. return err;
  1547. recv_urg:
  1548. err = tcp_recv_urg(sk, msg, len, flags);
  1549. goto out;
  1550. }
  1551. EXPORT_SYMBOL(tcp_recvmsg);
  1552. void tcp_set_state(struct sock *sk, int state)
  1553. {
  1554. int oldstate = sk->sk_state;
  1555. switch (state) {
  1556. case TCP_ESTABLISHED:
  1557. if (oldstate != TCP_ESTABLISHED)
  1558. TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
  1559. break;
  1560. case TCP_CLOSE:
  1561. if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED)
  1562. TCP_INC_STATS(sock_net(sk), TCP_MIB_ESTABRESETS);
  1563. sk->sk_prot->unhash(sk);
  1564. if (inet_csk(sk)->icsk_bind_hash &&
  1565. !(sk->sk_userlocks & SOCK_BINDPORT_LOCK))
  1566. inet_put_port(sk);
  1567. /* fall through */
  1568. default:
  1569. if (oldstate == TCP_ESTABLISHED)
  1570. TCP_DEC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
  1571. }
  1572. /* Change state AFTER socket is unhashed to avoid closed
  1573. * socket sitting in hash tables.
  1574. */
  1575. sk->sk_state = state;
  1576. #ifdef STATE_TRACE
  1577. SOCK_DEBUG(sk, "TCP sk=%p, State %s -> %s\n", sk, statename[oldstate], statename[state]);
  1578. #endif
  1579. }
  1580. EXPORT_SYMBOL_GPL(tcp_set_state);
  1581. /*
  1582. * State processing on a close. This implements the state shift for
  1583. * sending our FIN frame. Note that we only send a FIN for some
  1584. * states. A shutdown() may have already sent the FIN, or we may be
  1585. * closed.
  1586. */
  1587. static const unsigned char new_state[16] = {
  1588. /* current state: new state: action: */
  1589. /* (Invalid) */ TCP_CLOSE,
  1590. /* TCP_ESTABLISHED */ TCP_FIN_WAIT1 | TCP_ACTION_FIN,
  1591. /* TCP_SYN_SENT */ TCP_CLOSE,
  1592. /* TCP_SYN_RECV */ TCP_FIN_WAIT1 | TCP_ACTION_FIN,
  1593. /* TCP_FIN_WAIT1 */ TCP_FIN_WAIT1,
  1594. /* TCP_FIN_WAIT2 */ TCP_FIN_WAIT2,
  1595. /* TCP_TIME_WAIT */ TCP_CLOSE,
  1596. /* TCP_CLOSE */ TCP_CLOSE,
  1597. /* TCP_CLOSE_WAIT */ TCP_LAST_ACK | TCP_ACTION_FIN,
  1598. /* TCP_LAST_ACK */ TCP_LAST_ACK,
  1599. /* TCP_LISTEN */ TCP_CLOSE,
  1600. /* TCP_CLOSING */ TCP_CLOSING,
  1601. };
  1602. static int tcp_close_state(struct sock *sk)
  1603. {
  1604. int next = (int)new_state[sk->sk_state];
  1605. int ns = next & TCP_STATE_MASK;
  1606. tcp_set_state(sk, ns);
  1607. return next & TCP_ACTION_FIN;
  1608. }
  1609. /*
  1610. * Shutdown the sending side of a connection. Much like close except
  1611. * that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD).
  1612. */
  1613. void tcp_shutdown(struct sock *sk, int how)
  1614. {
  1615. /* We need to grab some memory, and put together a FIN,
  1616. * and then put it into the queue to be sent.
  1617. * Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92.
  1618. */
  1619. if (!(how & SEND_SHUTDOWN))
  1620. return;
  1621. /* If we've already sent a FIN, or it's a closed state, skip this. */
  1622. if ((1 << sk->sk_state) &
  1623. (TCPF_ESTABLISHED | TCPF_SYN_SENT

Large files files are truncated, but you can click here to view the full file