tcp.c 85 KB

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