tcp.c 86 KB

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