tcp.c 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719
  1. /*
  2. * INET An implementation of the TCP/IP protocol suite for the LINUX
  3. * operating system. INET is implemented using the BSD Socket
  4. * interface as the means of communication with the user level.
  5. *
  6. * Implementation of the Transmission Control Protocol(TCP).
  7. *
  8. * Version: $Id: tcp.c,v 1.216 2002/02/01 22:01:04 davem Exp $
  9. *
  10. * Authors: Ross Biro
  11. * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
  12. * Mark Evans, <evansmp@uhura.aston.ac.uk>
  13. * Corey Minyard <wf-rch!minyard@relay.EU.net>
  14. * Florian La Roche, <flla@stud.uni-sb.de>
  15. * Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
  16. * Linus Torvalds, <torvalds@cs.helsinki.fi>
  17. * Alan Cox, <gw4pts@gw4pts.ampr.org>
  18. * Matthew Dillon, <dillon@apollo.west.oic.com>
  19. * Arnt Gulbrandsen, <agulbra@nvg.unit.no>
  20. * Jorge Cwik, <jorge@laser.satlink.net>
  21. *
  22. * Fixes:
  23. * Alan Cox : Numerous verify_area() calls
  24. * Alan Cox : Set the ACK bit on a reset
  25. * Alan Cox : Stopped it crashing if it closed while
  26. * sk->inuse=1 and was trying to connect
  27. * (tcp_err()).
  28. * Alan Cox : All icmp error handling was broken
  29. * pointers passed where wrong and the
  30. * socket was looked up backwards. Nobody
  31. * tested any icmp error code obviously.
  32. * Alan Cox : tcp_err() now handled properly. It
  33. * wakes people on errors. poll
  34. * behaves and the icmp error race
  35. * has gone by moving it into sock.c
  36. * Alan Cox : tcp_send_reset() fixed to work for
  37. * everything not just packets for
  38. * unknown sockets.
  39. * Alan Cox : tcp option processing.
  40. * Alan Cox : Reset tweaked (still not 100%) [Had
  41. * syn rule wrong]
  42. * Herp Rosmanith : More reset fixes
  43. * Alan Cox : No longer acks invalid rst frames.
  44. * Acking any kind of RST is right out.
  45. * Alan Cox : Sets an ignore me flag on an rst
  46. * receive otherwise odd bits of prattle
  47. * escape still
  48. * Alan Cox : Fixed another acking RST frame bug.
  49. * Should stop LAN workplace lockups.
  50. * Alan Cox : Some tidyups using the new skb list
  51. * facilities
  52. * Alan Cox : sk->keepopen now seems to work
  53. * Alan Cox : Pulls options out correctly on accepts
  54. * Alan Cox : Fixed assorted sk->rqueue->next errors
  55. * Alan Cox : PSH doesn't end a TCP read. Switched a
  56. * bit to skb ops.
  57. * Alan Cox : Tidied tcp_data to avoid a potential
  58. * nasty.
  59. * Alan Cox : Added some better commenting, as the
  60. * tcp is hard to follow
  61. * Alan Cox : Removed incorrect check for 20 * psh
  62. * Michael O'Reilly : ack < copied bug fix.
  63. * Johannes Stille : Misc tcp fixes (not all in yet).
  64. * Alan Cox : FIN with no memory -> CRASH
  65. * Alan Cox : Added socket option proto entries.
  66. * Also added awareness of them to accept.
  67. * Alan Cox : Added TCP options (SOL_TCP)
  68. * Alan Cox : Switched wakeup calls to callbacks,
  69. * so the kernel can layer network
  70. * sockets.
  71. * Alan Cox : Use ip_tos/ip_ttl settings.
  72. * Alan Cox : Handle FIN (more) properly (we hope).
  73. * Alan Cox : RST frames sent on unsynchronised
  74. * state ack error.
  75. * Alan Cox : Put in missing check for SYN bit.
  76. * Alan Cox : Added tcp_select_window() aka NET2E
  77. * window non shrink trick.
  78. * Alan Cox : Added a couple of small NET2E timer
  79. * fixes
  80. * Charles Hedrick : TCP fixes
  81. * Toomas Tamm : TCP window fixes
  82. * Alan Cox : Small URG fix to rlogin ^C ack fight
  83. * Charles Hedrick : Rewrote most of it to actually work
  84. * Linus : Rewrote tcp_read() and URG handling
  85. * completely
  86. * Gerhard Koerting: Fixed some missing timer handling
  87. * Matthew Dillon : Reworked TCP machine states as per RFC
  88. * Gerhard Koerting: PC/TCP workarounds
  89. * Adam Caldwell : Assorted timer/timing errors
  90. * Matthew Dillon : Fixed another RST bug
  91. * Alan Cox : Move to kernel side addressing changes.
  92. * Alan Cox : Beginning work on TCP fastpathing
  93. * (not yet usable)
  94. * Arnt Gulbrandsen: Turbocharged tcp_check() routine.
  95. * Alan Cox : TCP fast path debugging
  96. * Alan Cox : Window clamping
  97. * Michael Riepe : Bug in tcp_check()
  98. * Matt Dillon : More TCP improvements and RST bug fixes
  99. * Matt Dillon : Yet more small nasties remove from the
  100. * TCP code (Be very nice to this man if
  101. * tcp finally works 100%) 8)
  102. * Alan Cox : BSD accept semantics.
  103. * Alan Cox : Reset on closedown bug.
  104. * Peter De Schrijver : ENOTCONN check missing in tcp_sendto().
  105. * Michael Pall : Handle poll() after URG properly in
  106. * all cases.
  107. * Michael Pall : Undo the last fix in tcp_read_urg()
  108. * (multi URG PUSH broke rlogin).
  109. * Michael Pall : Fix the multi URG PUSH problem in
  110. * tcp_readable(), poll() after URG
  111. * works now.
  112. * Michael Pall : recv(...,MSG_OOB) never blocks in the
  113. * BSD api.
  114. * Alan Cox : Changed the semantics of sk->socket to
  115. * fix a race and a signal problem with
  116. * accept() and async I/O.
  117. * Alan Cox : Relaxed the rules on tcp_sendto().
  118. * Yury Shevchuk : Really fixed accept() blocking problem.
  119. * Craig I. Hagan : Allow for BSD compatible TIME_WAIT for
  120. * clients/servers which listen in on
  121. * fixed ports.
  122. * Alan Cox : Cleaned the above up and shrank it to
  123. * a sensible code size.
  124. * Alan Cox : Self connect lockup fix.
  125. * Alan Cox : No connect to multicast.
  126. * Ross Biro : Close unaccepted children on master
  127. * socket close.
  128. * Alan Cox : Reset tracing code.
  129. * Alan Cox : Spurious resets on shutdown.
  130. * Alan Cox : Giant 15 minute/60 second timer error
  131. * Alan Cox : Small whoops in polling before an
  132. * accept.
  133. * Alan Cox : Kept the state trace facility since
  134. * it's handy for debugging.
  135. * Alan Cox : More reset handler fixes.
  136. * Alan Cox : Started rewriting the code based on
  137. * the RFC's for other useful protocol
  138. * references see: Comer, KA9Q NOS, and
  139. * for a reference on the difference
  140. * between specifications and how BSD
  141. * works see the 4.4lite source.
  142. * A.N.Kuznetsov : Don't time wait on completion of tidy
  143. * close.
  144. * Linus Torvalds : Fin/Shutdown & copied_seq changes.
  145. * Linus Torvalds : Fixed BSD port reuse to work first syn
  146. * Alan Cox : Reimplemented timers as per the RFC
  147. * and using multiple timers for sanity.
  148. * Alan Cox : Small bug fixes, and a lot of new
  149. * comments.
  150. * Alan Cox : Fixed dual reader crash by locking
  151. * the buffers (much like datagram.c)
  152. * Alan Cox : Fixed stuck sockets in probe. A probe
  153. * now gets fed up of retrying without
  154. * (even a no space) answer.
  155. * Alan Cox : Extracted closing code better
  156. * Alan Cox : Fixed the closing state machine to
  157. * resemble the RFC.
  158. * Alan Cox : More 'per spec' fixes.
  159. * Jorge Cwik : Even faster checksumming.
  160. * Alan Cox : tcp_data() doesn't ack illegal PSH
  161. * only frames. At least one pc tcp stack
  162. * generates them.
  163. * Alan Cox : Cache last socket.
  164. * Alan Cox : Per route irtt.
  165. * Matt Day : poll()->select() match BSD precisely on error
  166. * Alan Cox : New buffers
  167. * Marc Tamsky : Various sk->prot->retransmits and
  168. * sk->retransmits misupdating fixed.
  169. * Fixed tcp_write_timeout: stuck close,
  170. * and TCP syn retries gets used now.
  171. * Mark Yarvis : In tcp_read_wakeup(), don't send an
  172. * ack if state is TCP_CLOSED.
  173. * Alan Cox : Look up device on a retransmit - routes may
  174. * change. Doesn't yet cope with MSS shrink right
  175. * but it's a start!
  176. * Marc Tamsky : Closing in closing fixes.
  177. * Mike Shaver : RFC1122 verifications.
  178. * Alan Cox : rcv_saddr errors.
  179. * Alan Cox : Block double connect().
  180. * Alan Cox : Small hooks for enSKIP.
  181. * Alexey Kuznetsov: Path MTU discovery.
  182. * Alan Cox : Support soft errors.
  183. * Alan Cox : Fix MTU discovery pathological case
  184. * when the remote claims no mtu!
  185. * Marc Tamsky : TCP_CLOSE fix.
  186. * Colin (G3TNE) : Send a reset on syn ack replies in
  187. * window but wrong (fixes NT lpd problems)
  188. * Pedro Roque : Better TCP window handling, delayed ack.
  189. * Joerg Reuter : No modification of locked buffers in
  190. * tcp_do_retransmit()
  191. * Eric Schenk : Changed receiver side silly window
  192. * avoidance algorithm to BSD style
  193. * algorithm. This doubles throughput
  194. * against machines running Solaris,
  195. * and seems to result in general
  196. * improvement.
  197. * Stefan Magdalinski : adjusted tcp_readable() to fix FIONREAD
  198. * Willy Konynenberg : Transparent proxying support.
  199. * Mike McLagan : Routing by source
  200. * Keith Owens : Do proper merging with partial SKB's in
  201. * tcp_do_sendmsg to avoid burstiness.
  202. * Eric Schenk : Fix fast close down bug with
  203. * shutdown() followed by close().
  204. * Andi Kleen : Make poll agree with SIGIO
  205. * Salvatore Sanfilippo : Support SO_LINGER with linger == 1 and
  206. * lingertime == 0 (RFC 793 ABORT Call)
  207. * Hirokazu Takahashi : Use copy_from_user() instead of
  208. * csum_and_copy_from_user() if possible.
  209. *
  210. * This program is free software; you can redistribute it and/or
  211. * modify it under the terms of the GNU General Public License
  212. * as published by the Free Software Foundation; either version
  213. * 2 of the License, or(at your option) any later version.
  214. *
  215. * Description of States:
  216. *
  217. * TCP_SYN_SENT sent a connection request, waiting for ack
  218. *
  219. * TCP_SYN_RECV received a connection request, sent ack,
  220. * waiting for final ack in three-way handshake.
  221. *
  222. * TCP_ESTABLISHED connection established
  223. *
  224. * TCP_FIN_WAIT1 our side has shutdown, waiting to complete
  225. * transmission of remaining buffered data
  226. *
  227. * TCP_FIN_WAIT2 all buffered data sent, waiting for remote
  228. * to shutdown
  229. *
  230. * TCP_CLOSING both sides have shutdown but we still have
  231. * data we have to finish sending
  232. *
  233. * TCP_TIME_WAIT timeout to catch resent junk before entering
  234. * closed, can only be entered from FIN_WAIT2
  235. * or CLOSING. Required because the other end
  236. * may not have gotten our last ACK causing it
  237. * to retransmit the data packet (which we ignore)
  238. *
  239. * TCP_CLOSE_WAIT remote side has shutdown and is waiting for
  240. * us to finish writing our data and to shutdown
  241. * (we have to close() to move on to LAST_ACK)
  242. *
  243. * TCP_LAST_ACK out side has shutdown after remote has
  244. * shutdown. There may still be data in our
  245. * buffer that we have to finish sending
  246. *
  247. * TCP_CLOSE socket is finished
  248. */
  249. #include <linux/kernel.h>
  250. #include <linux/module.h>
  251. #include <linux/types.h>
  252. #include <linux/fcntl.h>
  253. #include <linux/poll.h>
  254. #include <linux/init.h>
  255. #include <linux/fs.h>
  256. #include <linux/skbuff.h>
  257. #include <linux/splice.h>
  258. #include <linux/net.h>
  259. #include <linux/socket.h>
  260. #include <linux/random.h>
  261. #include <linux/bootmem.h>
  262. #include <linux/cache.h>
  263. #include <linux/err.h>
  264. #include <linux/crypto.h>
  265. #include <net/icmp.h>
  266. #include <net/tcp.h>
  267. #include <net/xfrm.h>
  268. #include <net/ip.h>
  269. #include <net/netdma.h>
  270. #include <net/sock.h>
  271. #include <asm/uaccess.h>
  272. #include <asm/ioctls.h>
  273. int sysctl_tcp_fin_timeout __read_mostly = TCP_FIN_TIMEOUT;
  274. DEFINE_SNMP_STAT(struct tcp_mib, tcp_statistics) __read_mostly;
  275. atomic_t tcp_orphan_count = ATOMIC_INIT(0);
  276. EXPORT_SYMBOL_GPL(tcp_orphan_count);
  277. int sysctl_tcp_mem[3] __read_mostly;
  278. int sysctl_tcp_wmem[3] __read_mostly;
  279. int sysctl_tcp_rmem[3] __read_mostly;
  280. EXPORT_SYMBOL(sysctl_tcp_mem);
  281. EXPORT_SYMBOL(sysctl_tcp_rmem);
  282. EXPORT_SYMBOL(sysctl_tcp_wmem);
  283. atomic_t tcp_memory_allocated; /* Current allocated memory. */
  284. atomic_t tcp_sockets_allocated; /* Current number of TCP sockets. */
  285. EXPORT_SYMBOL(tcp_memory_allocated);
  286. EXPORT_SYMBOL(tcp_sockets_allocated);
  287. /*
  288. * TCP splice context
  289. */
  290. struct tcp_splice_state {
  291. struct pipe_inode_info *pipe;
  292. size_t len;
  293. unsigned int flags;
  294. };
  295. /*
  296. * Pressure flag: try to collapse.
  297. * Technical note: it is used by multiple contexts non atomically.
  298. * All the __sk_mem_schedule() is of this nature: accounting
  299. * is strict, actions are advisory and have some latency.
  300. */
  301. int tcp_memory_pressure __read_mostly;
  302. EXPORT_SYMBOL(tcp_memory_pressure);
  303. void tcp_enter_memory_pressure(void)
  304. {
  305. if (!tcp_memory_pressure) {
  306. NET_INC_STATS(LINUX_MIB_TCPMEMORYPRESSURES);
  307. tcp_memory_pressure = 1;
  308. }
  309. }
  310. EXPORT_SYMBOL(tcp_enter_memory_pressure);
  311. /*
  312. * Wait for a TCP event.
  313. *
  314. * Note that we don't need to lock the socket, as the upper poll layers
  315. * take care of normal races (between the test and the event) and we don't
  316. * go look at any of the socket buffers directly.
  317. */
  318. unsigned int tcp_poll(struct file *file, struct socket *sock, poll_table *wait)
  319. {
  320. unsigned int mask;
  321. struct sock *sk = sock->sk;
  322. struct tcp_sock *tp = tcp_sk(sk);
  323. poll_wait(file, sk->sk_sleep, wait);
  324. if (sk->sk_state == TCP_LISTEN)
  325. return inet_csk_listen_poll(sk);
  326. /* Socket is not locked. We are protected from async events
  327. by poll logic and correct handling of state changes
  328. made by another threads is impossible in any case.
  329. */
  330. mask = 0;
  331. if (sk->sk_err)
  332. mask = POLLERR;
  333. /*
  334. * POLLHUP is certainly not done right. But poll() doesn't
  335. * have a notion of HUP in just one direction, and for a
  336. * socket the read side is more interesting.
  337. *
  338. * Some poll() documentation says that POLLHUP is incompatible
  339. * with the POLLOUT/POLLWR flags, so somebody should check this
  340. * all. But careful, it tends to be safer to return too many
  341. * bits than too few, and you can easily break real applications
  342. * if you don't tell them that something has hung up!
  343. *
  344. * Check-me.
  345. *
  346. * Check number 1. POLLHUP is _UNMASKABLE_ event (see UNIX98 and
  347. * our fs/select.c). It means that after we received EOF,
  348. * poll always returns immediately, making impossible poll() on write()
  349. * in state CLOSE_WAIT. One solution is evident --- to set POLLHUP
  350. * if and only if shutdown has been made in both directions.
  351. * Actually, it is interesting to look how Solaris and DUX
  352. * solve this dilemma. I would prefer, if PULLHUP were maskable,
  353. * then we could set it on SND_SHUTDOWN. BTW examples given
  354. * in Stevens' books assume exactly this behaviour, it explains
  355. * why PULLHUP is incompatible with POLLOUT. --ANK
  356. *
  357. * NOTE. Check for TCP_CLOSE is added. The goal is to prevent
  358. * blocking on fresh not-connected or disconnected socket. --ANK
  359. */
  360. if (sk->sk_shutdown == SHUTDOWN_MASK || sk->sk_state == TCP_CLOSE)
  361. mask |= POLLHUP;
  362. if (sk->sk_shutdown & RCV_SHUTDOWN)
  363. mask |= POLLIN | POLLRDNORM | POLLRDHUP;
  364. /* Connected? */
  365. if ((1 << sk->sk_state) & ~(TCPF_SYN_SENT | TCPF_SYN_RECV)) {
  366. /* Potential race condition. If read of tp below will
  367. * escape above sk->sk_state, we can be illegally awaken
  368. * in SYN_* states. */
  369. if ((tp->rcv_nxt != tp->copied_seq) &&
  370. (tp->urg_seq != tp->copied_seq ||
  371. tp->rcv_nxt != tp->copied_seq + 1 ||
  372. sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data))
  373. mask |= POLLIN | POLLRDNORM;
  374. if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
  375. if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk)) {
  376. mask |= POLLOUT | POLLWRNORM;
  377. } else { /* send SIGIO later */
  378. set_bit(SOCK_ASYNC_NOSPACE,
  379. &sk->sk_socket->flags);
  380. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  381. /* Race breaker. If space is freed after
  382. * wspace test but before the flags are set,
  383. * IO signal will be lost.
  384. */
  385. if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk))
  386. mask |= POLLOUT | POLLWRNORM;
  387. }
  388. }
  389. if (tp->urg_data & TCP_URG_VALID)
  390. mask |= POLLPRI;
  391. }
  392. return mask;
  393. }
  394. int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg)
  395. {
  396. struct tcp_sock *tp = tcp_sk(sk);
  397. int answ;
  398. switch (cmd) {
  399. case SIOCINQ:
  400. if (sk->sk_state == TCP_LISTEN)
  401. return -EINVAL;
  402. lock_sock(sk);
  403. if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
  404. answ = 0;
  405. else if (sock_flag(sk, SOCK_URGINLINE) ||
  406. !tp->urg_data ||
  407. before(tp->urg_seq, tp->copied_seq) ||
  408. !before(tp->urg_seq, tp->rcv_nxt)) {
  409. answ = tp->rcv_nxt - tp->copied_seq;
  410. /* Subtract 1, if FIN is in queue. */
  411. if (answ && !skb_queue_empty(&sk->sk_receive_queue))
  412. answ -=
  413. tcp_hdr((struct sk_buff *)sk->sk_receive_queue.prev)->fin;
  414. } else
  415. answ = tp->urg_seq - tp->copied_seq;
  416. release_sock(sk);
  417. break;
  418. case SIOCATMARK:
  419. answ = tp->urg_data && tp->urg_seq == tp->copied_seq;
  420. break;
  421. case SIOCOUTQ:
  422. if (sk->sk_state == TCP_LISTEN)
  423. return -EINVAL;
  424. if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
  425. answ = 0;
  426. else
  427. answ = tp->write_seq - tp->snd_una;
  428. break;
  429. default:
  430. return -ENOIOCTLCMD;
  431. }
  432. return put_user(answ, (int __user *)arg);
  433. }
  434. static inline void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb)
  435. {
  436. TCP_SKB_CB(skb)->flags |= TCPCB_FLAG_PSH;
  437. tp->pushed_seq = tp->write_seq;
  438. }
  439. static inline int forced_push(struct tcp_sock *tp)
  440. {
  441. return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1));
  442. }
  443. static inline void skb_entail(struct sock *sk, struct sk_buff *skb)
  444. {
  445. struct tcp_sock *tp = tcp_sk(sk);
  446. struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
  447. skb->csum = 0;
  448. tcb->seq = tcb->end_seq = tp->write_seq;
  449. tcb->flags = TCPCB_FLAG_ACK;
  450. tcb->sacked = 0;
  451. skb_header_release(skb);
  452. tcp_add_write_queue_tail(sk, skb);
  453. sk->sk_wmem_queued += skb->truesize;
  454. sk_mem_charge(sk, skb->truesize);
  455. if (tp->nonagle & TCP_NAGLE_PUSH)
  456. tp->nonagle &= ~TCP_NAGLE_PUSH;
  457. }
  458. static inline void tcp_mark_urg(struct tcp_sock *tp, int flags,
  459. struct sk_buff *skb)
  460. {
  461. if (flags & MSG_OOB) {
  462. tp->urg_mode = 1;
  463. tp->snd_up = tp->write_seq;
  464. }
  465. }
  466. static inline void tcp_push(struct sock *sk, int flags, int mss_now,
  467. int nonagle)
  468. {
  469. struct tcp_sock *tp = tcp_sk(sk);
  470. if (tcp_send_head(sk)) {
  471. struct sk_buff *skb = tcp_write_queue_tail(sk);
  472. if (!(flags & MSG_MORE) || forced_push(tp))
  473. tcp_mark_push(tp, skb);
  474. tcp_mark_urg(tp, flags, skb);
  475. __tcp_push_pending_frames(sk, mss_now,
  476. (flags & MSG_MORE) ? TCP_NAGLE_CORK : nonagle);
  477. }
  478. }
  479. static int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
  480. unsigned int offset, size_t len)
  481. {
  482. struct tcp_splice_state *tss = rd_desc->arg.data;
  483. return skb_splice_bits(skb, offset, tss->pipe, tss->len, tss->flags);
  484. }
  485. static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss)
  486. {
  487. /* Store TCP splice context information in read_descriptor_t. */
  488. read_descriptor_t rd_desc = {
  489. .arg.data = tss,
  490. };
  491. return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv);
  492. }
  493. /**
  494. * tcp_splice_read - splice data from TCP socket to a pipe
  495. * @sock: socket to splice from
  496. * @ppos: position (not valid)
  497. * @pipe: pipe to splice to
  498. * @len: number of bytes to splice
  499. * @flags: splice modifier flags
  500. *
  501. * Description:
  502. * Will read pages from given socket and fill them into a pipe.
  503. *
  504. **/
  505. ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
  506. struct pipe_inode_info *pipe, size_t len,
  507. unsigned int flags)
  508. {
  509. struct sock *sk = sock->sk;
  510. struct tcp_splice_state tss = {
  511. .pipe = pipe,
  512. .len = len,
  513. .flags = flags,
  514. };
  515. long timeo;
  516. ssize_t spliced;
  517. int ret;
  518. /*
  519. * We can't seek on a socket input
  520. */
  521. if (unlikely(*ppos))
  522. return -ESPIPE;
  523. ret = spliced = 0;
  524. lock_sock(sk);
  525. timeo = sock_rcvtimeo(sk, flags & SPLICE_F_NONBLOCK);
  526. while (tss.len) {
  527. ret = __tcp_splice_read(sk, &tss);
  528. if (ret < 0)
  529. break;
  530. else if (!ret) {
  531. if (spliced)
  532. break;
  533. if (flags & SPLICE_F_NONBLOCK) {
  534. ret = -EAGAIN;
  535. break;
  536. }
  537. if (sock_flag(sk, SOCK_DONE))
  538. break;
  539. if (sk->sk_err) {
  540. ret = sock_error(sk);
  541. break;
  542. }
  543. if (sk->sk_shutdown & RCV_SHUTDOWN)
  544. break;
  545. if (sk->sk_state == TCP_CLOSE) {
  546. /*
  547. * This occurs when user tries to read
  548. * from never connected socket.
  549. */
  550. if (!sock_flag(sk, SOCK_DONE))
  551. ret = -ENOTCONN;
  552. break;
  553. }
  554. if (!timeo) {
  555. ret = -EAGAIN;
  556. break;
  557. }
  558. sk_wait_data(sk, &timeo);
  559. if (signal_pending(current)) {
  560. ret = sock_intr_errno(timeo);
  561. break;
  562. }
  563. continue;
  564. }
  565. tss.len -= ret;
  566. spliced += ret;
  567. release_sock(sk);
  568. lock_sock(sk);
  569. if (sk->sk_err || sk->sk_state == TCP_CLOSE ||
  570. (sk->sk_shutdown & RCV_SHUTDOWN) || !timeo ||
  571. signal_pending(current))
  572. break;
  573. }
  574. release_sock(sk);
  575. if (spliced)
  576. return spliced;
  577. return ret;
  578. }
  579. struct sk_buff *sk_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp)
  580. {
  581. struct sk_buff *skb;
  582. /* The TCP header must be at least 32-bit aligned. */
  583. size = ALIGN(size, 4);
  584. skb = alloc_skb_fclone(size + sk->sk_prot->max_header, gfp);
  585. if (skb) {
  586. if (sk_wmem_schedule(sk, skb->truesize)) {
  587. /*
  588. * Make sure that we have exactly size bytes
  589. * available to the caller, no more, no less.
  590. */
  591. skb_reserve(skb, skb_tailroom(skb) - size);
  592. return skb;
  593. }
  594. __kfree_skb(skb);
  595. } else {
  596. sk->sk_prot->enter_memory_pressure();
  597. sk_stream_moderate_sndbuf(sk);
  598. }
  599. return NULL;
  600. }
  601. static ssize_t do_tcp_sendpages(struct sock *sk, struct page **pages, int poffset,
  602. size_t psize, int flags)
  603. {
  604. struct tcp_sock *tp = tcp_sk(sk);
  605. int mss_now, size_goal;
  606. int err;
  607. ssize_t copied;
  608. long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
  609. /* Wait for a connection to finish. */
  610. if ((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT))
  611. if ((err = sk_stream_wait_connect(sk, &timeo)) != 0)
  612. goto out_err;
  613. clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
  614. mss_now = tcp_current_mss(sk, !(flags&MSG_OOB));
  615. size_goal = tp->xmit_size_goal;
  616. copied = 0;
  617. err = -EPIPE;
  618. if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
  619. goto do_error;
  620. while (psize > 0) {
  621. struct sk_buff *skb = tcp_write_queue_tail(sk);
  622. struct page *page = pages[poffset / PAGE_SIZE];
  623. int copy, i, can_coalesce;
  624. int offset = poffset % PAGE_SIZE;
  625. int size = min_t(size_t, psize, PAGE_SIZE - offset);
  626. if (!tcp_send_head(sk) || (copy = size_goal - skb->len) <= 0) {
  627. new_segment:
  628. if (!sk_stream_memory_free(sk))
  629. goto wait_for_sndbuf;
  630. skb = sk_stream_alloc_skb(sk, 0, sk->sk_allocation);
  631. if (!skb)
  632. goto wait_for_memory;
  633. skb_entail(sk, skb);
  634. copy = size_goal;
  635. }
  636. if (copy > size)
  637. copy = size;
  638. i = skb_shinfo(skb)->nr_frags;
  639. can_coalesce = skb_can_coalesce(skb, i, page, offset);
  640. if (!can_coalesce && i >= MAX_SKB_FRAGS) {
  641. tcp_mark_push(tp, skb);
  642. goto new_segment;
  643. }
  644. if (!sk_wmem_schedule(sk, copy))
  645. goto wait_for_memory;
  646. if (can_coalesce) {
  647. skb_shinfo(skb)->frags[i - 1].size += copy;
  648. } else {
  649. get_page(page);
  650. skb_fill_page_desc(skb, i, page, offset, copy);
  651. }
  652. skb->len += copy;
  653. skb->data_len += copy;
  654. skb->truesize += copy;
  655. sk->sk_wmem_queued += copy;
  656. sk_mem_charge(sk, copy);
  657. skb->ip_summed = CHECKSUM_PARTIAL;
  658. tp->write_seq += copy;
  659. TCP_SKB_CB(skb)->end_seq += copy;
  660. skb_shinfo(skb)->gso_segs = 0;
  661. if (!copied)
  662. TCP_SKB_CB(skb)->flags &= ~TCPCB_FLAG_PSH;
  663. copied += copy;
  664. poffset += copy;
  665. if (!(psize -= copy))
  666. goto out;
  667. if (skb->len < size_goal || (flags & MSG_OOB))
  668. continue;
  669. if (forced_push(tp)) {
  670. tcp_mark_push(tp, skb);
  671. __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
  672. } else if (skb == tcp_send_head(sk))
  673. tcp_push_one(sk, mss_now);
  674. continue;
  675. wait_for_sndbuf:
  676. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  677. wait_for_memory:
  678. if (copied)
  679. tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH);
  680. if ((err = sk_stream_wait_memory(sk, &timeo)) != 0)
  681. goto do_error;
  682. mss_now = tcp_current_mss(sk, !(flags&MSG_OOB));
  683. size_goal = tp->xmit_size_goal;
  684. }
  685. out:
  686. if (copied)
  687. tcp_push(sk, flags, mss_now, tp->nonagle);
  688. return copied;
  689. do_error:
  690. if (copied)
  691. goto out;
  692. out_err:
  693. return sk_stream_error(sk, flags, err);
  694. }
  695. ssize_t tcp_sendpage(struct socket *sock, struct page *page, int offset,
  696. size_t size, int flags)
  697. {
  698. ssize_t res;
  699. struct sock *sk = sock->sk;
  700. if (!(sk->sk_route_caps & NETIF_F_SG) ||
  701. !(sk->sk_route_caps & NETIF_F_ALL_CSUM))
  702. return sock_no_sendpage(sock, page, offset, size, flags);
  703. lock_sock(sk);
  704. TCP_CHECK_TIMER(sk);
  705. res = do_tcp_sendpages(sk, &page, offset, size, flags);
  706. TCP_CHECK_TIMER(sk);
  707. release_sock(sk);
  708. return res;
  709. }
  710. #define TCP_PAGE(sk) (sk->sk_sndmsg_page)
  711. #define TCP_OFF(sk) (sk->sk_sndmsg_off)
  712. static inline int select_size(struct sock *sk)
  713. {
  714. struct tcp_sock *tp = tcp_sk(sk);
  715. int tmp = tp->mss_cache;
  716. if (sk->sk_route_caps & NETIF_F_SG) {
  717. if (sk_can_gso(sk))
  718. tmp = 0;
  719. else {
  720. int pgbreak = SKB_MAX_HEAD(MAX_TCP_HEADER);
  721. if (tmp >= pgbreak &&
  722. tmp <= pgbreak + (MAX_SKB_FRAGS - 1) * PAGE_SIZE)
  723. tmp = pgbreak;
  724. }
  725. }
  726. return tmp;
  727. }
  728. int tcp_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
  729. size_t size)
  730. {
  731. struct sock *sk = sock->sk;
  732. struct iovec *iov;
  733. struct tcp_sock *tp = tcp_sk(sk);
  734. struct sk_buff *skb;
  735. int iovlen, flags;
  736. int mss_now, size_goal;
  737. int err, copied;
  738. long timeo;
  739. lock_sock(sk);
  740. TCP_CHECK_TIMER(sk);
  741. flags = msg->msg_flags;
  742. timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
  743. /* Wait for a connection to finish. */
  744. if ((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT))
  745. if ((err = sk_stream_wait_connect(sk, &timeo)) != 0)
  746. goto out_err;
  747. /* This should be in poll */
  748. clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
  749. mss_now = tcp_current_mss(sk, !(flags&MSG_OOB));
  750. size_goal = tp->xmit_size_goal;
  751. /* Ok commence sending. */
  752. iovlen = msg->msg_iovlen;
  753. iov = msg->msg_iov;
  754. copied = 0;
  755. err = -EPIPE;
  756. if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
  757. goto do_error;
  758. while (--iovlen >= 0) {
  759. int seglen = iov->iov_len;
  760. unsigned char __user *from = iov->iov_base;
  761. iov++;
  762. while (seglen > 0) {
  763. int copy;
  764. skb = tcp_write_queue_tail(sk);
  765. if (!tcp_send_head(sk) ||
  766. (copy = size_goal - skb->len) <= 0) {
  767. new_segment:
  768. /* Allocate new segment. If the interface is SG,
  769. * allocate skb fitting to single page.
  770. */
  771. if (!sk_stream_memory_free(sk))
  772. goto wait_for_sndbuf;
  773. skb = sk_stream_alloc_skb(sk, select_size(sk),
  774. sk->sk_allocation);
  775. if (!skb)
  776. goto wait_for_memory;
  777. /*
  778. * Check whether we can use HW checksum.
  779. */
  780. if (sk->sk_route_caps & NETIF_F_ALL_CSUM)
  781. skb->ip_summed = CHECKSUM_PARTIAL;
  782. skb_entail(sk, skb);
  783. copy = size_goal;
  784. }
  785. /* Try to append data to the end of skb. */
  786. if (copy > seglen)
  787. copy = seglen;
  788. /* Where to copy to? */
  789. if (skb_tailroom(skb) > 0) {
  790. /* We have some space in skb head. Superb! */
  791. if (copy > skb_tailroom(skb))
  792. copy = skb_tailroom(skb);
  793. if ((err = skb_add_data(skb, from, copy)) != 0)
  794. goto do_fault;
  795. } else {
  796. int merge = 0;
  797. int i = skb_shinfo(skb)->nr_frags;
  798. struct page *page = TCP_PAGE(sk);
  799. int off = TCP_OFF(sk);
  800. if (skb_can_coalesce(skb, i, page, off) &&
  801. off != PAGE_SIZE) {
  802. /* We can extend the last page
  803. * fragment. */
  804. merge = 1;
  805. } else if (i == MAX_SKB_FRAGS ||
  806. (!i &&
  807. !(sk->sk_route_caps & NETIF_F_SG))) {
  808. /* Need to add new fragment and cannot
  809. * do this because interface is non-SG,
  810. * or because all the page slots are
  811. * busy. */
  812. tcp_mark_push(tp, skb);
  813. goto new_segment;
  814. } else if (page) {
  815. if (off == PAGE_SIZE) {
  816. put_page(page);
  817. TCP_PAGE(sk) = page = NULL;
  818. off = 0;
  819. }
  820. } else
  821. off = 0;
  822. if (copy > PAGE_SIZE - off)
  823. copy = PAGE_SIZE - off;
  824. if (!sk_wmem_schedule(sk, copy))
  825. goto wait_for_memory;
  826. if (!page) {
  827. /* Allocate new cache page. */
  828. if (!(page = sk_stream_alloc_page(sk)))
  829. goto wait_for_memory;
  830. }
  831. /* Time to copy data. We are close to
  832. * the end! */
  833. err = skb_copy_to_page(sk, from, skb, page,
  834. off, copy);
  835. if (err) {
  836. /* If this page was new, give it to the
  837. * socket so it does not get leaked.
  838. */
  839. if (!TCP_PAGE(sk)) {
  840. TCP_PAGE(sk) = page;
  841. TCP_OFF(sk) = 0;
  842. }
  843. goto do_error;
  844. }
  845. /* Update the skb. */
  846. if (merge) {
  847. skb_shinfo(skb)->frags[i - 1].size +=
  848. copy;
  849. } else {
  850. skb_fill_page_desc(skb, i, page, off, copy);
  851. if (TCP_PAGE(sk)) {
  852. get_page(page);
  853. } else if (off + copy < PAGE_SIZE) {
  854. get_page(page);
  855. TCP_PAGE(sk) = page;
  856. }
  857. }
  858. TCP_OFF(sk) = off + copy;
  859. }
  860. if (!copied)
  861. TCP_SKB_CB(skb)->flags &= ~TCPCB_FLAG_PSH;
  862. tp->write_seq += copy;
  863. TCP_SKB_CB(skb)->end_seq += copy;
  864. skb_shinfo(skb)->gso_segs = 0;
  865. from += copy;
  866. copied += copy;
  867. if ((seglen -= copy) == 0 && iovlen == 0)
  868. goto out;
  869. if (skb->len < size_goal || (flags & MSG_OOB))
  870. continue;
  871. if (forced_push(tp)) {
  872. tcp_mark_push(tp, skb);
  873. __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
  874. } else if (skb == tcp_send_head(sk))
  875. tcp_push_one(sk, mss_now);
  876. continue;
  877. wait_for_sndbuf:
  878. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  879. wait_for_memory:
  880. if (copied)
  881. tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH);
  882. if ((err = sk_stream_wait_memory(sk, &timeo)) != 0)
  883. goto do_error;
  884. mss_now = tcp_current_mss(sk, !(flags&MSG_OOB));
  885. size_goal = tp->xmit_size_goal;
  886. }
  887. }
  888. out:
  889. if (copied)
  890. tcp_push(sk, flags, mss_now, tp->nonagle);
  891. TCP_CHECK_TIMER(sk);
  892. release_sock(sk);
  893. return copied;
  894. do_fault:
  895. if (!skb->len) {
  896. tcp_unlink_write_queue(skb, sk);
  897. /* It is the one place in all of TCP, except connection
  898. * reset, where we can be unlinking the send_head.
  899. */
  900. tcp_check_send_head(sk, skb);
  901. sk_wmem_free_skb(sk, skb);
  902. }
  903. do_error:
  904. if (copied)
  905. goto out;
  906. out_err:
  907. err = sk_stream_error(sk, flags, err);
  908. TCP_CHECK_TIMER(sk);
  909. release_sock(sk);
  910. return err;
  911. }
  912. /*
  913. * Handle reading urgent data. BSD has very simple semantics for
  914. * this, no blocking and very strange errors 8)
  915. */
  916. static int tcp_recv_urg(struct sock *sk, long timeo,
  917. struct msghdr *msg, int len, int flags,
  918. int *addr_len)
  919. {
  920. struct tcp_sock *tp = tcp_sk(sk);
  921. /* No URG data to read. */
  922. if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data ||
  923. tp->urg_data == TCP_URG_READ)
  924. return -EINVAL; /* Yes this is right ! */
  925. if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE))
  926. return -ENOTCONN;
  927. if (tp->urg_data & TCP_URG_VALID) {
  928. int err = 0;
  929. char c = tp->urg_data;
  930. if (!(flags & MSG_PEEK))
  931. tp->urg_data = TCP_URG_READ;
  932. /* Read urgent data. */
  933. msg->msg_flags |= MSG_OOB;
  934. if (len > 0) {
  935. if (!(flags & MSG_TRUNC))
  936. err = memcpy_toiovec(msg->msg_iov, &c, 1);
  937. len = 1;
  938. } else
  939. msg->msg_flags |= MSG_TRUNC;
  940. return err ? -EFAULT : len;
  941. }
  942. if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN))
  943. return 0;
  944. /* Fixed the recv(..., MSG_OOB) behaviour. BSD docs and
  945. * the available implementations agree in this case:
  946. * this call should never block, independent of the
  947. * blocking state of the socket.
  948. * Mike <pall@rz.uni-karlsruhe.de>
  949. */
  950. return -EAGAIN;
  951. }
  952. /* Clean up the receive buffer for full frames taken by the user,
  953. * then send an ACK if necessary. COPIED is the number of bytes
  954. * tcp_recvmsg has given to the user so far, it speeds up the
  955. * calculation of whether or not we must ACK for the sake of
  956. * a window update.
  957. */
  958. void tcp_cleanup_rbuf(struct sock *sk, int copied)
  959. {
  960. struct tcp_sock *tp = tcp_sk(sk);
  961. int time_to_ack = 0;
  962. #if TCP_DEBUG
  963. struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
  964. BUG_TRAP(!skb || before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq));
  965. #endif
  966. if (inet_csk_ack_scheduled(sk)) {
  967. const struct inet_connection_sock *icsk = inet_csk(sk);
  968. /* Delayed ACKs frequently hit locked sockets during bulk
  969. * receive. */
  970. if (icsk->icsk_ack.blocked ||
  971. /* Once-per-two-segments ACK was not sent by tcp_input.c */
  972. tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss ||
  973. /*
  974. * If this read emptied read buffer, we send ACK, if
  975. * connection is not bidirectional, user drained
  976. * receive buffer and there was a small segment
  977. * in queue.
  978. */
  979. (copied > 0 &&
  980. ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) ||
  981. ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) &&
  982. !icsk->icsk_ack.pingpong)) &&
  983. !atomic_read(&sk->sk_rmem_alloc)))
  984. time_to_ack = 1;
  985. }
  986. /* We send an ACK if we can now advertise a non-zero window
  987. * which has been raised "significantly".
  988. *
  989. * Even if window raised up to infinity, do not send window open ACK
  990. * in states, where we will not receive more. It is useless.
  991. */
  992. if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
  993. __u32 rcv_window_now = tcp_receive_window(tp);
  994. /* Optimize, __tcp_select_window() is not cheap. */
  995. if (2*rcv_window_now <= tp->window_clamp) {
  996. __u32 new_window = __tcp_select_window(sk);
  997. /* Send ACK now, if this read freed lots of space
  998. * in our buffer. Certainly, new_window is new window.
  999. * We can advertise it now, if it is not less than current one.
  1000. * "Lots" means "at least twice" here.
  1001. */
  1002. if (new_window && new_window >= 2 * rcv_window_now)
  1003. time_to_ack = 1;
  1004. }
  1005. }
  1006. if (time_to_ack)
  1007. tcp_send_ack(sk);
  1008. }
  1009. static void tcp_prequeue_process(struct sock *sk)
  1010. {
  1011. struct sk_buff *skb;
  1012. struct tcp_sock *tp = tcp_sk(sk);
  1013. NET_INC_STATS_USER(LINUX_MIB_TCPPREQUEUED);
  1014. /* RX process wants to run with disabled BHs, though it is not
  1015. * necessary */
  1016. local_bh_disable();
  1017. while ((skb = __skb_dequeue(&tp->ucopy.prequeue)) != NULL)
  1018. sk->sk_backlog_rcv(sk, skb);
  1019. local_bh_enable();
  1020. /* Clear memory counter. */
  1021. tp->ucopy.memory = 0;
  1022. }
  1023. static inline struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off)
  1024. {
  1025. struct sk_buff *skb;
  1026. u32 offset;
  1027. skb_queue_walk(&sk->sk_receive_queue, skb) {
  1028. offset = seq - TCP_SKB_CB(skb)->seq;
  1029. if (tcp_hdr(skb)->syn)
  1030. offset--;
  1031. if (offset < skb->len || tcp_hdr(skb)->fin) {
  1032. *off = offset;
  1033. return skb;
  1034. }
  1035. }
  1036. return NULL;
  1037. }
  1038. /*
  1039. * This routine provides an alternative to tcp_recvmsg() for routines
  1040. * that would like to handle copying from skbuffs directly in 'sendfile'
  1041. * fashion.
  1042. * Note:
  1043. * - It is assumed that the socket was locked by the caller.
  1044. * - The routine does not block.
  1045. * - At present, there is no support for reading OOB data
  1046. * or for 'peeking' the socket using this routine
  1047. * (although both would be easy to implement).
  1048. */
  1049. int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
  1050. sk_read_actor_t recv_actor)
  1051. {
  1052. struct sk_buff *skb;
  1053. struct tcp_sock *tp = tcp_sk(sk);
  1054. u32 seq = tp->copied_seq;
  1055. u32 offset;
  1056. int copied = 0;
  1057. if (sk->sk_state == TCP_LISTEN)
  1058. return -ENOTCONN;
  1059. while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
  1060. if (offset < skb->len) {
  1061. size_t used, len;
  1062. len = skb->len - offset;
  1063. /* Stop reading if we hit a patch of urgent data */
  1064. if (tp->urg_data) {
  1065. u32 urg_offset = tp->urg_seq - seq;
  1066. if (urg_offset < len)
  1067. len = urg_offset;
  1068. if (!len)
  1069. break;
  1070. }
  1071. used = recv_actor(desc, skb, offset, len);
  1072. if (used < 0) {
  1073. if (!copied)
  1074. copied = used;
  1075. break;
  1076. } else if (used <= len) {
  1077. seq += used;
  1078. copied += used;
  1079. offset += used;
  1080. }
  1081. if (offset != skb->len)
  1082. break;
  1083. }
  1084. if (tcp_hdr(skb)->fin) {
  1085. sk_eat_skb(sk, skb, 0);
  1086. ++seq;
  1087. break;
  1088. }
  1089. sk_eat_skb(sk, skb, 0);
  1090. if (!desc->count)
  1091. break;
  1092. }
  1093. tp->copied_seq = seq;
  1094. tcp_rcv_space_adjust(sk);
  1095. /* Clean up data we have read: This will do ACK frames. */
  1096. if (copied > 0)
  1097. tcp_cleanup_rbuf(sk, copied);
  1098. return copied;
  1099. }
  1100. /*
  1101. * This routine copies from a sock struct into the user buffer.
  1102. *
  1103. * Technical note: in 2.3 we work on _locked_ socket, so that
  1104. * tricks with *seq access order and skb->users are not required.
  1105. * Probably, code can be easily improved even more.
  1106. */
  1107. int tcp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
  1108. size_t len, int nonblock, int flags, int *addr_len)
  1109. {
  1110. struct tcp_sock *tp = tcp_sk(sk);
  1111. int copied = 0;
  1112. u32 peek_seq;
  1113. u32 *seq;
  1114. unsigned long used;
  1115. int err;
  1116. int target; /* Read at least this many bytes */
  1117. long timeo;
  1118. struct task_struct *user_recv = NULL;
  1119. int copied_early = 0;
  1120. struct sk_buff *skb;
  1121. lock_sock(sk);
  1122. TCP_CHECK_TIMER(sk);
  1123. err = -ENOTCONN;
  1124. if (sk->sk_state == TCP_LISTEN)
  1125. goto out;
  1126. timeo = sock_rcvtimeo(sk, nonblock);
  1127. /* Urgent data needs to be handled specially. */
  1128. if (flags & MSG_OOB)
  1129. goto recv_urg;
  1130. seq = &tp->copied_seq;
  1131. if (flags & MSG_PEEK) {
  1132. peek_seq = tp->copied_seq;
  1133. seq = &peek_seq;
  1134. }
  1135. target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
  1136. #ifdef CONFIG_NET_DMA
  1137. tp->ucopy.dma_chan = NULL;
  1138. preempt_disable();
  1139. skb = skb_peek_tail(&sk->sk_receive_queue);
  1140. {
  1141. int available = 0;
  1142. if (skb)
  1143. available = TCP_SKB_CB(skb)->seq + skb->len - (*seq);
  1144. if ((available < target) &&
  1145. (len > sysctl_tcp_dma_copybreak) && !(flags & MSG_PEEK) &&
  1146. !sysctl_tcp_low_latency &&
  1147. __get_cpu_var(softnet_data).net_dma) {
  1148. preempt_enable_no_resched();
  1149. tp->ucopy.pinned_list =
  1150. dma_pin_iovec_pages(msg->msg_iov, len);
  1151. } else {
  1152. preempt_enable_no_resched();
  1153. }
  1154. }
  1155. #endif
  1156. do {
  1157. u32 offset;
  1158. /* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */
  1159. if (tp->urg_data && tp->urg_seq == *seq) {
  1160. if (copied)
  1161. break;
  1162. if (signal_pending(current)) {
  1163. copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
  1164. break;
  1165. }
  1166. }
  1167. /* Next get a buffer. */
  1168. skb = skb_peek(&sk->sk_receive_queue);
  1169. do {
  1170. if (!skb)
  1171. break;
  1172. /* Now that we have two receive queues this
  1173. * shouldn't happen.
  1174. */
  1175. if (before(*seq, TCP_SKB_CB(skb)->seq)) {
  1176. printk(KERN_INFO "recvmsg bug: copied %X "
  1177. "seq %X\n", *seq, TCP_SKB_CB(skb)->seq);
  1178. break;
  1179. }
  1180. offset = *seq - TCP_SKB_CB(skb)->seq;
  1181. if (tcp_hdr(skb)->syn)
  1182. offset--;
  1183. if (offset < skb->len)
  1184. goto found_ok_skb;
  1185. if (tcp_hdr(skb)->fin)
  1186. goto found_fin_ok;
  1187. BUG_TRAP(flags & MSG_PEEK);
  1188. skb = skb->next;
  1189. } while (skb != (struct sk_buff *)&sk->sk_receive_queue);
  1190. /* Well, if we have backlog, try to process it now yet. */
  1191. if (copied >= target && !sk->sk_backlog.tail)
  1192. break;
  1193. if (copied) {
  1194. if (sk->sk_err ||
  1195. sk->sk_state == TCP_CLOSE ||
  1196. (sk->sk_shutdown & RCV_SHUTDOWN) ||
  1197. !timeo ||
  1198. signal_pending(current) ||
  1199. (flags & MSG_PEEK))
  1200. break;
  1201. } else {
  1202. if (sock_flag(sk, SOCK_DONE))
  1203. break;
  1204. if (sk->sk_err) {
  1205. copied = sock_error(sk);
  1206. break;
  1207. }
  1208. if (sk->sk_shutdown & RCV_SHUTDOWN)
  1209. break;
  1210. if (sk->sk_state == TCP_CLOSE) {
  1211. if (!sock_flag(sk, SOCK_DONE)) {
  1212. /* This occurs when user tries to read
  1213. * from never connected socket.
  1214. */
  1215. copied = -ENOTCONN;
  1216. break;
  1217. }
  1218. break;
  1219. }
  1220. if (!timeo) {
  1221. copied = -EAGAIN;
  1222. break;
  1223. }
  1224. if (signal_pending(current)) {
  1225. copied = sock_intr_errno(timeo);
  1226. break;
  1227. }
  1228. }
  1229. tcp_cleanup_rbuf(sk, copied);
  1230. if (!sysctl_tcp_low_latency && tp->ucopy.task == user_recv) {
  1231. /* Install new reader */
  1232. if (!user_recv && !(flags & (MSG_TRUNC | MSG_PEEK))) {
  1233. user_recv = current;
  1234. tp->ucopy.task = user_recv;
  1235. tp->ucopy.iov = msg->msg_iov;
  1236. }
  1237. tp->ucopy.len = len;
  1238. BUG_TRAP(tp->copied_seq == tp->rcv_nxt ||
  1239. (flags & (MSG_PEEK | MSG_TRUNC)));
  1240. /* Ugly... If prequeue is not empty, we have to
  1241. * process it before releasing socket, otherwise
  1242. * order will be broken at second iteration.
  1243. * More elegant solution is required!!!
  1244. *
  1245. * Look: we have the following (pseudo)queues:
  1246. *
  1247. * 1. packets in flight
  1248. * 2. backlog
  1249. * 3. prequeue
  1250. * 4. receive_queue
  1251. *
  1252. * Each queue can be processed only if the next ones
  1253. * are empty. At this point we have empty receive_queue.
  1254. * But prequeue _can_ be not empty after 2nd iteration,
  1255. * when we jumped to start of loop because backlog
  1256. * processing added something to receive_queue.
  1257. * We cannot release_sock(), because backlog contains
  1258. * packets arrived _after_ prequeued ones.
  1259. *
  1260. * Shortly, algorithm is clear --- to process all
  1261. * the queues in order. We could make it more directly,
  1262. * requeueing packets from backlog to prequeue, if
  1263. * is not empty. It is more elegant, but eats cycles,
  1264. * unfortunately.
  1265. */
  1266. if (!skb_queue_empty(&tp->ucopy.prequeue))
  1267. goto do_prequeue;
  1268. /* __ Set realtime policy in scheduler __ */
  1269. }
  1270. if (copied >= target) {
  1271. /* Do not sleep, just process backlog. */
  1272. release_sock(sk);
  1273. lock_sock(sk);
  1274. } else
  1275. sk_wait_data(sk, &timeo);
  1276. #ifdef CONFIG_NET_DMA
  1277. tp->ucopy.wakeup = 0;
  1278. #endif
  1279. if (user_recv) {
  1280. int chunk;
  1281. /* __ Restore normal policy in scheduler __ */
  1282. if ((chunk = len - tp->ucopy.len) != 0) {
  1283. NET_ADD_STATS_USER(LINUX_MIB_TCPDIRECTCOPYFROMBACKLOG, chunk);
  1284. len -= chunk;
  1285. copied += chunk;
  1286. }
  1287. if (tp->rcv_nxt == tp->copied_seq &&
  1288. !skb_queue_empty(&tp->ucopy.prequeue)) {
  1289. do_prequeue:
  1290. tcp_prequeue_process(sk);
  1291. if ((chunk = len - tp->ucopy.len) != 0) {
  1292. NET_ADD_STATS_USER(LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
  1293. len -= chunk;
  1294. copied += chunk;
  1295. }
  1296. }
  1297. }
  1298. if ((flags & MSG_PEEK) && peek_seq != tp->copied_seq) {
  1299. if (net_ratelimit())
  1300. printk(KERN_DEBUG "TCP(%s:%d): Application bug, race in MSG_PEEK.\n",
  1301. current->comm, task_pid_nr(current));
  1302. peek_seq = tp->copied_seq;
  1303. }
  1304. continue;
  1305. found_ok_skb:
  1306. /* Ok so how much can we use? */
  1307. used = skb->len - offset;
  1308. if (len < used)
  1309. used = len;
  1310. /* Do we have urgent data here? */
  1311. if (tp->urg_data) {
  1312. u32 urg_offset = tp->urg_seq - *seq;
  1313. if (urg_offset < used) {
  1314. if (!urg_offset) {
  1315. if (!sock_flag(sk, SOCK_URGINLINE)) {
  1316. ++*seq;
  1317. offset++;
  1318. used--;
  1319. if (!used)
  1320. goto skip_copy;
  1321. }
  1322. } else
  1323. used = urg_offset;
  1324. }
  1325. }
  1326. if (!(flags & MSG_TRUNC)) {
  1327. #ifdef CONFIG_NET_DMA
  1328. if (!tp->ucopy.dma_chan && tp->ucopy.pinned_list)
  1329. tp->ucopy.dma_chan = get_softnet_dma();
  1330. if (tp->ucopy.dma_chan) {
  1331. tp->ucopy.dma_cookie = dma_skb_copy_datagram_iovec(
  1332. tp->ucopy.dma_chan, skb, offset,
  1333. msg->msg_iov, used,
  1334. tp->ucopy.pinned_list);
  1335. if (tp->ucopy.dma_cookie < 0) {
  1336. printk(KERN_ALERT "dma_cookie < 0\n");
  1337. /* Exception. Bailout! */
  1338. if (!copied)
  1339. copied = -EFAULT;
  1340. break;
  1341. }
  1342. if ((offset + used) == skb->len)
  1343. copied_early = 1;
  1344. } else
  1345. #endif
  1346. {
  1347. err = skb_copy_datagram_iovec(skb, offset,
  1348. msg->msg_iov, used);
  1349. if (err) {
  1350. /* Exception. Bailout! */
  1351. if (!copied)
  1352. copied = -EFAULT;
  1353. break;
  1354. }
  1355. }
  1356. }
  1357. *seq += used;
  1358. copied += used;
  1359. len -= used;
  1360. tcp_rcv_space_adjust(sk);
  1361. skip_copy:
  1362. if (tp->urg_data && after(tp->copied_seq, tp->urg_seq)) {
  1363. tp->urg_data = 0;
  1364. tcp_fast_path_check(sk);
  1365. }
  1366. if (used + offset < skb->len)
  1367. continue;
  1368. if (tcp_hdr(skb)->fin)
  1369. goto found_fin_ok;
  1370. if (!(flags & MSG_PEEK)) {
  1371. sk_eat_skb(sk, skb, copied_early);
  1372. copied_early = 0;
  1373. }
  1374. continue;
  1375. found_fin_ok:
  1376. /* Process the FIN. */
  1377. ++*seq;
  1378. if (!(flags & MSG_PEEK)) {
  1379. sk_eat_skb(sk, skb, copied_early);
  1380. copied_early = 0;
  1381. }
  1382. break;
  1383. } while (len > 0);
  1384. if (user_recv) {
  1385. if (!skb_queue_empty(&tp->ucopy.prequeue)) {
  1386. int chunk;
  1387. tp->ucopy.len = copied > 0 ? len : 0;
  1388. tcp_prequeue_process(sk);
  1389. if (copied > 0 && (chunk = len - tp->ucopy.len) != 0) {
  1390. NET_ADD_STATS_USER(LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
  1391. len -= chunk;
  1392. copied += chunk;
  1393. }
  1394. }
  1395. tp->ucopy.task = NULL;
  1396. tp->ucopy.len = 0;
  1397. }
  1398. #ifdef CONFIG_NET_DMA
  1399. if (tp->ucopy.dma_chan) {
  1400. dma_cookie_t done, used;
  1401. dma_async_memcpy_issue_pending(tp->ucopy.dma_chan);
  1402. while (dma_async_memcpy_complete(tp->ucopy.dma_chan,
  1403. tp->ucopy.dma_cookie, &done,
  1404. &used) == DMA_IN_PROGRESS) {
  1405. /* do partial cleanup of sk_async_wait_queue */
  1406. while ((skb = skb_peek(&sk->sk_async_wait_queue)) &&
  1407. (dma_async_is_complete(skb->dma_cookie, done,
  1408. used) == DMA_SUCCESS)) {
  1409. __skb_dequeue(&sk->sk_async_wait_queue);
  1410. kfree_skb(skb);
  1411. }
  1412. }
  1413. /* Safe to free early-copied skbs now */
  1414. __skb_queue_purge(&sk->sk_async_wait_queue);
  1415. dma_chan_put(tp->ucopy.dma_chan);
  1416. tp->ucopy.dma_chan = NULL;
  1417. }
  1418. if (tp->ucopy.pinned_list) {
  1419. dma_unpin_iovec_pages(tp->ucopy.pinned_list);
  1420. tp->ucopy.pinned_list = NULL;
  1421. }
  1422. #endif
  1423. /* According to UNIX98, msg_name/msg_namelen are ignored
  1424. * on connected socket. I was just happy when found this 8) --ANK
  1425. */
  1426. /* Clean up data we have read: This will do ACK frames. */
  1427. tcp_cleanup_rbuf(sk, copied);
  1428. TCP_CHECK_TIMER(sk);
  1429. release_sock(sk);
  1430. return copied;
  1431. out:
  1432. TCP_CHECK_TIMER(sk);
  1433. release_sock(sk);
  1434. return err;
  1435. recv_urg:
  1436. err = tcp_recv_urg(sk, timeo, msg, len, flags, addr_len);
  1437. goto out;
  1438. }
  1439. void tcp_set_state(struct sock *sk, int state)
  1440. {
  1441. int oldstate = sk->sk_state;
  1442. switch (state) {
  1443. case TCP_ESTABLISHED:
  1444. if (oldstate != TCP_ESTABLISHED)
  1445. TCP_INC_STATS(TCP_MIB_CURRESTAB);
  1446. break;
  1447. case TCP_CLOSE:
  1448. if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED)
  1449. TCP_INC_STATS(TCP_MIB_ESTABRESETS);
  1450. sk->sk_prot->unhash(sk);
  1451. if (inet_csk(sk)->icsk_bind_hash &&
  1452. !(sk->sk_userlocks & SOCK_BINDPORT_LOCK))
  1453. inet_put_port(sk);
  1454. /* fall through */
  1455. default:
  1456. if (oldstate==TCP_ESTABLISHED)
  1457. TCP_DEC_STATS(TCP_MIB_CURRESTAB);
  1458. }
  1459. /* Change state AFTER socket is unhashed to avoid closed
  1460. * socket sitting in hash tables.
  1461. */
  1462. sk->sk_state = state;
  1463. #ifdef STATE_TRACE
  1464. SOCK_DEBUG(sk, "TCP sk=%p, State %s -> %s\n",sk, statename[oldstate],statename[state]);
  1465. #endif
  1466. }
  1467. EXPORT_SYMBOL_GPL(tcp_set_state);
  1468. /*
  1469. * State processing on a close. This implements the state shift for
  1470. * sending our FIN frame. Note that we only send a FIN for some
  1471. * states. A shutdown() may have already sent the FIN, or we may be
  1472. * closed.
  1473. */
  1474. static const unsigned char new_state[16] = {
  1475. /* current state: new state: action: */
  1476. /* (Invalid) */ TCP_CLOSE,
  1477. /* TCP_ESTABLISHED */ TCP_FIN_WAIT1 | TCP_ACTION_FIN,
  1478. /* TCP_SYN_SENT */ TCP_CLOSE,
  1479. /* TCP_SYN_RECV */ TCP_FIN_WAIT1 | TCP_ACTION_FIN,
  1480. /* TCP_FIN_WAIT1 */ TCP_FIN_WAIT1,
  1481. /* TCP_FIN_WAIT2 */ TCP_FIN_WAIT2,
  1482. /* TCP_TIME_WAIT */ TCP_CLOSE,
  1483. /* TCP_CLOSE */ TCP_CLOSE,
  1484. /* TCP_CLOSE_WAIT */ TCP_LAST_ACK | TCP_ACTION_FIN,
  1485. /* TCP_LAST_ACK */ TCP_LAST_ACK,
  1486. /* TCP_LISTEN */ TCP_CLOSE,
  1487. /* TCP_CLOSING */ TCP_CLOSING,
  1488. };
  1489. static int tcp_close_state(struct sock *sk)
  1490. {
  1491. int next = (int)new_state[sk->sk_state];
  1492. int ns = next & TCP_STATE_MASK;
  1493. tcp_set_state(sk, ns);
  1494. return next & TCP_ACTION_FIN;
  1495. }
  1496. /*
  1497. * Shutdown the sending side of a connection. Much like close except
  1498. * that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD).
  1499. */
  1500. void tcp_shutdown(struct sock *sk, int how)
  1501. {
  1502. /* We need to grab some memory, and put together a FIN,
  1503. * and then put it into the queue to be sent.
  1504. * Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92.
  1505. */
  1506. if (!(how & SEND_SHUTDOWN))
  1507. return;
  1508. /* If we've already sent a FIN, or it's a closed state, skip this. */
  1509. if ((1 << sk->sk_state) &
  1510. (TCPF_ESTABLISHED | TCPF_SYN_SENT |
  1511. TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) {
  1512. /* Clear out any half completed packets. FIN if needed. */
  1513. if (tcp_close_state(sk))
  1514. tcp_send_fin(sk);
  1515. }
  1516. }
  1517. void tcp_close(struct sock *sk, long timeout)
  1518. {
  1519. struct sk_buff *skb;
  1520. int data_was_unread = 0;
  1521. int state;
  1522. lock_sock(sk);
  1523. sk->sk_shutdown = SHUTDOWN_MASK;
  1524. if (sk->sk_state == TCP_LISTEN) {
  1525. tcp_set_state(sk, TCP_CLOSE);
  1526. /* Special case. */
  1527. inet_csk_listen_stop(sk);
  1528. goto adjudge_to_death;
  1529. }
  1530. /* We need to flush the recv. buffs. We do this only on the
  1531. * descriptor close, not protocol-sourced closes, because the
  1532. * reader process may not have drained the data yet!
  1533. */
  1534. while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
  1535. u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq -
  1536. tcp_hdr(skb)->fin;
  1537. data_was_unread += len;
  1538. __kfree_skb(skb);
  1539. }
  1540. sk_mem_reclaim(sk);
  1541. /* As outlined in RFC 2525, section 2.17, we send a RST here because
  1542. * data was lost. To witness the awful effects of the old behavior of
  1543. * always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk
  1544. * GET in an FTP client, suspend the process, wait for the client to
  1545. * advertise a zero window, then kill -9 the FTP client, wheee...
  1546. * Note: timeout is always zero in such a case.
  1547. */
  1548. if (data_was_unread) {
  1549. /* Unread data was tossed, zap the connection. */
  1550. NET_INC_STATS_USER(LINUX_MIB_TCPABORTONCLOSE);
  1551. tcp_set_state(sk, TCP_CLOSE);
  1552. tcp_send_active_reset(sk, GFP_KERNEL);
  1553. } else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
  1554. /* Check zero linger _after_ checking for unread data. */
  1555. sk->sk_prot->disconnect(sk, 0);
  1556. NET_INC_STATS_USER(LINUX_MIB_TCPABORTONDATA);
  1557. } else if (tcp_close_state(sk)) {
  1558. /* We FIN if the application ate all the data before
  1559. * zapping the connection.
  1560. */
  1561. /* RED-PEN. Formally speaking, we have broken TCP state
  1562. * machine. State transitions:
  1563. *
  1564. * TCP_ESTABLISHED -> TCP_FIN_WAIT1
  1565. * TCP_SYN_RECV -> TCP_FIN_WAIT1 (forget it, it's impossible)
  1566. * TCP_CLOSE_WAIT -> TCP_LAST_ACK
  1567. *
  1568. * are legal only when FIN has been sent (i.e. in window),
  1569. * rather than queued out of window. Purists blame.
  1570. *
  1571. * F.e. "RFC state" is ESTABLISHED,
  1572. * if Linux state is FIN-WAIT-1, but FIN is still not sent.
  1573. *
  1574. * The visible declinations are that sometimes
  1575. * we enter time-wait state, when it is not required really
  1576. * (harmless), do not send active resets, when they are
  1577. * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when
  1578. * they look as CLOSING or LAST_ACK for Linux)
  1579. * Probably, I missed some more holelets.
  1580. * --ANK
  1581. */
  1582. tcp_send_fin(sk);
  1583. }
  1584. sk_stream_wait_close(sk, timeout);
  1585. adjudge_to_death:
  1586. state = sk->sk_state;
  1587. sock_hold(sk);
  1588. sock_orphan(sk);
  1589. atomic_inc(sk->sk_prot->orphan_count);
  1590. /* It is the last release_sock in its life. It will remove backlog. */
  1591. release_sock(sk);
  1592. /* Now socket is owned by kernel and we acquire BH lock
  1593. to finish close. No need to check for user refs.
  1594. */
  1595. local_bh_disable();
  1596. bh_lock_sock(sk);
  1597. BUG_TRAP(!sock_owned_by_user(sk));
  1598. /* Have we already been destroyed by a softirq or backlog? */
  1599. if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE)
  1600. goto out;
  1601. /* This is a (useful) BSD violating of the RFC. There is a
  1602. * problem with TCP as specified in that the other end could
  1603. * keep a socket open forever with no application left this end.
  1604. * We use a 3 minute timeout (about the same as BSD) then kill
  1605. * our end. If they send after that then tough - BUT: long enough
  1606. * that we won't make the old 4*rto = almost no time - whoops
  1607. * reset mistake.
  1608. *
  1609. * Nope, it was not mistake. It is really desired behaviour
  1610. * f.e. on http servers, when such sockets are useless, but
  1611. * consume significant resources. Let's do it with special
  1612. * linger2 option. --ANK
  1613. */
  1614. if (sk->sk_state == TCP_FIN_WAIT2) {
  1615. struct tcp_sock *tp = tcp_sk(sk);
  1616. if (tp->linger2 < 0) {
  1617. tcp_set_state(sk, TCP_CLOSE);
  1618. tcp_send_active_reset(sk, GFP_ATOMIC);
  1619. NET_INC_STATS_BH(LINUX_MIB_TCPABORTONLINGER);
  1620. } else {
  1621. const int tmo = tcp_fin_time(sk);
  1622. if (tmo > TCP_TIMEWAIT_LEN) {
  1623. inet_csk_reset_keepalive_timer(sk,
  1624. tmo - TCP_TIMEWAIT_LEN);
  1625. } else {
  1626. tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
  1627. goto out;
  1628. }
  1629. }
  1630. }
  1631. if (sk->sk_state != TCP_CLOSE) {
  1632. sk_mem_reclaim(sk);
  1633. if (tcp_too_many_orphans(sk,
  1634. atomic_read(sk->sk_prot->orphan_count))) {
  1635. if (net_ratelimit())
  1636. printk(KERN_INFO "TCP: too many of orphaned "
  1637. "sockets\n");
  1638. tcp_set_state(sk, TCP_CLOSE);
  1639. tcp_send_active_reset(sk, GFP_ATOMIC);
  1640. NET_INC_STATS_BH(LINUX_MIB_TCPABORTONMEMORY);
  1641. }
  1642. }
  1643. if (sk->sk_state == TCP_CLOSE)
  1644. inet_csk_destroy_sock(sk);
  1645. /* Otherwise, socket is reprieved until protocol close. */
  1646. out:
  1647. bh_unlock_sock(sk);
  1648. local_bh_enable();
  1649. sock_put(sk);
  1650. }
  1651. /* These states need RST on ABORT according to RFC793 */
  1652. static inline int tcp_need_reset(int state)
  1653. {
  1654. return (1 << state) &
  1655. (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 |
  1656. TCPF_FIN_WAIT2 | TCPF_SYN_RECV);
  1657. }
  1658. int tcp_disconnect(struct sock *sk, int flags)
  1659. {
  1660. struct inet_sock *inet = inet_sk(sk);
  1661. struct inet_connection_sock *icsk = inet_csk(sk);
  1662. struct tcp_sock *tp = tcp_sk(sk);
  1663. int err = 0;
  1664. int old_state = sk->sk_state;
  1665. if (old_state != TCP_CLOSE)
  1666. tcp_set_state(sk, TCP_CLOSE);
  1667. /* ABORT function of RFC793 */
  1668. if (old_state == TCP_LISTEN) {
  1669. inet_csk_listen_stop(sk);
  1670. } else if (tcp_need_reset(old_state) ||
  1671. (tp->snd_nxt != tp->write_seq &&
  1672. (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {
  1673. /* The last check adjusts for discrepancy of Linux wrt. RFC
  1674. * states
  1675. */
  1676. tcp_send_active_reset(sk, gfp_any());
  1677. sk->sk_err = ECONNRESET;
  1678. } else if (old_state == TCP_SYN_SENT)
  1679. sk->sk_err = ECONNRESET;
  1680. tcp_clear_xmit_timers(sk);
  1681. __skb_queue_purge(&sk->sk_receive_queue);
  1682. tcp_write_queue_purge(sk);
  1683. __skb_queue_purge(&tp->out_of_order_queue);
  1684. #ifdef CONFIG_NET_DMA
  1685. __skb_queue_purge(&sk->sk_async_wait_queue);
  1686. #endif
  1687. inet->dport = 0;
  1688. if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
  1689. inet_reset_saddr(sk);
  1690. sk->sk_shutdown = 0;
  1691. sock_reset_flag(sk, SOCK_DONE);
  1692. tp->srtt = 0;
  1693. if ((tp->write_seq += tp->max_window + 2) == 0)
  1694. tp->write_seq = 1;
  1695. icsk->icsk_backoff = 0;
  1696. tp->snd_cwnd = 2;
  1697. icsk->icsk_probes_out = 0;
  1698. tp->packets_out = 0;
  1699. tp->snd_ssthresh = 0x7fffffff;
  1700. tp->snd_cwnd_cnt = 0;
  1701. tp->bytes_acked = 0;
  1702. tcp_set_ca_state(sk, TCP_CA_Open);
  1703. tcp_clear_retrans(tp);
  1704. inet_csk_delack_init(sk);
  1705. tcp_init_send_head(sk);
  1706. memset(&tp->rx_opt, 0, sizeof(tp->rx_opt));
  1707. __sk_dst_reset(sk);
  1708. BUG_TRAP(!inet->num || icsk->icsk_bind_hash);
  1709. sk->sk_error_report(sk);
  1710. return err;
  1711. }
  1712. /*
  1713. * Socket option code for TCP.
  1714. */
  1715. static int do_tcp_setsockopt(struct sock *sk, int level,
  1716. int optname, char __user *optval, int optlen)
  1717. {
  1718. struct tcp_sock *tp = tcp_sk(sk);
  1719. struct inet_connection_sock *icsk = inet_csk(sk);
  1720. int val;
  1721. int err = 0;
  1722. /* This is a string value all the others are int's */
  1723. if (optname == TCP_CONGESTION) {
  1724. char name[TCP_CA_NAME_MAX];
  1725. if (optlen < 1)
  1726. return -EINVAL;
  1727. val = strncpy_from_user(name, optval,
  1728. min(TCP_CA_NAME_MAX-1, optlen));
  1729. if (val < 0)
  1730. return -EFAULT;
  1731. name[val] = 0;
  1732. lock_sock(sk);
  1733. err = tcp_set_congestion_control(sk, name);
  1734. release_sock(sk);
  1735. return err;
  1736. }
  1737. if (optlen < sizeof(int))
  1738. return -EINVAL;
  1739. if (get_user(val, (int __user *)optval))
  1740. return -EFAULT;
  1741. lock_sock(sk);
  1742. switch (optname) {
  1743. case TCP_MAXSEG:
  1744. /* Values greater than interface MTU won't take effect. However
  1745. * at the point when this call is done we typically don't yet
  1746. * know which interface is going to be used */
  1747. if (val < 8 || val > MAX_TCP_WINDOW) {
  1748. err = -EINVAL;
  1749. break;
  1750. }
  1751. tp->rx_opt.user_mss = val;
  1752. break;
  1753. case TCP_NODELAY:
  1754. if (val) {
  1755. /* TCP_NODELAY is weaker than TCP_CORK, so that
  1756. * this option on corked socket is remembered, but
  1757. * it is not activated until cork is cleared.
  1758. *
  1759. * However, when TCP_NODELAY is set we make
  1760. * an explicit push, which overrides even TCP_CORK
  1761. * for currently queued segments.
  1762. */
  1763. tp->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH;
  1764. tcp_push_pending_frames(sk);
  1765. } else {
  1766. tp->nonagle &= ~TCP_NAGLE_OFF;
  1767. }
  1768. break;
  1769. case TCP_CORK:
  1770. /* When set indicates to always queue non-full frames.
  1771. * Later the user clears this option and we transmit
  1772. * any pending partial frames in the queue. This is
  1773. * meant to be used alongside sendfile() to get properly
  1774. * filled frames when the user (for example) must write
  1775. * out headers with a write() call first and then use
  1776. * sendfile to send out the data parts.
  1777. *
  1778. * TCP_CORK can be set together with TCP_NODELAY and it is
  1779. * stronger than TCP_NODELAY.
  1780. */
  1781. if (val) {
  1782. tp->nonagle |= TCP_NAGLE_CORK;
  1783. } else {
  1784. tp->nonagle &= ~TCP_NAGLE_CORK;
  1785. if (tp->nonagle&TCP_NAGLE_OFF)
  1786. tp->nonagle |= TCP_NAGLE_PUSH;
  1787. tcp_push_pending_frames(sk);
  1788. }
  1789. break;
  1790. case TCP_KEEPIDLE:
  1791. if (val < 1 || val > MAX_TCP_KEEPIDLE)
  1792. err = -EINVAL;
  1793. else {
  1794. tp->keepalive_time = val * HZ;
  1795. if (sock_flag(sk, SOCK_KEEPOPEN) &&
  1796. !((1 << sk->sk_state) &
  1797. (TCPF_CLOSE | TCPF_LISTEN))) {
  1798. __u32 elapsed = tcp_time_stamp - tp->rcv_tstamp;
  1799. if (tp->keepalive_time > elapsed)
  1800. elapsed = tp->keepalive_time - elapsed;
  1801. else
  1802. elapsed = 0;
  1803. inet_csk_reset_keepalive_timer(sk, elapsed);
  1804. }
  1805. }
  1806. break;
  1807. case TCP_KEEPINTVL:
  1808. if (val < 1 || val > MAX_TCP_KEEPINTVL)
  1809. err = -EINVAL;
  1810. else
  1811. tp->keepalive_intvl = val * HZ;
  1812. break;
  1813. case TCP_KEEPCNT:
  1814. if (val < 1 || val > MAX_TCP_KEEPCNT)
  1815. err = -EINVAL;
  1816. else
  1817. tp->keepalive_probes = val;
  1818. break;
  1819. case TCP_SYNCNT:
  1820. if (val < 1 || val > MAX_TCP_SYNCNT)
  1821. err = -EINVAL;
  1822. else
  1823. icsk->icsk_syn_retries = val;
  1824. break;
  1825. case TCP_LINGER2:
  1826. if (val < 0)
  1827. tp->linger2 = -1;
  1828. else if (val > sysctl_tcp_fin_timeout / HZ)
  1829. tp->linger2 = 0;
  1830. else
  1831. tp->linger2 = val * HZ;
  1832. break;
  1833. case TCP_DEFER_ACCEPT:
  1834. if (val < 0) {
  1835. err = -EINVAL;
  1836. } else {
  1837. if (val > MAX_TCP_ACCEPT_DEFERRED)
  1838. val = MAX_TCP_ACCEPT_DEFERRED;
  1839. icsk->icsk_accept_queue.rskq_defer_accept = val;
  1840. }
  1841. break;
  1842. case TCP_WINDOW_CLAMP:
  1843. if (!val) {
  1844. if (sk->sk_state != TCP_CLOSE) {
  1845. err = -EINVAL;
  1846. break;
  1847. }
  1848. tp->window_clamp = 0;
  1849. } else
  1850. tp->window_clamp = val < SOCK_MIN_RCVBUF / 2 ?
  1851. SOCK_MIN_RCVBUF / 2 : val;
  1852. break;
  1853. case TCP_QUICKACK:
  1854. if (!val) {
  1855. icsk->icsk_ack.pingpong = 1;
  1856. } else {
  1857. icsk->icsk_ack.pingpong = 0;
  1858. if ((1 << sk->sk_state) &
  1859. (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) &&
  1860. inet_csk_ack_scheduled(sk)) {
  1861. icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
  1862. tcp_cleanup_rbuf(sk, 1);
  1863. if (!(val & 1))
  1864. icsk->icsk_ack.pingpong = 1;
  1865. }
  1866. }
  1867. break;
  1868. #ifdef CONFIG_TCP_MD5SIG
  1869. case TCP_MD5SIG:
  1870. /* Read the IP->Key mappings from userspace */
  1871. err = tp->af_specific->md5_parse(sk, optval, optlen);
  1872. break;
  1873. #endif
  1874. default:
  1875. err = -ENOPROTOOPT;
  1876. break;
  1877. }
  1878. release_sock(sk);
  1879. return err;
  1880. }
  1881. int tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval,
  1882. int optlen)
  1883. {
  1884. struct inet_connection_sock *icsk = inet_csk(sk);
  1885. if (level != SOL_TCP)
  1886. return icsk->icsk_af_ops->setsockopt(sk, level, optname,
  1887. optval, optlen);
  1888. return do_tcp_setsockopt(sk, level, optname, optval, optlen);
  1889. }
  1890. #ifdef CONFIG_COMPAT
  1891. int compat_tcp_setsockopt(struct sock *sk, int level, int optname,
  1892. char __user *optval, int optlen)
  1893. {
  1894. if (level != SOL_TCP)
  1895. return inet_csk_compat_setsockopt(sk, level, optname,
  1896. optval, optlen);
  1897. return do_tcp_setsockopt(sk, level, optname, optval, optlen);
  1898. }
  1899. EXPORT_SYMBOL(compat_tcp_setsockopt);
  1900. #endif
  1901. /* Return information about state of tcp endpoint in API format. */
  1902. void tcp_get_info(struct sock *sk, struct tcp_info *info)
  1903. {
  1904. struct tcp_sock *tp = tcp_sk(sk);
  1905. const struct inet_connection_sock *icsk = inet_csk(sk);
  1906. u32 now = tcp_time_stamp;
  1907. memset(info, 0, sizeof(*info));
  1908. info->tcpi_state = sk->sk_state;
  1909. info->tcpi_ca_state = icsk->icsk_ca_state;
  1910. info->tcpi_retransmits = icsk->icsk_retransmits;
  1911. info->tcpi_probes = icsk->icsk_probes_out;
  1912. info->tcpi_backoff = icsk->icsk_backoff;
  1913. if (tp->rx_opt.tstamp_ok)
  1914. info->tcpi_options |= TCPI_OPT_TIMESTAMPS;
  1915. if (tcp_is_sack(tp))
  1916. info->tcpi_options |= TCPI_OPT_SACK;
  1917. if (tp->rx_opt.wscale_ok) {
  1918. info->tcpi_options |= TCPI_OPT_WSCALE;
  1919. info->tcpi_snd_wscale = tp->rx_opt.snd_wscale;
  1920. info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale;
  1921. }
  1922. if (tp->ecn_flags&TCP_ECN_OK)
  1923. info->tcpi_options |= TCPI_OPT_ECN;
  1924. info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto);
  1925. info->tcpi_ato = jiffies_to_usecs(icsk->icsk_ack.ato);
  1926. info->tcpi_snd_mss = tp->mss_cache;
  1927. info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss;
  1928. if (sk->sk_state == TCP_LISTEN) {
  1929. info->tcpi_unacked = sk->sk_ack_backlog;
  1930. info->tcpi_sacked = sk->sk_max_ack_backlog;
  1931. } else {
  1932. info->tcpi_unacked = tp->packets_out;
  1933. info->tcpi_sacked = tp->sacked_out;
  1934. }
  1935. info->tcpi_lost = tp->lost_out;
  1936. info->tcpi_retrans = tp->retrans_out;
  1937. info->tcpi_fackets = tp->fackets_out;
  1938. info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime);
  1939. info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime);
  1940. info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp);
  1941. info->tcpi_pmtu = icsk->icsk_pmtu_cookie;
  1942. info->tcpi_rcv_ssthresh = tp->rcv_ssthresh;
  1943. info->tcpi_rtt = jiffies_to_usecs(tp->srtt)>>3;
  1944. info->tcpi_rttvar = jiffies_to_usecs(tp->mdev)>>2;
  1945. info->tcpi_snd_ssthresh = tp->snd_ssthresh;
  1946. info->tcpi_snd_cwnd = tp->snd_cwnd;
  1947. info->tcpi_advmss = tp->advmss;
  1948. info->tcpi_reordering = tp->reordering;
  1949. info->tcpi_rcv_rtt = jiffies_to_usecs(tp->rcv_rtt_est.rtt)>>3;
  1950. info->tcpi_rcv_space = tp->rcvq_space.space;
  1951. info->tcpi_total_retrans = tp->total_retrans;
  1952. }
  1953. EXPORT_SYMBOL_GPL(tcp_get_info);
  1954. static int do_tcp_getsockopt(struct sock *sk, int level,
  1955. int optname, char __user *optval, int __user *optlen)
  1956. {
  1957. struct inet_connection_sock *icsk = inet_csk(sk);
  1958. struct tcp_sock *tp = tcp_sk(sk);
  1959. int val, len;
  1960. if (get_user(len, optlen))
  1961. return -EFAULT;
  1962. len = min_t(unsigned int, len, sizeof(int));
  1963. if (len < 0)
  1964. return -EINVAL;
  1965. switch (optname) {
  1966. case TCP_MAXSEG:
  1967. val = tp->mss_cache;
  1968. if (!val && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
  1969. val = tp->rx_opt.user_mss;
  1970. break;
  1971. case TCP_NODELAY:
  1972. val = !!(tp->nonagle&TCP_NAGLE_OFF);
  1973. break;
  1974. case TCP_CORK:
  1975. val = !!(tp->nonagle&TCP_NAGLE_CORK);
  1976. break;
  1977. case TCP_KEEPIDLE:
  1978. val = (tp->keepalive_time ? : sysctl_tcp_keepalive_time) / HZ;
  1979. break;
  1980. case TCP_KEEPINTVL:
  1981. val = (tp->keepalive_intvl ? : sysctl_tcp_keepalive_intvl) / HZ;
  1982. break;
  1983. case TCP_KEEPCNT:
  1984. val = tp->keepalive_probes ? : sysctl_tcp_keepalive_probes;
  1985. break;
  1986. case TCP_SYNCNT:
  1987. val = icsk->icsk_syn_retries ? : sysctl_tcp_syn_retries;
  1988. break;
  1989. case TCP_LINGER2:
  1990. val = tp->linger2;
  1991. if (val >= 0)
  1992. val = (val ? : sysctl_tcp_fin_timeout) / HZ;
  1993. break;
  1994. case TCP_DEFER_ACCEPT:
  1995. val = icsk->icsk_accept_queue.rskq_defer_accept;
  1996. break;
  1997. case TCP_WINDOW_CLAMP:
  1998. val = tp->window_clamp;
  1999. break;
  2000. case TCP_INFO: {
  2001. struct tcp_info info;
  2002. if (get_user(len, optlen))
  2003. return -EFAULT;
  2004. tcp_get_info(sk, &info);
  2005. len = min_t(unsigned int, len, sizeof(info));
  2006. if (put_user(len, optlen))
  2007. return -EFAULT;
  2008. if (copy_to_user(optval, &info, len))
  2009. return -EFAULT;
  2010. return 0;
  2011. }
  2012. case TCP_QUICKACK:
  2013. val = !icsk->icsk_ack.pingpong;
  2014. break;
  2015. case TCP_CONGESTION:
  2016. if (get_user(len, optlen))
  2017. return -EFAULT;
  2018. len = min_t(unsigned int, len, TCP_CA_NAME_MAX);
  2019. if (put_user(len, optlen))
  2020. return -EFAULT;
  2021. if (copy_to_user(optval, icsk->icsk_ca_ops->name, len))
  2022. return -EFAULT;
  2023. return 0;
  2024. default:
  2025. return -ENOPROTOOPT;
  2026. }
  2027. if (put_user(len, optlen))
  2028. return -EFAULT;
  2029. if (copy_to_user(optval, &val, len))
  2030. return -EFAULT;
  2031. return 0;
  2032. }
  2033. int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval,
  2034. int __user *optlen)
  2035. {
  2036. struct inet_connection_sock *icsk = inet_csk(sk);
  2037. if (level != SOL_TCP)
  2038. return icsk->icsk_af_ops->getsockopt(sk, level, optname,
  2039. optval, optlen);
  2040. return do_tcp_getsockopt(sk, level, optname, optval, optlen);
  2041. }
  2042. #ifdef CONFIG_COMPAT
  2043. int compat_tcp_getsockopt(struct sock *sk, int level, int optname,
  2044. char __user *optval, int __user *optlen)
  2045. {
  2046. if (level != SOL_TCP)
  2047. return inet_csk_compat_getsockopt(sk, level, optname,
  2048. optval, optlen);
  2049. return do_tcp_getsockopt(sk, level, optname, optval, optlen);
  2050. }
  2051. EXPORT_SYMBOL(compat_tcp_getsockopt);
  2052. #endif
  2053. struct sk_buff *tcp_tso_segment(struct sk_buff *skb, int features)
  2054. {
  2055. struct sk_buff *segs = ERR_PTR(-EINVAL);
  2056. struct tcphdr *th;
  2057. unsigned thlen;
  2058. unsigned int seq;
  2059. __be32 delta;
  2060. unsigned int oldlen;
  2061. unsigned int len;
  2062. if (!pskb_may_pull(skb, sizeof(*th)))
  2063. goto out;
  2064. th = tcp_hdr(skb);
  2065. thlen = th->doff * 4;
  2066. if (thlen < sizeof(*th))
  2067. goto out;
  2068. if (!pskb_may_pull(skb, thlen))
  2069. goto out;
  2070. oldlen = (u16)~skb->len;
  2071. __skb_pull(skb, thlen);
  2072. if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) {
  2073. /* Packet is from an untrusted source, reset gso_segs. */
  2074. int type = skb_shinfo(skb)->gso_type;
  2075. int mss;
  2076. if (unlikely(type &
  2077. ~(SKB_GSO_TCPV4 |
  2078. SKB_GSO_DODGY |
  2079. SKB_GSO_TCP_ECN |
  2080. SKB_GSO_TCPV6 |
  2081. 0) ||
  2082. !(type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))))
  2083. goto out;
  2084. mss = skb_shinfo(skb)->gso_size;
  2085. skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss);
  2086. segs = NULL;
  2087. goto out;
  2088. }
  2089. segs = skb_segment(skb, features);
  2090. if (IS_ERR(segs))
  2091. goto out;
  2092. len = skb_shinfo(skb)->gso_size;
  2093. delta = htonl(oldlen + (thlen + len));
  2094. skb = segs;
  2095. th = tcp_hdr(skb);
  2096. seq = ntohl(th->seq);
  2097. do {
  2098. th->fin = th->psh = 0;
  2099. th->check = ~csum_fold((__force __wsum)((__force u32)th->check +
  2100. (__force u32)delta));
  2101. if (skb->ip_summed != CHECKSUM_PARTIAL)
  2102. th->check =
  2103. csum_fold(csum_partial(skb_transport_header(skb),
  2104. thlen, skb->csum));
  2105. seq += len;
  2106. skb = skb->next;
  2107. th = tcp_hdr(skb);
  2108. th->seq = htonl(seq);
  2109. th->cwr = 0;
  2110. } while (skb->next);
  2111. delta = htonl(oldlen + (skb->tail - skb->transport_header) +
  2112. skb->data_len);
  2113. th->check = ~csum_fold((__force __wsum)((__force u32)th->check +
  2114. (__force u32)delta));
  2115. if (skb->ip_summed != CHECKSUM_PARTIAL)
  2116. th->check = csum_fold(csum_partial(skb_transport_header(skb),
  2117. thlen, skb->csum));
  2118. out:
  2119. return segs;
  2120. }
  2121. EXPORT_SYMBOL(tcp_tso_segment);
  2122. #ifdef CONFIG_TCP_MD5SIG
  2123. static unsigned long tcp_md5sig_users;
  2124. static struct tcp_md5sig_pool **tcp_md5sig_pool;
  2125. static DEFINE_SPINLOCK(tcp_md5sig_pool_lock);
  2126. static void __tcp_free_md5sig_pool(struct tcp_md5sig_pool **pool)
  2127. {
  2128. int cpu;
  2129. for_each_possible_cpu(cpu) {
  2130. struct tcp_md5sig_pool *p = *per_cpu_ptr(pool, cpu);
  2131. if (p) {
  2132. if (p->md5_desc.tfm)
  2133. crypto_free_hash(p->md5_desc.tfm);
  2134. kfree(p);
  2135. p = NULL;
  2136. }
  2137. }
  2138. free_percpu(pool);
  2139. }
  2140. void tcp_free_md5sig_pool(void)
  2141. {
  2142. struct tcp_md5sig_pool **pool = NULL;
  2143. spin_lock_bh(&tcp_md5sig_pool_lock);
  2144. if (--tcp_md5sig_users == 0) {
  2145. pool = tcp_md5sig_pool;
  2146. tcp_md5sig_pool = NULL;
  2147. }
  2148. spin_unlock_bh(&tcp_md5sig_pool_lock);
  2149. if (pool)
  2150. __tcp_free_md5sig_pool(pool);
  2151. }
  2152. EXPORT_SYMBOL(tcp_free_md5sig_pool);
  2153. static struct tcp_md5sig_pool **__tcp_alloc_md5sig_pool(void)
  2154. {
  2155. int cpu;
  2156. struct tcp_md5sig_pool **pool;
  2157. pool = alloc_percpu(struct tcp_md5sig_pool *);
  2158. if (!pool)
  2159. return NULL;
  2160. for_each_possible_cpu(cpu) {
  2161. struct tcp_md5sig_pool *p;
  2162. struct crypto_hash *hash;
  2163. p = kzalloc(sizeof(*p), GFP_KERNEL);
  2164. if (!p)
  2165. goto out_free;
  2166. *per_cpu_ptr(pool, cpu) = p;
  2167. hash = crypto_alloc_hash("md5", 0, CRYPTO_ALG_ASYNC);
  2168. if (!hash || IS_ERR(hash))
  2169. goto out_free;
  2170. p->md5_desc.tfm = hash;
  2171. }
  2172. return pool;
  2173. out_free:
  2174. __tcp_free_md5sig_pool(pool);
  2175. return NULL;
  2176. }
  2177. struct tcp_md5sig_pool **tcp_alloc_md5sig_pool(void)
  2178. {
  2179. struct tcp_md5sig_pool **pool;
  2180. int alloc = 0;
  2181. retry:
  2182. spin_lock_bh(&tcp_md5sig_pool_lock);
  2183. pool = tcp_md5sig_pool;
  2184. if (tcp_md5sig_users++ == 0) {
  2185. alloc = 1;
  2186. spin_unlock_bh(&tcp_md5sig_pool_lock);
  2187. } else if (!pool) {
  2188. tcp_md5sig_users--;
  2189. spin_unlock_bh(&tcp_md5sig_pool_lock);
  2190. cpu_relax();
  2191. goto retry;
  2192. } else
  2193. spin_unlock_bh(&tcp_md5sig_pool_lock);
  2194. if (alloc) {
  2195. /* we cannot hold spinlock here because this may sleep. */
  2196. struct tcp_md5sig_pool **p = __tcp_alloc_md5sig_pool();
  2197. spin_lock_bh(&tcp_md5sig_pool_lock);
  2198. if (!p) {
  2199. tcp_md5sig_users--;
  2200. spin_unlock_bh(&tcp_md5sig_pool_lock);
  2201. return NULL;
  2202. }
  2203. pool = tcp_md5sig_pool;
  2204. if (pool) {
  2205. /* oops, it has already been assigned. */
  2206. spin_unlock_bh(&tcp_md5sig_pool_lock);
  2207. __tcp_free_md5sig_pool(p);
  2208. } else {
  2209. tcp_md5sig_pool = pool = p;
  2210. spin_unlock_bh(&tcp_md5sig_pool_lock);
  2211. }
  2212. }
  2213. return pool;
  2214. }
  2215. EXPORT_SYMBOL(tcp_alloc_md5sig_pool);
  2216. struct tcp_md5sig_pool *__tcp_get_md5sig_pool(int cpu)
  2217. {
  2218. struct tcp_md5sig_pool **p;
  2219. spin_lock_bh(&tcp_md5sig_pool_lock);
  2220. p = tcp_md5sig_pool;
  2221. if (p)
  2222. tcp_md5sig_users++;
  2223. spin_unlock_bh(&tcp_md5sig_pool_lock);
  2224. return (p ? *per_cpu_ptr(p, cpu) : NULL);
  2225. }
  2226. EXPORT_SYMBOL(__tcp_get_md5sig_pool);
  2227. void __tcp_put_md5sig_pool(void)
  2228. {
  2229. tcp_free_md5sig_pool();
  2230. }
  2231. EXPORT_SYMBOL(__tcp_put_md5sig_pool);
  2232. #endif
  2233. void tcp_done(struct sock *sk)
  2234. {
  2235. if(sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV)
  2236. TCP_INC_STATS_BH(TCP_MIB_ATTEMPTFAILS);
  2237. tcp_set_state(sk, TCP_CLOSE);
  2238. tcp_clear_xmit_timers(sk);
  2239. sk->sk_shutdown = SHUTDOWN_MASK;
  2240. if (!sock_flag(sk, SOCK_DEAD))
  2241. sk->sk_state_change(sk);
  2242. else
  2243. inet_csk_destroy_sock(sk);
  2244. }
  2245. EXPORT_SYMBOL_GPL(tcp_done);
  2246. extern struct tcp_congestion_ops tcp_reno;
  2247. static __initdata unsigned long thash_entries;
  2248. static int __init set_thash_entries(char *str)
  2249. {
  2250. if (!str)
  2251. return 0;
  2252. thash_entries = simple_strtoul(str, &str, 0);
  2253. return 1;
  2254. }
  2255. __setup("thash_entries=", set_thash_entries);
  2256. void __init tcp_init(void)
  2257. {
  2258. struct sk_buff *skb = NULL;
  2259. unsigned long limit;
  2260. int order, i, max_share;
  2261. BUILD_BUG_ON(sizeof(struct tcp_skb_cb) > sizeof(skb->cb));
  2262. tcp_hashinfo.bind_bucket_cachep =
  2263. kmem_cache_create("tcp_bind_bucket",
  2264. sizeof(struct inet_bind_bucket), 0,
  2265. SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
  2266. /* Size and allocate the main established and bind bucket
  2267. * hash tables.
  2268. *
  2269. * The methodology is similar to that of the buffer cache.
  2270. */
  2271. tcp_hashinfo.ehash =
  2272. alloc_large_system_hash("TCP established",
  2273. sizeof(struct inet_ehash_bucket),
  2274. thash_entries,
  2275. (num_physpages >= 128 * 1024) ?
  2276. 13 : 15,
  2277. 0,
  2278. &tcp_hashinfo.ehash_size,
  2279. NULL,
  2280. thash_entries ? 0 : 512 * 1024);
  2281. tcp_hashinfo.ehash_size = 1 << tcp_hashinfo.ehash_size;
  2282. for (i = 0; i < tcp_hashinfo.ehash_size; i++) {
  2283. INIT_HLIST_HEAD(&tcp_hashinfo.ehash[i].chain);
  2284. INIT_HLIST_HEAD(&tcp_hashinfo.ehash[i].twchain);
  2285. }
  2286. if (inet_ehash_locks_alloc(&tcp_hashinfo))
  2287. panic("TCP: failed to alloc ehash_locks");
  2288. tcp_hashinfo.bhash =
  2289. alloc_large_system_hash("TCP bind",
  2290. sizeof(struct inet_bind_hashbucket),
  2291. tcp_hashinfo.ehash_size,
  2292. (num_physpages >= 128 * 1024) ?
  2293. 13 : 15,
  2294. 0,
  2295. &tcp_hashinfo.bhash_size,
  2296. NULL,
  2297. 64 * 1024);
  2298. tcp_hashinfo.bhash_size = 1 << tcp_hashinfo.bhash_size;
  2299. for (i = 0; i < tcp_hashinfo.bhash_size; i++) {
  2300. spin_lock_init(&tcp_hashinfo.bhash[i].lock);
  2301. INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain);
  2302. }
  2303. /* Try to be a bit smarter and adjust defaults depending
  2304. * on available memory.
  2305. */
  2306. for (order = 0; ((1 << order) << PAGE_SHIFT) <
  2307. (tcp_hashinfo.bhash_size * sizeof(struct inet_bind_hashbucket));
  2308. order++)
  2309. ;
  2310. if (order >= 4) {
  2311. tcp_death_row.sysctl_max_tw_buckets = 180000;
  2312. sysctl_tcp_max_orphans = 4096 << (order - 4);
  2313. sysctl_max_syn_backlog = 1024;
  2314. } else if (order < 3) {
  2315. tcp_death_row.sysctl_max_tw_buckets >>= (3 - order);
  2316. sysctl_tcp_max_orphans >>= (3 - order);
  2317. sysctl_max_syn_backlog = 128;
  2318. }
  2319. /* Set the pressure threshold to be a fraction of global memory that
  2320. * is up to 1/2 at 256 MB, decreasing toward zero with the amount of
  2321. * memory, with a floor of 128 pages.
  2322. */
  2323. limit = min(nr_all_pages, 1UL<<(28-PAGE_SHIFT)) >> (20-PAGE_SHIFT);
  2324. limit = (limit * (nr_all_pages >> (20-PAGE_SHIFT))) >> (PAGE_SHIFT-11);
  2325. limit = max(limit, 128UL);
  2326. sysctl_tcp_mem[0] = limit / 4 * 3;
  2327. sysctl_tcp_mem[1] = limit;
  2328. sysctl_tcp_mem[2] = sysctl_tcp_mem[0] * 2;
  2329. /* Set per-socket limits to no more than 1/128 the pressure threshold */
  2330. limit = ((unsigned long)sysctl_tcp_mem[1]) << (PAGE_SHIFT - 7);
  2331. max_share = min(4UL*1024*1024, limit);
  2332. sysctl_tcp_wmem[0] = SK_MEM_QUANTUM;
  2333. sysctl_tcp_wmem[1] = 16*1024;
  2334. sysctl_tcp_wmem[2] = max(64*1024, max_share);
  2335. sysctl_tcp_rmem[0] = SK_MEM_QUANTUM;
  2336. sysctl_tcp_rmem[1] = 87380;
  2337. sysctl_tcp_rmem[2] = max(87380, max_share);
  2338. printk(KERN_INFO "TCP: Hash tables configured "
  2339. "(established %d bind %d)\n",
  2340. tcp_hashinfo.ehash_size, tcp_hashinfo.bhash_size);
  2341. tcp_register_congestion_control(&tcp_reno);
  2342. }
  2343. EXPORT_SYMBOL(tcp_close);
  2344. EXPORT_SYMBOL(tcp_disconnect);
  2345. EXPORT_SYMBOL(tcp_getsockopt);
  2346. EXPORT_SYMBOL(tcp_ioctl);
  2347. EXPORT_SYMBOL(tcp_poll);
  2348. EXPORT_SYMBOL(tcp_read_sock);
  2349. EXPORT_SYMBOL(tcp_recvmsg);
  2350. EXPORT_SYMBOL(tcp_sendmsg);
  2351. EXPORT_SYMBOL(tcp_splice_read);
  2352. EXPORT_SYMBOL(tcp_sendpage);
  2353. EXPORT_SYMBOL(tcp_setsockopt);
  2354. EXPORT_SYMBOL(tcp_shutdown);
  2355. EXPORT_SYMBOL(tcp_statistics);