PageRenderTime 87ms CodeModel.GetById 39ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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 |
  1624. TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) {
  1625. /* Clear out any half completed packets. FIN if needed. */
  1626. if (tcp_close_state(sk))
  1627. tcp_send_fin(sk);
  1628. }
  1629. }
  1630. EXPORT_SYMBOL(tcp_shutdown);
  1631. void tcp_close(struct sock *sk, long timeout)
  1632. {
  1633. struct sk_buff *skb;
  1634. int data_was_unread = 0;
  1635. int state;
  1636. lock_sock(sk);
  1637. sk->sk_shutdown = SHUTDOWN_MASK;
  1638. if (sk->sk_state == TCP_LISTEN) {
  1639. tcp_set_state(sk, TCP_CLOSE);
  1640. /* Special case. */
  1641. inet_csk_listen_stop(sk);
  1642. goto adjudge_to_death;
  1643. }
  1644. /* We need to flush the recv. buffs. We do this only on the
  1645. * descriptor close, not protocol-sourced closes, because the
  1646. * reader process may not have drained the data yet!
  1647. */
  1648. while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
  1649. u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq -
  1650. tcp_hdr(skb)->fin;
  1651. data_was_unread += len;
  1652. __kfree_skb(skb);
  1653. }
  1654. sk_mem_reclaim(sk);
  1655. /* If socket has been already reset (e.g. in tcp_reset()) - kill it. */
  1656. if (sk->sk_state == TCP_CLOSE)
  1657. goto adjudge_to_death;
  1658. /* As outlined in RFC 2525, section 2.17, we send a RST here because
  1659. * data was lost. To witness the awful effects of the old behavior of
  1660. * always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk
  1661. * GET in an FTP client, suspend the process, wait for the client to
  1662. * advertise a zero window, then kill -9 the FTP client, wheee...
  1663. * Note: timeout is always zero in such a case.
  1664. */
  1665. if (data_was_unread) {
  1666. /* Unread data was tossed, zap the connection. */
  1667. NET_INC_STATS_USER(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE);
  1668. tcp_set_state(sk, TCP_CLOSE);
  1669. tcp_send_active_reset(sk, sk->sk_allocation);
  1670. } else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
  1671. /* Check zero linger _after_ checking for unread data. */
  1672. sk->sk_prot->disconnect(sk, 0);
  1673. NET_INC_STATS_USER(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
  1674. } else if (tcp_close_state(sk)) {
  1675. /* We FIN if the application ate all the data before
  1676. * zapping the connection.
  1677. */
  1678. /* RED-PEN. Formally speaking, we have broken TCP state
  1679. * machine. State transitions:
  1680. *
  1681. * TCP_ESTABLISHED -> TCP_FIN_WAIT1
  1682. * TCP_SYN_RECV -> TCP_FIN_WAIT1 (forget it, it's impossible)
  1683. * TCP_CLOSE_WAIT -> TCP_LAST_ACK
  1684. *
  1685. * are legal only when FIN has been sent (i.e. in window),
  1686. * rather than queued out of window. Purists blame.
  1687. *
  1688. * F.e. "RFC state" is ESTABLISHED,
  1689. * if Linux state is FIN-WAIT-1, but FIN is still not sent.
  1690. *
  1691. * The visible declinations are that sometimes
  1692. * we enter time-wait state, when it is not required really
  1693. * (harmless), do not send active resets, when they are
  1694. * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when
  1695. * they look as CLOSING or LAST_ACK for Linux)
  1696. * Probably, I missed some more holelets.
  1697. * --ANK
  1698. */
  1699. tcp_send_fin(sk);
  1700. }
  1701. sk_stream_wait_close(sk, timeout);
  1702. adjudge_to_death:
  1703. state = sk->sk_state;
  1704. sock_hold(sk);
  1705. sock_orphan(sk);
  1706. /* It is the last release_sock in its life. It will remove backlog. */
  1707. release_sock(sk);
  1708. /* Now socket is owned by kernel and we acquire BH lock
  1709. to finish close. No need to check for user refs.
  1710. */
  1711. local_bh_disable();
  1712. bh_lock_sock(sk);
  1713. WARN_ON(sock_owned_by_user(sk));
  1714. percpu_counter_inc(sk->sk_prot->orphan_count);
  1715. /* Have we already been destroyed by a softirq or backlog? */
  1716. if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE)
  1717. goto out;
  1718. /* This is a (useful) BSD violating of the RFC. There is a
  1719. * problem with TCP as specified in that the other end could
  1720. * keep a socket open forever with no application left this end.
  1721. * We use a 3 minute timeout (about the same as BSD) then kill
  1722. * our end. If they send after that then tough - BUT: long enough
  1723. * that we won't make the old 4*rto = almost no time - whoops
  1724. * reset mistake.
  1725. *
  1726. * Nope, it was not mistake. It is really desired behaviour
  1727. * f.e. on http servers, when such sockets are useless, but
  1728. * consume significant resources. Let's do it with special
  1729. * linger2 option. --ANK
  1730. */
  1731. if (sk->sk_state == TCP_FIN_WAIT2) {
  1732. struct tcp_sock *tp = tcp_sk(sk);
  1733. if (tp->linger2 < 0) {
  1734. tcp_set_state(sk, TCP_CLOSE);
  1735. tcp_send_active_reset(sk, GFP_ATOMIC);
  1736. NET_INC_STATS_BH(sock_net(sk),
  1737. LINUX_MIB_TCPABORTONLINGER);
  1738. } else {
  1739. const int tmo = tcp_fin_time(sk);
  1740. if (tmo > TCP_TIMEWAIT_LEN) {
  1741. inet_csk_reset_keepalive_timer(sk,
  1742. tmo - TCP_TIMEWAIT_LEN);
  1743. } else {
  1744. tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
  1745. goto out;
  1746. }
  1747. }
  1748. }
  1749. if (sk->sk_state != TCP_CLOSE) {
  1750. sk_mem_reclaim(sk);
  1751. if (tcp_too_many_orphans(sk, 0)) {
  1752. if (net_ratelimit())
  1753. printk(KERN_INFO "TCP: too many of orphaned "
  1754. "sockets\n");
  1755. tcp_set_state(sk, TCP_CLOSE);
  1756. tcp_send_active_reset(sk, GFP_ATOMIC);
  1757. NET_INC_STATS_BH(sock_net(sk),
  1758. LINUX_MIB_TCPABORTONMEMORY);
  1759. }
  1760. }
  1761. if (sk->sk_state == TCP_CLOSE)
  1762. inet_csk_destroy_sock(sk);
  1763. /* Otherwise, socket is reprieved until protocol close. */
  1764. out:
  1765. bh_unlock_sock(sk);
  1766. local_bh_enable();
  1767. sock_put(sk);
  1768. }
  1769. EXPORT_SYMBOL(tcp_close);
  1770. /* These states need RST on ABORT according to RFC793 */
  1771. static inline int tcp_need_reset(int state)
  1772. {
  1773. return (1 << state) &
  1774. (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 |
  1775. TCPF_FIN_WAIT2 | TCPF_SYN_RECV);
  1776. }
  1777. int tcp_disconnect(struct sock *sk, int flags)
  1778. {
  1779. struct inet_sock *inet = inet_sk(sk);
  1780. struct inet_connection_sock *icsk = inet_csk(sk);
  1781. struct tcp_sock *tp = tcp_sk(sk);
  1782. int err = 0;
  1783. int old_state = sk->sk_state;
  1784. if (old_state != TCP_CLOSE)
  1785. tcp_set_state(sk, TCP_CLOSE);
  1786. /* ABORT function of RFC793 */
  1787. if (old_state == TCP_LISTEN) {
  1788. inet_csk_listen_stop(sk);
  1789. } else if (tcp_need_reset(old_state) ||
  1790. (tp->snd_nxt != tp->write_seq &&
  1791. (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {
  1792. /* The last check adjusts for discrepancy of Linux wrt. RFC
  1793. * states
  1794. */
  1795. tcp_send_active_reset(sk, gfp_any());
  1796. sk->sk_err = ECONNRESET;
  1797. } else if (old_state == TCP_SYN_SENT)
  1798. sk->sk_err = ECONNRESET;
  1799. tcp_clear_xmit_timers(sk);
  1800. __skb_queue_purge(&sk->sk_receive_queue);
  1801. tcp_write_queue_purge(sk);
  1802. __skb_queue_purge(&tp->out_of_order_queue);
  1803. #ifdef CONFIG_NET_DMA
  1804. __skb_queue_purge(&sk->sk_async_wait_queue);
  1805. #endif
  1806. inet->inet_dport = 0;
  1807. if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
  1808. inet_reset_saddr(sk);
  1809. sk->sk_shutdown = 0;
  1810. sock_reset_flag(sk, SOCK_DONE);
  1811. tp->srtt = 0;
  1812. if ((tp->write_seq += tp->max_window + 2) == 0)
  1813. tp->write_seq = 1;
  1814. icsk->icsk_backoff = 0;
  1815. tp->snd_cwnd = 2;
  1816. icsk->icsk_probes_out = 0;
  1817. tp->packets_out = 0;
  1818. tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
  1819. tp->snd_cwnd_cnt = 0;
  1820. tp->bytes_acked = 0;
  1821. tp->window_clamp = 0;
  1822. tcp_set_ca_state(sk, TCP_CA_Open);
  1823. tcp_clear_retrans(tp);
  1824. inet_csk_delack_init(sk);
  1825. tcp_init_send_head(sk);
  1826. memset(&tp->rx_opt, 0, sizeof(tp->rx_opt));
  1827. __sk_dst_reset(sk);
  1828. WARN_ON(inet->inet_num && !icsk->icsk_bind_hash);
  1829. sk->sk_error_report(sk);
  1830. return err;
  1831. }
  1832. EXPORT_SYMBOL(tcp_disconnect);
  1833. /*
  1834. * Socket option code for TCP.
  1835. */
  1836. static int do_tcp_setsockopt(struct sock *sk, int level,
  1837. int optname, char __user *optval, unsigned int optlen)
  1838. {
  1839. struct tcp_sock *tp = tcp_sk(sk);
  1840. struct inet_connection_sock *icsk = inet_csk(sk);
  1841. int val;
  1842. int err = 0;
  1843. /* These are data/string values, all the others are ints */
  1844. switch (optname) {
  1845. case TCP_CONGESTION: {
  1846. char name[TCP_CA_NAME_MAX];
  1847. if (optlen < 1)
  1848. return -EINVAL;
  1849. val = strncpy_from_user(name, optval,
  1850. min_t(long, TCP_CA_NAME_MAX-1, optlen));
  1851. if (val < 0)
  1852. return -EFAULT;
  1853. name[val] = 0;
  1854. lock_sock(sk);
  1855. err = tcp_set_congestion_control(sk, name);
  1856. release_sock(sk);
  1857. return err;
  1858. }
  1859. case TCP_COOKIE_TRANSACTIONS: {
  1860. struct tcp_cookie_transactions ctd;
  1861. struct tcp_cookie_values *cvp = NULL;
  1862. if (sizeof(ctd) > optlen)
  1863. return -EINVAL;
  1864. if (copy_from_user(&ctd, optval, sizeof(ctd)))
  1865. return -EFAULT;
  1866. if (ctd.tcpct_used > sizeof(ctd.tcpct_value) ||
  1867. ctd.tcpct_s_data_desired > TCP_MSS_DESIRED)
  1868. return -EINVAL;
  1869. if (ctd.tcpct_cookie_desired == 0) {
  1870. /* default to global value */
  1871. } else if ((0x1 & ctd.tcpct_cookie_desired) ||
  1872. ctd.tcpct_cookie_desired > TCP_COOKIE_MAX ||
  1873. ctd.tcpct_cookie_desired < TCP_COOKIE_MIN) {
  1874. return -EINVAL;
  1875. }
  1876. if (TCP_COOKIE_OUT_NEVER & ctd.tcpct_flags) {
  1877. /* Supercedes all other values */
  1878. lock_sock(sk);
  1879. if (tp->cookie_values != NULL) {
  1880. kref_put(&tp->cookie_values->kref,
  1881. tcp_cookie_values_release);
  1882. tp->cookie_values = NULL;
  1883. }
  1884. tp->rx_opt.cookie_in_always = 0; /* false */
  1885. tp->rx_opt.cookie_out_never = 1; /* true */
  1886. release_sock(sk);
  1887. return err;
  1888. }
  1889. /* Allocate ancillary memory before locking.
  1890. */
  1891. if (ctd.tcpct_used > 0 ||
  1892. (tp->cookie_values == NULL &&
  1893. (sysctl_tcp_cookie_size > 0 ||
  1894. ctd.tcpct_cookie_desired > 0 ||
  1895. ctd.tcpct_s_data_desired > 0))) {
  1896. cvp = kzalloc(sizeof(*cvp) + ctd.tcpct_used,
  1897. GFP_KERNEL);
  1898. if (cvp == NULL)
  1899. return -ENOMEM;
  1900. kref_init(&cvp->kref);
  1901. }
  1902. lock_sock(sk);
  1903. tp->rx_opt.cookie_in_always =
  1904. (TCP_COOKIE_IN_ALWAYS & ctd.tcpct_flags);
  1905. tp->rx_opt.cookie_out_never = 0; /* false */
  1906. if (tp->cookie_values != NULL) {
  1907. if (cvp != NULL) {
  1908. /* Changed values are recorded by a changed
  1909. * pointer, ensuring the cookie will differ,
  1910. * without separately hashing each value later.
  1911. */
  1912. kref_put(&tp->cookie_values->kref,
  1913. tcp_cookie_values_release);
  1914. } else {
  1915. cvp = tp->cookie_values;
  1916. }
  1917. }
  1918. if (cvp != NULL) {
  1919. cvp->cookie_desired = ctd.tcpct_cookie_desired;
  1920. if (ctd.tcpct_used > 0) {
  1921. memcpy(cvp->s_data_payload, ctd.tcpct_value,
  1922. ctd.tcpct_used);
  1923. cvp->s_data_desired = ctd.tcpct_used;
  1924. cvp->s_data_constant = 1; /* true */
  1925. } else {
  1926. /* No constant payload data. */
  1927. cvp->s_data_desired = ctd.tcpct_s_data_desired;
  1928. cvp->s_data_constant = 0; /* false */
  1929. }
  1930. tp->cookie_values = cvp;
  1931. }
  1932. release_sock(sk);
  1933. return err;
  1934. }
  1935. default:
  1936. /* fallthru */
  1937. break;
  1938. }
  1939. if (optlen < sizeof(int))
  1940. return -EINVAL;
  1941. if (get_user(val, (int __user *)optval))
  1942. return -EFAULT;
  1943. lock_sock(sk);
  1944. switch (optname) {
  1945. case TCP_MAXSEG:
  1946. /* Values greater than interface MTU won't take effect. However
  1947. * at the point when this call is done we typically don't yet
  1948. * know which interface is going to be used */
  1949. if (val < TCP_MIN_MSS || val > MAX_TCP_WINDOW) {
  1950. err = -EINVAL;
  1951. break;
  1952. }
  1953. tp->rx_opt.user_mss = val;
  1954. break;
  1955. case TCP_NODELAY:
  1956. if (val) {
  1957. /* TCP_NODELAY is weaker than TCP_CORK, so that
  1958. * this option on corked socket is remembered, but
  1959. * it is not activated until cork is cleared.
  1960. *
  1961. * However, when TCP_NODELAY is set we make
  1962. * an explicit push, which overrides even TCP_CORK
  1963. * for currently queued segments.
  1964. */
  1965. tp->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH;
  1966. tcp_push_pending_frames(sk);
  1967. } else {
  1968. tp->nonagle &= ~TCP_NAGLE_OFF;
  1969. }
  1970. break;
  1971. case TCP_THIN_LINEAR_TIMEOUTS:
  1972. if (val < 0 || val > 1)
  1973. err = -EINVAL;
  1974. else
  1975. tp->thin_lto = val;
  1976. break;
  1977. case TCP_THIN_DUPACK:
  1978. if (val < 0 || val > 1)
  1979. err = -EINVAL;
  1980. else
  1981. tp->thin_dupack = val;
  1982. break;
  1983. case TCP_CORK:
  1984. /* When set indicates to always queue non-full frames.
  1985. * Later the user clears this option and we transmit
  1986. * any pending partial frames in the queue. This is
  1987. * meant to be used alongside sendfile() to get properly
  1988. * filled frames when the user (for example) must write
  1989. * out headers with a write() call first and then use
  1990. * sendfile to send out the data parts.
  1991. *
  1992. * TCP_CORK can be set together with TCP_NODELAY and it is
  1993. * stronger than TCP_NODELAY.
  1994. */
  1995. if (val) {
  1996. tp->nonagle |= TCP_NAGLE_CORK;
  1997. } else {
  1998. tp->nonagle &= ~TCP_NAGLE_CORK;
  1999. if (tp->nonagle&TCP_NAGLE_OFF)
  2000. tp->nonagle |= TCP_NAGLE_PUSH;
  2001. tcp_push_pending_frames(sk);
  2002. }
  2003. break;
  2004. case TCP_KEEPIDLE:
  2005. if (val < 1 || val > MAX_TCP_KEEPIDLE)
  2006. err = -EINVAL;
  2007. else {
  2008. tp->keepalive_time = val * HZ;
  2009. if (sock_flag(sk, SOCK_KEEPOPEN) &&
  2010. !((1 << sk->sk_state) &
  2011. (TCPF_CLOSE | TCPF_LISTEN))) {
  2012. u32 elapsed = keepalive_time_elapsed(tp);
  2013. if (tp->keepalive_time > elapsed)
  2014. elapsed = tp->keepalive_time - elapsed;
  2015. else
  2016. elapsed = 0;
  2017. inet_csk_reset_keepalive_timer(sk, elapsed);
  2018. }
  2019. }
  2020. break;
  2021. case TCP_KEEPINTVL:
  2022. if (val < 1 || val > MAX_TCP_KEEPINTVL)
  2023. err = -EINVAL;
  2024. else
  2025. tp->keepalive_intvl = val * HZ;
  2026. break;
  2027. case TCP_KEEPCNT:
  2028. if (val < 1 || val > MAX_TCP_KEEPCNT)
  2029. err = -EINVAL;
  2030. else
  2031. tp->keepalive_probes = val;
  2032. break;
  2033. case TCP_SYNCNT:
  2034. if (val < 1 || val > MAX_TCP_SYNCNT)
  2035. err = -EINVAL;
  2036. else
  2037. icsk->icsk_syn_retries = val;
  2038. break;
  2039. case TCP_LINGER2:
  2040. if (val < 0)
  2041. tp->linger2 = -1;
  2042. else if (val > sysctl_tcp_fin_timeout / HZ)
  2043. tp->linger2 = 0;
  2044. else
  2045. tp->linger2 = val * HZ;
  2046. break;
  2047. case TCP_DEFER_ACCEPT:
  2048. /* Translate value in seconds to number of retransmits */
  2049. icsk->icsk_accept_queue.rskq_defer_accept =
  2050. secs_to_retrans(val, TCP_TIMEOUT_INIT / HZ,
  2051. TCP_RTO_MAX / HZ);
  2052. break;
  2053. case TCP_WINDOW_CLAMP:
  2054. if (!val) {
  2055. if (sk->sk_state != TCP_CLOSE) {
  2056. err = -EINVAL;
  2057. break;
  2058. }
  2059. tp->window_clamp = 0;
  2060. } else
  2061. tp->window_clamp = val < SOCK_MIN_RCVBUF / 2 ?
  2062. SOCK_MIN_RCVBUF / 2 : val;
  2063. break;
  2064. case TCP_QUICKACK:
  2065. if (!val) {
  2066. icsk->icsk_ack.pingpong = 1;
  2067. } else {
  2068. icsk->icsk_ack.pingpong = 0;
  2069. if ((1 << sk->sk_state) &
  2070. (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) &&
  2071. inet_csk_ack_scheduled(sk)) {
  2072. icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
  2073. tcp_cleanup_rbuf(sk, 1);
  2074. if (!(val & 1))
  2075. icsk->icsk_ack.pingpong = 1;
  2076. }
  2077. }
  2078. break;
  2079. #ifdef CONFIG_TCP_MD5SIG
  2080. case TCP_MD5SIG:
  2081. /* Read the IP->Key mappings from userspace */
  2082. err = tp->af_specific->md5_parse(sk, optval, optlen);
  2083. break;
  2084. #endif
  2085. case TCP_USER_TIMEOUT:
  2086. /* Cap the max timeout in ms TCP will retry/retrans
  2087. * before giving up and aborting (ETIMEDOUT) a connection.
  2088. */
  2089. if (val < 0)
  2090. err = -EINVAL;
  2091. else
  2092. icsk->icsk_user_timeout = msecs_to_jiffies(val);
  2093. break;
  2094. default:
  2095. err = -ENOPROTOOPT;
  2096. break;
  2097. }
  2098. release_sock(sk);
  2099. return err;
  2100. }
  2101. int tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval,
  2102. unsigned int optlen)
  2103. {
  2104. const struct inet_connection_sock *icsk = inet_csk(sk);
  2105. if (level != SOL_TCP)
  2106. return icsk->icsk_af_ops->setsockopt(sk, level, optname,
  2107. optval, optlen);
  2108. return do_tcp_setsockopt(sk, level, optname, optval, optlen);
  2109. }
  2110. EXPORT_SYMBOL(tcp_setsockopt);
  2111. #ifdef CONFIG_COMPAT
  2112. int compat_tcp_setsockopt(struct sock *sk, int level, int optname,
  2113. char __user *optval, unsigned int optlen)
  2114. {
  2115. if (level != SOL_TCP)
  2116. return inet_csk_compat_setsockopt(sk, level, optname,
  2117. optval, optlen);
  2118. return do_tcp_setsockopt(sk, level, optname, optval, optlen);
  2119. }
  2120. EXPORT_SYMBOL(compat_tcp_setsockopt);
  2121. #endif
  2122. /* Return information about state of tcp endpoint in API format. */
  2123. void tcp_get_info(const struct sock *sk, struct tcp_info *info)
  2124. {
  2125. const struct tcp_sock *tp = tcp_sk(sk);
  2126. const struct inet_connection_sock *icsk = inet_csk(sk);
  2127. u32 now = tcp_time_stamp;
  2128. memset(info, 0, sizeof(*info));
  2129. info->tcpi_state = sk->sk_state;
  2130. info->tcpi_ca_state = icsk->icsk_ca_state;
  2131. info->tcpi_retransmits = icsk->icsk_retransmits;
  2132. info->tcpi_probes = icsk->icsk_probes_out;
  2133. info->tcpi_backoff = icsk->icsk_backoff;
  2134. if (tp->rx_opt.tstamp_ok)
  2135. info->tcpi_options |= TCPI_OPT_TIMESTAMPS;
  2136. if (tcp_is_sack(tp))
  2137. info->tcpi_options |= TCPI_OPT_SACK;
  2138. if (tp->rx_opt.wscale_ok) {
  2139. info->tcpi_options |= TCPI_OPT_WSCALE;
  2140. info->tcpi_snd_wscale = tp->rx_opt.snd_wscale;
  2141. info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale;
  2142. }
  2143. if (tp->ecn_flags & TCP_ECN_OK)
  2144. info->tcpi_options |= TCPI_OPT_ECN;
  2145. if (tp->ecn_flags & TCP_ECN_SEEN)
  2146. info->tcpi_options |= TCPI_OPT_ECN_SEEN;
  2147. info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto);
  2148. info->tcpi_ato = jiffies_to_usecs(icsk->icsk_ack.ato);
  2149. info->tcpi_snd_mss = tp->mss_cache;
  2150. info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss;
  2151. if (sk->sk_state == TCP_LISTEN) {
  2152. info->tcpi_unacked = sk->sk_ack_backlog;
  2153. info->tcpi_sacked = sk->sk_max_ack_backlog;
  2154. } else {
  2155. info->tcpi_unacked = tp->packets_out;
  2156. info->tcpi_sacked = tp->sacked_out;
  2157. }
  2158. info->tcpi_lost = tp->lost_out;
  2159. info->tcpi_retrans = tp->retrans_out;
  2160. info->tcpi_fackets = tp->fackets_out;
  2161. info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime);
  2162. info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime);
  2163. info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp);
  2164. info->tcpi_pmtu = icsk->icsk_pmtu_cookie;
  2165. info->tcpi_rcv_ssthresh = tp->rcv_ssthresh;
  2166. info->tcpi_rtt = jiffies_to_usecs(tp->srtt)>>3;
  2167. info->tcpi_rttvar = jiffies_to_usecs(tp->mdev)>>2;
  2168. info->tcpi_snd_ssthresh = tp->snd_ssthresh;
  2169. info->tcpi_snd_cwnd = tp->snd_cwnd;
  2170. info->tcpi_advmss = tp->advmss;
  2171. info->tcpi_reordering = tp->reordering;
  2172. info->tcpi_rcv_rtt = jiffies_to_usecs(tp->rcv_rtt_est.rtt)>>3;
  2173. info->tcpi_rcv_space = tp->rcvq_space.space;
  2174. info->tcpi_total_retrans = tp->total_retrans;
  2175. }
  2176. EXPORT_SYMBOL_GPL(tcp_get_info);
  2177. static int do_tcp_getsockopt(struct sock *sk, int level,
  2178. int optname, char __user *optval, int __user *optlen)
  2179. {
  2180. struct inet_connection_sock *icsk = inet_csk(sk);
  2181. struct tcp_sock *tp = tcp_sk(sk);
  2182. int val, len;
  2183. if (get_user(len, optlen))
  2184. return -EFAULT;
  2185. len = min_t(unsigned int, len, sizeof(int));
  2186. if (len < 0)
  2187. return -EINVAL;
  2188. switch (optname) {
  2189. case TCP_MAXSEG:
  2190. val = tp->mss_cache;
  2191. if (!val && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
  2192. val = tp->rx_opt.user_mss;
  2193. break;
  2194. case TCP_NODELAY:
  2195. val = !!(tp->nonagle&TCP_NAGLE_OFF);
  2196. break;
  2197. case TCP_CORK:
  2198. val = !!(tp->nonagle&TCP_NAGLE_CORK);
  2199. break;
  2200. case TCP_KEEPIDLE:
  2201. val = keepalive_time_when(tp) / HZ;
  2202. break;
  2203. case TCP_KEEPINTVL:
  2204. val = keepalive_intvl_when(tp) / HZ;
  2205. break;
  2206. case TCP_KEEPCNT:
  2207. val = keepalive_probes(tp);
  2208. break;
  2209. case TCP_SYNCNT:
  2210. val = icsk->icsk_syn_retries ? : sysctl_tcp_syn_retries;
  2211. break;
  2212. case TCP_LINGER2:
  2213. val = tp->linger2;
  2214. if (val >= 0)
  2215. val = (val ? : sysctl_tcp_fin_timeout) / HZ;
  2216. break;
  2217. case TCP_DEFER_ACCEPT:
  2218. val = retrans_to_secs(icsk->icsk_accept_queue.rskq_defer_accept,
  2219. TCP_TIMEOUT_INIT / HZ, TCP_RTO_MAX / HZ);
  2220. break;
  2221. case TCP_WINDOW_CLAMP:
  2222. val = tp->window_clamp;
  2223. break;
  2224. case TCP_INFO: {
  2225. struct tcp_info info;
  2226. if (get_user(len, optlen))
  2227. return -EFAULT;
  2228. tcp_get_info(sk, &info);
  2229. len = min_t(unsigned int, len, sizeof(info));
  2230. if (put_user(len, optlen))
  2231. return -EFAULT;
  2232. if (copy_to_user(optval, &info, len))
  2233. return -EFAULT;
  2234. return 0;
  2235. }
  2236. case TCP_QUICKACK:
  2237. val = !icsk->icsk_ack.pingpong;
  2238. break;
  2239. case TCP_CONGESTION:
  2240. if (get_user(len, optlen))
  2241. return -EFAULT;
  2242. len = min_t(unsigned int, len, TCP_CA_NAME_MAX);
  2243. if (put_user(len, optlen))
  2244. return -EFAULT;
  2245. if (copy_to_user(optval, icsk->icsk_ca_ops->name, len))
  2246. return -EFAULT;
  2247. return 0;
  2248. case TCP_COOKIE_TRANSACTIONS: {
  2249. struct tcp_cookie_transactions ctd;
  2250. struct tcp_cookie_values *cvp = tp->cookie_values;
  2251. if (get_user(len, optlen))
  2252. return -EFAULT;
  2253. if (len < sizeof(ctd))
  2254. return -EINVAL;
  2255. memset(&ctd, 0, sizeof(ctd));
  2256. ctd.tcpct_flags = (tp->rx_opt.cookie_in_always ?
  2257. TCP_COOKIE_IN_ALWAYS : 0)
  2258. | (tp->rx_opt.cookie_out_never ?
  2259. TCP_COOKIE_OUT_NEVER : 0);
  2260. if (cvp != NULL) {
  2261. ctd.tcpct_flags |= (cvp->s_data_in ?
  2262. TCP_S_DATA_IN : 0)
  2263. | (cvp->s_data_out ?
  2264. TCP_S_DATA_OUT : 0);
  2265. ctd.tcpct_cookie_desired = cvp->cookie_desired;
  2266. ctd.tcpct_s_data_desired = cvp->s_data_desired;
  2267. memcpy(&ctd.tcpct_value[0], &cvp->cookie_pair[0],
  2268. cvp->cookie_pair_size);
  2269. ctd.tcpct_used = cvp->cookie_pair_size;
  2270. }
  2271. if (put_user(sizeof(ctd), optlen))
  2272. return -EFAULT;
  2273. if (copy_to_user(optval, &ctd, sizeof(ctd)))
  2274. return -EFAULT;
  2275. return 0;
  2276. }
  2277. case TCP_THIN_LINEAR_TIMEOUTS:
  2278. val = tp->thin_lto;
  2279. break;
  2280. case TCP_THIN_DUPACK:
  2281. val = tp->thin_dupack;
  2282. break;
  2283. case TCP_USER_TIMEOUT:
  2284. val = jiffies_to_msecs(icsk->icsk_user_timeout);
  2285. break;
  2286. default:
  2287. return -ENOPROTOOPT;
  2288. }
  2289. if (put_user(len, optlen))
  2290. return -EFAULT;
  2291. if (copy_to_user(optval, &val, len))
  2292. return -EFAULT;
  2293. return 0;
  2294. }
  2295. int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval,
  2296. int __user *optlen)
  2297. {
  2298. struct inet_connection_sock *icsk = inet_csk(sk);
  2299. if (level != SOL_TCP)
  2300. return icsk->icsk_af_ops->getsockopt(sk, level, optname,
  2301. optval, optlen);
  2302. return do_tcp_getsockopt(sk, level, optname, optval, optlen);
  2303. }
  2304. EXPORT_SYMBOL(tcp_getsockopt);
  2305. #ifdef CONFIG_COMPAT
  2306. int compat_tcp_getsockopt(struct sock *sk, int level, int optname,
  2307. char __user *optval, int __user *optlen)
  2308. {
  2309. if (level != SOL_TCP)
  2310. return inet_csk_compat_getsockopt(sk, level, optname,
  2311. optval, optlen);
  2312. return do_tcp_getsockopt(sk, level, optname, optval, optlen);
  2313. }
  2314. EXPORT_SYMBOL(compat_tcp_getsockopt);
  2315. #endif
  2316. struct sk_buff *tcp_tso_segment(struct sk_buff *skb, u32 features)
  2317. {
  2318. struct sk_buff *segs = ERR_PTR(-EINVAL);
  2319. struct tcphdr *th;
  2320. unsigned thlen;
  2321. unsigned int seq;
  2322. __be32 delta;
  2323. unsigned int oldlen;
  2324. unsigned int mss;
  2325. if (!pskb_may_pull(skb, sizeof(*th)))
  2326. goto out;
  2327. th = tcp_hdr(skb);
  2328. thlen = th->doff * 4;
  2329. if (thlen < sizeof(*th))
  2330. goto out;
  2331. if (!pskb_may_pull(skb, thlen))
  2332. goto out;
  2333. oldlen = (u16)~skb->len;
  2334. __skb_pull(skb, thlen);
  2335. mss = skb_shinfo(skb)->gso_size;
  2336. if (unlikely(skb->len <= mss))
  2337. goto out;
  2338. if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) {
  2339. /* Packet is from an untrusted source, reset gso_segs. */
  2340. int type = skb_shinfo(skb)->gso_type;
  2341. if (unlikely(type &
  2342. ~(SKB_GSO_TCPV4 |
  2343. SKB_GSO_DODGY |
  2344. SKB_GSO_TCP_ECN |
  2345. SKB_GSO_TCPV6 |
  2346. 0) ||
  2347. !(type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))))
  2348. goto out;
  2349. skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss);
  2350. segs = NULL;
  2351. goto out;
  2352. }
  2353. segs = skb_segment(skb, features);
  2354. if (IS_ERR(segs))
  2355. goto out;
  2356. delta = htonl(oldlen + (thlen + mss));
  2357. skb = segs;
  2358. th = tcp_hdr(skb);
  2359. seq = ntohl(th->seq);
  2360. do {
  2361. th->fin = th->psh = 0;
  2362. th->check = ~csum_fold((__force __wsum)((__force u32)th->check +
  2363. (__force u32)delta));
  2364. if (skb->ip_summed != CHECKSUM_PARTIAL)
  2365. th->check =
  2366. csum_fold(csum_partial(skb_transport_header(skb),
  2367. thlen, skb->csum));
  2368. seq += mss;
  2369. skb = skb->next;
  2370. th = tcp_hdr(skb);
  2371. th->seq = htonl(seq);
  2372. th->cwr = 0;
  2373. } while (skb->next);
  2374. delta = htonl(oldlen + (skb->tail - skb->transport_header) +
  2375. skb->data_len);
  2376. th->check = ~csum_fold((__force __wsum)((__force u32)th->check +
  2377. (__force u32)delta));
  2378. if (skb->ip_summed != CHECKSUM_PARTIAL)
  2379. th->check = csum_fold(csum_partial(skb_transport_header(skb),
  2380. thlen, skb->csum));
  2381. out:
  2382. return segs;
  2383. }
  2384. EXPORT_SYMBOL(tcp_tso_segment);
  2385. struct sk_buff **tcp_gro_receive(struct sk_buff **head, struct sk_buff *skb)
  2386. {
  2387. struct sk_buff **pp = NULL;
  2388. struct sk_buff *p;
  2389. struct tcphdr *th;
  2390. struct tcphdr *th2;
  2391. unsigned int len;
  2392. unsigned int thlen;
  2393. __be32 flags;
  2394. unsigned int mss = 1;
  2395. unsigned int hlen;
  2396. unsigned int off;
  2397. int flush = 1;
  2398. int i;
  2399. off = skb_gro_offset(skb);
  2400. hlen = off + sizeof(*th);
  2401. th = skb_gro_header_fast(skb, off);
  2402. if (skb_gro_header_hard(skb, hlen)) {
  2403. th = skb_gro_header_slow(skb, hlen, off);
  2404. if (unlikely(!th))
  2405. goto out;
  2406. }
  2407. thlen = th->doff * 4;
  2408. if (thlen < sizeof(*th))
  2409. goto out;
  2410. hlen = off + thlen;
  2411. if (skb_gro_header_hard(skb, hlen)) {
  2412. th = skb_gro_header_slow(skb, hlen, off);
  2413. if (unlikely(!th))
  2414. goto out;
  2415. }
  2416. skb_gro_pull(skb, thlen);
  2417. len = skb_gro_len(skb);
  2418. flags = tcp_flag_word(th);
  2419. for (; (p = *head); head = &p->next) {
  2420. if (!NAPI_GRO_CB(p)->same_flow)
  2421. continue;
  2422. th2 = tcp_hdr(p);
  2423. if (*(u32 *)&th->source ^ *(u32 *)&th2->source) {
  2424. NAPI_GRO_CB(p)->same_flow = 0;
  2425. continue;
  2426. }
  2427. goto found;
  2428. }
  2429. goto out_check_final;
  2430. found:
  2431. flush = NAPI_GRO_CB(p)->flush;
  2432. flush |= (__force int)(flags & TCP_FLAG_CWR);
  2433. flush |= (__force int)((flags ^ tcp_flag_word(th2)) &
  2434. ~(TCP_FLAG_CWR | TCP_FLAG_FIN | TCP_FLAG_PSH));
  2435. flush |= (__force int)(th->ack_seq ^ th2->ack_seq);
  2436. for (i = sizeof(*th); i < thlen; i += 4)
  2437. flush |= *(u32 *)((u8 *)th + i) ^
  2438. *(u32 *)((u8 *)th2 + i);
  2439. mss = skb_shinfo(p)->gso_size;
  2440. flush |= (len - 1) >= mss;
  2441. flush |= (ntohl(th2->seq) + skb_gro_len(p)) ^ ntohl(th->seq);
  2442. if (flush || skb_gro_receive(head, skb)) {
  2443. mss = 1;
  2444. goto out_check_final;
  2445. }
  2446. p = *head;
  2447. th2 = tcp_hdr(p);
  2448. tcp_flag_word(th2) |= flags & (TCP_FLAG_FIN | TCP_FLAG_PSH);
  2449. out_check_final:
  2450. flush = len < mss;
  2451. flush |= (__force int)(flags & (TCP_FLAG_URG | TCP_FLAG_PSH |
  2452. TCP_FLAG_RST | TCP_FLAG_SYN |
  2453. TCP_FLAG_FIN));
  2454. if (p && (!NAPI_GRO_CB(skb)->same_flow || flush))
  2455. pp = head;
  2456. out:
  2457. NAPI_GRO_CB(skb)->flush |= flush;
  2458. return pp;
  2459. }
  2460. EXPORT_SYMBOL(tcp_gro_receive);
  2461. int tcp_gro_complete(struct sk_buff *skb)
  2462. {
  2463. struct tcphdr *th = tcp_hdr(skb);
  2464. skb->csum_start = skb_transport_header(skb) - skb->head;
  2465. skb->csum_offset = offsetof(struct tcphdr, check);
  2466. skb->ip_summed = CHECKSUM_PARTIAL;
  2467. skb_shinfo(skb)->gso_segs = NAPI_GRO_CB(skb)->count;
  2468. if (th->cwr)
  2469. skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
  2470. return 0;
  2471. }
  2472. EXPORT_SYMBOL(tcp_gro_complete);
  2473. #ifdef CONFIG_TCP_MD5SIG
  2474. static unsigned long tcp_md5sig_users;
  2475. static struct tcp_md5sig_pool __percpu *tcp_md5sig_pool;
  2476. static DEFINE_SPINLOCK(tcp_md5sig_pool_lock);
  2477. static void __tcp_free_md5sig_pool(struct tcp_md5sig_pool __percpu *pool)
  2478. {
  2479. int cpu;
  2480. for_each_possible_cpu(cpu) {
  2481. struct tcp_md5sig_pool *p = per_cpu_ptr(pool, cpu);
  2482. if (p->md5_desc.tfm)
  2483. crypto_free_hash(p->md5_desc.tfm);
  2484. }
  2485. free_percpu(pool);
  2486. }
  2487. void tcp_free_md5sig_pool(void)
  2488. {
  2489. struct tcp_md5sig_pool __percpu *pool = NULL;
  2490. spin_lock_bh(&tcp_md5sig_pool_lock);
  2491. if (--tcp_md5sig_users == 0) {
  2492. pool = tcp_md5sig_pool;
  2493. tcp_md5sig_pool = NULL;
  2494. }
  2495. spin_unlock_bh(&tcp_md5sig_pool_lock);
  2496. if (pool)
  2497. __tcp_free_md5sig_pool(pool);
  2498. }
  2499. EXPORT_SYMBOL(tcp_free_md5sig_pool);
  2500. static struct tcp_md5sig_pool __percpu *
  2501. __tcp_alloc_md5sig_pool(struct sock *sk)
  2502. {
  2503. int cpu;
  2504. struct tcp_md5sig_pool __percpu *pool;
  2505. pool = alloc_percpu(struct tcp_md5sig_pool);
  2506. if (!pool)
  2507. return NULL;
  2508. for_each_possible_cpu(cpu) {
  2509. struct crypto_hash *hash;
  2510. hash = crypto_alloc_hash("md5", 0, CRYPTO_ALG_ASYNC);
  2511. if (!hash || IS_ERR(hash))
  2512. goto out_free;
  2513. per_cpu_ptr(pool, cpu)->md5_desc.tfm = hash;
  2514. }
  2515. return pool;
  2516. out_free:
  2517. __tcp_free_md5sig_pool(pool);
  2518. return NULL;
  2519. }
  2520. struct tcp_md5sig_pool __percpu *tcp_alloc_md5sig_pool(struct sock *sk)
  2521. {
  2522. struct tcp_md5sig_pool __percpu *pool;
  2523. int alloc = 0;
  2524. retry:
  2525. spin_lock_bh(&tcp_md5sig_pool_lock);
  2526. pool = tcp_md5sig_pool;
  2527. if (tcp_md5sig_users++ == 0) {
  2528. alloc = 1;
  2529. spin_unlock_bh(&tcp_md5sig_pool_lock);
  2530. } else if (!pool) {
  2531. tcp_md5sig_users--;
  2532. spin_unlock_bh(&tcp_md5sig_pool_lock);
  2533. cpu_relax();
  2534. goto retry;
  2535. } else
  2536. spin_unlock_bh(&tcp_md5sig_pool_lock);
  2537. if (alloc) {
  2538. /* we cannot hold spinlock here because this may sleep. */
  2539. struct tcp_md5sig_pool __percpu *p;
  2540. p = __tcp_alloc_md5sig_pool(sk);
  2541. spin_lock_bh(&tcp_md5sig_pool_lock);
  2542. if (!p) {
  2543. tcp_md5sig_users--;
  2544. spin_unlock_bh(&tcp_md5sig_pool_lock);
  2545. return NULL;
  2546. }
  2547. pool = tcp_md5sig_pool;
  2548. if (pool) {
  2549. /* oops, it has already been assigned. */
  2550. spin_unlock_bh(&tcp_md5sig_pool_lock);
  2551. __tcp_free_md5sig_pool(p);
  2552. } else {
  2553. tcp_md5sig_pool = pool = p;
  2554. spin_unlock_bh(&tcp_md5sig_pool_lock);
  2555. }
  2556. }
  2557. return pool;
  2558. }
  2559. EXPORT_SYMBOL(tcp_alloc_md5sig_pool);
  2560. /**
  2561. * tcp_get_md5sig_pool - get md5sig_pool for this user
  2562. *
  2563. * We use percpu structure, so if we succeed, we exit with preemption
  2564. * and BH disabled, to make sure another thread or softirq handling
  2565. * wont try to get same context.
  2566. */
  2567. struct tcp_md5sig_pool *tcp_get_md5sig_pool(void)
  2568. {
  2569. struct tcp_md5sig_pool __percpu *p;
  2570. local_bh_disable();
  2571. spin_lock(&tcp_md5sig_pool_lock);
  2572. p = tcp_md5sig_pool;
  2573. if (p)
  2574. tcp_md5sig_users++;
  2575. spin_unlock(&tcp_md5sig_pool_lock);
  2576. if (p)
  2577. return this_cpu_ptr(p);
  2578. local_bh_enable();
  2579. return NULL;
  2580. }
  2581. EXPORT_SYMBOL(tcp_get_md5sig_pool);
  2582. void tcp_put_md5sig_pool(void)
  2583. {
  2584. local_bh_enable();
  2585. tcp_free_md5sig_pool();
  2586. }
  2587. EXPORT_SYMBOL(tcp_put_md5sig_pool);
  2588. int tcp_md5_hash_header(struct tcp_md5sig_pool *hp,
  2589. const struct tcphdr *th)
  2590. {
  2591. struct scatterlist sg;
  2592. struct tcphdr hdr;
  2593. int err;
  2594. /* We are not allowed to change tcphdr, make a local copy */
  2595. memcpy(&hdr, th, sizeof(hdr));
  2596. hdr.check = 0;
  2597. /* options aren't included in the hash */
  2598. sg_init_one(&sg, &hdr, sizeof(hdr));
  2599. err = crypto_hash_update(&hp->md5_desc, &sg, sizeof(hdr));
  2600. return err;
  2601. }
  2602. EXPORT_SYMBOL(tcp_md5_hash_header);
  2603. int tcp_md5_hash_skb_data(struct tcp_md5sig_pool *hp,
  2604. const struct sk_buff *skb, unsigned int header_len)
  2605. {
  2606. struct scatterlist sg;
  2607. const struct tcphdr *tp = tcp_hdr(skb);
  2608. struct hash_desc *desc = &hp->md5_desc;
  2609. unsigned i;
  2610. const unsigned head_data_len = skb_headlen(skb) > header_len ?
  2611. skb_headlen(skb) - header_len : 0;
  2612. const struct skb_shared_info *shi = skb_shinfo(skb);
  2613. struct sk_buff *frag_iter;
  2614. sg_init_table(&sg, 1);
  2615. sg_set_buf(&sg, ((u8 *) tp) + header_len, head_data_len);
  2616. if (crypto_hash_update(desc, &sg, head_data_len))
  2617. return 1;
  2618. for (i = 0; i < shi->nr_frags; ++i) {
  2619. const struct skb_frag_struct *f = &shi->frags[i];
  2620. struct page *page = skb_frag_page(f);
  2621. sg_set_page(&sg, page, skb_frag_size(f), f->page_offset);
  2622. if (crypto_hash_update(desc, &sg, skb_frag_size(f)))
  2623. return 1;
  2624. }
  2625. skb_walk_frags(skb, frag_iter)
  2626. if (tcp_md5_hash_skb_data(hp, frag_iter, 0))
  2627. return 1;
  2628. return 0;
  2629. }
  2630. EXPORT_SYMBOL(tcp_md5_hash_skb_data);
  2631. int tcp_md5_hash_key(struct tcp_md5sig_pool *hp, const struct tcp_md5sig_key *key)
  2632. {
  2633. struct scatterlist sg;
  2634. sg_init_one(&sg, key->key, key->keylen);
  2635. return crypto_hash_update(&hp->md5_desc, &sg, key->keylen);
  2636. }
  2637. EXPORT_SYMBOL(tcp_md5_hash_key);
  2638. #endif
  2639. /**
  2640. * Each Responder maintains up to two secret values concurrently for
  2641. * efficient secret rollover. Each secret value has 4 states:
  2642. *
  2643. * Generating. (tcp_secret_generating != tcp_secret_primary)
  2644. * Generates new Responder-Cookies, but not yet used for primary
  2645. * verification. This is a short-term state, typically lasting only
  2646. * one round trip time (RTT).
  2647. *
  2648. * Primary. (tcp_secret_generating == tcp_secret_primary)
  2649. * Used both for generation and primary verification.
  2650. *
  2651. * Retiring. (tcp_secret_retiring != tcp_secret_secondary)
  2652. * Used for verification, until the first failure that can be
  2653. * verified by the newer Generating secret. At that time, this
  2654. * cookie's state is changed to Secondary, and the Generating
  2655. * cookie's state is changed to Primary. This is a short-term state,
  2656. * typically lasting only one round trip time (RTT).
  2657. *
  2658. * Secondary. (tcp_secret_retiring == tcp_secret_secondary)
  2659. * Used for secondary verification, after primary verification
  2660. * failures. This state lasts no more than twice the Maximum Segment
  2661. * Lifetime (2MSL). Then, the secret is discarded.
  2662. */
  2663. struct tcp_cookie_secret {
  2664. /* The secret is divided into two parts. The digest part is the
  2665. * equivalent of previously hashing a secret and saving the state,
  2666. * and serves as an initialization vector (IV). The message part
  2667. * serves as the trailing secret.
  2668. */
  2669. u32 secrets[COOKIE_WORKSPACE_WORDS];
  2670. unsigned long expires;
  2671. };
  2672. #define TCP_SECRET_1MSL (HZ * TCP_PAWS_MSL)
  2673. #define TCP_SECRET_2MSL (HZ * TCP_PAWS_MSL * 2)
  2674. #define TCP_SECRET_LIFE (HZ * 600)
  2675. static struct tcp_cookie_secret tcp_secret_one;
  2676. static struct tcp_cookie_secret tcp_secret_two;
  2677. /* Essentially a circular list, without dynamic allocation. */
  2678. static struct tcp_cookie_secret *tcp_secret_generating;
  2679. static struct tcp_cookie_secret *tcp_secret_primary;
  2680. static struct tcp_cookie_secret *tcp_secret_retiring;
  2681. static struct tcp_cookie_secret *tcp_secret_secondary;
  2682. static DEFINE_SPINLOCK(tcp_secret_locker);
  2683. /* Select a pseudo-random word in the cookie workspace.
  2684. */
  2685. static inline u32 tcp_cookie_work(const u32 *ws, const int n)
  2686. {
  2687. return ws[COOKIE_DIGEST_WORDS + ((COOKIE_MESSAGE_WORDS-1) & ws[n])];
  2688. }
  2689. /* Fill bakery[COOKIE_WORKSPACE_WORDS] with generator, updating as needed.
  2690. * Called in softirq context.
  2691. * Returns: 0 for success.
  2692. */
  2693. int tcp_cookie_generator(u32 *bakery)
  2694. {
  2695. unsigned long jiffy = jiffies;
  2696. if (unlikely(time_after_eq(jiffy, tcp_secret_generating->expires))) {
  2697. spin_lock_bh(&tcp_secret_locker);
  2698. if (!time_after_eq(jiffy, tcp_secret_generating->expires)) {
  2699. /* refreshed by another */
  2700. memcpy(bakery,
  2701. &tcp_secret_generating->secrets[0],
  2702. COOKIE_WORKSPACE_WORDS);
  2703. } else {
  2704. /* still needs refreshing */
  2705. get_random_bytes(bakery, COOKIE_WORKSPACE_WORDS);
  2706. /* The first time, paranoia assumes that the
  2707. * randomization function isn't as strong. But,
  2708. * this secret initialization is delayed until
  2709. * the last possible moment (packet arrival).
  2710. * Although that time is observable, it is
  2711. * unpredictably variable. Mash in the most
  2712. * volatile clock bits available, and expire the
  2713. * secret extra quickly.
  2714. */
  2715. if (unlikely(tcp_secret_primary->expires ==
  2716. tcp_secret_secondary->expires)) {
  2717. struct timespec tv;
  2718. getnstimeofday(&tv);
  2719. bakery[COOKIE_DIGEST_WORDS+0] ^=
  2720. (u32)tv.tv_nsec;
  2721. tcp_secret_secondary->expires = jiffy
  2722. + TCP_SECRET_1MSL
  2723. + (0x0f & tcp_cookie_work(bakery, 0));
  2724. } else {
  2725. tcp_secret_secondary->expires = jiffy
  2726. + TCP_SECRET_LIFE
  2727. + (0xff & tcp_cookie_work(bakery, 1));
  2728. tcp_secret_primary->expires = jiffy
  2729. + TCP_SECRET_2MSL
  2730. + (0x1f & tcp_cookie_work(bakery, 2));
  2731. }
  2732. memcpy(&tcp_secret_secondary->secrets[0],
  2733. bakery, COOKIE_WORKSPACE_WORDS);
  2734. rcu_assign_pointer(tcp_secret_generating,
  2735. tcp_secret_secondary);
  2736. rcu_assign_pointer(tcp_secret_retiring,
  2737. tcp_secret_primary);
  2738. /*
  2739. * Neither call_rcu() nor synchronize_rcu() needed.
  2740. * Retiring data is not freed. It is replaced after
  2741. * further (locked) pointer updates, and a quiet time
  2742. * (minimum 1MSL, maximum LIFE - 2MSL).
  2743. */
  2744. }
  2745. spin_unlock_bh(&tcp_secret_locker);
  2746. } else {
  2747. rcu_read_lock_bh();
  2748. memcpy(bakery,
  2749. &rcu_dereference(tcp_secret_generating)->secrets[0],
  2750. COOKIE_WORKSPACE_WORDS);
  2751. rcu_read_unlock_bh();
  2752. }
  2753. return 0;
  2754. }
  2755. EXPORT_SYMBOL(tcp_cookie_generator);
  2756. void tcp_done(struct sock *sk)
  2757. {
  2758. if (sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV)
  2759. TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_ATTEMPTFAILS);
  2760. tcp_set_state(sk, TCP_CLOSE);
  2761. tcp_clear_xmit_timers(sk);
  2762. sk->sk_shutdown = SHUTDOWN_MASK;
  2763. if (!sock_flag(sk, SOCK_DEAD))
  2764. sk->sk_state_change(sk);
  2765. else
  2766. inet_csk_destroy_sock(sk);
  2767. }
  2768. EXPORT_SYMBOL_GPL(tcp_done);
  2769. extern struct tcp_congestion_ops tcp_reno;
  2770. static __initdata unsigned long thash_entries;
  2771. static int __init set_thash_entries(char *str)
  2772. {
  2773. if (!str)
  2774. return 0;
  2775. thash_entries = simple_strtoul(str, &str, 0);
  2776. return 1;
  2777. }
  2778. __setup("thash_entries=", set_thash_entries);
  2779. void __init tcp_init(void)
  2780. {
  2781. struct sk_buff *skb = NULL;
  2782. unsigned long limit;
  2783. int i, max_rshare, max_wshare, cnt;
  2784. unsigned long jiffy = jiffies;
  2785. BUILD_BUG_ON(sizeof(struct tcp_skb_cb) > sizeof(skb->cb));
  2786. percpu_counter_init(&tcp_sockets_allocated, 0);
  2787. percpu_counter_init(&tcp_orphan_count, 0);
  2788. tcp_hashinfo.bind_bucket_cachep =
  2789. kmem_cache_create("tcp_bind_bucket",
  2790. sizeof(struct inet_bind_bucket), 0,
  2791. SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
  2792. /* Size and allocate the main established and bind bucket
  2793. * hash tables.
  2794. *
  2795. * The methodology is similar to that of the buffer cache.
  2796. */
  2797. tcp_hashinfo.ehash =
  2798. alloc_large_system_hash("TCP established",
  2799. sizeof(struct inet_ehash_bucket),
  2800. thash_entries,
  2801. (totalram_pages >= 128 * 1024) ?
  2802. 13 : 15,
  2803. 0,
  2804. NULL,
  2805. &tcp_hashinfo.ehash_mask,
  2806. thash_entries ? 0 : 512 * 1024);
  2807. for (i = 0; i <= tcp_hashinfo.ehash_mask; i++) {
  2808. INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i);
  2809. INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].twchain, i);
  2810. }
  2811. if (inet_ehash_locks_alloc(&tcp_hashinfo))
  2812. panic("TCP: failed to alloc ehash_locks");
  2813. tcp_hashinfo.bhash =
  2814. alloc_large_system_hash("TCP bind",
  2815. sizeof(struct inet_bind_hashbucket),
  2816. tcp_hashinfo.ehash_mask + 1,
  2817. (totalram_pages >= 128 * 1024) ?
  2818. 13 : 15,
  2819. 0,
  2820. &tcp_hashinfo.bhash_size,
  2821. NULL,
  2822. 64 * 1024);
  2823. tcp_hashinfo.bhash_size = 1 << tcp_hashinfo.bhash_size;
  2824. for (i = 0; i < tcp_hashinfo.bhash_size; i++) {
  2825. spin_lock_init(&tcp_hashinfo.bhash[i].lock);
  2826. INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain);
  2827. }
  2828. cnt = tcp_hashinfo.ehash_mask + 1;
  2829. tcp_death_row.sysctl_max_tw_buckets = cnt / 2;
  2830. sysctl_tcp_max_orphans = cnt / 2;
  2831. sysctl_max_syn_backlog = max(128, cnt / 256);
  2832. limit = nr_free_buffer_pages() / 8;
  2833. limit = max(limit, 128UL);
  2834. sysctl_tcp_mem[0] = limit / 4 * 3;
  2835. sysctl_tcp_mem[1] = limit;
  2836. sysctl_tcp_mem[2] = sysctl_tcp_mem[0] * 2;
  2837. /* Set per-socket limits to no more than 1/128 the pressure threshold */
  2838. limit = ((unsigned long)sysctl_tcp_mem[1]) << (PAGE_SHIFT - 7);
  2839. max_wshare = min(4UL*1024*1024, limit);
  2840. max_rshare = min(6UL*1024*1024, limit);
  2841. sysctl_tcp_wmem[0] = SK_MEM_QUANTUM;
  2842. sysctl_tcp_wmem[1] = 16*1024;
  2843. sysctl_tcp_wmem[2] = max(64*1024, max_wshare);
  2844. sysctl_tcp_rmem[0] = SK_MEM_QUANTUM;
  2845. sysctl_tcp_rmem[1] = 87380;
  2846. sysctl_tcp_rmem[2] = max(87380, max_rshare);
  2847. printk(KERN_INFO "TCP: Hash tables configured "
  2848. "(established %u bind %u)\n",
  2849. tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size);
  2850. tcp_register_congestion_control(&tcp_reno);
  2851. memset(&tcp_secret_one.secrets[0], 0, sizeof(tcp_secret_one.secrets));
  2852. memset(&tcp_secret_two.secrets[0], 0, sizeof(tcp_secret_two.secrets));
  2853. tcp_secret_one.expires = jiffy; /* past due */
  2854. tcp_secret_two.expires = jiffy; /* past due */
  2855. tcp_secret_generating = &tcp_secret_one;
  2856. tcp_secret_primary = &tcp_secret_one;
  2857. tcp_secret_retiring = &tcp_secret_two;
  2858. tcp_secret_secondary = &tcp_secret_two;
  2859. }