tcp.c 73 KB

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