PageRenderTime 60ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/linux-2.6.21.x/net/ipv4/tcp.c

https://bitbucket.org/altlc/wive-rtnl-ralink-rt305x-routers-firmware-amod
C | 2575 lines | 1643 code | 347 blank | 585 comment | 420 complexity | 31306c0e00323655ecf70156bd98d8df MD5 | raw file
Possible License(s): CC-BY-SA-3.0, BSD-3-Clause, MPL-2.0-no-copyleft-exception, GPL-2.0, GPL-3.0, LGPL-3.0, 0BSD, AGPL-1.0, LGPL-2.1, LGPL-2.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. * Version: $Id: tcp.c,v 1.1.1.1 2007-05-25 06:50:00 bruce Exp $
  9. *
  10. * Authors: Ross Biro
  11. * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
  12. * Mark Evans, <evansmp@uhura.aston.ac.uk>
  13. * Corey Minyard <wf-rch!minyard@relay.EU.net>
  14. * Florian La Roche, <flla@stud.uni-sb.de>
  15. * Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
  16. * Linus Torvalds, <torvalds@cs.helsinki.fi>
  17. * Alan Cox, <gw4pts@gw4pts.ampr.org>
  18. * Matthew Dillon, <dillon@apollo.west.oic.com>
  19. * Arnt Gulbrandsen, <agulbra@nvg.unit.no>
  20. * Jorge Cwik, <jorge@laser.satlink.net>
  21. *
  22. * Fixes:
  23. * Alan Cox : Numerous verify_area() calls
  24. * Alan Cox : Set the ACK bit on a reset
  25. * Alan Cox : Stopped it crashing if it closed while
  26. * sk->inuse=1 and was trying to connect
  27. * (tcp_err()).
  28. * Alan Cox : All icmp error handling was broken
  29. * pointers passed where wrong and the
  30. * socket was looked up backwards. Nobody
  31. * tested any icmp error code obviously.
  32. * Alan Cox : tcp_err() now handled properly. It
  33. * wakes people on errors. poll
  34. * behaves and the icmp error race
  35. * has gone by moving it into sock.c
  36. * Alan Cox : tcp_send_reset() fixed to work for
  37. * everything not just packets for
  38. * unknown sockets.
  39. * Alan Cox : tcp option processing.
  40. * Alan Cox : Reset tweaked (still not 100%) [Had
  41. * syn rule wrong]
  42. * Herp Rosmanith : More reset fixes
  43. * Alan Cox : No longer acks invalid rst frames.
  44. * Acking any kind of RST is right out.
  45. * Alan Cox : Sets an ignore me flag on an rst
  46. * receive otherwise odd bits of prattle
  47. * escape still
  48. * Alan Cox : Fixed another acking RST frame bug.
  49. * Should stop LAN workplace lockups.
  50. * Alan Cox : Some tidyups using the new skb list
  51. * facilities
  52. * Alan Cox : sk->keepopen now seems to work
  53. * Alan Cox : Pulls options out correctly on accepts
  54. * Alan Cox : Fixed assorted sk->rqueue->next errors
  55. * Alan Cox : PSH doesn't end a TCP read. Switched a
  56. * bit to skb ops.
  57. * Alan Cox : Tidied tcp_data to avoid a potential
  58. * nasty.
  59. * Alan Cox : Added some better commenting, as the
  60. * tcp is hard to follow
  61. * Alan Cox : Removed incorrect check for 20 * psh
  62. * Michael O'Reilly : ack < copied bug fix.
  63. * Johannes Stille : Misc tcp fixes (not all in yet).
  64. * Alan Cox : FIN with no memory -> CRASH
  65. * Alan Cox : Added socket option proto entries.
  66. * Also added awareness of them to accept.
  67. * Alan Cox : Added TCP options (SOL_TCP)
  68. * Alan Cox : Switched wakeup calls to callbacks,
  69. * so the kernel can layer network
  70. * sockets.
  71. * Alan Cox : Use ip_tos/ip_ttl settings.
  72. * Alan Cox : Handle FIN (more) properly (we hope).
  73. * Alan Cox : RST frames sent on unsynchronised
  74. * state ack error.
  75. * Alan Cox : Put in missing check for SYN bit.
  76. * Alan Cox : Added tcp_select_window() aka NET2E
  77. * window non shrink trick.
  78. * Alan Cox : Added a couple of small NET2E timer
  79. * fixes
  80. * Charles Hedrick : TCP fixes
  81. * Toomas Tamm : TCP window fixes
  82. * Alan Cox : Small URG fix to rlogin ^C ack fight
  83. * Charles Hedrick : Rewrote most of it to actually work
  84. * Linus : Rewrote tcp_read() and URG handling
  85. * completely
  86. * Gerhard Koerting: Fixed some missing timer handling
  87. * Matthew Dillon : Reworked TCP machine states as per RFC
  88. * Gerhard Koerting: PC/TCP workarounds
  89. * Adam Caldwell : Assorted timer/timing errors
  90. * Matthew Dillon : Fixed another RST bug
  91. * Alan Cox : Move to kernel side addressing changes.
  92. * Alan Cox : Beginning work on TCP fastpathing
  93. * (not yet usable)
  94. * Arnt Gulbrandsen: Turbocharged tcp_check() routine.
  95. * Alan Cox : TCP fast path debugging
  96. * Alan Cox : Window clamping
  97. * Michael Riepe : Bug in tcp_check()
  98. * Matt Dillon : More TCP improvements and RST bug fixes
  99. * Matt Dillon : Yet more small nasties remove from the
  100. * TCP code (Be very nice to this man if
  101. * tcp finally works 100%) 8)
  102. * Alan Cox : BSD accept semantics.
  103. * Alan Cox : Reset on closedown bug.
  104. * Peter De Schrijver : ENOTCONN check missing in tcp_sendto().
  105. * Michael Pall : Handle poll() after URG properly in
  106. * all cases.
  107. * Michael Pall : Undo the last fix in tcp_read_urg()
  108. * (multi URG PUSH broke rlogin).
  109. * Michael Pall : Fix the multi URG PUSH problem in
  110. * tcp_readable(), poll() after URG
  111. * works now.
  112. * Michael Pall : recv(...,MSG_OOB) never blocks in the
  113. * BSD api.
  114. * Alan Cox : Changed the semantics of sk->socket to
  115. * fix a race and a signal problem with
  116. * accept() and async I/O.
  117. * Alan Cox : Relaxed the rules on tcp_sendto().
  118. * Yury Shevchuk : Really fixed accept() blocking problem.
  119. * Craig I. Hagan : Allow for BSD compatible TIME_WAIT for
  120. * clients/servers which listen in on
  121. * fixed ports.
  122. * Alan Cox : Cleaned the above up and shrank it to
  123. * a sensible code size.
  124. * Alan Cox : Self connect lockup fix.
  125. * Alan Cox : No connect to multicast.
  126. * Ross Biro : Close unaccepted children on master
  127. * socket close.
  128. * Alan Cox : Reset tracing code.
  129. * Alan Cox : Spurious resets on shutdown.
  130. * Alan Cox : Giant 15 minute/60 second timer error
  131. * Alan Cox : Small whoops in polling before an
  132. * accept.
  133. * Alan Cox : Kept the state trace facility since
  134. * it's handy for debugging.
  135. * Alan Cox : More reset handler fixes.
  136. * Alan Cox : Started rewriting the code based on
  137. * the RFC's for other useful protocol
  138. * references see: Comer, KA9Q NOS, and
  139. * for a reference on the difference
  140. * between specifications and how BSD
  141. * works see the 4.4lite source.
  142. * A.N.Kuznetsov : Don't time wait on completion of tidy
  143. * close.
  144. * Linus Torvalds : Fin/Shutdown & copied_seq changes.
  145. * Linus Torvalds : Fixed BSD port reuse to work first syn
  146. * Alan Cox : Reimplemented timers as per the RFC
  147. * and using multiple timers for sanity.
  148. * Alan Cox : Small bug fixes, and a lot of new
  149. * comments.
  150. * Alan Cox : Fixed dual reader crash by locking
  151. * the buffers (much like datagram.c)
  152. * Alan Cox : Fixed stuck sockets in probe. A probe
  153. * now gets fed up of retrying without
  154. * (even a no space) answer.
  155. * Alan Cox : Extracted closing code better
  156. * Alan Cox : Fixed the closing state machine to
  157. * resemble the RFC.
  158. * Alan Cox : More 'per spec' fixes.
  159. * Jorge Cwik : Even faster checksumming.
  160. * Alan Cox : tcp_data() doesn't ack illegal PSH
  161. * only frames. At least one pc tcp stack
  162. * generates them.
  163. * Alan Cox : Cache last socket.
  164. * Alan Cox : Per route irtt.
  165. * Matt Day : poll()->select() match BSD precisely on error
  166. * Alan Cox : New buffers
  167. * Marc Tamsky : Various sk->prot->retransmits and
  168. * sk->retransmits misupdating fixed.
  169. * Fixed tcp_write_timeout: stuck close,
  170. * and TCP syn retries gets used now.
  171. * Mark Yarvis : In tcp_read_wakeup(), don't send an
  172. * ack if state is TCP_CLOSED.
  173. * Alan Cox : Look up device on a retransmit - routes may
  174. * change. Doesn't yet cope with MSS shrink right
  175. * but it's a start!
  176. * Marc Tamsky : Closing in closing fixes.
  177. * Mike Shaver : RFC1122 verifications.
  178. * Alan Cox : rcv_saddr errors.
  179. * Alan Cox : Block double connect().
  180. * Alan Cox : Small hooks for enSKIP.
  181. * Alexey Kuznetsov: Path MTU discovery.
  182. * Alan Cox : Support soft errors.
  183. * Alan Cox : Fix MTU discovery pathological case
  184. * when the remote claims no mtu!
  185. * Marc Tamsky : TCP_CLOSE fix.
  186. * Colin (G3TNE) : Send a reset on syn ack replies in
  187. * window but wrong (fixes NT lpd problems)
  188. * Pedro Roque : Better TCP window handling, delayed ack.
  189. * Joerg Reuter : No modification of locked buffers in
  190. * tcp_do_retransmit()
  191. * Eric Schenk : Changed receiver side silly window
  192. * avoidance algorithm to BSD style
  193. * algorithm. This doubles throughput
  194. * against machines running Solaris,
  195. * and seems to result in general
  196. * improvement.
  197. * Stefan Magdalinski : adjusted tcp_readable() to fix FIONREAD
  198. * Willy Konynenberg : Transparent proxying support.
  199. * Mike McLagan : Routing by source
  200. * Keith Owens : Do proper merging with partial SKB's in
  201. * tcp_do_sendmsg to avoid burstiness.
  202. * Eric Schenk : Fix fast close down bug with
  203. * shutdown() followed by close().
  204. * Andi Kleen : Make poll agree with SIGIO
  205. * Salvatore Sanfilippo : Support SO_LINGER with linger == 1 and
  206. * lingertime == 0 (RFC 793 ABORT Call)
  207. * Hirokazu Takahashi : Use copy_from_user() instead of
  208. * csum_and_copy_from_user() if possible.
  209. *
  210. * This program is free software; you can redistribute it and/or
  211. * modify it under the terms of the GNU General Public License
  212. * as published by the Free Software Foundation; either version
  213. * 2 of the License, or(at your option) any later version.
  214. *
  215. * Description of States:
  216. *
  217. * TCP_SYN_SENT sent a connection request, waiting for ack
  218. *
  219. * TCP_SYN_RECV received a connection request, sent ack,
  220. * waiting for final ack in three-way handshake.
  221. *
  222. * TCP_ESTABLISHED connection established
  223. *
  224. * TCP_FIN_WAIT1 our side has shutdown, waiting to complete
  225. * transmission of remaining buffered data
  226. *
  227. * TCP_FIN_WAIT2 all buffered data sent, waiting for remote
  228. * to shutdown
  229. *
  230. * TCP_CLOSING both sides have shutdown but we still have
  231. * data we have to finish sending
  232. *
  233. * TCP_TIME_WAIT timeout to catch resent junk before entering
  234. * closed, can only be entered from FIN_WAIT2
  235. * or CLOSING. Required because the other end
  236. * may not have gotten our last ACK causing it
  237. * to retransmit the data packet (which we ignore)
  238. *
  239. * TCP_CLOSE_WAIT remote side has shutdown and is waiting for
  240. * us to finish writing our data and to shutdown
  241. * (we have to close() to move on to LAST_ACK)
  242. *
  243. * TCP_LAST_ACK out side has shutdown after remote has
  244. * shutdown. There may still be data in our
  245. * buffer that we have to finish sending
  246. *
  247. * TCP_CLOSE socket is finished
  248. */
  249. #include <linux/module.h>
  250. #include <linux/types.h>
  251. #include <linux/fcntl.h>
  252. #include <linux/poll.h>
  253. #include <linux/init.h>
  254. #include <linux/fs.h>
  255. #include <linux/random.h>
  256. #include <linux/bootmem.h>
  257. #include <linux/highmem.h>
  258. #include <linux/swap.h>
  259. #include <linux/cache.h>
  260. #include <linux/err.h>
  261. #include <linux/crypto.h>
  262. #include <net/icmp.h>
  263. #include <net/tcp.h>
  264. #include <net/xfrm.h>
  265. #include <net/ip.h>
  266. #include <net/netdma.h>
  267. #include <asm/uaccess.h>
  268. #include <asm/ioctls.h>
  269. int sysctl_tcp_fin_timeout __read_mostly = TCP_FIN_TIMEOUT;
  270. DEFINE_SNMP_STAT(struct tcp_mib, tcp_statistics) __read_mostly;
  271. atomic_t tcp_orphan_count = ATOMIC_INIT(0);
  272. EXPORT_SYMBOL_GPL(tcp_orphan_count);
  273. int sysctl_tcp_mem[3] __read_mostly;
  274. int sysctl_tcp_wmem[3] __read_mostly;
  275. int sysctl_tcp_rmem[3] __read_mostly;
  276. EXPORT_SYMBOL(sysctl_tcp_mem);
  277. EXPORT_SYMBOL(sysctl_tcp_rmem);
  278. EXPORT_SYMBOL(sysctl_tcp_wmem);
  279. atomic_t tcp_memory_allocated; /* Current allocated memory. */
  280. atomic_t tcp_sockets_allocated; /* Current number of TCP sockets. */
  281. EXPORT_SYMBOL(tcp_memory_allocated);
  282. EXPORT_SYMBOL(tcp_sockets_allocated);
  283. /*
  284. * Pressure flag: try to collapse.
  285. * Technical note: it is used by multiple contexts non atomically.
  286. * All the sk_stream_mem_schedule() is of this nature: accounting
  287. * is strict, actions are advisory and have some latency.
  288. */
  289. int tcp_memory_pressure __read_mostly;
  290. EXPORT_SYMBOL(tcp_memory_pressure);
  291. void tcp_enter_memory_pressure(void)
  292. {
  293. if (!tcp_memory_pressure) {
  294. NET_INC_STATS(LINUX_MIB_TCPMEMORYPRESSURES);
  295. tcp_memory_pressure = 1;
  296. }
  297. }
  298. EXPORT_SYMBOL(tcp_enter_memory_pressure);
  299. /*
  300. * Wait for a TCP event.
  301. *
  302. * Note that we don't need to lock the socket, as the upper poll layers
  303. * take care of normal races (between the test and the event) and we don't
  304. * go look at any of the socket buffers directly.
  305. */
  306. unsigned int tcp_poll(struct file *file, struct socket *sock, poll_table *wait)
  307. {
  308. unsigned int mask;
  309. struct sock *sk = sock->sk;
  310. struct tcp_sock *tp = tcp_sk(sk);
  311. poll_wait(file, sk->sk_sleep, wait);
  312. if (sk->sk_state == TCP_LISTEN)
  313. return inet_csk_listen_poll(sk);
  314. /* Socket is not locked. We are protected from async events
  315. by poll logic and correct handling of state changes
  316. made by another threads is impossible in any case.
  317. */
  318. mask = 0;
  319. /*
  320. * POLLHUP is certainly not done right. But poll() doesn't
  321. * have a notion of HUP in just one direction, and for a
  322. * socket the read side is more interesting.
  323. *
  324. * Some poll() documentation says that POLLHUP is incompatible
  325. * with the POLLOUT/POLLWR flags, so somebody should check this
  326. * all. But careful, it tends to be safer to return too many
  327. * bits than too few, and you can easily break real applications
  328. * if you don't tell them that something has hung up!
  329. *
  330. * Check-me.
  331. *
  332. * Check number 1. POLLHUP is _UNMASKABLE_ event (see UNIX98 and
  333. * our fs/select.c). It means that after we received EOF,
  334. * poll always returns immediately, making impossible poll() on write()
  335. * in state CLOSE_WAIT. One solution is evident --- to set POLLHUP
  336. * if and only if shutdown has been made in both directions.
  337. * Actually, it is interesting to look how Solaris and DUX
  338. * solve this dilemma. I would prefer, if PULLHUP were maskable,
  339. * then we could set it on SND_SHUTDOWN. BTW examples given
  340. * in Stevens' books assume exactly this behaviour, it explains
  341. * why PULLHUP is incompatible with POLLOUT. --ANK
  342. *
  343. * NOTE. Check for TCP_CLOSE is added. The goal is to prevent
  344. * blocking on fresh not-connected or disconnected socket. --ANK
  345. */
  346. if (sk->sk_shutdown == SHUTDOWN_MASK || sk->sk_state == TCP_CLOSE)
  347. mask |= POLLHUP;
  348. if (sk->sk_shutdown & RCV_SHUTDOWN)
  349. mask |= POLLIN | POLLRDNORM | POLLRDHUP;
  350. /* Connected? */
  351. if ((1 << sk->sk_state) & ~(TCPF_SYN_SENT | TCPF_SYN_RECV)) {
  352. /* Potential race condition. If read of tp below will
  353. * escape above sk->sk_state, we can be illegally awaken
  354. * in SYN_* states. */
  355. if ((tp->rcv_nxt != tp->copied_seq) &&
  356. (tp->urg_seq != tp->copied_seq ||
  357. tp->rcv_nxt != tp->copied_seq + 1 ||
  358. sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data))
  359. mask |= POLLIN | POLLRDNORM;
  360. if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
  361. if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk)) {
  362. mask |= POLLOUT | POLLWRNORM;
  363. } else { /* send SIGIO later */
  364. set_bit(SOCK_ASYNC_NOSPACE,
  365. &sk->sk_socket->flags);
  366. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  367. /* Race breaker. If space is freed after
  368. * wspace test but before the flags are set,
  369. * IO signal will be lost.
  370. */
  371. if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk))
  372. mask |= POLLOUT | POLLWRNORM;
  373. }
  374. } else
  375. mask |= POLLOUT | POLLWRNORM;
  376. if (tp->urg_data & TCP_URG_VALID)
  377. mask |= POLLPRI;
  378. }
  379. /* This barrier is coupled with smp_wmb() in tcp_reset() */
  380. smp_rmb();
  381. if (sk->sk_err)
  382. mask |= POLLERR;
  383. return mask;
  384. }
  385. int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg)
  386. {
  387. struct tcp_sock *tp = tcp_sk(sk);
  388. int answ;
  389. switch (cmd) {
  390. case SIOCINQ:
  391. if (sk->sk_state == TCP_LISTEN)
  392. return -EINVAL;
  393. lock_sock(sk);
  394. if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
  395. answ = 0;
  396. else if (sock_flag(sk, SOCK_URGINLINE) ||
  397. !tp->urg_data ||
  398. before(tp->urg_seq, tp->copied_seq) ||
  399. !before(tp->urg_seq, tp->rcv_nxt)) {
  400. answ = tp->rcv_nxt - tp->copied_seq;
  401. /* Subtract 1, if FIN is in queue. */
  402. if (answ && !skb_queue_empty(&sk->sk_receive_queue))
  403. answ -=
  404. ((struct sk_buff *)sk->sk_receive_queue.prev)->h.th->fin;
  405. } else
  406. answ = tp->urg_seq - tp->copied_seq;
  407. release_sock(sk);
  408. break;
  409. case SIOCATMARK:
  410. answ = tp->urg_data && tp->urg_seq == tp->copied_seq;
  411. break;
  412. case SIOCOUTQ:
  413. if (sk->sk_state == TCP_LISTEN)
  414. return -EINVAL;
  415. if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
  416. answ = 0;
  417. else
  418. answ = tp->write_seq - tp->snd_una;
  419. break;
  420. default:
  421. return -ENOIOCTLCMD;
  422. };
  423. return put_user(answ, (int __user *)arg);
  424. }
  425. static inline void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb)
  426. {
  427. TCP_SKB_CB(skb)->flags |= TCPHDR_PSH;
  428. tp->pushed_seq = tp->write_seq;
  429. }
  430. static inline int forced_push(struct tcp_sock *tp)
  431. {
  432. return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1));
  433. }
  434. static inline void skb_entail(struct sock *sk, struct sk_buff *skb)
  435. {
  436. struct tcp_sock *tp = tcp_sk(sk);
  437. struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
  438. skb->csum = 0;
  439. tcb->seq = tcb->end_seq = tp->write_seq;
  440. tcb->flags = TCPHDR_ACK;
  441. tcb->sacked = 0;
  442. skb_header_release(skb);
  443. __skb_queue_tail(&sk->sk_write_queue, skb);
  444. sk_charge_skb(sk, skb);
  445. if (!sk->sk_send_head)
  446. sk->sk_send_head = skb;
  447. if (tp->nonagle & TCP_NAGLE_PUSH)
  448. tp->nonagle &= ~TCP_NAGLE_PUSH;
  449. }
  450. static inline void tcp_mark_urg(struct tcp_sock *tp, int flags,
  451. struct sk_buff *skb)
  452. {
  453. if (flags & MSG_OOB) {
  454. tp->urg_mode = 1;
  455. tp->snd_up = tp->write_seq;
  456. TCP_SKB_CB(skb)->sacked |= TCPCB_URG;
  457. }
  458. }
  459. static inline void tcp_push(struct sock *sk, int flags, int mss_now,
  460. int nonagle)
  461. {
  462. struct tcp_sock *tp = tcp_sk(sk);
  463. if (sk->sk_send_head) {
  464. struct sk_buff *skb = sk->sk_write_queue.prev;
  465. if (!(flags & MSG_MORE) || forced_push(tp))
  466. tcp_mark_push(tp, skb);
  467. tcp_mark_urg(tp, flags, skb);
  468. __tcp_push_pending_frames(sk, mss_now, (flags & MSG_MORE) ? TCP_NAGLE_CORK : nonagle);
  469. }
  470. }
  471. struct sk_buff *sk_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp)
  472. {
  473. struct sk_buff *skb;
  474. /* The TCP header must be at least 32-bit aligned. */
  475. size = ALIGN(size, 4);
  476. skb = alloc_skb_fclone(size + sk->sk_prot->max_header, gfp);
  477. if (skb) {
  478. if (sk_stream_wmem_schedule(sk, skb->truesize)) {
  479. skb_reserve(skb, sk->sk_prot->max_header);
  480. /*
  481. * Make sure that we have exactly size bytes
  482. * available to the caller, no more, no less.
  483. */
  484. skb->avail_size = size;
  485. return skb;
  486. }
  487. __kfree_skb(skb);
  488. } else {
  489. sk->sk_prot->enter_memory_pressure();
  490. sk_stream_moderate_sndbuf(sk);
  491. }
  492. return NULL;
  493. }
  494. static ssize_t do_tcp_sendpages(struct sock *sk, struct page *page, int offset,
  495. size_t size, int flags)
  496. {
  497. struct tcp_sock *tp = tcp_sk(sk);
  498. int mss_now, size_goal;
  499. int err;
  500. ssize_t copied;
  501. long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
  502. /* Wait for a connection to finish. */
  503. if ((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT))
  504. if ((err = sk_stream_wait_connect(sk, &timeo)) != 0)
  505. goto out_err;
  506. clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
  507. mss_now = tcp_current_mss(sk, !(flags&MSG_OOB));
  508. size_goal = tp->xmit_size_goal;
  509. copied = 0;
  510. err = -EPIPE;
  511. if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
  512. goto do_error;
  513. while (size > 0) {
  514. struct sk_buff *skb = sk->sk_write_queue.prev;
  515. int copy, i, can_coalesce;
  516. if (!sk->sk_send_head || (copy = size_goal - skb->len) <= 0) {
  517. new_segment:
  518. if (!sk_stream_memory_free(sk))
  519. goto wait_for_sndbuf;
  520. skb = sk_stream_alloc_skb(sk, 0, sk->sk_allocation);
  521. if (!skb)
  522. goto wait_for_memory;
  523. skb_entail(sk, skb);
  524. copy = size_goal;
  525. }
  526. if (copy > size)
  527. copy = size;
  528. i = skb_shinfo(skb)->nr_frags;
  529. can_coalesce = skb_can_coalesce(skb, i, page, offset);
  530. if (!can_coalesce && i >= MAX_SKB_FRAGS) {
  531. tcp_mark_push(tp, skb);
  532. goto new_segment;
  533. }
  534. if (!sk_stream_wmem_schedule(sk, copy))
  535. goto wait_for_memory;
  536. if (can_coalesce) {
  537. skb_shinfo(skb)->frags[i - 1].size += copy;
  538. } else {
  539. get_page(page);
  540. skb_fill_page_desc(skb, i, page, offset, copy);
  541. }
  542. skb->len += copy;
  543. skb->data_len += copy;
  544. skb->truesize += copy;
  545. sk->sk_wmem_queued += copy;
  546. sk->sk_forward_alloc -= copy;
  547. skb->ip_summed = CHECKSUM_PARTIAL;
  548. tp->write_seq += copy;
  549. TCP_SKB_CB(skb)->end_seq += copy;
  550. skb_shinfo(skb)->gso_segs = 0;
  551. if (!copied)
  552. TCP_SKB_CB(skb)->flags &= ~TCPHDR_PSH;
  553. copied += copy;
  554. offset += copy;
  555. if (!(size -= copy))
  556. goto out;
  557. if (skb->len < size_goal || (flags & MSG_OOB))
  558. continue;
  559. if (forced_push(tp)) {
  560. tcp_mark_push(tp, skb);
  561. __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
  562. } else if (skb == sk->sk_send_head)
  563. tcp_push_one(sk, mss_now);
  564. continue;
  565. wait_for_sndbuf:
  566. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  567. wait_for_memory:
  568. tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH);
  569. if ((err = sk_stream_wait_memory(sk, &timeo)) != 0)
  570. goto do_error;
  571. mss_now = tcp_current_mss(sk, !(flags&MSG_OOB));
  572. size_goal = tp->xmit_size_goal;
  573. }
  574. out:
  575. if (copied)
  576. tcp_push(sk, flags, mss_now, tp->nonagle);
  577. return copied;
  578. do_error:
  579. if (copied)
  580. goto out;
  581. out_err:
  582. return sk_stream_error(sk, flags, err);
  583. }
  584. ssize_t tcp_sendpage(struct socket *sock, struct page *page, int offset,
  585. size_t size, int flags)
  586. {
  587. ssize_t res;
  588. struct sock *sk = sock->sk;
  589. if (!(sk->sk_route_caps & NETIF_F_SG) ||
  590. !(sk->sk_route_caps & NETIF_F_ALL_CSUM))
  591. return sock_no_sendpage(sock, page, offset, size, flags);
  592. lock_sock(sk);
  593. res = do_tcp_sendpages(sk, page, offset, size, flags);
  594. release_sock(sk);
  595. return res;
  596. }
  597. static inline int select_size(struct sock *sk, bool sg)
  598. {
  599. struct tcp_sock *tp = tcp_sk(sk);
  600. int tmp = tp->mss_cache;
  601. if (sg) {
  602. if (sk_can_gso(sk)) {
  603. /* Small frames wont use a full page:
  604. * Payload will immediately follow tcp header.
  605. */
  606. tmp = SKB_WITH_OVERHEAD(2048 - MAX_TCP_HEADER);
  607. } else {
  608. int pgbreak = SKB_MAX_HEAD(MAX_TCP_HEADER);
  609. if (tmp >= pgbreak &&
  610. tmp <= pgbreak + (MAX_SKB_FRAGS - 1) * PAGE_SIZE)
  611. tmp = pgbreak;
  612. }
  613. }
  614. return tmp;
  615. }
  616. int tcp_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
  617. size_t size)
  618. {
  619. struct sock *sk = sock->sk;
  620. struct iovec *iov;
  621. struct tcp_sock *tp = tcp_sk(sk);
  622. struct sk_buff *skb;
  623. int iovlen, flags, err, copied;
  624. int mss_now, size_goal;
  625. bool sg;
  626. long timeo;
  627. lock_sock(sk);
  628. flags = msg->msg_flags;
  629. timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
  630. /* Wait for a connection to finish. */
  631. if ((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT))
  632. if ((err = sk_stream_wait_connect(sk, &timeo)) != 0)
  633. goto out_err;
  634. /* This should be in poll */
  635. clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
  636. mss_now = tcp_current_mss(sk, !(flags&MSG_OOB));
  637. size_goal = tp->xmit_size_goal;
  638. /* Ok commence sending. */
  639. iovlen = msg->msg_iovlen;
  640. iov = msg->msg_iov;
  641. copied = 0;
  642. err = -EPIPE;
  643. if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
  644. goto do_error;
  645. sg = !!(sk->sk_route_caps & NETIF_F_SG);
  646. while (--iovlen >= 0) {
  647. int seglen = iov->iov_len;
  648. unsigned char __user *from = iov->iov_base;
  649. iov++;
  650. while (seglen > 0) {
  651. int copy;
  652. skb = sk->sk_write_queue.prev;
  653. if (!sk->sk_send_head ||
  654. (copy = size_goal - skb->len) <= 0) {
  655. new_segment:
  656. /* Allocate new segment. If the interface is SG,
  657. * allocate skb fitting to single page.
  658. */
  659. if (!sk_stream_memory_free(sk))
  660. goto wait_for_sndbuf;
  661. skb = sk_stream_alloc_skb(sk,
  662. select_size(sk, sg),
  663. sk->sk_allocation);
  664. if (!skb)
  665. goto wait_for_memory;
  666. /*
  667. * Check whether we can use HW checksum.
  668. */
  669. if (sk->sk_route_caps & NETIF_F_ALL_CSUM)
  670. skb->ip_summed = CHECKSUM_PARTIAL;
  671. skb_entail(sk, skb);
  672. copy = size_goal;
  673. }
  674. /* Try to append data to the end of skb. */
  675. if (copy > seglen)
  676. copy = seglen;
  677. /* Where to copy to? */
  678. if (skb_availroom(skb) > 0) {
  679. /* We have some space in skb head. Superb! */
  680. copy = min_t(int, copy, skb_availroom(skb));
  681. if ((err = skb_add_data(skb, from, copy)) != 0)
  682. goto do_fault;
  683. } else {
  684. int merge = 0;
  685. int i = skb_shinfo(skb)->nr_frags;
  686. struct page *page = sk->sk_sndmsg_page;
  687. int off;
  688. if (page && page_count(page) == 1)
  689. sk->sk_sndmsg_off = 0;
  690. off = sk->sk_sndmsg_off;
  691. if (skb_can_coalesce(skb, i, page, off) &&
  692. off != PAGE_SIZE) {
  693. /* We can extend the last page
  694. * fragment. */
  695. merge = 1;
  696. } else if (i == MAX_SKB_FRAGS || !sg) {
  697. /* Need to add new fragment and cannot
  698. * do this because interface is non-SG,
  699. * or because all the page slots are
  700. * busy. */
  701. tcp_mark_push(tp, skb);
  702. goto new_segment;
  703. } else if (page) {
  704. if (off == PAGE_SIZE) {
  705. put_page(page);
  706. sk->sk_sndmsg_page = page = NULL;
  707. off = 0;
  708. }
  709. } else
  710. off = 0;
  711. if (copy > PAGE_SIZE - off)
  712. copy = PAGE_SIZE - off;
  713. if (!sk_stream_wmem_schedule(sk, copy))
  714. goto wait_for_memory;
  715. if (!page) {
  716. /* Allocate new cache page. */
  717. if (!(page = sk_stream_alloc_page(sk)))
  718. goto wait_for_memory;
  719. }
  720. /* Time to copy data. We are close to
  721. * the end! */
  722. err = skb_copy_to_page(sk, from, skb, page,
  723. off, copy);
  724. if (err) {
  725. /* If this page was new, give it to the
  726. * socket so it does not get leaked.
  727. */
  728. if (!sk->sk_sndmsg_page) {
  729. sk->sk_sndmsg_page = page;
  730. sk->sk_sndmsg_off = 0;
  731. }
  732. goto do_error;
  733. }
  734. /* Update the skb. */
  735. if (merge) {
  736. skb_shinfo(skb)->frags[i - 1].size +=
  737. copy;
  738. } else {
  739. skb_fill_page_desc(skb, i, page, off, copy);
  740. if (sk->sk_sndmsg_page) {
  741. get_page(page);
  742. } else if (off + copy < PAGE_SIZE) {
  743. get_page(page);
  744. sk->sk_sndmsg_page = page;
  745. }
  746. }
  747. sk->sk_sndmsg_off = off + copy;
  748. }
  749. if (!copied)
  750. TCP_SKB_CB(skb)->flags &= ~TCPHDR_PSH;
  751. tp->write_seq += copy;
  752. TCP_SKB_CB(skb)->end_seq += copy;
  753. skb_shinfo(skb)->gso_segs = 0;
  754. from += copy;
  755. copied += copy;
  756. if ((seglen -= copy) == 0 && iovlen == 0)
  757. goto out;
  758. if (skb->len < size_goal || (flags & MSG_OOB))
  759. continue;
  760. if (forced_push(tp)) {
  761. tcp_mark_push(tp, skb);
  762. __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
  763. } else if (skb == sk->sk_send_head)
  764. tcp_push_one(sk, mss_now);
  765. continue;
  766. wait_for_sndbuf:
  767. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  768. wait_for_memory:
  769. if (copied)
  770. tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH);
  771. if ((err = sk_stream_wait_memory(sk, &timeo)) != 0)
  772. goto do_error;
  773. mss_now = tcp_current_mss(sk, !(flags&MSG_OOB));
  774. size_goal = tp->xmit_size_goal;
  775. }
  776. }
  777. out:
  778. if (copied)
  779. tcp_push(sk, flags, mss_now, tp->nonagle);
  780. release_sock(sk);
  781. return copied;
  782. do_fault:
  783. if (!skb->len) {
  784. if (sk->sk_send_head == skb)
  785. sk->sk_send_head = NULL;
  786. __skb_unlink(skb, &sk->sk_write_queue);
  787. sk_stream_free_skb(sk, skb);
  788. }
  789. do_error:
  790. if (copied)
  791. goto out;
  792. out_err:
  793. err = sk_stream_error(sk, flags, err);
  794. release_sock(sk);
  795. return err;
  796. }
  797. /*
  798. * Handle reading urgent data. BSD has very simple semantics for
  799. * this, no blocking and very strange errors 8)
  800. */
  801. static int tcp_recv_urg(struct sock *sk, long timeo,
  802. struct msghdr *msg, int len, int flags,
  803. int *addr_len)
  804. {
  805. struct tcp_sock *tp = tcp_sk(sk);
  806. /* No URG data to read. */
  807. if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data ||
  808. tp->urg_data == TCP_URG_READ)
  809. return -EINVAL; /* Yes this is right ! */
  810. if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE))
  811. return -ENOTCONN;
  812. if (tp->urg_data & TCP_URG_VALID) {
  813. int err = 0;
  814. char c = tp->urg_data;
  815. if (!(flags & MSG_PEEK))
  816. tp->urg_data = TCP_URG_READ;
  817. /* Read urgent data. */
  818. msg->msg_flags |= MSG_OOB;
  819. if (len > 0) {
  820. if (!(flags & MSG_TRUNC))
  821. err = memcpy_toiovec(msg->msg_iov, &c, 1);
  822. len = 1;
  823. } else
  824. msg->msg_flags |= MSG_TRUNC;
  825. return err ? -EFAULT : len;
  826. }
  827. if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN))
  828. return 0;
  829. /* Fixed the recv(..., MSG_OOB) behaviour. BSD docs and
  830. * the available implementations agree in this case:
  831. * this call should never block, independent of the
  832. * blocking state of the socket.
  833. * Mike <pall@rz.uni-karlsruhe.de>
  834. */
  835. return -EAGAIN;
  836. }
  837. /* Clean up the receive buffer for full frames taken by the user,
  838. * then send an ACK if necessary. COPIED is the number of bytes
  839. * tcp_recvmsg has given to the user so far, it speeds up the
  840. * calculation of whether or not we must ACK for the sake of
  841. * a window update.
  842. */
  843. void tcp_cleanup_rbuf(struct sock *sk, int copied)
  844. {
  845. struct tcp_sock *tp = tcp_sk(sk);
  846. int time_to_ack = 0;
  847. struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
  848. WARN_ON(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq));
  849. if (inet_csk_ack_scheduled(sk)) {
  850. const struct inet_connection_sock *icsk = inet_csk(sk);
  851. /* Delayed ACKs frequently hit locked sockets during bulk
  852. * receive. */
  853. if (icsk->icsk_ack.blocked ||
  854. /* Once-per-two-segments ACK was not sent by tcp_input.c */
  855. tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss ||
  856. /*
  857. * If this read emptied read buffer, we send ACK, if
  858. * connection is not bidirectional, user drained
  859. * receive buffer and there was a small segment
  860. * in queue.
  861. */
  862. (copied > 0 &&
  863. ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) ||
  864. ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) &&
  865. !icsk->icsk_ack.pingpong)) &&
  866. !atomic_read(&sk->sk_rmem_alloc)))
  867. time_to_ack = 1;
  868. }
  869. /* We send an ACK if we can now advertise a non-zero window
  870. * which has been raised "significantly".
  871. *
  872. * Even if window raised up to infinity, do not send window open ACK
  873. * in states, where we will not receive more. It is useless.
  874. */
  875. if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
  876. __u32 rcv_window_now = tcp_receive_window(tp);
  877. /* Optimize, __tcp_select_window() is not cheap. */
  878. if (2*rcv_window_now <= tp->window_clamp) {
  879. __u32 new_window = __tcp_select_window(sk);
  880. /* Send ACK now, if this read freed lots of space
  881. * in our buffer. Certainly, new_window is new window.
  882. * We can advertise it now, if it is not less than current one.
  883. * "Lots" means "at least twice" here.
  884. */
  885. if (new_window && new_window >= 2 * rcv_window_now)
  886. time_to_ack = 1;
  887. }
  888. }
  889. if (time_to_ack)
  890. tcp_send_ack(sk);
  891. }
  892. static void tcp_prequeue_process(struct sock *sk)
  893. {
  894. struct sk_buff *skb;
  895. struct tcp_sock *tp = tcp_sk(sk);
  896. NET_INC_STATS_USER(LINUX_MIB_TCPPREQUEUED);
  897. /* RX process wants to run with disabled BHs, though it is not
  898. * necessary */
  899. local_bh_disable();
  900. while ((skb = __skb_dequeue(&tp->ucopy.prequeue)) != NULL)
  901. sk->sk_backlog_rcv(sk, skb);
  902. local_bh_enable();
  903. /* Clear memory counter. */
  904. tp->ucopy.memory = 0;
  905. }
  906. static struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off)
  907. {
  908. struct sk_buff *skb;
  909. u32 offset;
  910. while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) {
  911. offset = seq - TCP_SKB_CB(skb)->seq;
  912. if (skb->h.th->syn)
  913. offset--;
  914. if (offset < skb->len || skb->h.th->fin) {
  915. *off = offset;
  916. return skb;
  917. }
  918. /* This looks weird, but this can happen if TCP collapsing
  919. * splitted a fat GRO packet, while we released socket lock
  920. * in skb_splice_bits()
  921. */
  922. sk_eat_skb(sk, skb, false);
  923. }
  924. return NULL;
  925. }
  926. /*
  927. * This routine provides an alternative to tcp_recvmsg() for routines
  928. * that would like to handle copying from skbuffs directly in 'sendfile'
  929. * fashion.
  930. * Note:
  931. * - It is assumed that the socket was locked by the caller.
  932. * - The routine does not block.
  933. * - At present, there is no support for reading OOB data
  934. * or for 'peeking' the socket using this routine
  935. * (although both would be easy to implement).
  936. */
  937. int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
  938. sk_read_actor_t recv_actor)
  939. {
  940. struct sk_buff *skb;
  941. struct tcp_sock *tp = tcp_sk(sk);
  942. u32 seq = tp->copied_seq;
  943. u32 offset;
  944. int copied = 0;
  945. if (sk->sk_state == TCP_LISTEN)
  946. return -ENOTCONN;
  947. while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
  948. if (offset < skb->len) {
  949. int used;
  950. size_t len;
  951. len = skb->len - offset;
  952. /* Stop reading if we hit a patch of urgent data */
  953. if (tp->urg_data) {
  954. u32 urg_offset = tp->urg_seq - seq;
  955. if (urg_offset < len)
  956. len = urg_offset;
  957. if (!len)
  958. break;
  959. }
  960. used = recv_actor(desc, skb, offset, len);
  961. if (used <= 0) {
  962. if (!copied)
  963. copied = used;
  964. break;
  965. } else if (used <= len) {
  966. seq += used;
  967. copied += used;
  968. offset += used;
  969. }
  970. if (offset != skb->len)
  971. break;
  972. }
  973. if (skb->h.th->fin) {
  974. sk_eat_skb(sk, skb, 0);
  975. ++seq;
  976. break;
  977. }
  978. sk_eat_skb(sk, skb, 0);
  979. if (!desc->count)
  980. break;
  981. tp->copied_seq = seq;
  982. }
  983. tp->copied_seq = seq;
  984. tcp_rcv_space_adjust(sk);
  985. /* Clean up data we have read: This will do ACK frames. */
  986. if (copied > 0) {
  987. tcp_recv_skb(sk, seq, &offset);
  988. tcp_cleanup_rbuf(sk, copied);
  989. }
  990. return copied;
  991. }
  992. /*
  993. * This routine copies from a sock struct into the user buffer.
  994. *
  995. * Technical note: in 2.3 we work on _locked_ socket, so that
  996. * tricks with *seq access order and skb->users are not required.
  997. * Probably, code can be easily improved even more.
  998. */
  999. int tcp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
  1000. size_t len, int nonblock, int flags, int *addr_len)
  1001. {
  1002. struct tcp_sock *tp = tcp_sk(sk);
  1003. int copied = 0;
  1004. u32 peek_seq;
  1005. u32 *seq;
  1006. unsigned long used;
  1007. int err;
  1008. int target; /* Read at least this many bytes */
  1009. long timeo;
  1010. struct task_struct *user_recv = NULL;
  1011. int copied_early = 0;
  1012. u32 urg_hole = 0;
  1013. lock_sock(sk);
  1014. err = -ENOTCONN;
  1015. if (sk->sk_state == TCP_LISTEN)
  1016. goto out;
  1017. timeo = sock_rcvtimeo(sk, nonblock);
  1018. /* Urgent data needs to be handled specially. */
  1019. if (flags & MSG_OOB)
  1020. goto recv_urg;
  1021. seq = &tp->copied_seq;
  1022. if (flags & MSG_PEEK) {
  1023. peek_seq = tp->copied_seq;
  1024. seq = &peek_seq;
  1025. }
  1026. target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
  1027. #ifdef CONFIG_NET_DMA
  1028. tp->ucopy.dma_chan = NULL;
  1029. preempt_disable();
  1030. if ((len > sysctl_tcp_dma_copybreak) && !(flags & MSG_PEEK) &&
  1031. !sysctl_tcp_low_latency && __get_cpu_var(softnet_data).net_dma) {
  1032. preempt_enable_no_resched();
  1033. tp->ucopy.pinned_list = dma_pin_iovec_pages(msg->msg_iov, len);
  1034. } else
  1035. preempt_enable_no_resched();
  1036. #endif
  1037. do {
  1038. struct sk_buff *skb;
  1039. u32 offset;
  1040. /* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */
  1041. if (tp->urg_data && tp->urg_seq == *seq) {
  1042. if (copied)
  1043. break;
  1044. if (signal_pending(current)) {
  1045. copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
  1046. break;
  1047. }
  1048. }
  1049. /* Next get a buffer. */
  1050. skb = skb_peek(&sk->sk_receive_queue);
  1051. do {
  1052. if (!skb)
  1053. break;
  1054. /* Now that we have two receive queues this
  1055. * shouldn't happen.
  1056. */
  1057. if (before(*seq, TCP_SKB_CB(skb)->seq)) {
  1058. printk(KERN_INFO "recvmsg bug: copied %X "
  1059. "seq %X\n", *seq, TCP_SKB_CB(skb)->seq);
  1060. break;
  1061. }
  1062. offset = *seq - TCP_SKB_CB(skb)->seq;
  1063. if (skb->h.th->syn)
  1064. offset--;
  1065. if (offset < skb->len)
  1066. goto found_ok_skb;
  1067. if (skb->h.th->fin)
  1068. goto found_fin_ok;
  1069. WARN_ON(!(flags & MSG_PEEK));
  1070. skb = skb->next;
  1071. } while (skb != (struct sk_buff *)&sk->sk_receive_queue);
  1072. /* Well, if we have backlog, try to process it now yet. */
  1073. if (copied >= target && !sk->sk_backlog.tail)
  1074. break;
  1075. if (copied) {
  1076. if (sk->sk_err ||
  1077. sk->sk_state == TCP_CLOSE ||
  1078. (sk->sk_shutdown & RCV_SHUTDOWN) ||
  1079. !timeo ||
  1080. signal_pending(current))
  1081. break;
  1082. } else {
  1083. if (sock_flag(sk, SOCK_DONE))
  1084. break;
  1085. if (sk->sk_err) {
  1086. copied = sock_error(sk);
  1087. break;
  1088. }
  1089. if (sk->sk_shutdown & RCV_SHUTDOWN)
  1090. break;
  1091. if (sk->sk_state == TCP_CLOSE) {
  1092. if (!sock_flag(sk, SOCK_DONE)) {
  1093. /* This occurs when user tries to read
  1094. * from never connected socket.
  1095. */
  1096. copied = -ENOTCONN;
  1097. break;
  1098. }
  1099. break;
  1100. }
  1101. if (!timeo) {
  1102. copied = -EAGAIN;
  1103. break;
  1104. }
  1105. if (signal_pending(current)) {
  1106. copied = sock_intr_errno(timeo);
  1107. break;
  1108. }
  1109. }
  1110. tcp_cleanup_rbuf(sk, copied);
  1111. if (!sysctl_tcp_low_latency && tp->ucopy.task == user_recv) {
  1112. /* Install new reader */
  1113. if (!user_recv && !(flags & (MSG_TRUNC | MSG_PEEK))) {
  1114. user_recv = current;
  1115. tp->ucopy.task = user_recv;
  1116. tp->ucopy.iov = msg->msg_iov;
  1117. }
  1118. tp->ucopy.len = len;
  1119. WARN_ON(tp->copied_seq != tp->rcv_nxt &&
  1120. !(flags & (MSG_PEEK | MSG_TRUNC)));
  1121. /* Ugly... If prequeue is not empty, we have to
  1122. * process it before releasing socket, otherwise
  1123. * order will be broken at second iteration.
  1124. * More elegant solution is required!!!
  1125. *
  1126. * Look: we have the following (pseudo)queues:
  1127. *
  1128. * 1. packets in flight
  1129. * 2. backlog
  1130. * 3. prequeue
  1131. * 4. receive_queue
  1132. *
  1133. * Each queue can be processed only if the next ones
  1134. * are empty. At this point we have empty receive_queue.
  1135. * But prequeue _can_ be not empty after 2nd iteration,
  1136. * when we jumped to start of loop because backlog
  1137. * processing added something to receive_queue.
  1138. * We cannot release_sock(), because backlog contains
  1139. * packets arrived _after_ prequeued ones.
  1140. *
  1141. * Shortly, algorithm is clear --- to process all
  1142. * the queues in order. We could make it more directly,
  1143. * requeueing packets from backlog to prequeue, if
  1144. * is not empty. It is more elegant, but eats cycles,
  1145. * unfortunately.
  1146. */
  1147. if (!skb_queue_empty(&tp->ucopy.prequeue))
  1148. goto do_prequeue;
  1149. /* __ Set realtime policy in scheduler __ */
  1150. }
  1151. if (copied >= target) {
  1152. /* Do not sleep, just process backlog. */
  1153. release_sock(sk);
  1154. lock_sock(sk);
  1155. } else
  1156. sk_wait_data(sk, &timeo);
  1157. #ifdef CONFIG_NET_DMA
  1158. tp->ucopy.wakeup = 0;
  1159. #endif
  1160. if (user_recv) {
  1161. int chunk;
  1162. /* __ Restore normal policy in scheduler __ */
  1163. if ((chunk = len - tp->ucopy.len) != 0) {
  1164. NET_ADD_STATS_USER(LINUX_MIB_TCPDIRECTCOPYFROMBACKLOG, chunk);
  1165. len -= chunk;
  1166. copied += chunk;
  1167. }
  1168. if (tp->rcv_nxt == tp->copied_seq &&
  1169. !skb_queue_empty(&tp->ucopy.prequeue)) {
  1170. do_prequeue:
  1171. tcp_prequeue_process(sk);
  1172. if ((chunk = len - tp->ucopy.len) != 0) {
  1173. NET_ADD_STATS_USER(LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
  1174. len -= chunk;
  1175. copied += chunk;
  1176. }
  1177. }
  1178. }
  1179. if ((flags & MSG_PEEK) &&
  1180. (peek_seq - copied - urg_hole != tp->copied_seq)) {
  1181. if (net_ratelimit())
  1182. printk(KERN_DEBUG "TCP(%s:%d): Application bug, race in MSG_PEEK.\n",
  1183. current->comm, current->pid);
  1184. peek_seq = tp->copied_seq;
  1185. }
  1186. continue;
  1187. found_ok_skb:
  1188. /* Ok so how much can we use? */
  1189. used = skb->len - offset;
  1190. if (len < used)
  1191. used = len;
  1192. /* Do we have urgent data here? */
  1193. if (tp->urg_data) {
  1194. u32 urg_offset = tp->urg_seq - *seq;
  1195. if (urg_offset < used) {
  1196. if (!urg_offset) {
  1197. if (!sock_flag(sk, SOCK_URGINLINE)) {
  1198. ++*seq;
  1199. urg_hole++;
  1200. offset++;
  1201. used--;
  1202. if (!used)
  1203. goto skip_copy;
  1204. }
  1205. } else
  1206. used = urg_offset;
  1207. }
  1208. }
  1209. if (!(flags & MSG_TRUNC)) {
  1210. #ifdef CONFIG_NET_DMA
  1211. if (!tp->ucopy.dma_chan && tp->ucopy.pinned_list)
  1212. tp->ucopy.dma_chan = get_softnet_dma();
  1213. if (tp->ucopy.dma_chan) {
  1214. tp->ucopy.dma_cookie = dma_skb_copy_datagram_iovec(
  1215. tp->ucopy.dma_chan, skb, offset,
  1216. msg->msg_iov, used,
  1217. tp->ucopy.pinned_list);
  1218. if (tp->ucopy.dma_cookie < 0) {
  1219. printk(KERN_ALERT "dma_cookie < 0\n");
  1220. /* Exception. Bailout! */
  1221. if (!copied)
  1222. copied = -EFAULT;
  1223. break;
  1224. }
  1225. if ((offset + used) == skb->len)
  1226. copied_early = 1;
  1227. } else
  1228. #endif
  1229. {
  1230. err = skb_copy_datagram_iovec(skb, offset,
  1231. msg->msg_iov, used);
  1232. if (err) {
  1233. /* Exception. Bailout! */
  1234. if (!copied)
  1235. copied = -EFAULT;
  1236. break;
  1237. }
  1238. }
  1239. }
  1240. *seq += used;
  1241. copied += used;
  1242. len -= used;
  1243. tcp_rcv_space_adjust(sk);
  1244. skip_copy:
  1245. if (tp->urg_data && after(tp->copied_seq, tp->urg_seq)) {
  1246. tp->urg_data = 0;
  1247. tcp_fast_path_check(sk);
  1248. }
  1249. if (used + offset < skb->len)
  1250. continue;
  1251. if (skb->h.th->fin)
  1252. goto found_fin_ok;
  1253. if (!(flags & MSG_PEEK)) {
  1254. sk_eat_skb(sk, skb, copied_early);
  1255. copied_early = 0;
  1256. }
  1257. continue;
  1258. found_fin_ok:
  1259. /* Process the FIN. */
  1260. ++*seq;
  1261. if (!(flags & MSG_PEEK)) {
  1262. sk_eat_skb(sk, skb, copied_early);
  1263. copied_early = 0;
  1264. }
  1265. break;
  1266. } while (len > 0);
  1267. if (user_recv) {
  1268. if (!skb_queue_empty(&tp->ucopy.prequeue)) {
  1269. int chunk;
  1270. tp->ucopy.len = copied > 0 ? len : 0;
  1271. tcp_prequeue_process(sk);
  1272. if (copied > 0 && (chunk = len - tp->ucopy.len) != 0) {
  1273. NET_ADD_STATS_USER(LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
  1274. len -= chunk;
  1275. copied += chunk;
  1276. }
  1277. }
  1278. tp->ucopy.task = NULL;
  1279. tp->ucopy.len = 0;
  1280. }
  1281. #ifdef CONFIG_NET_DMA
  1282. if (tp->ucopy.dma_chan) {
  1283. struct sk_buff *skb;
  1284. dma_cookie_t done, used;
  1285. dma_async_memcpy_issue_pending(tp->ucopy.dma_chan);
  1286. while (dma_async_memcpy_complete(tp->ucopy.dma_chan,
  1287. tp->ucopy.dma_cookie, &done,
  1288. &used) == DMA_IN_PROGRESS) {
  1289. /* do partial cleanup of sk_async_wait_queue */
  1290. while ((skb = skb_peek(&sk->sk_async_wait_queue)) &&
  1291. (dma_async_is_complete(skb->dma_cookie, done,
  1292. used) == DMA_SUCCESS)) {
  1293. __skb_dequeue(&sk->sk_async_wait_queue);
  1294. kfree_skb(skb);
  1295. }
  1296. }
  1297. /* Safe to free early-copied skbs now */
  1298. __skb_queue_purge(&sk->sk_async_wait_queue);
  1299. dma_chan_put(tp->ucopy.dma_chan);
  1300. tp->ucopy.dma_chan = NULL;
  1301. }
  1302. if (tp->ucopy.pinned_list) {
  1303. dma_unpin_iovec_pages(tp->ucopy.pinned_list);
  1304. tp->ucopy.pinned_list = NULL;
  1305. }
  1306. #endif
  1307. /* According to UNIX98, msg_name/msg_namelen are ignored
  1308. * on connected socket. I was just happy when found this 8) --ANK
  1309. */
  1310. /* Clean up data we have read: This will do ACK frames. */
  1311. tcp_cleanup_rbuf(sk, copied);
  1312. release_sock(sk);
  1313. return copied;
  1314. out:
  1315. release_sock(sk);
  1316. return err;
  1317. recv_urg:
  1318. err = tcp_recv_urg(sk, timeo, msg, len, flags, addr_len);
  1319. goto out;
  1320. }
  1321. void tcp_set_state(struct sock *sk, int state)
  1322. {
  1323. int oldstate = sk->sk_state;
  1324. switch (state) {
  1325. case TCP_ESTABLISHED:
  1326. if (oldstate != TCP_ESTABLISHED)
  1327. TCP_INC_STATS(TCP_MIB_CURRESTAB);
  1328. break;
  1329. case TCP_CLOSE:
  1330. if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED)
  1331. TCP_INC_STATS(TCP_MIB_ESTABRESETS);
  1332. sk->sk_prot->unhash(sk);
  1333. if (inet_csk(sk)->icsk_bind_hash &&
  1334. !(sk->sk_userlocks & SOCK_BINDPORT_LOCK))
  1335. inet_put_port(sk);
  1336. /* fall through */
  1337. default:
  1338. if (oldstate==TCP_ESTABLISHED)
  1339. TCP_DEC_STATS(TCP_MIB_CURRESTAB);
  1340. }
  1341. /* Change state AFTER socket is unhashed to avoid closed
  1342. * socket sitting in hash tables.
  1343. */
  1344. sk->sk_state = state;
  1345. #ifdef STATE_TRACE
  1346. SOCK_DEBUG(sk, "TCP sk=%p, State %s -> %s\n",sk, statename[oldstate],statename[state]);
  1347. #endif
  1348. }
  1349. EXPORT_SYMBOL_GPL(tcp_set_state);
  1350. /*
  1351. * State processing on a close. This implements the state shift for
  1352. * sending our FIN frame. Note that we only send a FIN for some
  1353. * states. A shutdown() may have already sent the FIN, or we may be
  1354. * closed.
  1355. */
  1356. static const unsigned char new_state[16] = {
  1357. /* current state: new state: action: */
  1358. /* (Invalid) */ TCP_CLOSE,
  1359. /* TCP_ESTABLISHED */ TCP_FIN_WAIT1 | TCP_ACTION_FIN,
  1360. /* TCP_SYN_SENT */ TCP_CLOSE,
  1361. /* TCP_SYN_RECV */ TCP_FIN_WAIT1 | TCP_ACTION_FIN,
  1362. /* TCP_FIN_WAIT1 */ TCP_FIN_WAIT1,
  1363. /* TCP_FIN_WAIT2 */ TCP_FIN_WAIT2,
  1364. /* TCP_TIME_WAIT */ TCP_CLOSE,
  1365. /* TCP_CLOSE */ TCP_CLOSE,
  1366. /* TCP_CLOSE_WAIT */ TCP_LAST_ACK | TCP_ACTION_FIN,
  1367. /* TCP_LAST_ACK */ TCP_LAST_ACK,
  1368. /* TCP_LISTEN */ TCP_CLOSE,
  1369. /* TCP_CLOSING */ TCP_CLOSING,
  1370. };
  1371. static int tcp_close_state(struct sock *sk)
  1372. {
  1373. int next = (int)new_state[sk->sk_state];
  1374. int ns = next & TCP_STATE_MASK;
  1375. tcp_set_state(sk, ns);
  1376. return next & TCP_ACTION_FIN;
  1377. }
  1378. /*
  1379. * Shutdown the sending side of a connection. Much like close except
  1380. * that we don't receive shut down or set_sock_flag(sk, SOCK_DEAD).
  1381. */
  1382. void tcp_shutdown(struct sock *sk, int how)
  1383. {
  1384. /* We need to grab some memory, and put together a FIN,
  1385. * and then put it into the queue to be sent.
  1386. * Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92.
  1387. */
  1388. if (!(how & SEND_SHUTDOWN))
  1389. return;
  1390. /* If we've already sent a FIN, or it's a closed state, skip this. */
  1391. if ((1 << sk->sk_state) &
  1392. (TCPF_ESTABLISHED | TCPF_SYN_SENT |
  1393. TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) {
  1394. /* Clear out any half completed packets. FIN if needed. */
  1395. if (tcp_close_state(sk))
  1396. tcp_send_fin(sk);
  1397. }
  1398. }
  1399. void tcp_close(struct sock *sk, long timeout)
  1400. {
  1401. struct sk_buff *skb;
  1402. int data_was_unread = 0;
  1403. int state;
  1404. lock_sock(sk);
  1405. sk->sk_shutdown = SHUTDOWN_MASK;
  1406. if (sk->sk_state == TCP_LISTEN) {
  1407. tcp_set_state(sk, TCP_CLOSE);
  1408. /* Special case. */
  1409. inet_csk_listen_stop(sk);
  1410. goto adjudge_to_death;
  1411. }
  1412. /* We need to flush the recv. buffs. We do this only on the
  1413. * descriptor close, not protocol-sourced closes, because the
  1414. * reader process may not have drained the data yet!
  1415. */
  1416. while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
  1417. u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq -
  1418. skb->h.th->fin;
  1419. data_was_unread += len;
  1420. __kfree_skb(skb);
  1421. }
  1422. sk_stream_mem_reclaim(sk);
  1423. /* If socket has been already reset (e.g. in tcp_reset()) - kill it. */
  1424. if (sk->sk_state == TCP_CLOSE)
  1425. goto adjudge_to_death;
  1426. /* As outlined in draft-ietf-tcpimpl-prob-03.txt, section
  1427. * 3.10, we send a RST here because data was lost. To
  1428. * witness the awful effects of the old behavior of always
  1429. * doing a FIN, run an older 2.1.x kernel or 2.0.x, start
  1430. * a bulk GET in an FTP client, suspend the process, wait
  1431. * for the client to advertise a zero window, then kill -9
  1432. * the FTP client, wheee... Note: timeout is always zero
  1433. * in such a case.
  1434. */
  1435. if (data_was_unread) {
  1436. /* Unread data was tossed, zap the connection. */
  1437. NET_INC_STATS_USER(LINUX_MIB_TCPABORTONCLOSE);
  1438. tcp_set_state(sk, TCP_CLOSE);
  1439. tcp_send_active_reset(sk, sk->sk_allocation);
  1440. } else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
  1441. /* Check zero linger _after_ checking for unread data. */
  1442. sk->sk_prot->disconnect(sk, 0);
  1443. NET_INC_STATS_USER(LINUX_MIB_TCPABORTONDATA);
  1444. } else if (tcp_close_state(sk)) {
  1445. /* We FIN if the application ate all the data before
  1446. * zapping the connection.
  1447. */
  1448. /* RED-PEN. Formally speaking, we have broken TCP state
  1449. * machine. State transitions:
  1450. *
  1451. * TCP_ESTABLISHED -> TCP_FIN_WAIT1
  1452. * TCP_SYN_RECV -> TCP_FIN_WAIT1 (forget it, it's impossible)
  1453. * TCP_CLOSE_WAIT -> TCP_LAST_ACK
  1454. *
  1455. * are legal only when FIN has been sent (i.e. in window),
  1456. * rather than queued out of window. Purists blame.
  1457. *
  1458. * F.e. "RFC state" is ESTABLISHED,
  1459. * if Linux state is FIN-WAIT-1, but FIN is still not sent.
  1460. *
  1461. * The visible declinations are that sometimes
  1462. * we enter time-wait state, when it is not required really
  1463. * (harmless), do not send active resets, when they are
  1464. * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when
  1465. * they look as CLOSING or LAST_ACK for Linux)
  1466. * Probably, I missed some more holelets.
  1467. * --ANK
  1468. */
  1469. tcp_send_fin(sk);
  1470. }
  1471. sk_stream_wait_close(sk, timeout);
  1472. adjudge_to_death:
  1473. state = sk->sk_state;
  1474. sock_hold(sk);
  1475. sock_orphan(sk);
  1476. atomic_inc(sk->sk_prot->orphan_count);
  1477. /* It is the last release_sock in its life. It will remove backlog. */
  1478. release_sock(sk);
  1479. /* Now socket is owned by kernel and we acquire BH lock
  1480. to finish close. No need to check for user refs.
  1481. */
  1482. local_bh_disable();
  1483. bh_lock_sock(sk);
  1484. WARN_ON(sock_owned_by_user(sk));
  1485. /* Have we already been destroyed by a softirq or backlog? */
  1486. if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE)
  1487. goto out;
  1488. /* This is a (useful) BSD violating of the RFC. There is a
  1489. * problem with TCP as specified in that the other end could
  1490. * keep a socket open forever with no application left this end.
  1491. * We use a 3 minute timeout (about the same as BSD) then kill
  1492. * our end. If they send after that then tough - BUT: long enough
  1493. * that we won't make the old 4*rto = almost no time - whoops
  1494. * reset mistake.
  1495. *
  1496. * Nope, it was not mistake. It is really desired behaviour
  1497. * f.e. on http servers, when such sockets are useless, but
  1498. * consume significant resources. Let's do it with special
  1499. * linger2 option. --ANK
  1500. */
  1501. if (sk->sk_state == TCP_FIN_WAIT2) {
  1502. struct tcp_sock *tp = tcp_sk(sk);
  1503. if (tp->linger2 < 0) {
  1504. tcp_set_state(sk, TCP_CLOSE);
  1505. tcp_send_active_reset(sk, GFP_ATOMIC);
  1506. NET_INC_STATS_BH(LINUX_MIB_TCPABORTONLINGER);
  1507. } else {
  1508. const int tmo = tcp_fin_time(sk);
  1509. if (tmo > TCP_TIMEWAIT_LEN) {
  1510. inet_csk_reset_keepalive_timer(sk,
  1511. tmo - TCP_TIMEWAIT_LEN);
  1512. } else {
  1513. tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
  1514. goto out;
  1515. }
  1516. }
  1517. }
  1518. if (sk->sk_state != TCP_CLOSE) {
  1519. sk_stream_mem_reclaim(sk);
  1520. if (atomic_read(sk->sk_prot->orphan_count) > sysctl_tcp_max_orphans ||
  1521. (sk->sk_wmem_queued > SOCK_MIN_SNDBUF &&
  1522. atomic_read(&tcp_memory_allocated) > sysctl_tcp_mem[2])) {
  1523. if (net_ratelimit())
  1524. printk(KERN_INFO "TCP: too many of orphaned "
  1525. "sockets\n");
  1526. tcp_set_state(sk, TCP_CLOSE);
  1527. tcp_send_active_reset(sk, GFP_ATOMIC);
  1528. NET_INC_STATS_BH(LINUX_MIB_TCPABORTONMEMORY);
  1529. }
  1530. }
  1531. if (sk->sk_state == TCP_CLOSE)
  1532. inet_csk_destroy_sock(sk);
  1533. /* Otherwise, socket is reprieved until protocol close. */
  1534. out:
  1535. bh_unlock_sock(sk);
  1536. local_bh_enable();
  1537. sock_put(sk);
  1538. }
  1539. /* These states need RST on ABORT according to RFC793 */
  1540. static inline int tcp_need_reset(int state)
  1541. {
  1542. return (1 << state) &
  1543. (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 |
  1544. TCPF_FIN_WAIT2 | TCPF_SYN_RECV);
  1545. }
  1546. int tcp_disconnect(struct sock *sk, int flags)
  1547. {
  1548. struct inet_sock *inet = inet_sk(sk);
  1549. struct inet_connection_sock *icsk = inet_csk(sk);
  1550. struct tcp_sock *tp = tcp_sk(sk);
  1551. int err = 0;
  1552. int old_state = sk->sk_state;
  1553. if (old_state != TCP_CLOSE)
  1554. tcp_set_state(sk, TCP_CLOSE);
  1555. /* ABORT function of RFC793 */
  1556. if (old_state == TCP_LISTEN) {
  1557. inet_csk_listen_stop(sk);
  1558. } else if (tcp_need_reset(old_state) ||
  1559. (tp->snd_nxt != t

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