sock.c 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * INET An implementation of the TCP/IP protocol suite for the LINUX
  4. * operating system. INET is implemented using the BSD Socket
  5. * interface as the means of communication with the user level.
  6. *
  7. * Generic socket support routines. Memory allocators, socket lock/release
  8. * handler for protocols to use and generic option handler.
  9. *
  10. * Authors: Ross Biro
  11. * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
  12. * Florian La Roche, <flla@stud.uni-sb.de>
  13. * Alan Cox, <A.Cox@swansea.ac.uk>
  14. *
  15. * Fixes:
  16. * Alan Cox : Numerous verify_area() problems
  17. * Alan Cox : Connecting on a connecting socket
  18. * now returns an error for tcp.
  19. * Alan Cox : sock->protocol is set correctly.
  20. * and is not sometimes left as 0.
  21. * Alan Cox : connect handles icmp errors on a
  22. * connect properly. Unfortunately there
  23. * is a restart syscall nasty there. I
  24. * can't match BSD without hacking the C
  25. * library. Ideas urgently sought!
  26. * Alan Cox : Disallow bind() to addresses that are
  27. * not ours - especially broadcast ones!!
  28. * Alan Cox : Socket 1024 _IS_ ok for users. (fencepost)
  29. * Alan Cox : sock_wfree/sock_rfree don't destroy sockets,
  30. * instead they leave that for the DESTROY timer.
  31. * Alan Cox : Clean up error flag in accept
  32. * Alan Cox : TCP ack handling is buggy, the DESTROY timer
  33. * was buggy. Put a remove_sock() in the handler
  34. * for memory when we hit 0. Also altered the timer
  35. * code. The ACK stuff can wait and needs major
  36. * TCP layer surgery.
  37. * Alan Cox : Fixed TCP ack bug, removed remove sock
  38. * and fixed timer/inet_bh race.
  39. * Alan Cox : Added zapped flag for TCP
  40. * Alan Cox : Move kfree_skb into skbuff.c and tidied up surplus code
  41. * Alan Cox : for new sk_buff allocations wmalloc/rmalloc now call alloc_skb
  42. * Alan Cox : kfree_s calls now are kfree_skbmem so we can track skb resources
  43. * Alan Cox : Supports socket option broadcast now as does udp. Packet and raw need fixing.
  44. * Alan Cox : Added RCVBUF,SNDBUF size setting. It suddenly occurred to me how easy it was so...
  45. * Rick Sladkey : Relaxed UDP rules for matching packets.
  46. * C.E.Hawkins : IFF_PROMISC/SIOCGHWADDR support
  47. * Pauline Middelink : identd support
  48. * Alan Cox : Fixed connect() taking signals I think.
  49. * Alan Cox : SO_LINGER supported
  50. * Alan Cox : Error reporting fixes
  51. * Anonymous : inet_create tidied up (sk->reuse setting)
  52. * Alan Cox : inet sockets don't set sk->type!
  53. * Alan Cox : Split socket option code
  54. * Alan Cox : Callbacks
  55. * Alan Cox : Nagle flag for Charles & Johannes stuff
  56. * Alex : Removed restriction on inet fioctl
  57. * Alan Cox : Splitting INET from NET core
  58. * Alan Cox : Fixed bogus SO_TYPE handling in getsockopt()
  59. * Adam Caldwell : Missing return in SO_DONTROUTE/SO_DEBUG code
  60. * Alan Cox : Split IP from generic code
  61. * Alan Cox : New kfree_skbmem()
  62. * Alan Cox : Make SO_DEBUG superuser only.
  63. * Alan Cox : Allow anyone to clear SO_DEBUG
  64. * (compatibility fix)
  65. * Alan Cox : Added optimistic memory grabbing for AF_UNIX throughput.
  66. * Alan Cox : Allocator for a socket is settable.
  67. * Alan Cox : SO_ERROR includes soft errors.
  68. * Alan Cox : Allow NULL arguments on some SO_ opts
  69. * Alan Cox : Generic socket allocation to make hooks
  70. * easier (suggested by Craig Metz).
  71. * Michael Pall : SO_ERROR returns positive errno again
  72. * Steve Whitehouse: Added default destructor to free
  73. * protocol private data.
  74. * Steve Whitehouse: Added various other default routines
  75. * common to several socket families.
  76. * Chris Evans : Call suser() check last on F_SETOWN
  77. * Jay Schulist : Added SO_ATTACH_FILTER and SO_DETACH_FILTER.
  78. * Andi Kleen : Add sock_kmalloc()/sock_kfree_s()
  79. * Andi Kleen : Fix write_space callback
  80. * Chris Evans : Security fixes - signedness again
  81. * Arnaldo C. Melo : cleanups, use skb_queue_purge
  82. *
  83. * To Fix:
  84. */
  85. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  86. #include <linux/unaligned.h>
  87. #include <linux/capability.h>
  88. #include <linux/errno.h>
  89. #include <linux/errqueue.h>
  90. #include <linux/types.h>
  91. #include <linux/socket.h>
  92. #include <linux/in.h>
  93. #include <linux/kernel.h>
  94. #include <linux/module.h>
  95. #include <linux/proc_fs.h>
  96. #include <linux/seq_file.h>
  97. #include <linux/sched.h>
  98. #include <linux/sched/mm.h>
  99. #include <linux/timer.h>
  100. #include <linux/string.h>
  101. #include <linux/sockios.h>
  102. #include <linux/net.h>
  103. #include <linux/mm.h>
  104. #include <linux/slab.h>
  105. #include <linux/interrupt.h>
  106. #include <linux/poll.h>
  107. #include <linux/tcp.h>
  108. #include <linux/udp.h>
  109. #include <linux/init.h>
  110. #include <linux/highmem.h>
  111. #include <linux/user_namespace.h>
  112. #include <linux/static_key.h>
  113. #include <linux/memcontrol.h>
  114. #include <linux/prefetch.h>
  115. #include <linux/compat.h>
  116. #include <linux/mroute.h>
  117. #include <linux/mroute6.h>
  118. #include <linux/icmpv6.h>
  119. #include <linux/uaccess.h>
  120. #include <linux/netdevice.h>
  121. #include <net/protocol.h>
  122. #include <linux/skbuff.h>
  123. #include <linux/skbuff_ref.h>
  124. #include <net/net_namespace.h>
  125. #include <net/request_sock.h>
  126. #include <net/sock.h>
  127. #include <net/proto_memory.h>
  128. #include <linux/net_tstamp.h>
  129. #include <net/xfrm.h>
  130. #include <linux/ipsec.h>
  131. #include <net/cls_cgroup.h>
  132. #include <net/netprio_cgroup.h>
  133. #include <linux/sock_diag.h>
  134. #include <linux/filter.h>
  135. #include <net/sock_reuseport.h>
  136. #include <net/bpf_sk_storage.h>
  137. #include <trace/events/sock.h>
  138. #include <net/tcp.h>
  139. #include <net/busy_poll.h>
  140. #include <net/phonet/phonet.h>
  141. #include <linux/ethtool.h>
  142. #include "dev.h"
  143. static DEFINE_MUTEX(proto_list_mutex);
  144. static LIST_HEAD(proto_list);
  145. static void sock_def_write_space_wfree(struct sock *sk);
  146. static void sock_def_write_space(struct sock *sk);
  147. /**
  148. * sk_ns_capable - General socket capability test
  149. * @sk: Socket to use a capability on or through
  150. * @user_ns: The user namespace of the capability to use
  151. * @cap: The capability to use
  152. *
  153. * Test to see if the opener of the socket had when the socket was
  154. * created and the current process has the capability @cap in the user
  155. * namespace @user_ns.
  156. */
  157. bool sk_ns_capable(const struct sock *sk,
  158. struct user_namespace *user_ns, int cap)
  159. {
  160. return file_ns_capable(sk->sk_socket->file, user_ns, cap) &&
  161. ns_capable(user_ns, cap);
  162. }
  163. EXPORT_SYMBOL(sk_ns_capable);
  164. /**
  165. * sk_capable - Socket global capability test
  166. * @sk: Socket to use a capability on or through
  167. * @cap: The global capability to use
  168. *
  169. * Test to see if the opener of the socket had when the socket was
  170. * created and the current process has the capability @cap in all user
  171. * namespaces.
  172. */
  173. bool sk_capable(const struct sock *sk, int cap)
  174. {
  175. return sk_ns_capable(sk, &init_user_ns, cap);
  176. }
  177. EXPORT_SYMBOL(sk_capable);
  178. /**
  179. * sk_net_capable - Network namespace socket capability test
  180. * @sk: Socket to use a capability on or through
  181. * @cap: The capability to use
  182. *
  183. * Test to see if the opener of the socket had when the socket was created
  184. * and the current process has the capability @cap over the network namespace
  185. * the socket is a member of.
  186. */
  187. bool sk_net_capable(const struct sock *sk, int cap)
  188. {
  189. return sk_ns_capable(sk, sock_net(sk)->user_ns, cap);
  190. }
  191. EXPORT_SYMBOL(sk_net_capable);
  192. /*
  193. * Each address family might have different locking rules, so we have
  194. * one slock key per address family and separate keys for internal and
  195. * userspace sockets.
  196. */
  197. static struct lock_class_key af_family_keys[AF_MAX];
  198. static struct lock_class_key af_family_kern_keys[AF_MAX];
  199. static struct lock_class_key af_family_slock_keys[AF_MAX];
  200. static struct lock_class_key af_family_kern_slock_keys[AF_MAX];
  201. /*
  202. * Make lock validator output more readable. (we pre-construct these
  203. * strings build-time, so that runtime initialization of socket
  204. * locks is fast):
  205. */
  206. #define _sock_locks(x) \
  207. x "AF_UNSPEC", x "AF_UNIX" , x "AF_INET" , \
  208. x "AF_AX25" , x "AF_IPX" , x "AF_APPLETALK", \
  209. x "AF_NETROM", x "AF_BRIDGE" , x "AF_ATMPVC" , \
  210. x "AF_X25" , x "AF_INET6" , x "AF_ROSE" , \
  211. x "AF_DECnet", x "AF_NETBEUI" , x "AF_SECURITY" , \
  212. x "AF_KEY" , x "AF_NETLINK" , x "AF_PACKET" , \
  213. x "AF_ASH" , x "AF_ECONET" , x "AF_ATMSVC" , \
  214. x "AF_RDS" , x "AF_SNA" , x "AF_IRDA" , \
  215. x "AF_PPPOX" , x "AF_WANPIPE" , x "AF_LLC" , \
  216. x "27" , x "28" , x "AF_CAN" , \
  217. x "AF_TIPC" , x "AF_BLUETOOTH", x "IUCV" , \
  218. x "AF_RXRPC" , x "AF_ISDN" , x "AF_PHONET" , \
  219. x "AF_IEEE802154", x "AF_CAIF" , x "AF_ALG" , \
  220. x "AF_NFC" , x "AF_VSOCK" , x "AF_KCM" , \
  221. x "AF_QIPCRTR", x "AF_SMC" , x "AF_XDP" , \
  222. x "AF_MCTP" , \
  223. x "AF_MAX"
  224. static const char *const af_family_key_strings[AF_MAX+1] = {
  225. _sock_locks("sk_lock-")
  226. };
  227. static const char *const af_family_slock_key_strings[AF_MAX+1] = {
  228. _sock_locks("slock-")
  229. };
  230. static const char *const af_family_clock_key_strings[AF_MAX+1] = {
  231. _sock_locks("clock-")
  232. };
  233. static const char *const af_family_kern_key_strings[AF_MAX+1] = {
  234. _sock_locks("k-sk_lock-")
  235. };
  236. static const char *const af_family_kern_slock_key_strings[AF_MAX+1] = {
  237. _sock_locks("k-slock-")
  238. };
  239. static const char *const af_family_kern_clock_key_strings[AF_MAX+1] = {
  240. _sock_locks("k-clock-")
  241. };
  242. static const char *const af_family_rlock_key_strings[AF_MAX+1] = {
  243. _sock_locks("rlock-")
  244. };
  245. static const char *const af_family_wlock_key_strings[AF_MAX+1] = {
  246. _sock_locks("wlock-")
  247. };
  248. static const char *const af_family_elock_key_strings[AF_MAX+1] = {
  249. _sock_locks("elock-")
  250. };
  251. /*
  252. * sk_callback_lock and sk queues locking rules are per-address-family,
  253. * so split the lock classes by using a per-AF key:
  254. */
  255. static struct lock_class_key af_callback_keys[AF_MAX];
  256. static struct lock_class_key af_rlock_keys[AF_MAX];
  257. static struct lock_class_key af_wlock_keys[AF_MAX];
  258. static struct lock_class_key af_elock_keys[AF_MAX];
  259. static struct lock_class_key af_kern_callback_keys[AF_MAX];
  260. /* Run time adjustable parameters. */
  261. __u32 sysctl_wmem_max __read_mostly = SK_WMEM_MAX;
  262. EXPORT_SYMBOL(sysctl_wmem_max);
  263. __u32 sysctl_rmem_max __read_mostly = SK_RMEM_MAX;
  264. EXPORT_SYMBOL(sysctl_rmem_max);
  265. __u32 sysctl_wmem_default __read_mostly = SK_WMEM_MAX;
  266. __u32 sysctl_rmem_default __read_mostly = SK_RMEM_MAX;
  267. int sysctl_tstamp_allow_data __read_mostly = 1;
  268. DEFINE_STATIC_KEY_FALSE(memalloc_socks_key);
  269. EXPORT_SYMBOL_GPL(memalloc_socks_key);
  270. /**
  271. * sk_set_memalloc - sets %SOCK_MEMALLOC
  272. * @sk: socket to set it on
  273. *
  274. * Set %SOCK_MEMALLOC on a socket for access to emergency reserves.
  275. * It's the responsibility of the admin to adjust min_free_kbytes
  276. * to meet the requirements
  277. */
  278. void sk_set_memalloc(struct sock *sk)
  279. {
  280. sock_set_flag(sk, SOCK_MEMALLOC);
  281. sk->sk_allocation |= __GFP_MEMALLOC;
  282. static_branch_inc(&memalloc_socks_key);
  283. }
  284. EXPORT_SYMBOL_GPL(sk_set_memalloc);
  285. void sk_clear_memalloc(struct sock *sk)
  286. {
  287. sock_reset_flag(sk, SOCK_MEMALLOC);
  288. sk->sk_allocation &= ~__GFP_MEMALLOC;
  289. static_branch_dec(&memalloc_socks_key);
  290. /*
  291. * SOCK_MEMALLOC is allowed to ignore rmem limits to ensure forward
  292. * progress of swapping. SOCK_MEMALLOC may be cleared while
  293. * it has rmem allocations due to the last swapfile being deactivated
  294. * but there is a risk that the socket is unusable due to exceeding
  295. * the rmem limits. Reclaim the reserves and obey rmem limits again.
  296. */
  297. sk_mem_reclaim(sk);
  298. }
  299. EXPORT_SYMBOL_GPL(sk_clear_memalloc);
  300. int __sk_backlog_rcv(struct sock *sk, struct sk_buff *skb)
  301. {
  302. int ret;
  303. unsigned int noreclaim_flag;
  304. /* these should have been dropped before queueing */
  305. BUG_ON(!sock_flag(sk, SOCK_MEMALLOC));
  306. noreclaim_flag = memalloc_noreclaim_save();
  307. ret = INDIRECT_CALL_INET(sk->sk_backlog_rcv,
  308. tcp_v6_do_rcv,
  309. tcp_v4_do_rcv,
  310. sk, skb);
  311. memalloc_noreclaim_restore(noreclaim_flag);
  312. return ret;
  313. }
  314. EXPORT_SYMBOL(__sk_backlog_rcv);
  315. void sk_error_report(struct sock *sk)
  316. {
  317. sk->sk_error_report(sk);
  318. switch (sk->sk_family) {
  319. case AF_INET:
  320. fallthrough;
  321. case AF_INET6:
  322. trace_inet_sk_error_report(sk);
  323. break;
  324. default:
  325. break;
  326. }
  327. }
  328. EXPORT_SYMBOL(sk_error_report);
  329. int sock_get_timeout(long timeo, void *optval, bool old_timeval)
  330. {
  331. struct __kernel_sock_timeval tv;
  332. if (timeo == MAX_SCHEDULE_TIMEOUT) {
  333. tv.tv_sec = 0;
  334. tv.tv_usec = 0;
  335. } else {
  336. tv.tv_sec = timeo / HZ;
  337. tv.tv_usec = ((timeo % HZ) * USEC_PER_SEC) / HZ;
  338. }
  339. if (old_timeval && in_compat_syscall() && !COMPAT_USE_64BIT_TIME) {
  340. struct old_timeval32 tv32 = { tv.tv_sec, tv.tv_usec };
  341. *(struct old_timeval32 *)optval = tv32;
  342. return sizeof(tv32);
  343. }
  344. if (old_timeval) {
  345. struct __kernel_old_timeval old_tv;
  346. old_tv.tv_sec = tv.tv_sec;
  347. old_tv.tv_usec = tv.tv_usec;
  348. *(struct __kernel_old_timeval *)optval = old_tv;
  349. return sizeof(old_tv);
  350. }
  351. *(struct __kernel_sock_timeval *)optval = tv;
  352. return sizeof(tv);
  353. }
  354. EXPORT_SYMBOL(sock_get_timeout);
  355. int sock_copy_user_timeval(struct __kernel_sock_timeval *tv,
  356. sockptr_t optval, int optlen, bool old_timeval)
  357. {
  358. if (old_timeval && in_compat_syscall() && !COMPAT_USE_64BIT_TIME) {
  359. struct old_timeval32 tv32;
  360. if (optlen < sizeof(tv32))
  361. return -EINVAL;
  362. if (copy_from_sockptr(&tv32, optval, sizeof(tv32)))
  363. return -EFAULT;
  364. tv->tv_sec = tv32.tv_sec;
  365. tv->tv_usec = tv32.tv_usec;
  366. } else if (old_timeval) {
  367. struct __kernel_old_timeval old_tv;
  368. if (optlen < sizeof(old_tv))
  369. return -EINVAL;
  370. if (copy_from_sockptr(&old_tv, optval, sizeof(old_tv)))
  371. return -EFAULT;
  372. tv->tv_sec = old_tv.tv_sec;
  373. tv->tv_usec = old_tv.tv_usec;
  374. } else {
  375. if (optlen < sizeof(*tv))
  376. return -EINVAL;
  377. if (copy_from_sockptr(tv, optval, sizeof(*tv)))
  378. return -EFAULT;
  379. }
  380. return 0;
  381. }
  382. EXPORT_SYMBOL(sock_copy_user_timeval);
  383. static int sock_set_timeout(long *timeo_p, sockptr_t optval, int optlen,
  384. bool old_timeval)
  385. {
  386. struct __kernel_sock_timeval tv;
  387. int err = sock_copy_user_timeval(&tv, optval, optlen, old_timeval);
  388. long val;
  389. if (err)
  390. return err;
  391. if (tv.tv_usec < 0 || tv.tv_usec >= USEC_PER_SEC)
  392. return -EDOM;
  393. if (tv.tv_sec < 0) {
  394. static int warned __read_mostly;
  395. WRITE_ONCE(*timeo_p, 0);
  396. if (warned < 10 && net_ratelimit()) {
  397. warned++;
  398. pr_info("%s: `%s' (pid %d) tries to set negative timeout\n",
  399. __func__, current->comm, task_pid_nr(current));
  400. }
  401. return 0;
  402. }
  403. val = MAX_SCHEDULE_TIMEOUT;
  404. if ((tv.tv_sec || tv.tv_usec) &&
  405. (tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1)))
  406. val = tv.tv_sec * HZ + DIV_ROUND_UP((unsigned long)tv.tv_usec,
  407. USEC_PER_SEC / HZ);
  408. WRITE_ONCE(*timeo_p, val);
  409. return 0;
  410. }
  411. static bool sock_needs_netstamp(const struct sock *sk)
  412. {
  413. switch (sk->sk_family) {
  414. case AF_UNSPEC:
  415. case AF_UNIX:
  416. return false;
  417. default:
  418. return true;
  419. }
  420. }
  421. static void sock_disable_timestamp(struct sock *sk, unsigned long flags)
  422. {
  423. if (sk->sk_flags & flags) {
  424. sk->sk_flags &= ~flags;
  425. if (sock_needs_netstamp(sk) &&
  426. !(sk->sk_flags & SK_FLAGS_TIMESTAMP))
  427. net_disable_timestamp();
  428. }
  429. }
  430. int __sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
  431. {
  432. unsigned long flags;
  433. struct sk_buff_head *list = &sk->sk_receive_queue;
  434. if (atomic_read(&sk->sk_rmem_alloc) >= READ_ONCE(sk->sk_rcvbuf)) {
  435. atomic_inc(&sk->sk_drops);
  436. trace_sock_rcvqueue_full(sk, skb);
  437. return -ENOMEM;
  438. }
  439. if (!sk_rmem_schedule(sk, skb, skb->truesize)) {
  440. atomic_inc(&sk->sk_drops);
  441. return -ENOBUFS;
  442. }
  443. skb->dev = NULL;
  444. skb_set_owner_r(skb, sk);
  445. /* we escape from rcu protected region, make sure we dont leak
  446. * a norefcounted dst
  447. */
  448. skb_dst_force(skb);
  449. spin_lock_irqsave(&list->lock, flags);
  450. sock_skb_set_dropcount(sk, skb);
  451. __skb_queue_tail(list, skb);
  452. spin_unlock_irqrestore(&list->lock, flags);
  453. if (!sock_flag(sk, SOCK_DEAD))
  454. sk->sk_data_ready(sk);
  455. return 0;
  456. }
  457. EXPORT_SYMBOL(__sock_queue_rcv_skb);
  458. int sock_queue_rcv_skb_reason(struct sock *sk, struct sk_buff *skb,
  459. enum skb_drop_reason *reason)
  460. {
  461. enum skb_drop_reason drop_reason;
  462. int err;
  463. err = sk_filter(sk, skb);
  464. if (err) {
  465. drop_reason = SKB_DROP_REASON_SOCKET_FILTER;
  466. goto out;
  467. }
  468. err = __sock_queue_rcv_skb(sk, skb);
  469. switch (err) {
  470. case -ENOMEM:
  471. drop_reason = SKB_DROP_REASON_SOCKET_RCVBUFF;
  472. break;
  473. case -ENOBUFS:
  474. drop_reason = SKB_DROP_REASON_PROTO_MEM;
  475. break;
  476. default:
  477. drop_reason = SKB_NOT_DROPPED_YET;
  478. break;
  479. }
  480. out:
  481. if (reason)
  482. *reason = drop_reason;
  483. return err;
  484. }
  485. EXPORT_SYMBOL(sock_queue_rcv_skb_reason);
  486. int __sk_receive_skb(struct sock *sk, struct sk_buff *skb,
  487. const int nested, unsigned int trim_cap, bool refcounted)
  488. {
  489. int rc = NET_RX_SUCCESS;
  490. if (sk_filter_trim_cap(sk, skb, trim_cap))
  491. goto discard_and_relse;
  492. skb->dev = NULL;
  493. if (sk_rcvqueues_full(sk, READ_ONCE(sk->sk_rcvbuf))) {
  494. atomic_inc(&sk->sk_drops);
  495. goto discard_and_relse;
  496. }
  497. if (nested)
  498. bh_lock_sock_nested(sk);
  499. else
  500. bh_lock_sock(sk);
  501. if (!sock_owned_by_user(sk)) {
  502. /*
  503. * trylock + unlock semantics:
  504. */
  505. mutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_);
  506. rc = sk_backlog_rcv(sk, skb);
  507. mutex_release(&sk->sk_lock.dep_map, _RET_IP_);
  508. } else if (sk_add_backlog(sk, skb, READ_ONCE(sk->sk_rcvbuf))) {
  509. bh_unlock_sock(sk);
  510. atomic_inc(&sk->sk_drops);
  511. goto discard_and_relse;
  512. }
  513. bh_unlock_sock(sk);
  514. out:
  515. if (refcounted)
  516. sock_put(sk);
  517. return rc;
  518. discard_and_relse:
  519. kfree_skb(skb);
  520. goto out;
  521. }
  522. EXPORT_SYMBOL(__sk_receive_skb);
  523. INDIRECT_CALLABLE_DECLARE(struct dst_entry *ip6_dst_check(struct dst_entry *,
  524. u32));
  525. INDIRECT_CALLABLE_DECLARE(struct dst_entry *ipv4_dst_check(struct dst_entry *,
  526. u32));
  527. struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie)
  528. {
  529. struct dst_entry *dst = __sk_dst_get(sk);
  530. if (dst && dst->obsolete &&
  531. INDIRECT_CALL_INET(dst->ops->check, ip6_dst_check, ipv4_dst_check,
  532. dst, cookie) == NULL) {
  533. sk_tx_queue_clear(sk);
  534. WRITE_ONCE(sk->sk_dst_pending_confirm, 0);
  535. RCU_INIT_POINTER(sk->sk_dst_cache, NULL);
  536. dst_release(dst);
  537. return NULL;
  538. }
  539. return dst;
  540. }
  541. EXPORT_SYMBOL(__sk_dst_check);
  542. struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie)
  543. {
  544. struct dst_entry *dst = sk_dst_get(sk);
  545. if (dst && dst->obsolete &&
  546. INDIRECT_CALL_INET(dst->ops->check, ip6_dst_check, ipv4_dst_check,
  547. dst, cookie) == NULL) {
  548. sk_dst_reset(sk);
  549. dst_release(dst);
  550. return NULL;
  551. }
  552. return dst;
  553. }
  554. EXPORT_SYMBOL(sk_dst_check);
  555. static int sock_bindtoindex_locked(struct sock *sk, int ifindex)
  556. {
  557. int ret = -ENOPROTOOPT;
  558. #ifdef CONFIG_NETDEVICES
  559. struct net *net = sock_net(sk);
  560. /* Sorry... */
  561. ret = -EPERM;
  562. if (sk->sk_bound_dev_if && !ns_capable(net->user_ns, CAP_NET_RAW))
  563. goto out;
  564. ret = -EINVAL;
  565. if (ifindex < 0)
  566. goto out;
  567. /* Paired with all READ_ONCE() done locklessly. */
  568. WRITE_ONCE(sk->sk_bound_dev_if, ifindex);
  569. if (sk->sk_prot->rehash)
  570. sk->sk_prot->rehash(sk);
  571. sk_dst_reset(sk);
  572. ret = 0;
  573. out:
  574. #endif
  575. return ret;
  576. }
  577. int sock_bindtoindex(struct sock *sk, int ifindex, bool lock_sk)
  578. {
  579. int ret;
  580. if (lock_sk)
  581. lock_sock(sk);
  582. ret = sock_bindtoindex_locked(sk, ifindex);
  583. if (lock_sk)
  584. release_sock(sk);
  585. return ret;
  586. }
  587. EXPORT_SYMBOL(sock_bindtoindex);
  588. static int sock_setbindtodevice(struct sock *sk, sockptr_t optval, int optlen)
  589. {
  590. int ret = -ENOPROTOOPT;
  591. #ifdef CONFIG_NETDEVICES
  592. struct net *net = sock_net(sk);
  593. char devname[IFNAMSIZ];
  594. int index;
  595. ret = -EINVAL;
  596. if (optlen < 0)
  597. goto out;
  598. /* Bind this socket to a particular device like "eth0",
  599. * as specified in the passed interface name. If the
  600. * name is "" or the option length is zero the socket
  601. * is not bound.
  602. */
  603. if (optlen > IFNAMSIZ - 1)
  604. optlen = IFNAMSIZ - 1;
  605. memset(devname, 0, sizeof(devname));
  606. ret = -EFAULT;
  607. if (copy_from_sockptr(devname, optval, optlen))
  608. goto out;
  609. index = 0;
  610. if (devname[0] != '\0') {
  611. struct net_device *dev;
  612. rcu_read_lock();
  613. dev = dev_get_by_name_rcu(net, devname);
  614. if (dev)
  615. index = dev->ifindex;
  616. rcu_read_unlock();
  617. ret = -ENODEV;
  618. if (!dev)
  619. goto out;
  620. }
  621. sockopt_lock_sock(sk);
  622. ret = sock_bindtoindex_locked(sk, index);
  623. sockopt_release_sock(sk);
  624. out:
  625. #endif
  626. return ret;
  627. }
  628. static int sock_getbindtodevice(struct sock *sk, sockptr_t optval,
  629. sockptr_t optlen, int len)
  630. {
  631. int ret = -ENOPROTOOPT;
  632. #ifdef CONFIG_NETDEVICES
  633. int bound_dev_if = READ_ONCE(sk->sk_bound_dev_if);
  634. struct net *net = sock_net(sk);
  635. char devname[IFNAMSIZ];
  636. if (bound_dev_if == 0) {
  637. len = 0;
  638. goto zero;
  639. }
  640. ret = -EINVAL;
  641. if (len < IFNAMSIZ)
  642. goto out;
  643. ret = netdev_get_name(net, devname, bound_dev_if);
  644. if (ret)
  645. goto out;
  646. len = strlen(devname) + 1;
  647. ret = -EFAULT;
  648. if (copy_to_sockptr(optval, devname, len))
  649. goto out;
  650. zero:
  651. ret = -EFAULT;
  652. if (copy_to_sockptr(optlen, &len, sizeof(int)))
  653. goto out;
  654. ret = 0;
  655. out:
  656. #endif
  657. return ret;
  658. }
  659. bool sk_mc_loop(const struct sock *sk)
  660. {
  661. if (dev_recursion_level())
  662. return false;
  663. if (!sk)
  664. return true;
  665. /* IPV6_ADDRFORM can change sk->sk_family under us. */
  666. switch (READ_ONCE(sk->sk_family)) {
  667. case AF_INET:
  668. return inet_test_bit(MC_LOOP, sk);
  669. #if IS_ENABLED(CONFIG_IPV6)
  670. case AF_INET6:
  671. return inet6_test_bit(MC6_LOOP, sk);
  672. #endif
  673. }
  674. WARN_ON_ONCE(1);
  675. return true;
  676. }
  677. EXPORT_SYMBOL(sk_mc_loop);
  678. void sock_set_reuseaddr(struct sock *sk)
  679. {
  680. lock_sock(sk);
  681. sk->sk_reuse = SK_CAN_REUSE;
  682. release_sock(sk);
  683. }
  684. EXPORT_SYMBOL(sock_set_reuseaddr);
  685. void sock_set_reuseport(struct sock *sk)
  686. {
  687. lock_sock(sk);
  688. sk->sk_reuseport = true;
  689. release_sock(sk);
  690. }
  691. EXPORT_SYMBOL(sock_set_reuseport);
  692. void sock_no_linger(struct sock *sk)
  693. {
  694. lock_sock(sk);
  695. WRITE_ONCE(sk->sk_lingertime, 0);
  696. sock_set_flag(sk, SOCK_LINGER);
  697. release_sock(sk);
  698. }
  699. EXPORT_SYMBOL(sock_no_linger);
  700. void sock_set_priority(struct sock *sk, u32 priority)
  701. {
  702. WRITE_ONCE(sk->sk_priority, priority);
  703. }
  704. EXPORT_SYMBOL(sock_set_priority);
  705. void sock_set_sndtimeo(struct sock *sk, s64 secs)
  706. {
  707. lock_sock(sk);
  708. if (secs && secs < MAX_SCHEDULE_TIMEOUT / HZ - 1)
  709. WRITE_ONCE(sk->sk_sndtimeo, secs * HZ);
  710. else
  711. WRITE_ONCE(sk->sk_sndtimeo, MAX_SCHEDULE_TIMEOUT);
  712. release_sock(sk);
  713. }
  714. EXPORT_SYMBOL(sock_set_sndtimeo);
  715. static void __sock_set_timestamps(struct sock *sk, bool val, bool new, bool ns)
  716. {
  717. if (val) {
  718. sock_valbool_flag(sk, SOCK_TSTAMP_NEW, new);
  719. sock_valbool_flag(sk, SOCK_RCVTSTAMPNS, ns);
  720. sock_set_flag(sk, SOCK_RCVTSTAMP);
  721. sock_enable_timestamp(sk, SOCK_TIMESTAMP);
  722. } else {
  723. sock_reset_flag(sk, SOCK_RCVTSTAMP);
  724. sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
  725. }
  726. }
  727. void sock_enable_timestamps(struct sock *sk)
  728. {
  729. lock_sock(sk);
  730. __sock_set_timestamps(sk, true, false, true);
  731. release_sock(sk);
  732. }
  733. EXPORT_SYMBOL(sock_enable_timestamps);
  734. void sock_set_timestamp(struct sock *sk, int optname, bool valbool)
  735. {
  736. switch (optname) {
  737. case SO_TIMESTAMP_OLD:
  738. __sock_set_timestamps(sk, valbool, false, false);
  739. break;
  740. case SO_TIMESTAMP_NEW:
  741. __sock_set_timestamps(sk, valbool, true, false);
  742. break;
  743. case SO_TIMESTAMPNS_OLD:
  744. __sock_set_timestamps(sk, valbool, false, true);
  745. break;
  746. case SO_TIMESTAMPNS_NEW:
  747. __sock_set_timestamps(sk, valbool, true, true);
  748. break;
  749. }
  750. }
  751. static int sock_timestamping_bind_phc(struct sock *sk, int phc_index)
  752. {
  753. struct net *net = sock_net(sk);
  754. struct net_device *dev = NULL;
  755. bool match = false;
  756. int *vclock_index;
  757. int i, num;
  758. if (sk->sk_bound_dev_if)
  759. dev = dev_get_by_index(net, sk->sk_bound_dev_if);
  760. if (!dev) {
  761. pr_err("%s: sock not bind to device\n", __func__);
  762. return -EOPNOTSUPP;
  763. }
  764. num = ethtool_get_phc_vclocks(dev, &vclock_index);
  765. dev_put(dev);
  766. for (i = 0; i < num; i++) {
  767. if (*(vclock_index + i) == phc_index) {
  768. match = true;
  769. break;
  770. }
  771. }
  772. if (num > 0)
  773. kfree(vclock_index);
  774. if (!match)
  775. return -EINVAL;
  776. WRITE_ONCE(sk->sk_bind_phc, phc_index);
  777. return 0;
  778. }
  779. int sock_set_timestamping(struct sock *sk, int optname,
  780. struct so_timestamping timestamping)
  781. {
  782. int val = timestamping.flags;
  783. int ret;
  784. if (val & ~SOF_TIMESTAMPING_MASK)
  785. return -EINVAL;
  786. if (val & SOF_TIMESTAMPING_OPT_ID_TCP &&
  787. !(val & SOF_TIMESTAMPING_OPT_ID))
  788. return -EINVAL;
  789. if (val & SOF_TIMESTAMPING_OPT_ID &&
  790. !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) {
  791. if (sk_is_tcp(sk)) {
  792. if ((1 << sk->sk_state) &
  793. (TCPF_CLOSE | TCPF_LISTEN))
  794. return -EINVAL;
  795. if (val & SOF_TIMESTAMPING_OPT_ID_TCP)
  796. atomic_set(&sk->sk_tskey, tcp_sk(sk)->write_seq);
  797. else
  798. atomic_set(&sk->sk_tskey, tcp_sk(sk)->snd_una);
  799. } else {
  800. atomic_set(&sk->sk_tskey, 0);
  801. }
  802. }
  803. if (val & SOF_TIMESTAMPING_OPT_STATS &&
  804. !(val & SOF_TIMESTAMPING_OPT_TSONLY))
  805. return -EINVAL;
  806. if (val & SOF_TIMESTAMPING_BIND_PHC) {
  807. ret = sock_timestamping_bind_phc(sk, timestamping.bind_phc);
  808. if (ret)
  809. return ret;
  810. }
  811. WRITE_ONCE(sk->sk_tsflags, val);
  812. sock_valbool_flag(sk, SOCK_TSTAMP_NEW, optname == SO_TIMESTAMPING_NEW);
  813. if (val & SOF_TIMESTAMPING_RX_SOFTWARE)
  814. sock_enable_timestamp(sk,
  815. SOCK_TIMESTAMPING_RX_SOFTWARE);
  816. else
  817. sock_disable_timestamp(sk,
  818. (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE));
  819. return 0;
  820. }
  821. void sock_set_keepalive(struct sock *sk)
  822. {
  823. lock_sock(sk);
  824. if (sk->sk_prot->keepalive)
  825. sk->sk_prot->keepalive(sk, true);
  826. sock_valbool_flag(sk, SOCK_KEEPOPEN, true);
  827. release_sock(sk);
  828. }
  829. EXPORT_SYMBOL(sock_set_keepalive);
  830. static void __sock_set_rcvbuf(struct sock *sk, int val)
  831. {
  832. /* Ensure val * 2 fits into an int, to prevent max_t() from treating it
  833. * as a negative value.
  834. */
  835. val = min_t(int, val, INT_MAX / 2);
  836. sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
  837. /* We double it on the way in to account for "struct sk_buff" etc.
  838. * overhead. Applications assume that the SO_RCVBUF setting they make
  839. * will allow that much actual data to be received on that socket.
  840. *
  841. * Applications are unaware that "struct sk_buff" and other overheads
  842. * allocate from the receive buffer during socket buffer allocation.
  843. *
  844. * And after considering the possible alternatives, returning the value
  845. * we actually used in getsockopt is the most desirable behavior.
  846. */
  847. WRITE_ONCE(sk->sk_rcvbuf, max_t(int, val * 2, SOCK_MIN_RCVBUF));
  848. }
  849. void sock_set_rcvbuf(struct sock *sk, int val)
  850. {
  851. lock_sock(sk);
  852. __sock_set_rcvbuf(sk, val);
  853. release_sock(sk);
  854. }
  855. EXPORT_SYMBOL(sock_set_rcvbuf);
  856. static void __sock_set_mark(struct sock *sk, u32 val)
  857. {
  858. if (val != sk->sk_mark) {
  859. WRITE_ONCE(sk->sk_mark, val);
  860. sk_dst_reset(sk);
  861. }
  862. }
  863. void sock_set_mark(struct sock *sk, u32 val)
  864. {
  865. lock_sock(sk);
  866. __sock_set_mark(sk, val);
  867. release_sock(sk);
  868. }
  869. EXPORT_SYMBOL(sock_set_mark);
  870. static void sock_release_reserved_memory(struct sock *sk, int bytes)
  871. {
  872. /* Round down bytes to multiple of pages */
  873. bytes = round_down(bytes, PAGE_SIZE);
  874. WARN_ON(bytes > sk->sk_reserved_mem);
  875. WRITE_ONCE(sk->sk_reserved_mem, sk->sk_reserved_mem - bytes);
  876. sk_mem_reclaim(sk);
  877. }
  878. static int sock_reserve_memory(struct sock *sk, int bytes)
  879. {
  880. long allocated;
  881. bool charged;
  882. int pages;
  883. if (!mem_cgroup_sockets_enabled || !sk->sk_memcg || !sk_has_account(sk))
  884. return -EOPNOTSUPP;
  885. if (!bytes)
  886. return 0;
  887. pages = sk_mem_pages(bytes);
  888. /* pre-charge to memcg */
  889. charged = mem_cgroup_charge_skmem(sk->sk_memcg, pages,
  890. GFP_KERNEL | __GFP_RETRY_MAYFAIL);
  891. if (!charged)
  892. return -ENOMEM;
  893. /* pre-charge to forward_alloc */
  894. sk_memory_allocated_add(sk, pages);
  895. allocated = sk_memory_allocated(sk);
  896. /* If the system goes into memory pressure with this
  897. * precharge, give up and return error.
  898. */
  899. if (allocated > sk_prot_mem_limits(sk, 1)) {
  900. sk_memory_allocated_sub(sk, pages);
  901. mem_cgroup_uncharge_skmem(sk->sk_memcg, pages);
  902. return -ENOMEM;
  903. }
  904. sk_forward_alloc_add(sk, pages << PAGE_SHIFT);
  905. WRITE_ONCE(sk->sk_reserved_mem,
  906. sk->sk_reserved_mem + (pages << PAGE_SHIFT));
  907. return 0;
  908. }
  909. #ifdef CONFIG_PAGE_POOL
  910. /* This is the number of tokens and frags that the user can SO_DEVMEM_DONTNEED
  911. * in 1 syscall. The limit exists to limit the amount of memory the kernel
  912. * allocates to copy these tokens, and to prevent looping over the frags for
  913. * too long.
  914. */
  915. #define MAX_DONTNEED_TOKENS 128
  916. #define MAX_DONTNEED_FRAGS 1024
  917. static noinline_for_stack int
  918. sock_devmem_dontneed(struct sock *sk, sockptr_t optval, unsigned int optlen)
  919. {
  920. unsigned int num_tokens, i, j, k, netmem_num = 0;
  921. struct dmabuf_token *tokens;
  922. int ret = 0, num_frags = 0;
  923. netmem_ref netmems[16];
  924. if (!sk_is_tcp(sk))
  925. return -EBADF;
  926. if (optlen % sizeof(*tokens) ||
  927. optlen > sizeof(*tokens) * MAX_DONTNEED_TOKENS)
  928. return -EINVAL;
  929. num_tokens = optlen / sizeof(*tokens);
  930. tokens = kvmalloc_array(num_tokens, sizeof(*tokens), GFP_KERNEL);
  931. if (!tokens)
  932. return -ENOMEM;
  933. if (copy_from_sockptr(tokens, optval, optlen)) {
  934. kvfree(tokens);
  935. return -EFAULT;
  936. }
  937. xa_lock_bh(&sk->sk_user_frags);
  938. for (i = 0; i < num_tokens; i++) {
  939. for (j = 0; j < tokens[i].token_count; j++) {
  940. if (++num_frags > MAX_DONTNEED_FRAGS)
  941. goto frag_limit_reached;
  942. netmem_ref netmem = (__force netmem_ref)__xa_erase(
  943. &sk->sk_user_frags, tokens[i].token_start + j);
  944. if (!netmem || WARN_ON_ONCE(!netmem_is_net_iov(netmem)))
  945. continue;
  946. netmems[netmem_num++] = netmem;
  947. if (netmem_num == ARRAY_SIZE(netmems)) {
  948. xa_unlock_bh(&sk->sk_user_frags);
  949. for (k = 0; k < netmem_num; k++)
  950. WARN_ON_ONCE(!napi_pp_put_page(netmems[k]));
  951. netmem_num = 0;
  952. xa_lock_bh(&sk->sk_user_frags);
  953. }
  954. ret++;
  955. }
  956. }
  957. frag_limit_reached:
  958. xa_unlock_bh(&sk->sk_user_frags);
  959. for (k = 0; k < netmem_num; k++)
  960. WARN_ON_ONCE(!napi_pp_put_page(netmems[k]));
  961. kvfree(tokens);
  962. return ret;
  963. }
  964. #endif
  965. void sockopt_lock_sock(struct sock *sk)
  966. {
  967. /* When current->bpf_ctx is set, the setsockopt is called from
  968. * a bpf prog. bpf has ensured the sk lock has been
  969. * acquired before calling setsockopt().
  970. */
  971. if (has_current_bpf_ctx())
  972. return;
  973. lock_sock(sk);
  974. }
  975. EXPORT_SYMBOL(sockopt_lock_sock);
  976. void sockopt_release_sock(struct sock *sk)
  977. {
  978. if (has_current_bpf_ctx())
  979. return;
  980. release_sock(sk);
  981. }
  982. EXPORT_SYMBOL(sockopt_release_sock);
  983. bool sockopt_ns_capable(struct user_namespace *ns, int cap)
  984. {
  985. return has_current_bpf_ctx() || ns_capable(ns, cap);
  986. }
  987. EXPORT_SYMBOL(sockopt_ns_capable);
  988. bool sockopt_capable(int cap)
  989. {
  990. return has_current_bpf_ctx() || capable(cap);
  991. }
  992. EXPORT_SYMBOL(sockopt_capable);
  993. static int sockopt_validate_clockid(__kernel_clockid_t value)
  994. {
  995. switch (value) {
  996. case CLOCK_REALTIME:
  997. case CLOCK_MONOTONIC:
  998. case CLOCK_TAI:
  999. return 0;
  1000. }
  1001. return -EINVAL;
  1002. }
  1003. /*
  1004. * This is meant for all protocols to use and covers goings on
  1005. * at the socket level. Everything here is generic.
  1006. */
  1007. int sk_setsockopt(struct sock *sk, int level, int optname,
  1008. sockptr_t optval, unsigned int optlen)
  1009. {
  1010. struct so_timestamping timestamping;
  1011. struct socket *sock = sk->sk_socket;
  1012. struct sock_txtime sk_txtime;
  1013. int val;
  1014. int valbool;
  1015. struct linger ling;
  1016. int ret = 0;
  1017. /*
  1018. * Options without arguments
  1019. */
  1020. if (optname == SO_BINDTODEVICE)
  1021. return sock_setbindtodevice(sk, optval, optlen);
  1022. if (optlen < sizeof(int))
  1023. return -EINVAL;
  1024. if (copy_from_sockptr(&val, optval, sizeof(val)))
  1025. return -EFAULT;
  1026. valbool = val ? 1 : 0;
  1027. /* handle options which do not require locking the socket. */
  1028. switch (optname) {
  1029. case SO_PRIORITY:
  1030. if ((val >= 0 && val <= 6) ||
  1031. sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_RAW) ||
  1032. sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) {
  1033. sock_set_priority(sk, val);
  1034. return 0;
  1035. }
  1036. return -EPERM;
  1037. case SO_PASSSEC:
  1038. assign_bit(SOCK_PASSSEC, &sock->flags, valbool);
  1039. return 0;
  1040. case SO_PASSCRED:
  1041. assign_bit(SOCK_PASSCRED, &sock->flags, valbool);
  1042. return 0;
  1043. case SO_PASSPIDFD:
  1044. assign_bit(SOCK_PASSPIDFD, &sock->flags, valbool);
  1045. return 0;
  1046. case SO_TYPE:
  1047. case SO_PROTOCOL:
  1048. case SO_DOMAIN:
  1049. case SO_ERROR:
  1050. return -ENOPROTOOPT;
  1051. #ifdef CONFIG_NET_RX_BUSY_POLL
  1052. case SO_BUSY_POLL:
  1053. if (val < 0)
  1054. return -EINVAL;
  1055. WRITE_ONCE(sk->sk_ll_usec, val);
  1056. return 0;
  1057. case SO_PREFER_BUSY_POLL:
  1058. if (valbool && !sockopt_capable(CAP_NET_ADMIN))
  1059. return -EPERM;
  1060. WRITE_ONCE(sk->sk_prefer_busy_poll, valbool);
  1061. return 0;
  1062. case SO_BUSY_POLL_BUDGET:
  1063. if (val > READ_ONCE(sk->sk_busy_poll_budget) &&
  1064. !sockopt_capable(CAP_NET_ADMIN))
  1065. return -EPERM;
  1066. if (val < 0 || val > U16_MAX)
  1067. return -EINVAL;
  1068. WRITE_ONCE(sk->sk_busy_poll_budget, val);
  1069. return 0;
  1070. #endif
  1071. case SO_MAX_PACING_RATE:
  1072. {
  1073. unsigned long ulval = (val == ~0U) ? ~0UL : (unsigned int)val;
  1074. unsigned long pacing_rate;
  1075. if (sizeof(ulval) != sizeof(val) &&
  1076. optlen >= sizeof(ulval) &&
  1077. copy_from_sockptr(&ulval, optval, sizeof(ulval))) {
  1078. return -EFAULT;
  1079. }
  1080. if (ulval != ~0UL)
  1081. cmpxchg(&sk->sk_pacing_status,
  1082. SK_PACING_NONE,
  1083. SK_PACING_NEEDED);
  1084. /* Pairs with READ_ONCE() from sk_getsockopt() */
  1085. WRITE_ONCE(sk->sk_max_pacing_rate, ulval);
  1086. pacing_rate = READ_ONCE(sk->sk_pacing_rate);
  1087. if (ulval < pacing_rate)
  1088. WRITE_ONCE(sk->sk_pacing_rate, ulval);
  1089. return 0;
  1090. }
  1091. case SO_TXREHASH:
  1092. if (val < -1 || val > 1)
  1093. return -EINVAL;
  1094. if ((u8)val == SOCK_TXREHASH_DEFAULT)
  1095. val = READ_ONCE(sock_net(sk)->core.sysctl_txrehash);
  1096. /* Paired with READ_ONCE() in tcp_rtx_synack()
  1097. * and sk_getsockopt().
  1098. */
  1099. WRITE_ONCE(sk->sk_txrehash, (u8)val);
  1100. return 0;
  1101. case SO_PEEK_OFF:
  1102. {
  1103. int (*set_peek_off)(struct sock *sk, int val);
  1104. set_peek_off = READ_ONCE(sock->ops)->set_peek_off;
  1105. if (set_peek_off)
  1106. ret = set_peek_off(sk, val);
  1107. else
  1108. ret = -EOPNOTSUPP;
  1109. return ret;
  1110. }
  1111. #ifdef CONFIG_PAGE_POOL
  1112. case SO_DEVMEM_DONTNEED:
  1113. return sock_devmem_dontneed(sk, optval, optlen);
  1114. #endif
  1115. }
  1116. sockopt_lock_sock(sk);
  1117. switch (optname) {
  1118. case SO_DEBUG:
  1119. if (val && !sockopt_capable(CAP_NET_ADMIN))
  1120. ret = -EACCES;
  1121. else
  1122. sock_valbool_flag(sk, SOCK_DBG, valbool);
  1123. break;
  1124. case SO_REUSEADDR:
  1125. sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE);
  1126. break;
  1127. case SO_REUSEPORT:
  1128. if (valbool && !sk_is_inet(sk))
  1129. ret = -EOPNOTSUPP;
  1130. else
  1131. sk->sk_reuseport = valbool;
  1132. break;
  1133. case SO_DONTROUTE:
  1134. sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool);
  1135. sk_dst_reset(sk);
  1136. break;
  1137. case SO_BROADCAST:
  1138. sock_valbool_flag(sk, SOCK_BROADCAST, valbool);
  1139. break;
  1140. case SO_SNDBUF:
  1141. /* Don't error on this BSD doesn't and if you think
  1142. * about it this is right. Otherwise apps have to
  1143. * play 'guess the biggest size' games. RCVBUF/SNDBUF
  1144. * are treated in BSD as hints
  1145. */
  1146. val = min_t(u32, val, READ_ONCE(sysctl_wmem_max));
  1147. set_sndbuf:
  1148. /* Ensure val * 2 fits into an int, to prevent max_t()
  1149. * from treating it as a negative value.
  1150. */
  1151. val = min_t(int, val, INT_MAX / 2);
  1152. sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
  1153. WRITE_ONCE(sk->sk_sndbuf,
  1154. max_t(int, val * 2, SOCK_MIN_SNDBUF));
  1155. /* Wake up sending tasks if we upped the value. */
  1156. sk->sk_write_space(sk);
  1157. break;
  1158. case SO_SNDBUFFORCE:
  1159. if (!sockopt_capable(CAP_NET_ADMIN)) {
  1160. ret = -EPERM;
  1161. break;
  1162. }
  1163. /* No negative values (to prevent underflow, as val will be
  1164. * multiplied by 2).
  1165. */
  1166. if (val < 0)
  1167. val = 0;
  1168. goto set_sndbuf;
  1169. case SO_RCVBUF:
  1170. /* Don't error on this BSD doesn't and if you think
  1171. * about it this is right. Otherwise apps have to
  1172. * play 'guess the biggest size' games. RCVBUF/SNDBUF
  1173. * are treated in BSD as hints
  1174. */
  1175. __sock_set_rcvbuf(sk, min_t(u32, val, READ_ONCE(sysctl_rmem_max)));
  1176. break;
  1177. case SO_RCVBUFFORCE:
  1178. if (!sockopt_capable(CAP_NET_ADMIN)) {
  1179. ret = -EPERM;
  1180. break;
  1181. }
  1182. /* No negative values (to prevent underflow, as val will be
  1183. * multiplied by 2).
  1184. */
  1185. __sock_set_rcvbuf(sk, max(val, 0));
  1186. break;
  1187. case SO_KEEPALIVE:
  1188. if (sk->sk_prot->keepalive)
  1189. sk->sk_prot->keepalive(sk, valbool);
  1190. sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool);
  1191. break;
  1192. case SO_OOBINLINE:
  1193. sock_valbool_flag(sk, SOCK_URGINLINE, valbool);
  1194. break;
  1195. case SO_NO_CHECK:
  1196. sk->sk_no_check_tx = valbool;
  1197. break;
  1198. case SO_LINGER:
  1199. if (optlen < sizeof(ling)) {
  1200. ret = -EINVAL; /* 1003.1g */
  1201. break;
  1202. }
  1203. if (copy_from_sockptr(&ling, optval, sizeof(ling))) {
  1204. ret = -EFAULT;
  1205. break;
  1206. }
  1207. if (!ling.l_onoff) {
  1208. sock_reset_flag(sk, SOCK_LINGER);
  1209. } else {
  1210. unsigned long t_sec = ling.l_linger;
  1211. if (t_sec >= MAX_SCHEDULE_TIMEOUT / HZ)
  1212. WRITE_ONCE(sk->sk_lingertime, MAX_SCHEDULE_TIMEOUT);
  1213. else
  1214. WRITE_ONCE(sk->sk_lingertime, t_sec * HZ);
  1215. sock_set_flag(sk, SOCK_LINGER);
  1216. }
  1217. break;
  1218. case SO_BSDCOMPAT:
  1219. break;
  1220. case SO_TIMESTAMP_OLD:
  1221. case SO_TIMESTAMP_NEW:
  1222. case SO_TIMESTAMPNS_OLD:
  1223. case SO_TIMESTAMPNS_NEW:
  1224. sock_set_timestamp(sk, optname, valbool);
  1225. break;
  1226. case SO_TIMESTAMPING_NEW:
  1227. case SO_TIMESTAMPING_OLD:
  1228. if (optlen == sizeof(timestamping)) {
  1229. if (copy_from_sockptr(&timestamping, optval,
  1230. sizeof(timestamping))) {
  1231. ret = -EFAULT;
  1232. break;
  1233. }
  1234. } else {
  1235. memset(&timestamping, 0, sizeof(timestamping));
  1236. timestamping.flags = val;
  1237. }
  1238. ret = sock_set_timestamping(sk, optname, timestamping);
  1239. break;
  1240. case SO_RCVLOWAT:
  1241. {
  1242. int (*set_rcvlowat)(struct sock *sk, int val) = NULL;
  1243. if (val < 0)
  1244. val = INT_MAX;
  1245. if (sock)
  1246. set_rcvlowat = READ_ONCE(sock->ops)->set_rcvlowat;
  1247. if (set_rcvlowat)
  1248. ret = set_rcvlowat(sk, val);
  1249. else
  1250. WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
  1251. break;
  1252. }
  1253. case SO_RCVTIMEO_OLD:
  1254. case SO_RCVTIMEO_NEW:
  1255. ret = sock_set_timeout(&sk->sk_rcvtimeo, optval,
  1256. optlen, optname == SO_RCVTIMEO_OLD);
  1257. break;
  1258. case SO_SNDTIMEO_OLD:
  1259. case SO_SNDTIMEO_NEW:
  1260. ret = sock_set_timeout(&sk->sk_sndtimeo, optval,
  1261. optlen, optname == SO_SNDTIMEO_OLD);
  1262. break;
  1263. case SO_ATTACH_FILTER: {
  1264. struct sock_fprog fprog;
  1265. ret = copy_bpf_fprog_from_user(&fprog, optval, optlen);
  1266. if (!ret)
  1267. ret = sk_attach_filter(&fprog, sk);
  1268. break;
  1269. }
  1270. case SO_ATTACH_BPF:
  1271. ret = -EINVAL;
  1272. if (optlen == sizeof(u32)) {
  1273. u32 ufd;
  1274. ret = -EFAULT;
  1275. if (copy_from_sockptr(&ufd, optval, sizeof(ufd)))
  1276. break;
  1277. ret = sk_attach_bpf(ufd, sk);
  1278. }
  1279. break;
  1280. case SO_ATTACH_REUSEPORT_CBPF: {
  1281. struct sock_fprog fprog;
  1282. ret = copy_bpf_fprog_from_user(&fprog, optval, optlen);
  1283. if (!ret)
  1284. ret = sk_reuseport_attach_filter(&fprog, sk);
  1285. break;
  1286. }
  1287. case SO_ATTACH_REUSEPORT_EBPF:
  1288. ret = -EINVAL;
  1289. if (optlen == sizeof(u32)) {
  1290. u32 ufd;
  1291. ret = -EFAULT;
  1292. if (copy_from_sockptr(&ufd, optval, sizeof(ufd)))
  1293. break;
  1294. ret = sk_reuseport_attach_bpf(ufd, sk);
  1295. }
  1296. break;
  1297. case SO_DETACH_REUSEPORT_BPF:
  1298. ret = reuseport_detach_prog(sk);
  1299. break;
  1300. case SO_DETACH_FILTER:
  1301. ret = sk_detach_filter(sk);
  1302. break;
  1303. case SO_LOCK_FILTER:
  1304. if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool)
  1305. ret = -EPERM;
  1306. else
  1307. sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool);
  1308. break;
  1309. case SO_MARK:
  1310. if (!sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_RAW) &&
  1311. !sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) {
  1312. ret = -EPERM;
  1313. break;
  1314. }
  1315. __sock_set_mark(sk, val);
  1316. break;
  1317. case SO_RCVMARK:
  1318. sock_valbool_flag(sk, SOCK_RCVMARK, valbool);
  1319. break;
  1320. case SO_RXQ_OVFL:
  1321. sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool);
  1322. break;
  1323. case SO_WIFI_STATUS:
  1324. sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool);
  1325. break;
  1326. case SO_NOFCS:
  1327. sock_valbool_flag(sk, SOCK_NOFCS, valbool);
  1328. break;
  1329. case SO_SELECT_ERR_QUEUE:
  1330. sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool);
  1331. break;
  1332. case SO_INCOMING_CPU:
  1333. reuseport_update_incoming_cpu(sk, val);
  1334. break;
  1335. case SO_CNX_ADVICE:
  1336. if (val == 1)
  1337. dst_negative_advice(sk);
  1338. break;
  1339. case SO_ZEROCOPY:
  1340. if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6) {
  1341. if (!(sk_is_tcp(sk) ||
  1342. (sk->sk_type == SOCK_DGRAM &&
  1343. sk->sk_protocol == IPPROTO_UDP)))
  1344. ret = -EOPNOTSUPP;
  1345. } else if (sk->sk_family != PF_RDS) {
  1346. ret = -EOPNOTSUPP;
  1347. }
  1348. if (!ret) {
  1349. if (val < 0 || val > 1)
  1350. ret = -EINVAL;
  1351. else
  1352. sock_valbool_flag(sk, SOCK_ZEROCOPY, valbool);
  1353. }
  1354. break;
  1355. case SO_TXTIME:
  1356. if (optlen != sizeof(struct sock_txtime)) {
  1357. ret = -EINVAL;
  1358. break;
  1359. } else if (copy_from_sockptr(&sk_txtime, optval,
  1360. sizeof(struct sock_txtime))) {
  1361. ret = -EFAULT;
  1362. break;
  1363. } else if (sk_txtime.flags & ~SOF_TXTIME_FLAGS_MASK) {
  1364. ret = -EINVAL;
  1365. break;
  1366. }
  1367. /* CLOCK_MONOTONIC is only used by sch_fq, and this packet
  1368. * scheduler has enough safe guards.
  1369. */
  1370. if (sk_txtime.clockid != CLOCK_MONOTONIC &&
  1371. !sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) {
  1372. ret = -EPERM;
  1373. break;
  1374. }
  1375. ret = sockopt_validate_clockid(sk_txtime.clockid);
  1376. if (ret)
  1377. break;
  1378. sock_valbool_flag(sk, SOCK_TXTIME, true);
  1379. sk->sk_clockid = sk_txtime.clockid;
  1380. sk->sk_txtime_deadline_mode =
  1381. !!(sk_txtime.flags & SOF_TXTIME_DEADLINE_MODE);
  1382. sk->sk_txtime_report_errors =
  1383. !!(sk_txtime.flags & SOF_TXTIME_REPORT_ERRORS);
  1384. break;
  1385. case SO_BINDTOIFINDEX:
  1386. ret = sock_bindtoindex_locked(sk, val);
  1387. break;
  1388. case SO_BUF_LOCK:
  1389. if (val & ~SOCK_BUF_LOCK_MASK) {
  1390. ret = -EINVAL;
  1391. break;
  1392. }
  1393. sk->sk_userlocks = val | (sk->sk_userlocks &
  1394. ~SOCK_BUF_LOCK_MASK);
  1395. break;
  1396. case SO_RESERVE_MEM:
  1397. {
  1398. int delta;
  1399. if (val < 0) {
  1400. ret = -EINVAL;
  1401. break;
  1402. }
  1403. delta = val - sk->sk_reserved_mem;
  1404. if (delta < 0)
  1405. sock_release_reserved_memory(sk, -delta);
  1406. else
  1407. ret = sock_reserve_memory(sk, delta);
  1408. break;
  1409. }
  1410. default:
  1411. ret = -ENOPROTOOPT;
  1412. break;
  1413. }
  1414. sockopt_release_sock(sk);
  1415. return ret;
  1416. }
  1417. int sock_setsockopt(struct socket *sock, int level, int optname,
  1418. sockptr_t optval, unsigned int optlen)
  1419. {
  1420. return sk_setsockopt(sock->sk, level, optname,
  1421. optval, optlen);
  1422. }
  1423. EXPORT_SYMBOL(sock_setsockopt);
  1424. static const struct cred *sk_get_peer_cred(struct sock *sk)
  1425. {
  1426. const struct cred *cred;
  1427. spin_lock(&sk->sk_peer_lock);
  1428. cred = get_cred(sk->sk_peer_cred);
  1429. spin_unlock(&sk->sk_peer_lock);
  1430. return cred;
  1431. }
  1432. static void cred_to_ucred(struct pid *pid, const struct cred *cred,
  1433. struct ucred *ucred)
  1434. {
  1435. ucred->pid = pid_vnr(pid);
  1436. ucred->uid = ucred->gid = -1;
  1437. if (cred) {
  1438. struct user_namespace *current_ns = current_user_ns();
  1439. ucred->uid = from_kuid_munged(current_ns, cred->euid);
  1440. ucred->gid = from_kgid_munged(current_ns, cred->egid);
  1441. }
  1442. }
  1443. static int groups_to_user(sockptr_t dst, const struct group_info *src)
  1444. {
  1445. struct user_namespace *user_ns = current_user_ns();
  1446. int i;
  1447. for (i = 0; i < src->ngroups; i++) {
  1448. gid_t gid = from_kgid_munged(user_ns, src->gid[i]);
  1449. if (copy_to_sockptr_offset(dst, i * sizeof(gid), &gid, sizeof(gid)))
  1450. return -EFAULT;
  1451. }
  1452. return 0;
  1453. }
  1454. int sk_getsockopt(struct sock *sk, int level, int optname,
  1455. sockptr_t optval, sockptr_t optlen)
  1456. {
  1457. struct socket *sock = sk->sk_socket;
  1458. union {
  1459. int val;
  1460. u64 val64;
  1461. unsigned long ulval;
  1462. struct linger ling;
  1463. struct old_timeval32 tm32;
  1464. struct __kernel_old_timeval tm;
  1465. struct __kernel_sock_timeval stm;
  1466. struct sock_txtime txtime;
  1467. struct so_timestamping timestamping;
  1468. } v;
  1469. int lv = sizeof(int);
  1470. int len;
  1471. if (copy_from_sockptr(&len, optlen, sizeof(int)))
  1472. return -EFAULT;
  1473. if (len < 0)
  1474. return -EINVAL;
  1475. memset(&v, 0, sizeof(v));
  1476. switch (optname) {
  1477. case SO_DEBUG:
  1478. v.val = sock_flag(sk, SOCK_DBG);
  1479. break;
  1480. case SO_DONTROUTE:
  1481. v.val = sock_flag(sk, SOCK_LOCALROUTE);
  1482. break;
  1483. case SO_BROADCAST:
  1484. v.val = sock_flag(sk, SOCK_BROADCAST);
  1485. break;
  1486. case SO_SNDBUF:
  1487. v.val = READ_ONCE(sk->sk_sndbuf);
  1488. break;
  1489. case SO_RCVBUF:
  1490. v.val = READ_ONCE(sk->sk_rcvbuf);
  1491. break;
  1492. case SO_REUSEADDR:
  1493. v.val = sk->sk_reuse;
  1494. break;
  1495. case SO_REUSEPORT:
  1496. v.val = sk->sk_reuseport;
  1497. break;
  1498. case SO_KEEPALIVE:
  1499. v.val = sock_flag(sk, SOCK_KEEPOPEN);
  1500. break;
  1501. case SO_TYPE:
  1502. v.val = sk->sk_type;
  1503. break;
  1504. case SO_PROTOCOL:
  1505. v.val = sk->sk_protocol;
  1506. break;
  1507. case SO_DOMAIN:
  1508. v.val = sk->sk_family;
  1509. break;
  1510. case SO_ERROR:
  1511. v.val = -sock_error(sk);
  1512. if (v.val == 0)
  1513. v.val = xchg(&sk->sk_err_soft, 0);
  1514. break;
  1515. case SO_OOBINLINE:
  1516. v.val = sock_flag(sk, SOCK_URGINLINE);
  1517. break;
  1518. case SO_NO_CHECK:
  1519. v.val = sk->sk_no_check_tx;
  1520. break;
  1521. case SO_PRIORITY:
  1522. v.val = READ_ONCE(sk->sk_priority);
  1523. break;
  1524. case SO_LINGER:
  1525. lv = sizeof(v.ling);
  1526. v.ling.l_onoff = sock_flag(sk, SOCK_LINGER);
  1527. v.ling.l_linger = READ_ONCE(sk->sk_lingertime) / HZ;
  1528. break;
  1529. case SO_BSDCOMPAT:
  1530. break;
  1531. case SO_TIMESTAMP_OLD:
  1532. v.val = sock_flag(sk, SOCK_RCVTSTAMP) &&
  1533. !sock_flag(sk, SOCK_TSTAMP_NEW) &&
  1534. !sock_flag(sk, SOCK_RCVTSTAMPNS);
  1535. break;
  1536. case SO_TIMESTAMPNS_OLD:
  1537. v.val = sock_flag(sk, SOCK_RCVTSTAMPNS) && !sock_flag(sk, SOCK_TSTAMP_NEW);
  1538. break;
  1539. case SO_TIMESTAMP_NEW:
  1540. v.val = sock_flag(sk, SOCK_RCVTSTAMP) && sock_flag(sk, SOCK_TSTAMP_NEW);
  1541. break;
  1542. case SO_TIMESTAMPNS_NEW:
  1543. v.val = sock_flag(sk, SOCK_RCVTSTAMPNS) && sock_flag(sk, SOCK_TSTAMP_NEW);
  1544. break;
  1545. case SO_TIMESTAMPING_OLD:
  1546. case SO_TIMESTAMPING_NEW:
  1547. lv = sizeof(v.timestamping);
  1548. /* For the later-added case SO_TIMESTAMPING_NEW: Be strict about only
  1549. * returning the flags when they were set through the same option.
  1550. * Don't change the beviour for the old case SO_TIMESTAMPING_OLD.
  1551. */
  1552. if (optname == SO_TIMESTAMPING_OLD || sock_flag(sk, SOCK_TSTAMP_NEW)) {
  1553. v.timestamping.flags = READ_ONCE(sk->sk_tsflags);
  1554. v.timestamping.bind_phc = READ_ONCE(sk->sk_bind_phc);
  1555. }
  1556. break;
  1557. case SO_RCVTIMEO_OLD:
  1558. case SO_RCVTIMEO_NEW:
  1559. lv = sock_get_timeout(READ_ONCE(sk->sk_rcvtimeo), &v,
  1560. SO_RCVTIMEO_OLD == optname);
  1561. break;
  1562. case SO_SNDTIMEO_OLD:
  1563. case SO_SNDTIMEO_NEW:
  1564. lv = sock_get_timeout(READ_ONCE(sk->sk_sndtimeo), &v,
  1565. SO_SNDTIMEO_OLD == optname);
  1566. break;
  1567. case SO_RCVLOWAT:
  1568. v.val = READ_ONCE(sk->sk_rcvlowat);
  1569. break;
  1570. case SO_SNDLOWAT:
  1571. v.val = 1;
  1572. break;
  1573. case SO_PASSCRED:
  1574. v.val = !!test_bit(SOCK_PASSCRED, &sock->flags);
  1575. break;
  1576. case SO_PASSPIDFD:
  1577. v.val = !!test_bit(SOCK_PASSPIDFD, &sock->flags);
  1578. break;
  1579. case SO_PEERCRED:
  1580. {
  1581. struct ucred peercred;
  1582. if (len > sizeof(peercred))
  1583. len = sizeof(peercred);
  1584. spin_lock(&sk->sk_peer_lock);
  1585. cred_to_ucred(sk->sk_peer_pid, sk->sk_peer_cred, &peercred);
  1586. spin_unlock(&sk->sk_peer_lock);
  1587. if (copy_to_sockptr(optval, &peercred, len))
  1588. return -EFAULT;
  1589. goto lenout;
  1590. }
  1591. case SO_PEERPIDFD:
  1592. {
  1593. struct pid *peer_pid;
  1594. struct file *pidfd_file = NULL;
  1595. int pidfd;
  1596. if (len > sizeof(pidfd))
  1597. len = sizeof(pidfd);
  1598. spin_lock(&sk->sk_peer_lock);
  1599. peer_pid = get_pid(sk->sk_peer_pid);
  1600. spin_unlock(&sk->sk_peer_lock);
  1601. if (!peer_pid)
  1602. return -ENODATA;
  1603. pidfd = pidfd_prepare(peer_pid, 0, &pidfd_file);
  1604. put_pid(peer_pid);
  1605. if (pidfd < 0)
  1606. return pidfd;
  1607. if (copy_to_sockptr(optval, &pidfd, len) ||
  1608. copy_to_sockptr(optlen, &len, sizeof(int))) {
  1609. put_unused_fd(pidfd);
  1610. fput(pidfd_file);
  1611. return -EFAULT;
  1612. }
  1613. fd_install(pidfd, pidfd_file);
  1614. return 0;
  1615. }
  1616. case SO_PEERGROUPS:
  1617. {
  1618. const struct cred *cred;
  1619. int ret, n;
  1620. cred = sk_get_peer_cred(sk);
  1621. if (!cred)
  1622. return -ENODATA;
  1623. n = cred->group_info->ngroups;
  1624. if (len < n * sizeof(gid_t)) {
  1625. len = n * sizeof(gid_t);
  1626. put_cred(cred);
  1627. return copy_to_sockptr(optlen, &len, sizeof(int)) ? -EFAULT : -ERANGE;
  1628. }
  1629. len = n * sizeof(gid_t);
  1630. ret = groups_to_user(optval, cred->group_info);
  1631. put_cred(cred);
  1632. if (ret)
  1633. return ret;
  1634. goto lenout;
  1635. }
  1636. case SO_PEERNAME:
  1637. {
  1638. struct sockaddr_storage address;
  1639. lv = READ_ONCE(sock->ops)->getname(sock, (struct sockaddr *)&address, 2);
  1640. if (lv < 0)
  1641. return -ENOTCONN;
  1642. if (lv < len)
  1643. return -EINVAL;
  1644. if (copy_to_sockptr(optval, &address, len))
  1645. return -EFAULT;
  1646. goto lenout;
  1647. }
  1648. /* Dubious BSD thing... Probably nobody even uses it, but
  1649. * the UNIX standard wants it for whatever reason... -DaveM
  1650. */
  1651. case SO_ACCEPTCONN:
  1652. v.val = sk->sk_state == TCP_LISTEN;
  1653. break;
  1654. case SO_PASSSEC:
  1655. v.val = !!test_bit(SOCK_PASSSEC, &sock->flags);
  1656. break;
  1657. case SO_PEERSEC:
  1658. return security_socket_getpeersec_stream(sock,
  1659. optval, optlen, len);
  1660. case SO_MARK:
  1661. v.val = READ_ONCE(sk->sk_mark);
  1662. break;
  1663. case SO_RCVMARK:
  1664. v.val = sock_flag(sk, SOCK_RCVMARK);
  1665. break;
  1666. case SO_RXQ_OVFL:
  1667. v.val = sock_flag(sk, SOCK_RXQ_OVFL);
  1668. break;
  1669. case SO_WIFI_STATUS:
  1670. v.val = sock_flag(sk, SOCK_WIFI_STATUS);
  1671. break;
  1672. case SO_PEEK_OFF:
  1673. if (!READ_ONCE(sock->ops)->set_peek_off)
  1674. return -EOPNOTSUPP;
  1675. v.val = READ_ONCE(sk->sk_peek_off);
  1676. break;
  1677. case SO_NOFCS:
  1678. v.val = sock_flag(sk, SOCK_NOFCS);
  1679. break;
  1680. case SO_BINDTODEVICE:
  1681. return sock_getbindtodevice(sk, optval, optlen, len);
  1682. case SO_GET_FILTER:
  1683. len = sk_get_filter(sk, optval, len);
  1684. if (len < 0)
  1685. return len;
  1686. goto lenout;
  1687. case SO_LOCK_FILTER:
  1688. v.val = sock_flag(sk, SOCK_FILTER_LOCKED);
  1689. break;
  1690. case SO_BPF_EXTENSIONS:
  1691. v.val = bpf_tell_extensions();
  1692. break;
  1693. case SO_SELECT_ERR_QUEUE:
  1694. v.val = sock_flag(sk, SOCK_SELECT_ERR_QUEUE);
  1695. break;
  1696. #ifdef CONFIG_NET_RX_BUSY_POLL
  1697. case SO_BUSY_POLL:
  1698. v.val = READ_ONCE(sk->sk_ll_usec);
  1699. break;
  1700. case SO_PREFER_BUSY_POLL:
  1701. v.val = READ_ONCE(sk->sk_prefer_busy_poll);
  1702. break;
  1703. #endif
  1704. case SO_MAX_PACING_RATE:
  1705. /* The READ_ONCE() pair with the WRITE_ONCE() in sk_setsockopt() */
  1706. if (sizeof(v.ulval) != sizeof(v.val) && len >= sizeof(v.ulval)) {
  1707. lv = sizeof(v.ulval);
  1708. v.ulval = READ_ONCE(sk->sk_max_pacing_rate);
  1709. } else {
  1710. /* 32bit version */
  1711. v.val = min_t(unsigned long, ~0U,
  1712. READ_ONCE(sk->sk_max_pacing_rate));
  1713. }
  1714. break;
  1715. case SO_INCOMING_CPU:
  1716. v.val = READ_ONCE(sk->sk_incoming_cpu);
  1717. break;
  1718. case SO_MEMINFO:
  1719. {
  1720. u32 meminfo[SK_MEMINFO_VARS];
  1721. sk_get_meminfo(sk, meminfo);
  1722. len = min_t(unsigned int, len, sizeof(meminfo));
  1723. if (copy_to_sockptr(optval, &meminfo, len))
  1724. return -EFAULT;
  1725. goto lenout;
  1726. }
  1727. #ifdef CONFIG_NET_RX_BUSY_POLL
  1728. case SO_INCOMING_NAPI_ID:
  1729. v.val = READ_ONCE(sk->sk_napi_id);
  1730. /* aggregate non-NAPI IDs down to 0 */
  1731. if (v.val < MIN_NAPI_ID)
  1732. v.val = 0;
  1733. break;
  1734. #endif
  1735. case SO_COOKIE:
  1736. lv = sizeof(u64);
  1737. if (len < lv)
  1738. return -EINVAL;
  1739. v.val64 = sock_gen_cookie(sk);
  1740. break;
  1741. case SO_ZEROCOPY:
  1742. v.val = sock_flag(sk, SOCK_ZEROCOPY);
  1743. break;
  1744. case SO_TXTIME:
  1745. lv = sizeof(v.txtime);
  1746. v.txtime.clockid = sk->sk_clockid;
  1747. v.txtime.flags |= sk->sk_txtime_deadline_mode ?
  1748. SOF_TXTIME_DEADLINE_MODE : 0;
  1749. v.txtime.flags |= sk->sk_txtime_report_errors ?
  1750. SOF_TXTIME_REPORT_ERRORS : 0;
  1751. break;
  1752. case SO_BINDTOIFINDEX:
  1753. v.val = READ_ONCE(sk->sk_bound_dev_if);
  1754. break;
  1755. case SO_NETNS_COOKIE:
  1756. lv = sizeof(u64);
  1757. if (len != lv)
  1758. return -EINVAL;
  1759. v.val64 = sock_net(sk)->net_cookie;
  1760. break;
  1761. case SO_BUF_LOCK:
  1762. v.val = sk->sk_userlocks & SOCK_BUF_LOCK_MASK;
  1763. break;
  1764. case SO_RESERVE_MEM:
  1765. v.val = READ_ONCE(sk->sk_reserved_mem);
  1766. break;
  1767. case SO_TXREHASH:
  1768. /* Paired with WRITE_ONCE() in sk_setsockopt() */
  1769. v.val = READ_ONCE(sk->sk_txrehash);
  1770. break;
  1771. default:
  1772. /* We implement the SO_SNDLOWAT etc to not be settable
  1773. * (1003.1g 7).
  1774. */
  1775. return -ENOPROTOOPT;
  1776. }
  1777. if (len > lv)
  1778. len = lv;
  1779. if (copy_to_sockptr(optval, &v, len))
  1780. return -EFAULT;
  1781. lenout:
  1782. if (copy_to_sockptr(optlen, &len, sizeof(int)))
  1783. return -EFAULT;
  1784. return 0;
  1785. }
  1786. /*
  1787. * Initialize an sk_lock.
  1788. *
  1789. * (We also register the sk_lock with the lock validator.)
  1790. */
  1791. static inline void sock_lock_init(struct sock *sk)
  1792. {
  1793. sk_owner_clear(sk);
  1794. if (sk->sk_kern_sock)
  1795. sock_lock_init_class_and_name(
  1796. sk,
  1797. af_family_kern_slock_key_strings[sk->sk_family],
  1798. af_family_kern_slock_keys + sk->sk_family,
  1799. af_family_kern_key_strings[sk->sk_family],
  1800. af_family_kern_keys + sk->sk_family);
  1801. else
  1802. sock_lock_init_class_and_name(
  1803. sk,
  1804. af_family_slock_key_strings[sk->sk_family],
  1805. af_family_slock_keys + sk->sk_family,
  1806. af_family_key_strings[sk->sk_family],
  1807. af_family_keys + sk->sk_family);
  1808. }
  1809. /*
  1810. * Copy all fields from osk to nsk but nsk->sk_refcnt must not change yet,
  1811. * even temporarily, because of RCU lookups. sk_node should also be left as is.
  1812. * We must not copy fields between sk_dontcopy_begin and sk_dontcopy_end
  1813. */
  1814. static void sock_copy(struct sock *nsk, const struct sock *osk)
  1815. {
  1816. const struct proto *prot = READ_ONCE(osk->sk_prot);
  1817. #ifdef CONFIG_SECURITY_NETWORK
  1818. void *sptr = nsk->sk_security;
  1819. #endif
  1820. /* If we move sk_tx_queue_mapping out of the private section,
  1821. * we must check if sk_tx_queue_clear() is called after
  1822. * sock_copy() in sk_clone_lock().
  1823. */
  1824. BUILD_BUG_ON(offsetof(struct sock, sk_tx_queue_mapping) <
  1825. offsetof(struct sock, sk_dontcopy_begin) ||
  1826. offsetof(struct sock, sk_tx_queue_mapping) >=
  1827. offsetof(struct sock, sk_dontcopy_end));
  1828. memcpy(nsk, osk, offsetof(struct sock, sk_dontcopy_begin));
  1829. unsafe_memcpy(&nsk->sk_dontcopy_end, &osk->sk_dontcopy_end,
  1830. prot->obj_size - offsetof(struct sock, sk_dontcopy_end),
  1831. /* alloc is larger than struct, see sk_prot_alloc() */);
  1832. #ifdef CONFIG_SECURITY_NETWORK
  1833. nsk->sk_security = sptr;
  1834. security_sk_clone(osk, nsk);
  1835. #endif
  1836. }
  1837. static struct sock *sk_prot_alloc(struct proto *prot, gfp_t priority,
  1838. int family)
  1839. {
  1840. struct sock *sk;
  1841. struct kmem_cache *slab;
  1842. slab = prot->slab;
  1843. if (slab != NULL) {
  1844. sk = kmem_cache_alloc(slab, priority & ~__GFP_ZERO);
  1845. if (!sk)
  1846. return sk;
  1847. if (want_init_on_alloc(priority))
  1848. sk_prot_clear_nulls(sk, prot->obj_size);
  1849. } else
  1850. sk = kmalloc(prot->obj_size, priority);
  1851. if (sk != NULL) {
  1852. if (security_sk_alloc(sk, family, priority))
  1853. goto out_free;
  1854. if (!try_module_get(prot->owner))
  1855. goto out_free_sec;
  1856. }
  1857. return sk;
  1858. out_free_sec:
  1859. security_sk_free(sk);
  1860. out_free:
  1861. if (slab != NULL)
  1862. kmem_cache_free(slab, sk);
  1863. else
  1864. kfree(sk);
  1865. return NULL;
  1866. }
  1867. static void sk_prot_free(struct proto *prot, struct sock *sk)
  1868. {
  1869. struct kmem_cache *slab;
  1870. struct module *owner;
  1871. owner = prot->owner;
  1872. slab = prot->slab;
  1873. cgroup_sk_free(&sk->sk_cgrp_data);
  1874. mem_cgroup_sk_free(sk);
  1875. security_sk_free(sk);
  1876. sk_owner_put(sk);
  1877. if (slab != NULL)
  1878. kmem_cache_free(slab, sk);
  1879. else
  1880. kfree(sk);
  1881. module_put(owner);
  1882. }
  1883. /**
  1884. * sk_alloc - All socket objects are allocated here
  1885. * @net: the applicable net namespace
  1886. * @family: protocol family
  1887. * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
  1888. * @prot: struct proto associated with this new sock instance
  1889. * @kern: is this to be a kernel socket?
  1890. */
  1891. struct sock *sk_alloc(struct net *net, int family, gfp_t priority,
  1892. struct proto *prot, int kern)
  1893. {
  1894. struct sock *sk;
  1895. sk = sk_prot_alloc(prot, priority | __GFP_ZERO, family);
  1896. if (sk) {
  1897. sk->sk_family = family;
  1898. /*
  1899. * See comment in struct sock definition to understand
  1900. * why we need sk_prot_creator -acme
  1901. */
  1902. sk->sk_prot = sk->sk_prot_creator = prot;
  1903. sk->sk_kern_sock = kern;
  1904. sock_lock_init(sk);
  1905. sk->sk_net_refcnt = kern ? 0 : 1;
  1906. if (likely(sk->sk_net_refcnt)) {
  1907. get_net_track(net, &sk->ns_tracker, priority);
  1908. sock_inuse_add(net, 1);
  1909. } else {
  1910. net_passive_inc(net);
  1911. __netns_tracker_alloc(net, &sk->ns_tracker,
  1912. false, priority);
  1913. }
  1914. sock_net_set(sk, net);
  1915. refcount_set(&sk->sk_wmem_alloc, 1);
  1916. mem_cgroup_sk_alloc(sk);
  1917. cgroup_sk_alloc(&sk->sk_cgrp_data);
  1918. sock_update_classid(&sk->sk_cgrp_data);
  1919. sock_update_netprioidx(&sk->sk_cgrp_data);
  1920. sk_tx_queue_clear(sk);
  1921. }
  1922. return sk;
  1923. }
  1924. EXPORT_SYMBOL(sk_alloc);
  1925. /* Sockets having SOCK_RCU_FREE will call this function after one RCU
  1926. * grace period. This is the case for UDP sockets and TCP listeners.
  1927. */
  1928. static void __sk_destruct(struct rcu_head *head)
  1929. {
  1930. struct sock *sk = container_of(head, struct sock, sk_rcu);
  1931. struct net *net = sock_net(sk);
  1932. struct sk_filter *filter;
  1933. if (sk->sk_destruct)
  1934. sk->sk_destruct(sk);
  1935. filter = rcu_dereference_check(sk->sk_filter,
  1936. refcount_read(&sk->sk_wmem_alloc) == 0);
  1937. if (filter) {
  1938. sk_filter_uncharge(sk, filter);
  1939. RCU_INIT_POINTER(sk->sk_filter, NULL);
  1940. }
  1941. sock_disable_timestamp(sk, SK_FLAGS_TIMESTAMP);
  1942. #ifdef CONFIG_BPF_SYSCALL
  1943. bpf_sk_storage_free(sk);
  1944. #endif
  1945. if (atomic_read(&sk->sk_omem_alloc))
  1946. pr_debug("%s: optmem leakage (%d bytes) detected\n",
  1947. __func__, atomic_read(&sk->sk_omem_alloc));
  1948. if (sk->sk_frag.page) {
  1949. put_page(sk->sk_frag.page);
  1950. sk->sk_frag.page = NULL;
  1951. }
  1952. /* We do not need to acquire sk->sk_peer_lock, we are the last user. */
  1953. put_cred(sk->sk_peer_cred);
  1954. put_pid(sk->sk_peer_pid);
  1955. if (likely(sk->sk_net_refcnt)) {
  1956. put_net_track(net, &sk->ns_tracker);
  1957. } else {
  1958. __netns_tracker_free(net, &sk->ns_tracker, false);
  1959. net_passive_dec(net);
  1960. }
  1961. sk_prot_free(sk->sk_prot_creator, sk);
  1962. }
  1963. void sk_net_refcnt_upgrade(struct sock *sk)
  1964. {
  1965. struct net *net = sock_net(sk);
  1966. WARN_ON_ONCE(sk->sk_net_refcnt);
  1967. __netns_tracker_free(net, &sk->ns_tracker, false);
  1968. net_passive_dec(net);
  1969. sk->sk_net_refcnt = 1;
  1970. get_net_track(net, &sk->ns_tracker, GFP_KERNEL);
  1971. sock_inuse_add(net, 1);
  1972. }
  1973. EXPORT_SYMBOL_GPL(sk_net_refcnt_upgrade);
  1974. void sk_destruct(struct sock *sk)
  1975. {
  1976. bool use_call_rcu = sock_flag(sk, SOCK_RCU_FREE);
  1977. if (rcu_access_pointer(sk->sk_reuseport_cb)) {
  1978. reuseport_detach_sock(sk);
  1979. use_call_rcu = true;
  1980. }
  1981. if (use_call_rcu)
  1982. call_rcu(&sk->sk_rcu, __sk_destruct);
  1983. else
  1984. __sk_destruct(&sk->sk_rcu);
  1985. }
  1986. static void __sk_free(struct sock *sk)
  1987. {
  1988. if (likely(sk->sk_net_refcnt))
  1989. sock_inuse_add(sock_net(sk), -1);
  1990. if (unlikely(sk->sk_net_refcnt && sock_diag_has_destroy_listeners(sk)))
  1991. sock_diag_broadcast_destroy(sk);
  1992. else
  1993. sk_destruct(sk);
  1994. }
  1995. void sk_free(struct sock *sk)
  1996. {
  1997. /*
  1998. * We subtract one from sk_wmem_alloc and can know if
  1999. * some packets are still in some tx queue.
  2000. * If not null, sock_wfree() will call __sk_free(sk) later
  2001. */
  2002. if (refcount_dec_and_test(&sk->sk_wmem_alloc))
  2003. __sk_free(sk);
  2004. }
  2005. EXPORT_SYMBOL(sk_free);
  2006. static void sk_init_common(struct sock *sk)
  2007. {
  2008. skb_queue_head_init(&sk->sk_receive_queue);
  2009. skb_queue_head_init(&sk->sk_write_queue);
  2010. skb_queue_head_init(&sk->sk_error_queue);
  2011. rwlock_init(&sk->sk_callback_lock);
  2012. lockdep_set_class_and_name(&sk->sk_receive_queue.lock,
  2013. af_rlock_keys + sk->sk_family,
  2014. af_family_rlock_key_strings[sk->sk_family]);
  2015. lockdep_set_class_and_name(&sk->sk_write_queue.lock,
  2016. af_wlock_keys + sk->sk_family,
  2017. af_family_wlock_key_strings[sk->sk_family]);
  2018. lockdep_set_class_and_name(&sk->sk_error_queue.lock,
  2019. af_elock_keys + sk->sk_family,
  2020. af_family_elock_key_strings[sk->sk_family]);
  2021. if (sk->sk_kern_sock)
  2022. lockdep_set_class_and_name(&sk->sk_callback_lock,
  2023. af_kern_callback_keys + sk->sk_family,
  2024. af_family_kern_clock_key_strings[sk->sk_family]);
  2025. else
  2026. lockdep_set_class_and_name(&sk->sk_callback_lock,
  2027. af_callback_keys + sk->sk_family,
  2028. af_family_clock_key_strings[sk->sk_family]);
  2029. }
  2030. /**
  2031. * sk_clone_lock - clone a socket, and lock its clone
  2032. * @sk: the socket to clone
  2033. * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
  2034. *
  2035. * Caller must unlock socket even in error path (bh_unlock_sock(newsk))
  2036. */
  2037. struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority)
  2038. {
  2039. struct proto *prot = READ_ONCE(sk->sk_prot);
  2040. struct sk_filter *filter;
  2041. bool is_charged = true;
  2042. struct sock *newsk;
  2043. newsk = sk_prot_alloc(prot, priority, sk->sk_family);
  2044. if (!newsk)
  2045. goto out;
  2046. sock_copy(newsk, sk);
  2047. newsk->sk_prot_creator = prot;
  2048. /* SANITY */
  2049. if (likely(newsk->sk_net_refcnt)) {
  2050. get_net_track(sock_net(newsk), &newsk->ns_tracker, priority);
  2051. sock_inuse_add(sock_net(newsk), 1);
  2052. } else {
  2053. /* Kernel sockets are not elevating the struct net refcount.
  2054. * Instead, use a tracker to more easily detect if a layer
  2055. * is not properly dismantling its kernel sockets at netns
  2056. * destroy time.
  2057. */
  2058. net_passive_inc(sock_net(newsk));
  2059. __netns_tracker_alloc(sock_net(newsk), &newsk->ns_tracker,
  2060. false, priority);
  2061. }
  2062. sk_node_init(&newsk->sk_node);
  2063. sock_lock_init(newsk);
  2064. bh_lock_sock(newsk);
  2065. newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL;
  2066. newsk->sk_backlog.len = 0;
  2067. atomic_set(&newsk->sk_rmem_alloc, 0);
  2068. /* sk_wmem_alloc set to one (see sk_free() and sock_wfree()) */
  2069. refcount_set(&newsk->sk_wmem_alloc, 1);
  2070. atomic_set(&newsk->sk_omem_alloc, 0);
  2071. sk_init_common(newsk);
  2072. newsk->sk_dst_cache = NULL;
  2073. newsk->sk_dst_pending_confirm = 0;
  2074. newsk->sk_wmem_queued = 0;
  2075. newsk->sk_forward_alloc = 0;
  2076. newsk->sk_reserved_mem = 0;
  2077. atomic_set(&newsk->sk_drops, 0);
  2078. newsk->sk_send_head = NULL;
  2079. newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK;
  2080. atomic_set(&newsk->sk_zckey, 0);
  2081. sock_reset_flag(newsk, SOCK_DONE);
  2082. /* sk->sk_memcg will be populated at accept() time */
  2083. newsk->sk_memcg = NULL;
  2084. cgroup_sk_clone(&newsk->sk_cgrp_data);
  2085. rcu_read_lock();
  2086. filter = rcu_dereference(sk->sk_filter);
  2087. if (filter != NULL)
  2088. /* though it's an empty new sock, the charging may fail
  2089. * if sysctl_optmem_max was changed between creation of
  2090. * original socket and cloning
  2091. */
  2092. is_charged = sk_filter_charge(newsk, filter);
  2093. RCU_INIT_POINTER(newsk->sk_filter, filter);
  2094. rcu_read_unlock();
  2095. if (unlikely(!is_charged || xfrm_sk_clone_policy(newsk, sk))) {
  2096. /* We need to make sure that we don't uncharge the new
  2097. * socket if we couldn't charge it in the first place
  2098. * as otherwise we uncharge the parent's filter.
  2099. */
  2100. if (!is_charged)
  2101. RCU_INIT_POINTER(newsk->sk_filter, NULL);
  2102. sk_free_unlock_clone(newsk);
  2103. newsk = NULL;
  2104. goto out;
  2105. }
  2106. RCU_INIT_POINTER(newsk->sk_reuseport_cb, NULL);
  2107. if (bpf_sk_storage_clone(sk, newsk)) {
  2108. sk_free_unlock_clone(newsk);
  2109. newsk = NULL;
  2110. goto out;
  2111. }
  2112. /* Clear sk_user_data if parent had the pointer tagged
  2113. * as not suitable for copying when cloning.
  2114. */
  2115. if (sk_user_data_is_nocopy(newsk))
  2116. newsk->sk_user_data = NULL;
  2117. newsk->sk_err = 0;
  2118. newsk->sk_err_soft = 0;
  2119. newsk->sk_priority = 0;
  2120. newsk->sk_incoming_cpu = raw_smp_processor_id();
  2121. /* Before updating sk_refcnt, we must commit prior changes to memory
  2122. * (Documentation/RCU/rculist_nulls.rst for details)
  2123. */
  2124. smp_wmb();
  2125. refcount_set(&newsk->sk_refcnt, 2);
  2126. sk_set_socket(newsk, NULL);
  2127. sk_tx_queue_clear(newsk);
  2128. RCU_INIT_POINTER(newsk->sk_wq, NULL);
  2129. if (newsk->sk_prot->sockets_allocated)
  2130. sk_sockets_allocated_inc(newsk);
  2131. if (sock_needs_netstamp(sk) && newsk->sk_flags & SK_FLAGS_TIMESTAMP)
  2132. net_enable_timestamp();
  2133. out:
  2134. return newsk;
  2135. }
  2136. EXPORT_SYMBOL_GPL(sk_clone_lock);
  2137. void sk_free_unlock_clone(struct sock *sk)
  2138. {
  2139. /* It is still raw copy of parent, so invalidate
  2140. * destructor and make plain sk_free() */
  2141. sk->sk_destruct = NULL;
  2142. bh_unlock_sock(sk);
  2143. sk_free(sk);
  2144. }
  2145. EXPORT_SYMBOL_GPL(sk_free_unlock_clone);
  2146. static u32 sk_dst_gso_max_size(struct sock *sk, struct dst_entry *dst)
  2147. {
  2148. bool is_ipv6 = false;
  2149. u32 max_size;
  2150. #if IS_ENABLED(CONFIG_IPV6)
  2151. is_ipv6 = (sk->sk_family == AF_INET6 &&
  2152. !ipv6_addr_v4mapped(&sk->sk_v6_rcv_saddr));
  2153. #endif
  2154. /* pairs with the WRITE_ONCE() in netif_set_gso(_ipv4)_max_size() */
  2155. max_size = is_ipv6 ? READ_ONCE(dst_dev(dst)->gso_max_size) :
  2156. READ_ONCE(dst_dev(dst)->gso_ipv4_max_size);
  2157. if (max_size > GSO_LEGACY_MAX_SIZE && !sk_is_tcp(sk))
  2158. max_size = GSO_LEGACY_MAX_SIZE;
  2159. return max_size - (MAX_TCP_HEADER + 1);
  2160. }
  2161. void sk_setup_caps(struct sock *sk, struct dst_entry *dst)
  2162. {
  2163. u32 max_segs = 1;
  2164. sk->sk_route_caps = dst_dev(dst)->features;
  2165. if (sk_is_tcp(sk)) {
  2166. struct inet_connection_sock *icsk = inet_csk(sk);
  2167. sk->sk_route_caps |= NETIF_F_GSO;
  2168. icsk->icsk_ack.dst_quick_ack = dst_metric(dst, RTAX_QUICKACK);
  2169. }
  2170. if (sk->sk_route_caps & NETIF_F_GSO)
  2171. sk->sk_route_caps |= NETIF_F_GSO_SOFTWARE;
  2172. if (unlikely(sk->sk_gso_disabled))
  2173. sk->sk_route_caps &= ~NETIF_F_GSO_MASK;
  2174. if (sk_can_gso(sk)) {
  2175. if (dst->header_len && !xfrm_dst_offload_ok(dst)) {
  2176. sk->sk_route_caps &= ~NETIF_F_GSO_MASK;
  2177. } else {
  2178. sk->sk_route_caps |= NETIF_F_SG | NETIF_F_HW_CSUM;
  2179. sk->sk_gso_max_size = sk_dst_gso_max_size(sk, dst);
  2180. /* pairs with the WRITE_ONCE() in netif_set_gso_max_segs() */
  2181. max_segs = max_t(u32, READ_ONCE(dst_dev(dst)->gso_max_segs), 1);
  2182. }
  2183. }
  2184. sk->sk_gso_max_segs = max_segs;
  2185. sk_dst_set(sk, dst);
  2186. }
  2187. EXPORT_SYMBOL_GPL(sk_setup_caps);
  2188. /*
  2189. * Simple resource managers for sockets.
  2190. */
  2191. /*
  2192. * Write buffer destructor automatically called from kfree_skb.
  2193. */
  2194. void sock_wfree(struct sk_buff *skb)
  2195. {
  2196. struct sock *sk = skb->sk;
  2197. unsigned int len = skb->truesize;
  2198. bool free;
  2199. if (!sock_flag(sk, SOCK_USE_WRITE_QUEUE)) {
  2200. if (sock_flag(sk, SOCK_RCU_FREE) &&
  2201. sk->sk_write_space == sock_def_write_space) {
  2202. rcu_read_lock();
  2203. free = refcount_sub_and_test(len, &sk->sk_wmem_alloc);
  2204. sock_def_write_space_wfree(sk);
  2205. rcu_read_unlock();
  2206. if (unlikely(free))
  2207. __sk_free(sk);
  2208. return;
  2209. }
  2210. /*
  2211. * Keep a reference on sk_wmem_alloc, this will be released
  2212. * after sk_write_space() call
  2213. */
  2214. WARN_ON(refcount_sub_and_test(len - 1, &sk->sk_wmem_alloc));
  2215. sk->sk_write_space(sk);
  2216. len = 1;
  2217. }
  2218. /*
  2219. * if sk_wmem_alloc reaches 0, we must finish what sk_free()
  2220. * could not do because of in-flight packets
  2221. */
  2222. if (refcount_sub_and_test(len, &sk->sk_wmem_alloc))
  2223. __sk_free(sk);
  2224. }
  2225. EXPORT_SYMBOL(sock_wfree);
  2226. /* This variant of sock_wfree() is used by TCP,
  2227. * since it sets SOCK_USE_WRITE_QUEUE.
  2228. */
  2229. void __sock_wfree(struct sk_buff *skb)
  2230. {
  2231. struct sock *sk = skb->sk;
  2232. if (refcount_sub_and_test(skb->truesize, &sk->sk_wmem_alloc))
  2233. __sk_free(sk);
  2234. }
  2235. void skb_set_owner_w(struct sk_buff *skb, struct sock *sk)
  2236. {
  2237. skb_orphan(skb);
  2238. skb->sk = sk;
  2239. #ifdef CONFIG_INET
  2240. if (unlikely(!sk_fullsock(sk))) {
  2241. skb->destructor = sock_edemux;
  2242. sock_hold(sk);
  2243. return;
  2244. }
  2245. #endif
  2246. skb->destructor = sock_wfree;
  2247. skb_set_hash_from_sk(skb, sk);
  2248. /*
  2249. * We used to take a refcount on sk, but following operation
  2250. * is enough to guarantee sk_free() won't free this sock until
  2251. * all in-flight packets are completed
  2252. */
  2253. refcount_add(skb->truesize, &sk->sk_wmem_alloc);
  2254. }
  2255. EXPORT_SYMBOL(skb_set_owner_w);
  2256. static bool can_skb_orphan_partial(const struct sk_buff *skb)
  2257. {
  2258. /* Drivers depend on in-order delivery for crypto offload,
  2259. * partial orphan breaks out-of-order-OK logic.
  2260. */
  2261. if (skb_is_decrypted(skb))
  2262. return false;
  2263. return (skb->destructor == sock_wfree ||
  2264. (IS_ENABLED(CONFIG_INET) && skb->destructor == tcp_wfree));
  2265. }
  2266. /* This helper is used by netem, as it can hold packets in its
  2267. * delay queue. We want to allow the owner socket to send more
  2268. * packets, as if they were already TX completed by a typical driver.
  2269. * But we also want to keep skb->sk set because some packet schedulers
  2270. * rely on it (sch_fq for example).
  2271. */
  2272. void skb_orphan_partial(struct sk_buff *skb)
  2273. {
  2274. if (skb_is_tcp_pure_ack(skb))
  2275. return;
  2276. if (can_skb_orphan_partial(skb) && skb_set_owner_sk_safe(skb, skb->sk))
  2277. return;
  2278. skb_orphan(skb);
  2279. }
  2280. EXPORT_SYMBOL(skb_orphan_partial);
  2281. /*
  2282. * Read buffer destructor automatically called from kfree_skb.
  2283. */
  2284. void sock_rfree(struct sk_buff *skb)
  2285. {
  2286. struct sock *sk = skb->sk;
  2287. unsigned int len = skb->truesize;
  2288. atomic_sub(len, &sk->sk_rmem_alloc);
  2289. sk_mem_uncharge(sk, len);
  2290. }
  2291. EXPORT_SYMBOL(sock_rfree);
  2292. /*
  2293. * Buffer destructor for skbs that are not used directly in read or write
  2294. * path, e.g. for error handler skbs. Automatically called from kfree_skb.
  2295. */
  2296. void sock_efree(struct sk_buff *skb)
  2297. {
  2298. sock_put(skb->sk);
  2299. }
  2300. EXPORT_SYMBOL(sock_efree);
  2301. /* Buffer destructor for prefetch/receive path where reference count may
  2302. * not be held, e.g. for listen sockets.
  2303. */
  2304. #ifdef CONFIG_INET
  2305. void sock_pfree(struct sk_buff *skb)
  2306. {
  2307. struct sock *sk = skb->sk;
  2308. if (!sk_is_refcounted(sk))
  2309. return;
  2310. if (sk->sk_state == TCP_NEW_SYN_RECV && inet_reqsk(sk)->syncookie) {
  2311. inet_reqsk(sk)->rsk_listener = NULL;
  2312. reqsk_free(inet_reqsk(sk));
  2313. return;
  2314. }
  2315. sock_gen_put(sk);
  2316. }
  2317. EXPORT_SYMBOL(sock_pfree);
  2318. #endif /* CONFIG_INET */
  2319. kuid_t sock_i_uid(struct sock *sk)
  2320. {
  2321. kuid_t uid;
  2322. read_lock_bh(&sk->sk_callback_lock);
  2323. uid = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_uid : GLOBAL_ROOT_UID;
  2324. read_unlock_bh(&sk->sk_callback_lock);
  2325. return uid;
  2326. }
  2327. EXPORT_SYMBOL(sock_i_uid);
  2328. unsigned long __sock_i_ino(struct sock *sk)
  2329. {
  2330. unsigned long ino;
  2331. read_lock(&sk->sk_callback_lock);
  2332. ino = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_ino : 0;
  2333. read_unlock(&sk->sk_callback_lock);
  2334. return ino;
  2335. }
  2336. EXPORT_SYMBOL(__sock_i_ino);
  2337. unsigned long sock_i_ino(struct sock *sk)
  2338. {
  2339. unsigned long ino;
  2340. local_bh_disable();
  2341. ino = __sock_i_ino(sk);
  2342. local_bh_enable();
  2343. return ino;
  2344. }
  2345. EXPORT_SYMBOL(sock_i_ino);
  2346. /*
  2347. * Allocate a skb from the socket's send buffer.
  2348. */
  2349. struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force,
  2350. gfp_t priority)
  2351. {
  2352. if (force ||
  2353. refcount_read(&sk->sk_wmem_alloc) < READ_ONCE(sk->sk_sndbuf)) {
  2354. struct sk_buff *skb = alloc_skb(size, priority);
  2355. if (skb) {
  2356. skb_set_owner_w(skb, sk);
  2357. return skb;
  2358. }
  2359. }
  2360. return NULL;
  2361. }
  2362. EXPORT_SYMBOL(sock_wmalloc);
  2363. static void sock_ofree(struct sk_buff *skb)
  2364. {
  2365. struct sock *sk = skb->sk;
  2366. atomic_sub(skb->truesize, &sk->sk_omem_alloc);
  2367. }
  2368. struct sk_buff *sock_omalloc(struct sock *sk, unsigned long size,
  2369. gfp_t priority)
  2370. {
  2371. struct sk_buff *skb;
  2372. /* small safe race: SKB_TRUESIZE may differ from final skb->truesize */
  2373. if (atomic_read(&sk->sk_omem_alloc) + SKB_TRUESIZE(size) >
  2374. READ_ONCE(sock_net(sk)->core.sysctl_optmem_max))
  2375. return NULL;
  2376. skb = alloc_skb(size, priority);
  2377. if (!skb)
  2378. return NULL;
  2379. atomic_add(skb->truesize, &sk->sk_omem_alloc);
  2380. skb->sk = sk;
  2381. skb->destructor = sock_ofree;
  2382. return skb;
  2383. }
  2384. /*
  2385. * Allocate a memory block from the socket's option memory buffer.
  2386. */
  2387. void *sock_kmalloc(struct sock *sk, int size, gfp_t priority)
  2388. {
  2389. int optmem_max = READ_ONCE(sock_net(sk)->core.sysctl_optmem_max);
  2390. if ((unsigned int)size <= optmem_max &&
  2391. atomic_read(&sk->sk_omem_alloc) + size < optmem_max) {
  2392. void *mem;
  2393. /* First do the add, to avoid the race if kmalloc
  2394. * might sleep.
  2395. */
  2396. atomic_add(size, &sk->sk_omem_alloc);
  2397. mem = kmalloc(size, priority);
  2398. if (mem)
  2399. return mem;
  2400. atomic_sub(size, &sk->sk_omem_alloc);
  2401. }
  2402. return NULL;
  2403. }
  2404. EXPORT_SYMBOL(sock_kmalloc);
  2405. /* Free an option memory block. Note, we actually want the inline
  2406. * here as this allows gcc to detect the nullify and fold away the
  2407. * condition entirely.
  2408. */
  2409. static inline void __sock_kfree_s(struct sock *sk, void *mem, int size,
  2410. const bool nullify)
  2411. {
  2412. if (WARN_ON_ONCE(!mem))
  2413. return;
  2414. if (nullify)
  2415. kfree_sensitive(mem);
  2416. else
  2417. kfree(mem);
  2418. atomic_sub(size, &sk->sk_omem_alloc);
  2419. }
  2420. void sock_kfree_s(struct sock *sk, void *mem, int size)
  2421. {
  2422. __sock_kfree_s(sk, mem, size, false);
  2423. }
  2424. EXPORT_SYMBOL(sock_kfree_s);
  2425. void sock_kzfree_s(struct sock *sk, void *mem, int size)
  2426. {
  2427. __sock_kfree_s(sk, mem, size, true);
  2428. }
  2429. EXPORT_SYMBOL(sock_kzfree_s);
  2430. /* It is almost wait_for_tcp_memory minus release_sock/lock_sock.
  2431. I think, these locks should be removed for datagram sockets.
  2432. */
  2433. static long sock_wait_for_wmem(struct sock *sk, long timeo)
  2434. {
  2435. DEFINE_WAIT(wait);
  2436. sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
  2437. for (;;) {
  2438. if (!timeo)
  2439. break;
  2440. if (signal_pending(current))
  2441. break;
  2442. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  2443. prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
  2444. if (refcount_read(&sk->sk_wmem_alloc) < READ_ONCE(sk->sk_sndbuf))
  2445. break;
  2446. if (READ_ONCE(sk->sk_shutdown) & SEND_SHUTDOWN)
  2447. break;
  2448. if (READ_ONCE(sk->sk_err))
  2449. break;
  2450. timeo = schedule_timeout(timeo);
  2451. }
  2452. finish_wait(sk_sleep(sk), &wait);
  2453. return timeo;
  2454. }
  2455. /*
  2456. * Generic send/receive buffer handlers
  2457. */
  2458. struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
  2459. unsigned long data_len, int noblock,
  2460. int *errcode, int max_page_order)
  2461. {
  2462. struct sk_buff *skb;
  2463. long timeo;
  2464. int err;
  2465. timeo = sock_sndtimeo(sk, noblock);
  2466. for (;;) {
  2467. err = sock_error(sk);
  2468. if (err != 0)
  2469. goto failure;
  2470. err = -EPIPE;
  2471. if (READ_ONCE(sk->sk_shutdown) & SEND_SHUTDOWN)
  2472. goto failure;
  2473. if (sk_wmem_alloc_get(sk) < READ_ONCE(sk->sk_sndbuf))
  2474. break;
  2475. sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
  2476. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  2477. err = -EAGAIN;
  2478. if (!timeo)
  2479. goto failure;
  2480. if (signal_pending(current))
  2481. goto interrupted;
  2482. timeo = sock_wait_for_wmem(sk, timeo);
  2483. }
  2484. skb = alloc_skb_with_frags(header_len, data_len, max_page_order,
  2485. errcode, sk->sk_allocation);
  2486. if (skb)
  2487. skb_set_owner_w(skb, sk);
  2488. return skb;
  2489. interrupted:
  2490. err = sock_intr_errno(timeo);
  2491. failure:
  2492. *errcode = err;
  2493. return NULL;
  2494. }
  2495. EXPORT_SYMBOL(sock_alloc_send_pskb);
  2496. int __sock_cmsg_send(struct sock *sk, struct cmsghdr *cmsg,
  2497. struct sockcm_cookie *sockc)
  2498. {
  2499. u32 tsflags;
  2500. switch (cmsg->cmsg_type) {
  2501. case SO_MARK:
  2502. if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_RAW) &&
  2503. !ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
  2504. return -EPERM;
  2505. if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32)))
  2506. return -EINVAL;
  2507. sockc->mark = *(u32 *)CMSG_DATA(cmsg);
  2508. break;
  2509. case SO_TIMESTAMPING_OLD:
  2510. case SO_TIMESTAMPING_NEW:
  2511. if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32)))
  2512. return -EINVAL;
  2513. tsflags = *(u32 *)CMSG_DATA(cmsg);
  2514. if (tsflags & ~SOF_TIMESTAMPING_TX_RECORD_MASK)
  2515. return -EINVAL;
  2516. sockc->tsflags &= ~SOF_TIMESTAMPING_TX_RECORD_MASK;
  2517. sockc->tsflags |= tsflags;
  2518. break;
  2519. case SCM_TXTIME:
  2520. if (!sock_flag(sk, SOCK_TXTIME))
  2521. return -EINVAL;
  2522. if (cmsg->cmsg_len != CMSG_LEN(sizeof(u64)))
  2523. return -EINVAL;
  2524. sockc->transmit_time = get_unaligned((u64 *)CMSG_DATA(cmsg));
  2525. break;
  2526. /* SCM_RIGHTS and SCM_CREDENTIALS are semantically in SOL_UNIX. */
  2527. case SCM_RIGHTS:
  2528. case SCM_CREDENTIALS:
  2529. break;
  2530. default:
  2531. return -EINVAL;
  2532. }
  2533. return 0;
  2534. }
  2535. EXPORT_SYMBOL(__sock_cmsg_send);
  2536. int sock_cmsg_send(struct sock *sk, struct msghdr *msg,
  2537. struct sockcm_cookie *sockc)
  2538. {
  2539. struct cmsghdr *cmsg;
  2540. int ret;
  2541. for_each_cmsghdr(cmsg, msg) {
  2542. if (!CMSG_OK(msg, cmsg))
  2543. return -EINVAL;
  2544. if (cmsg->cmsg_level != SOL_SOCKET)
  2545. continue;
  2546. ret = __sock_cmsg_send(sk, cmsg, sockc);
  2547. if (ret)
  2548. return ret;
  2549. }
  2550. return 0;
  2551. }
  2552. EXPORT_SYMBOL(sock_cmsg_send);
  2553. static void sk_enter_memory_pressure(struct sock *sk)
  2554. {
  2555. if (!sk->sk_prot->enter_memory_pressure)
  2556. return;
  2557. sk->sk_prot->enter_memory_pressure(sk);
  2558. }
  2559. static void sk_leave_memory_pressure(struct sock *sk)
  2560. {
  2561. if (sk->sk_prot->leave_memory_pressure) {
  2562. INDIRECT_CALL_INET_1(sk->sk_prot->leave_memory_pressure,
  2563. tcp_leave_memory_pressure, sk);
  2564. } else {
  2565. unsigned long *memory_pressure = sk->sk_prot->memory_pressure;
  2566. if (memory_pressure && READ_ONCE(*memory_pressure))
  2567. WRITE_ONCE(*memory_pressure, 0);
  2568. }
  2569. }
  2570. DEFINE_STATIC_KEY_FALSE(net_high_order_alloc_disable_key);
  2571. /**
  2572. * skb_page_frag_refill - check that a page_frag contains enough room
  2573. * @sz: minimum size of the fragment we want to get
  2574. * @pfrag: pointer to page_frag
  2575. * @gfp: priority for memory allocation
  2576. *
  2577. * Note: While this allocator tries to use high order pages, there is
  2578. * no guarantee that allocations succeed. Therefore, @sz MUST be
  2579. * less or equal than PAGE_SIZE.
  2580. */
  2581. bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp)
  2582. {
  2583. if (pfrag->page) {
  2584. if (page_ref_count(pfrag->page) == 1) {
  2585. pfrag->offset = 0;
  2586. return true;
  2587. }
  2588. if (pfrag->offset + sz <= pfrag->size)
  2589. return true;
  2590. put_page(pfrag->page);
  2591. }
  2592. pfrag->offset = 0;
  2593. if (SKB_FRAG_PAGE_ORDER &&
  2594. !static_branch_unlikely(&net_high_order_alloc_disable_key)) {
  2595. /* Avoid direct reclaim but allow kswapd to wake */
  2596. pfrag->page = alloc_pages((gfp & ~__GFP_DIRECT_RECLAIM) |
  2597. __GFP_COMP | __GFP_NOWARN |
  2598. __GFP_NORETRY,
  2599. SKB_FRAG_PAGE_ORDER);
  2600. if (likely(pfrag->page)) {
  2601. pfrag->size = PAGE_SIZE << SKB_FRAG_PAGE_ORDER;
  2602. return true;
  2603. }
  2604. }
  2605. pfrag->page = alloc_page(gfp);
  2606. if (likely(pfrag->page)) {
  2607. pfrag->size = PAGE_SIZE;
  2608. return true;
  2609. }
  2610. return false;
  2611. }
  2612. EXPORT_SYMBOL(skb_page_frag_refill);
  2613. bool sk_page_frag_refill(struct sock *sk, struct page_frag *pfrag)
  2614. {
  2615. if (likely(skb_page_frag_refill(32U, pfrag, sk->sk_allocation)))
  2616. return true;
  2617. sk_enter_memory_pressure(sk);
  2618. sk_stream_moderate_sndbuf(sk);
  2619. return false;
  2620. }
  2621. EXPORT_SYMBOL(sk_page_frag_refill);
  2622. void __lock_sock(struct sock *sk)
  2623. __releases(&sk->sk_lock.slock)
  2624. __acquires(&sk->sk_lock.slock)
  2625. {
  2626. DEFINE_WAIT(wait);
  2627. for (;;) {
  2628. prepare_to_wait_exclusive(&sk->sk_lock.wq, &wait,
  2629. TASK_UNINTERRUPTIBLE);
  2630. spin_unlock_bh(&sk->sk_lock.slock);
  2631. schedule();
  2632. spin_lock_bh(&sk->sk_lock.slock);
  2633. if (!sock_owned_by_user(sk))
  2634. break;
  2635. }
  2636. finish_wait(&sk->sk_lock.wq, &wait);
  2637. }
  2638. void __release_sock(struct sock *sk)
  2639. __releases(&sk->sk_lock.slock)
  2640. __acquires(&sk->sk_lock.slock)
  2641. {
  2642. struct sk_buff *skb, *next;
  2643. while ((skb = sk->sk_backlog.head) != NULL) {
  2644. sk->sk_backlog.head = sk->sk_backlog.tail = NULL;
  2645. spin_unlock_bh(&sk->sk_lock.slock);
  2646. do {
  2647. next = skb->next;
  2648. prefetch(next);
  2649. DEBUG_NET_WARN_ON_ONCE(skb_dst_is_noref(skb));
  2650. skb_mark_not_on_list(skb);
  2651. sk_backlog_rcv(sk, skb);
  2652. cond_resched();
  2653. skb = next;
  2654. } while (skb != NULL);
  2655. spin_lock_bh(&sk->sk_lock.slock);
  2656. }
  2657. /*
  2658. * Doing the zeroing here guarantee we can not loop forever
  2659. * while a wild producer attempts to flood us.
  2660. */
  2661. sk->sk_backlog.len = 0;
  2662. }
  2663. void __sk_flush_backlog(struct sock *sk)
  2664. {
  2665. spin_lock_bh(&sk->sk_lock.slock);
  2666. __release_sock(sk);
  2667. if (sk->sk_prot->release_cb)
  2668. INDIRECT_CALL_INET_1(sk->sk_prot->release_cb,
  2669. tcp_release_cb, sk);
  2670. spin_unlock_bh(&sk->sk_lock.slock);
  2671. }
  2672. EXPORT_SYMBOL_GPL(__sk_flush_backlog);
  2673. /**
  2674. * sk_wait_data - wait for data to arrive at sk_receive_queue
  2675. * @sk: sock to wait on
  2676. * @timeo: for how long
  2677. * @skb: last skb seen on sk_receive_queue
  2678. *
  2679. * Now socket state including sk->sk_err is changed only under lock,
  2680. * hence we may omit checks after joining wait queue.
  2681. * We check receive queue before schedule() only as optimization;
  2682. * it is very likely that release_sock() added new data.
  2683. */
  2684. int sk_wait_data(struct sock *sk, long *timeo, const struct sk_buff *skb)
  2685. {
  2686. DEFINE_WAIT_FUNC(wait, woken_wake_function);
  2687. int rc;
  2688. add_wait_queue(sk_sleep(sk), &wait);
  2689. sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
  2690. rc = sk_wait_event(sk, timeo, skb_peek_tail(&sk->sk_receive_queue) != skb, &wait);
  2691. sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
  2692. remove_wait_queue(sk_sleep(sk), &wait);
  2693. return rc;
  2694. }
  2695. EXPORT_SYMBOL(sk_wait_data);
  2696. /**
  2697. * __sk_mem_raise_allocated - increase memory_allocated
  2698. * @sk: socket
  2699. * @size: memory size to allocate
  2700. * @amt: pages to allocate
  2701. * @kind: allocation type
  2702. *
  2703. * Similar to __sk_mem_schedule(), but does not update sk_forward_alloc.
  2704. *
  2705. * Unlike the globally shared limits among the sockets under same protocol,
  2706. * consuming the budget of a memcg won't have direct effect on other ones.
  2707. * So be optimistic about memcg's tolerance, and leave the callers to decide
  2708. * whether or not to raise allocated through sk_under_memory_pressure() or
  2709. * its variants.
  2710. */
  2711. int __sk_mem_raise_allocated(struct sock *sk, int size, int amt, int kind)
  2712. {
  2713. struct mem_cgroup *memcg = mem_cgroup_sockets_enabled ? sk->sk_memcg : NULL;
  2714. struct proto *prot = sk->sk_prot;
  2715. bool charged = true;
  2716. long allocated;
  2717. sk_memory_allocated_add(sk, amt);
  2718. allocated = sk_memory_allocated(sk);
  2719. if (memcg) {
  2720. charged = mem_cgroup_charge_skmem(memcg, amt, gfp_memcg_charge());
  2721. if (!charged)
  2722. goto suppress_allocation;
  2723. }
  2724. /* Under limit. */
  2725. if (allocated <= sk_prot_mem_limits(sk, 0)) {
  2726. sk_leave_memory_pressure(sk);
  2727. return 1;
  2728. }
  2729. /* Under pressure. */
  2730. if (allocated > sk_prot_mem_limits(sk, 1))
  2731. sk_enter_memory_pressure(sk);
  2732. /* Over hard limit. */
  2733. if (allocated > sk_prot_mem_limits(sk, 2))
  2734. goto suppress_allocation;
  2735. /* Guarantee minimum buffer size under pressure (either global
  2736. * or memcg) to make sure features described in RFC 7323 (TCP
  2737. * Extensions for High Performance) work properly.
  2738. *
  2739. * This rule does NOT stand when exceeds global or memcg's hard
  2740. * limit, or else a DoS attack can be taken place by spawning
  2741. * lots of sockets whose usage are under minimum buffer size.
  2742. */
  2743. if (kind == SK_MEM_RECV) {
  2744. if (atomic_read(&sk->sk_rmem_alloc) < sk_get_rmem0(sk, prot))
  2745. return 1;
  2746. } else { /* SK_MEM_SEND */
  2747. int wmem0 = sk_get_wmem0(sk, prot);
  2748. if (sk->sk_type == SOCK_STREAM) {
  2749. if (sk->sk_wmem_queued < wmem0)
  2750. return 1;
  2751. } else if (refcount_read(&sk->sk_wmem_alloc) < wmem0) {
  2752. return 1;
  2753. }
  2754. }
  2755. if (sk_has_memory_pressure(sk)) {
  2756. u64 alloc;
  2757. /* The following 'average' heuristic is within the
  2758. * scope of global accounting, so it only makes
  2759. * sense for global memory pressure.
  2760. */
  2761. if (!sk_under_global_memory_pressure(sk))
  2762. return 1;
  2763. /* Try to be fair among all the sockets under global
  2764. * pressure by allowing the ones that below average
  2765. * usage to raise.
  2766. */
  2767. alloc = sk_sockets_allocated_read_positive(sk);
  2768. if (sk_prot_mem_limits(sk, 2) > alloc *
  2769. sk_mem_pages(sk->sk_wmem_queued +
  2770. atomic_read(&sk->sk_rmem_alloc) +
  2771. sk->sk_forward_alloc))
  2772. return 1;
  2773. }
  2774. suppress_allocation:
  2775. if (kind == SK_MEM_SEND && sk->sk_type == SOCK_STREAM) {
  2776. sk_stream_moderate_sndbuf(sk);
  2777. /* Fail only if socket is _under_ its sndbuf.
  2778. * In this case we cannot block, so that we have to fail.
  2779. */
  2780. if (sk->sk_wmem_queued + size >= sk->sk_sndbuf) {
  2781. /* Force charge with __GFP_NOFAIL */
  2782. if (memcg && !charged) {
  2783. mem_cgroup_charge_skmem(memcg, amt,
  2784. gfp_memcg_charge() | __GFP_NOFAIL);
  2785. }
  2786. return 1;
  2787. }
  2788. }
  2789. if (kind == SK_MEM_SEND || (kind == SK_MEM_RECV && charged))
  2790. trace_sock_exceed_buf_limit(sk, prot, allocated, kind);
  2791. sk_memory_allocated_sub(sk, amt);
  2792. if (memcg && charged)
  2793. mem_cgroup_uncharge_skmem(memcg, amt);
  2794. return 0;
  2795. }
  2796. /**
  2797. * __sk_mem_schedule - increase sk_forward_alloc and memory_allocated
  2798. * @sk: socket
  2799. * @size: memory size to allocate
  2800. * @kind: allocation type
  2801. *
  2802. * If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means
  2803. * rmem allocation. This function assumes that protocols which have
  2804. * memory_pressure use sk_wmem_queued as write buffer accounting.
  2805. */
  2806. int __sk_mem_schedule(struct sock *sk, int size, int kind)
  2807. {
  2808. int ret, amt = sk_mem_pages(size);
  2809. sk_forward_alloc_add(sk, amt << PAGE_SHIFT);
  2810. ret = __sk_mem_raise_allocated(sk, size, amt, kind);
  2811. if (!ret)
  2812. sk_forward_alloc_add(sk, -(amt << PAGE_SHIFT));
  2813. return ret;
  2814. }
  2815. EXPORT_SYMBOL(__sk_mem_schedule);
  2816. /**
  2817. * __sk_mem_reduce_allocated - reclaim memory_allocated
  2818. * @sk: socket
  2819. * @amount: number of quanta
  2820. *
  2821. * Similar to __sk_mem_reclaim(), but does not update sk_forward_alloc
  2822. */
  2823. void __sk_mem_reduce_allocated(struct sock *sk, int amount)
  2824. {
  2825. sk_memory_allocated_sub(sk, amount);
  2826. if (mem_cgroup_sockets_enabled && sk->sk_memcg)
  2827. mem_cgroup_uncharge_skmem(sk->sk_memcg, amount);
  2828. if (sk_under_global_memory_pressure(sk) &&
  2829. (sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)))
  2830. sk_leave_memory_pressure(sk);
  2831. }
  2832. /**
  2833. * __sk_mem_reclaim - reclaim sk_forward_alloc and memory_allocated
  2834. * @sk: socket
  2835. * @amount: number of bytes (rounded down to a PAGE_SIZE multiple)
  2836. */
  2837. void __sk_mem_reclaim(struct sock *sk, int amount)
  2838. {
  2839. amount >>= PAGE_SHIFT;
  2840. sk_forward_alloc_add(sk, -(amount << PAGE_SHIFT));
  2841. __sk_mem_reduce_allocated(sk, amount);
  2842. }
  2843. EXPORT_SYMBOL(__sk_mem_reclaim);
  2844. int sk_set_peek_off(struct sock *sk, int val)
  2845. {
  2846. WRITE_ONCE(sk->sk_peek_off, val);
  2847. return 0;
  2848. }
  2849. EXPORT_SYMBOL_GPL(sk_set_peek_off);
  2850. /*
  2851. * Set of default routines for initialising struct proto_ops when
  2852. * the protocol does not support a particular function. In certain
  2853. * cases where it makes no sense for a protocol to have a "do nothing"
  2854. * function, some default processing is provided.
  2855. */
  2856. int sock_no_bind(struct socket *sock, struct sockaddr *saddr, int len)
  2857. {
  2858. return -EOPNOTSUPP;
  2859. }
  2860. EXPORT_SYMBOL(sock_no_bind);
  2861. int sock_no_connect(struct socket *sock, struct sockaddr *saddr,
  2862. int len, int flags)
  2863. {
  2864. return -EOPNOTSUPP;
  2865. }
  2866. EXPORT_SYMBOL(sock_no_connect);
  2867. int sock_no_socketpair(struct socket *sock1, struct socket *sock2)
  2868. {
  2869. return -EOPNOTSUPP;
  2870. }
  2871. EXPORT_SYMBOL(sock_no_socketpair);
  2872. int sock_no_accept(struct socket *sock, struct socket *newsock,
  2873. struct proto_accept_arg *arg)
  2874. {
  2875. return -EOPNOTSUPP;
  2876. }
  2877. EXPORT_SYMBOL(sock_no_accept);
  2878. int sock_no_getname(struct socket *sock, struct sockaddr *saddr,
  2879. int peer)
  2880. {
  2881. return -EOPNOTSUPP;
  2882. }
  2883. EXPORT_SYMBOL(sock_no_getname);
  2884. int sock_no_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
  2885. {
  2886. return -EOPNOTSUPP;
  2887. }
  2888. EXPORT_SYMBOL(sock_no_ioctl);
  2889. int sock_no_listen(struct socket *sock, int backlog)
  2890. {
  2891. return -EOPNOTSUPP;
  2892. }
  2893. EXPORT_SYMBOL(sock_no_listen);
  2894. int sock_no_shutdown(struct socket *sock, int how)
  2895. {
  2896. return -EOPNOTSUPP;
  2897. }
  2898. EXPORT_SYMBOL(sock_no_shutdown);
  2899. int sock_no_sendmsg(struct socket *sock, struct msghdr *m, size_t len)
  2900. {
  2901. return -EOPNOTSUPP;
  2902. }
  2903. EXPORT_SYMBOL(sock_no_sendmsg);
  2904. int sock_no_sendmsg_locked(struct sock *sk, struct msghdr *m, size_t len)
  2905. {
  2906. return -EOPNOTSUPP;
  2907. }
  2908. EXPORT_SYMBOL(sock_no_sendmsg_locked);
  2909. int sock_no_recvmsg(struct socket *sock, struct msghdr *m, size_t len,
  2910. int flags)
  2911. {
  2912. return -EOPNOTSUPP;
  2913. }
  2914. EXPORT_SYMBOL(sock_no_recvmsg);
  2915. int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma)
  2916. {
  2917. /* Mirror missing mmap method error code */
  2918. return -ENODEV;
  2919. }
  2920. EXPORT_SYMBOL(sock_no_mmap);
  2921. /*
  2922. * When a file is received (via SCM_RIGHTS, etc), we must bump the
  2923. * various sock-based usage counts.
  2924. */
  2925. void __receive_sock(struct file *file)
  2926. {
  2927. struct socket *sock;
  2928. sock = sock_from_file(file);
  2929. if (sock) {
  2930. sock_update_netprioidx(&sock->sk->sk_cgrp_data);
  2931. sock_update_classid(&sock->sk->sk_cgrp_data);
  2932. }
  2933. }
  2934. /*
  2935. * Default Socket Callbacks
  2936. */
  2937. static void sock_def_wakeup(struct sock *sk)
  2938. {
  2939. struct socket_wq *wq;
  2940. rcu_read_lock();
  2941. wq = rcu_dereference(sk->sk_wq);
  2942. if (skwq_has_sleeper(wq))
  2943. wake_up_interruptible_all(&wq->wait);
  2944. rcu_read_unlock();
  2945. }
  2946. static void sock_def_error_report(struct sock *sk)
  2947. {
  2948. struct socket_wq *wq;
  2949. rcu_read_lock();
  2950. wq = rcu_dereference(sk->sk_wq);
  2951. if (skwq_has_sleeper(wq))
  2952. wake_up_interruptible_poll(&wq->wait, EPOLLERR);
  2953. sk_wake_async_rcu(sk, SOCK_WAKE_IO, POLL_ERR);
  2954. rcu_read_unlock();
  2955. }
  2956. void sock_def_readable(struct sock *sk)
  2957. {
  2958. struct socket_wq *wq;
  2959. trace_sk_data_ready(sk);
  2960. rcu_read_lock();
  2961. wq = rcu_dereference(sk->sk_wq);
  2962. if (skwq_has_sleeper(wq))
  2963. wake_up_interruptible_sync_poll(&wq->wait, EPOLLIN | EPOLLPRI |
  2964. EPOLLRDNORM | EPOLLRDBAND);
  2965. sk_wake_async_rcu(sk, SOCK_WAKE_WAITD, POLL_IN);
  2966. rcu_read_unlock();
  2967. }
  2968. static void sock_def_write_space(struct sock *sk)
  2969. {
  2970. struct socket_wq *wq;
  2971. rcu_read_lock();
  2972. /* Do not wake up a writer until he can make "significant"
  2973. * progress. --DaveM
  2974. */
  2975. if (sock_writeable(sk)) {
  2976. wq = rcu_dereference(sk->sk_wq);
  2977. if (skwq_has_sleeper(wq))
  2978. wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT |
  2979. EPOLLWRNORM | EPOLLWRBAND);
  2980. /* Should agree with poll, otherwise some programs break */
  2981. sk_wake_async_rcu(sk, SOCK_WAKE_SPACE, POLL_OUT);
  2982. }
  2983. rcu_read_unlock();
  2984. }
  2985. /* An optimised version of sock_def_write_space(), should only be called
  2986. * for SOCK_RCU_FREE sockets under RCU read section and after putting
  2987. * ->sk_wmem_alloc.
  2988. */
  2989. static void sock_def_write_space_wfree(struct sock *sk)
  2990. {
  2991. /* Do not wake up a writer until he can make "significant"
  2992. * progress. --DaveM
  2993. */
  2994. if (sock_writeable(sk)) {
  2995. struct socket_wq *wq = rcu_dereference(sk->sk_wq);
  2996. /* rely on refcount_sub from sock_wfree() */
  2997. smp_mb__after_atomic();
  2998. if (wq && waitqueue_active(&wq->wait))
  2999. wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT |
  3000. EPOLLWRNORM | EPOLLWRBAND);
  3001. /* Should agree with poll, otherwise some programs break */
  3002. sk_wake_async_rcu(sk, SOCK_WAKE_SPACE, POLL_OUT);
  3003. }
  3004. }
  3005. static void sock_def_destruct(struct sock *sk)
  3006. {
  3007. }
  3008. void sk_send_sigurg(struct sock *sk)
  3009. {
  3010. if (sk->sk_socket && sk->sk_socket->file)
  3011. if (send_sigurg(sk->sk_socket->file))
  3012. sk_wake_async(sk, SOCK_WAKE_URG, POLL_PRI);
  3013. }
  3014. EXPORT_SYMBOL(sk_send_sigurg);
  3015. void sk_reset_timer(struct sock *sk, struct timer_list* timer,
  3016. unsigned long expires)
  3017. {
  3018. if (!mod_timer(timer, expires))
  3019. sock_hold(sk);
  3020. }
  3021. EXPORT_SYMBOL(sk_reset_timer);
  3022. void sk_stop_timer(struct sock *sk, struct timer_list* timer)
  3023. {
  3024. if (del_timer(timer))
  3025. __sock_put(sk);
  3026. }
  3027. EXPORT_SYMBOL(sk_stop_timer);
  3028. void sk_stop_timer_sync(struct sock *sk, struct timer_list *timer)
  3029. {
  3030. if (del_timer_sync(timer))
  3031. __sock_put(sk);
  3032. }
  3033. EXPORT_SYMBOL(sk_stop_timer_sync);
  3034. void sock_init_data_uid(struct socket *sock, struct sock *sk, kuid_t uid)
  3035. {
  3036. sk_init_common(sk);
  3037. sk->sk_send_head = NULL;
  3038. timer_setup(&sk->sk_timer, NULL, 0);
  3039. sk->sk_allocation = GFP_KERNEL;
  3040. sk->sk_rcvbuf = READ_ONCE(sysctl_rmem_default);
  3041. sk->sk_sndbuf = READ_ONCE(sysctl_wmem_default);
  3042. sk->sk_state = TCP_CLOSE;
  3043. sk->sk_use_task_frag = true;
  3044. sk_set_socket(sk, sock);
  3045. sock_set_flag(sk, SOCK_ZAPPED);
  3046. if (sock) {
  3047. sk->sk_type = sock->type;
  3048. RCU_INIT_POINTER(sk->sk_wq, &sock->wq);
  3049. sock->sk = sk;
  3050. } else {
  3051. RCU_INIT_POINTER(sk->sk_wq, NULL);
  3052. }
  3053. sk->sk_uid = uid;
  3054. sk->sk_state_change = sock_def_wakeup;
  3055. sk->sk_data_ready = sock_def_readable;
  3056. sk->sk_write_space = sock_def_write_space;
  3057. sk->sk_error_report = sock_def_error_report;
  3058. sk->sk_destruct = sock_def_destruct;
  3059. sk->sk_frag.page = NULL;
  3060. sk->sk_frag.offset = 0;
  3061. sk->sk_peek_off = -1;
  3062. sk->sk_peer_pid = NULL;
  3063. sk->sk_peer_cred = NULL;
  3064. spin_lock_init(&sk->sk_peer_lock);
  3065. sk->sk_write_pending = 0;
  3066. sk->sk_rcvlowat = 1;
  3067. sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT;
  3068. sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
  3069. sk->sk_stamp = SK_DEFAULT_STAMP;
  3070. #if BITS_PER_LONG==32
  3071. seqlock_init(&sk->sk_stamp_seq);
  3072. #endif
  3073. atomic_set(&sk->sk_zckey, 0);
  3074. #ifdef CONFIG_NET_RX_BUSY_POLL
  3075. sk->sk_napi_id = 0;
  3076. sk->sk_ll_usec = READ_ONCE(sysctl_net_busy_read);
  3077. #endif
  3078. sk->sk_max_pacing_rate = ~0UL;
  3079. sk->sk_pacing_rate = ~0UL;
  3080. WRITE_ONCE(sk->sk_pacing_shift, 10);
  3081. sk->sk_incoming_cpu = -1;
  3082. sk_rx_queue_clear(sk);
  3083. /*
  3084. * Before updating sk_refcnt, we must commit prior changes to memory
  3085. * (Documentation/RCU/rculist_nulls.rst for details)
  3086. */
  3087. smp_wmb();
  3088. refcount_set(&sk->sk_refcnt, 1);
  3089. atomic_set(&sk->sk_drops, 0);
  3090. }
  3091. EXPORT_SYMBOL(sock_init_data_uid);
  3092. void sock_init_data(struct socket *sock, struct sock *sk)
  3093. {
  3094. kuid_t uid = sock ?
  3095. SOCK_INODE(sock)->i_uid :
  3096. make_kuid(sock_net(sk)->user_ns, 0);
  3097. sock_init_data_uid(sock, sk, uid);
  3098. }
  3099. EXPORT_SYMBOL(sock_init_data);
  3100. void lock_sock_nested(struct sock *sk, int subclass)
  3101. {
  3102. /* The sk_lock has mutex_lock() semantics here. */
  3103. mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_);
  3104. might_sleep();
  3105. spin_lock_bh(&sk->sk_lock.slock);
  3106. if (sock_owned_by_user_nocheck(sk))
  3107. __lock_sock(sk);
  3108. sk->sk_lock.owned = 1;
  3109. spin_unlock_bh(&sk->sk_lock.slock);
  3110. }
  3111. EXPORT_SYMBOL(lock_sock_nested);
  3112. void release_sock(struct sock *sk)
  3113. {
  3114. spin_lock_bh(&sk->sk_lock.slock);
  3115. if (sk->sk_backlog.tail)
  3116. __release_sock(sk);
  3117. if (sk->sk_prot->release_cb)
  3118. INDIRECT_CALL_INET_1(sk->sk_prot->release_cb,
  3119. tcp_release_cb, sk);
  3120. sock_release_ownership(sk);
  3121. if (waitqueue_active(&sk->sk_lock.wq))
  3122. wake_up(&sk->sk_lock.wq);
  3123. spin_unlock_bh(&sk->sk_lock.slock);
  3124. }
  3125. EXPORT_SYMBOL(release_sock);
  3126. bool __lock_sock_fast(struct sock *sk) __acquires(&sk->sk_lock.slock)
  3127. {
  3128. might_sleep();
  3129. spin_lock_bh(&sk->sk_lock.slock);
  3130. if (!sock_owned_by_user_nocheck(sk)) {
  3131. /*
  3132. * Fast path return with bottom halves disabled and
  3133. * sock::sk_lock.slock held.
  3134. *
  3135. * The 'mutex' is not contended and holding
  3136. * sock::sk_lock.slock prevents all other lockers to
  3137. * proceed so the corresponding unlock_sock_fast() can
  3138. * avoid the slow path of release_sock() completely and
  3139. * just release slock.
  3140. *
  3141. * From a semantical POV this is equivalent to 'acquiring'
  3142. * the 'mutex', hence the corresponding lockdep
  3143. * mutex_release() has to happen in the fast path of
  3144. * unlock_sock_fast().
  3145. */
  3146. return false;
  3147. }
  3148. __lock_sock(sk);
  3149. sk->sk_lock.owned = 1;
  3150. __acquire(&sk->sk_lock.slock);
  3151. spin_unlock_bh(&sk->sk_lock.slock);
  3152. return true;
  3153. }
  3154. EXPORT_SYMBOL(__lock_sock_fast);
  3155. int sock_gettstamp(struct socket *sock, void __user *userstamp,
  3156. bool timeval, bool time32)
  3157. {
  3158. struct sock *sk = sock->sk;
  3159. struct timespec64 ts;
  3160. sock_enable_timestamp(sk, SOCK_TIMESTAMP);
  3161. ts = ktime_to_timespec64(sock_read_timestamp(sk));
  3162. if (ts.tv_sec == -1)
  3163. return -ENOENT;
  3164. if (ts.tv_sec == 0) {
  3165. ktime_t kt = ktime_get_real();
  3166. sock_write_timestamp(sk, kt);
  3167. ts = ktime_to_timespec64(kt);
  3168. }
  3169. if (timeval)
  3170. ts.tv_nsec /= 1000;
  3171. #ifdef CONFIG_COMPAT_32BIT_TIME
  3172. if (time32)
  3173. return put_old_timespec32(&ts, userstamp);
  3174. #endif
  3175. #ifdef CONFIG_SPARC64
  3176. /* beware of padding in sparc64 timeval */
  3177. if (timeval && !in_compat_syscall()) {
  3178. struct __kernel_old_timeval __user tv = {
  3179. .tv_sec = ts.tv_sec,
  3180. .tv_usec = ts.tv_nsec,
  3181. };
  3182. if (copy_to_user(userstamp, &tv, sizeof(tv)))
  3183. return -EFAULT;
  3184. return 0;
  3185. }
  3186. #endif
  3187. return put_timespec64(&ts, userstamp);
  3188. }
  3189. EXPORT_SYMBOL(sock_gettstamp);
  3190. void sock_enable_timestamp(struct sock *sk, enum sock_flags flag)
  3191. {
  3192. if (!sock_flag(sk, flag)) {
  3193. unsigned long previous_flags = sk->sk_flags;
  3194. sock_set_flag(sk, flag);
  3195. /*
  3196. * we just set one of the two flags which require net
  3197. * time stamping, but time stamping might have been on
  3198. * already because of the other one
  3199. */
  3200. if (sock_needs_netstamp(sk) &&
  3201. !(previous_flags & SK_FLAGS_TIMESTAMP))
  3202. net_enable_timestamp();
  3203. }
  3204. }
  3205. int sock_recv_errqueue(struct sock *sk, struct msghdr *msg, int len,
  3206. int level, int type)
  3207. {
  3208. struct sock_exterr_skb *serr;
  3209. struct sk_buff *skb;
  3210. int copied, err;
  3211. err = -EAGAIN;
  3212. skb = sock_dequeue_err_skb(sk);
  3213. if (skb == NULL)
  3214. goto out;
  3215. copied = skb->len;
  3216. if (copied > len) {
  3217. msg->msg_flags |= MSG_TRUNC;
  3218. copied = len;
  3219. }
  3220. err = skb_copy_datagram_msg(skb, 0, msg, copied);
  3221. if (err)
  3222. goto out_free_skb;
  3223. sock_recv_timestamp(msg, sk, skb);
  3224. serr = SKB_EXT_ERR(skb);
  3225. put_cmsg(msg, level, type, sizeof(serr->ee), &serr->ee);
  3226. msg->msg_flags |= MSG_ERRQUEUE;
  3227. err = copied;
  3228. out_free_skb:
  3229. kfree_skb(skb);
  3230. out:
  3231. return err;
  3232. }
  3233. EXPORT_SYMBOL(sock_recv_errqueue);
  3234. /*
  3235. * Get a socket option on an socket.
  3236. *
  3237. * FIX: POSIX 1003.1g is very ambiguous here. It states that
  3238. * asynchronous errors should be reported by getsockopt. We assume
  3239. * this means if you specify SO_ERROR (otherwise what is the point of it).
  3240. */
  3241. int sock_common_getsockopt(struct socket *sock, int level, int optname,
  3242. char __user *optval, int __user *optlen)
  3243. {
  3244. struct sock *sk = sock->sk;
  3245. /* IPV6_ADDRFORM can change sk->sk_prot under us. */
  3246. return READ_ONCE(sk->sk_prot)->getsockopt(sk, level, optname, optval, optlen);
  3247. }
  3248. EXPORT_SYMBOL(sock_common_getsockopt);
  3249. int sock_common_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
  3250. int flags)
  3251. {
  3252. struct sock *sk = sock->sk;
  3253. int addr_len = 0;
  3254. int err;
  3255. err = sk->sk_prot->recvmsg(sk, msg, size, flags, &addr_len);
  3256. if (err >= 0)
  3257. msg->msg_namelen = addr_len;
  3258. return err;
  3259. }
  3260. EXPORT_SYMBOL(sock_common_recvmsg);
  3261. /*
  3262. * Set socket options on an inet socket.
  3263. */
  3264. int sock_common_setsockopt(struct socket *sock, int level, int optname,
  3265. sockptr_t optval, unsigned int optlen)
  3266. {
  3267. struct sock *sk = sock->sk;
  3268. /* IPV6_ADDRFORM can change sk->sk_prot under us. */
  3269. return READ_ONCE(sk->sk_prot)->setsockopt(sk, level, optname, optval, optlen);
  3270. }
  3271. EXPORT_SYMBOL(sock_common_setsockopt);
  3272. void sk_common_release(struct sock *sk)
  3273. {
  3274. if (sk->sk_prot->destroy)
  3275. sk->sk_prot->destroy(sk);
  3276. /*
  3277. * Observation: when sk_common_release is called, processes have
  3278. * no access to socket. But net still has.
  3279. * Step one, detach it from networking:
  3280. *
  3281. * A. Remove from hash tables.
  3282. */
  3283. sk->sk_prot->unhash(sk);
  3284. if (sk->sk_socket)
  3285. sk->sk_socket->sk = NULL;
  3286. /*
  3287. * In this point socket cannot receive new packets, but it is possible
  3288. * that some packets are in flight because some CPU runs receiver and
  3289. * did hash table lookup before we unhashed socket. They will achieve
  3290. * receive queue and will be purged by socket destructor.
  3291. *
  3292. * Also we still have packets pending on receive queue and probably,
  3293. * our own packets waiting in device queues. sock_destroy will drain
  3294. * receive queue, but transmitted packets will delay socket destruction
  3295. * until the last reference will be released.
  3296. */
  3297. sock_orphan(sk);
  3298. xfrm_sk_free_policy(sk);
  3299. sock_put(sk);
  3300. }
  3301. EXPORT_SYMBOL(sk_common_release);
  3302. void sk_get_meminfo(const struct sock *sk, u32 *mem)
  3303. {
  3304. memset(mem, 0, sizeof(*mem) * SK_MEMINFO_VARS);
  3305. mem[SK_MEMINFO_RMEM_ALLOC] = sk_rmem_alloc_get(sk);
  3306. mem[SK_MEMINFO_RCVBUF] = READ_ONCE(sk->sk_rcvbuf);
  3307. mem[SK_MEMINFO_WMEM_ALLOC] = sk_wmem_alloc_get(sk);
  3308. mem[SK_MEMINFO_SNDBUF] = READ_ONCE(sk->sk_sndbuf);
  3309. mem[SK_MEMINFO_FWD_ALLOC] = sk_forward_alloc_get(sk);
  3310. mem[SK_MEMINFO_WMEM_QUEUED] = READ_ONCE(sk->sk_wmem_queued);
  3311. mem[SK_MEMINFO_OPTMEM] = atomic_read(&sk->sk_omem_alloc);
  3312. mem[SK_MEMINFO_BACKLOG] = READ_ONCE(sk->sk_backlog.len);
  3313. mem[SK_MEMINFO_DROPS] = atomic_read(&sk->sk_drops);
  3314. }
  3315. #ifdef CONFIG_PROC_FS
  3316. static DECLARE_BITMAP(proto_inuse_idx, PROTO_INUSE_NR);
  3317. int sock_prot_inuse_get(struct net *net, struct proto *prot)
  3318. {
  3319. int cpu, idx = prot->inuse_idx;
  3320. int res = 0;
  3321. for_each_possible_cpu(cpu)
  3322. res += per_cpu_ptr(net->core.prot_inuse, cpu)->val[idx];
  3323. return res >= 0 ? res : 0;
  3324. }
  3325. EXPORT_SYMBOL_GPL(sock_prot_inuse_get);
  3326. int sock_inuse_get(struct net *net)
  3327. {
  3328. int cpu, res = 0;
  3329. for_each_possible_cpu(cpu)
  3330. res += per_cpu_ptr(net->core.prot_inuse, cpu)->all;
  3331. return res;
  3332. }
  3333. EXPORT_SYMBOL_GPL(sock_inuse_get);
  3334. static int __net_init sock_inuse_init_net(struct net *net)
  3335. {
  3336. net->core.prot_inuse = alloc_percpu(struct prot_inuse);
  3337. if (net->core.prot_inuse == NULL)
  3338. return -ENOMEM;
  3339. return 0;
  3340. }
  3341. static void __net_exit sock_inuse_exit_net(struct net *net)
  3342. {
  3343. free_percpu(net->core.prot_inuse);
  3344. }
  3345. static struct pernet_operations net_inuse_ops = {
  3346. .init = sock_inuse_init_net,
  3347. .exit = sock_inuse_exit_net,
  3348. };
  3349. static __init int net_inuse_init(void)
  3350. {
  3351. if (register_pernet_subsys(&net_inuse_ops))
  3352. panic("Cannot initialize net inuse counters");
  3353. return 0;
  3354. }
  3355. core_initcall(net_inuse_init);
  3356. static int assign_proto_idx(struct proto *prot)
  3357. {
  3358. prot->inuse_idx = find_first_zero_bit(proto_inuse_idx, PROTO_INUSE_NR);
  3359. if (unlikely(prot->inuse_idx == PROTO_INUSE_NR)) {
  3360. pr_err("PROTO_INUSE_NR exhausted\n");
  3361. return -ENOSPC;
  3362. }
  3363. set_bit(prot->inuse_idx, proto_inuse_idx);
  3364. return 0;
  3365. }
  3366. static void release_proto_idx(struct proto *prot)
  3367. {
  3368. if (prot->inuse_idx != PROTO_INUSE_NR)
  3369. clear_bit(prot->inuse_idx, proto_inuse_idx);
  3370. }
  3371. #else
  3372. static inline int assign_proto_idx(struct proto *prot)
  3373. {
  3374. return 0;
  3375. }
  3376. static inline void release_proto_idx(struct proto *prot)
  3377. {
  3378. }
  3379. #endif
  3380. static void tw_prot_cleanup(struct timewait_sock_ops *twsk_prot)
  3381. {
  3382. if (!twsk_prot)
  3383. return;
  3384. kfree(twsk_prot->twsk_slab_name);
  3385. twsk_prot->twsk_slab_name = NULL;
  3386. kmem_cache_destroy(twsk_prot->twsk_slab);
  3387. twsk_prot->twsk_slab = NULL;
  3388. }
  3389. static int tw_prot_init(const struct proto *prot)
  3390. {
  3391. struct timewait_sock_ops *twsk_prot = prot->twsk_prot;
  3392. if (!twsk_prot)
  3393. return 0;
  3394. twsk_prot->twsk_slab_name = kasprintf(GFP_KERNEL, "tw_sock_%s",
  3395. prot->name);
  3396. if (!twsk_prot->twsk_slab_name)
  3397. return -ENOMEM;
  3398. twsk_prot->twsk_slab =
  3399. kmem_cache_create(twsk_prot->twsk_slab_name,
  3400. twsk_prot->twsk_obj_size, 0,
  3401. SLAB_ACCOUNT | prot->slab_flags,
  3402. NULL);
  3403. if (!twsk_prot->twsk_slab) {
  3404. pr_crit("%s: Can't create timewait sock SLAB cache!\n",
  3405. prot->name);
  3406. return -ENOMEM;
  3407. }
  3408. return 0;
  3409. }
  3410. static void req_prot_cleanup(struct request_sock_ops *rsk_prot)
  3411. {
  3412. if (!rsk_prot)
  3413. return;
  3414. kfree(rsk_prot->slab_name);
  3415. rsk_prot->slab_name = NULL;
  3416. kmem_cache_destroy(rsk_prot->slab);
  3417. rsk_prot->slab = NULL;
  3418. }
  3419. static int req_prot_init(const struct proto *prot)
  3420. {
  3421. struct request_sock_ops *rsk_prot = prot->rsk_prot;
  3422. if (!rsk_prot)
  3423. return 0;
  3424. rsk_prot->slab_name = kasprintf(GFP_KERNEL, "request_sock_%s",
  3425. prot->name);
  3426. if (!rsk_prot->slab_name)
  3427. return -ENOMEM;
  3428. rsk_prot->slab = kmem_cache_create(rsk_prot->slab_name,
  3429. rsk_prot->obj_size, 0,
  3430. SLAB_ACCOUNT | prot->slab_flags,
  3431. NULL);
  3432. if (!rsk_prot->slab) {
  3433. pr_crit("%s: Can't create request sock SLAB cache!\n",
  3434. prot->name);
  3435. return -ENOMEM;
  3436. }
  3437. return 0;
  3438. }
  3439. int proto_register(struct proto *prot, int alloc_slab)
  3440. {
  3441. int ret = -ENOBUFS;
  3442. if (prot->memory_allocated && !prot->sysctl_mem) {
  3443. pr_err("%s: missing sysctl_mem\n", prot->name);
  3444. return -EINVAL;
  3445. }
  3446. if (prot->memory_allocated && !prot->per_cpu_fw_alloc) {
  3447. pr_err("%s: missing per_cpu_fw_alloc\n", prot->name);
  3448. return -EINVAL;
  3449. }
  3450. if (alloc_slab) {
  3451. prot->slab = kmem_cache_create_usercopy(prot->name,
  3452. prot->obj_size, 0,
  3453. SLAB_HWCACHE_ALIGN | SLAB_ACCOUNT |
  3454. prot->slab_flags,
  3455. prot->useroffset, prot->usersize,
  3456. NULL);
  3457. if (prot->slab == NULL) {
  3458. pr_crit("%s: Can't create sock SLAB cache!\n",
  3459. prot->name);
  3460. goto out;
  3461. }
  3462. if (req_prot_init(prot))
  3463. goto out_free_request_sock_slab;
  3464. if (tw_prot_init(prot))
  3465. goto out_free_timewait_sock_slab;
  3466. }
  3467. mutex_lock(&proto_list_mutex);
  3468. ret = assign_proto_idx(prot);
  3469. if (ret) {
  3470. mutex_unlock(&proto_list_mutex);
  3471. goto out_free_timewait_sock_slab;
  3472. }
  3473. list_add(&prot->node, &proto_list);
  3474. mutex_unlock(&proto_list_mutex);
  3475. return ret;
  3476. out_free_timewait_sock_slab:
  3477. if (alloc_slab)
  3478. tw_prot_cleanup(prot->twsk_prot);
  3479. out_free_request_sock_slab:
  3480. if (alloc_slab) {
  3481. req_prot_cleanup(prot->rsk_prot);
  3482. kmem_cache_destroy(prot->slab);
  3483. prot->slab = NULL;
  3484. }
  3485. out:
  3486. return ret;
  3487. }
  3488. EXPORT_SYMBOL(proto_register);
  3489. void proto_unregister(struct proto *prot)
  3490. {
  3491. mutex_lock(&proto_list_mutex);
  3492. release_proto_idx(prot);
  3493. list_del(&prot->node);
  3494. mutex_unlock(&proto_list_mutex);
  3495. kmem_cache_destroy(prot->slab);
  3496. prot->slab = NULL;
  3497. req_prot_cleanup(prot->rsk_prot);
  3498. tw_prot_cleanup(prot->twsk_prot);
  3499. }
  3500. EXPORT_SYMBOL(proto_unregister);
  3501. int sock_load_diag_module(int family, int protocol)
  3502. {
  3503. if (!protocol) {
  3504. if (!sock_is_registered(family))
  3505. return -ENOENT;
  3506. return request_module("net-pf-%d-proto-%d-type-%d", PF_NETLINK,
  3507. NETLINK_SOCK_DIAG, family);
  3508. }
  3509. #ifdef CONFIG_INET
  3510. if (family == AF_INET &&
  3511. protocol != IPPROTO_RAW &&
  3512. protocol < MAX_INET_PROTOS &&
  3513. !rcu_access_pointer(inet_protos[protocol]))
  3514. return -ENOENT;
  3515. #endif
  3516. return request_module("net-pf-%d-proto-%d-type-%d-%d", PF_NETLINK,
  3517. NETLINK_SOCK_DIAG, family, protocol);
  3518. }
  3519. EXPORT_SYMBOL(sock_load_diag_module);
  3520. #ifdef CONFIG_PROC_FS
  3521. static void *proto_seq_start(struct seq_file *seq, loff_t *pos)
  3522. __acquires(proto_list_mutex)
  3523. {
  3524. mutex_lock(&proto_list_mutex);
  3525. return seq_list_start_head(&proto_list, *pos);
  3526. }
  3527. static void *proto_seq_next(struct seq_file *seq, void *v, loff_t *pos)
  3528. {
  3529. return seq_list_next(v, &proto_list, pos);
  3530. }
  3531. static void proto_seq_stop(struct seq_file *seq, void *v)
  3532. __releases(proto_list_mutex)
  3533. {
  3534. mutex_unlock(&proto_list_mutex);
  3535. }
  3536. static char proto_method_implemented(const void *method)
  3537. {
  3538. return method == NULL ? 'n' : 'y';
  3539. }
  3540. static long sock_prot_memory_allocated(struct proto *proto)
  3541. {
  3542. return proto->memory_allocated != NULL ? proto_memory_allocated(proto) : -1L;
  3543. }
  3544. static const char *sock_prot_memory_pressure(struct proto *proto)
  3545. {
  3546. return proto->memory_pressure != NULL ?
  3547. proto_memory_pressure(proto) ? "yes" : "no" : "NI";
  3548. }
  3549. static void proto_seq_printf(struct seq_file *seq, struct proto *proto)
  3550. {
  3551. seq_printf(seq, "%-9s %4u %6d %6ld %-3s %6u %-3s %-10s "
  3552. "%2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c\n",
  3553. proto->name,
  3554. proto->obj_size,
  3555. sock_prot_inuse_get(seq_file_net(seq), proto),
  3556. sock_prot_memory_allocated(proto),
  3557. sock_prot_memory_pressure(proto),
  3558. proto->max_header,
  3559. proto->slab == NULL ? "no" : "yes",
  3560. module_name(proto->owner),
  3561. proto_method_implemented(proto->close),
  3562. proto_method_implemented(proto->connect),
  3563. proto_method_implemented(proto->disconnect),
  3564. proto_method_implemented(proto->accept),
  3565. proto_method_implemented(proto->ioctl),
  3566. proto_method_implemented(proto->init),
  3567. proto_method_implemented(proto->destroy),
  3568. proto_method_implemented(proto->shutdown),
  3569. proto_method_implemented(proto->setsockopt),
  3570. proto_method_implemented(proto->getsockopt),
  3571. proto_method_implemented(proto->sendmsg),
  3572. proto_method_implemented(proto->recvmsg),
  3573. proto_method_implemented(proto->bind),
  3574. proto_method_implemented(proto->backlog_rcv),
  3575. proto_method_implemented(proto->hash),
  3576. proto_method_implemented(proto->unhash),
  3577. proto_method_implemented(proto->get_port),
  3578. proto_method_implemented(proto->enter_memory_pressure));
  3579. }
  3580. static int proto_seq_show(struct seq_file *seq, void *v)
  3581. {
  3582. if (v == &proto_list)
  3583. seq_printf(seq, "%-9s %-4s %-8s %-6s %-5s %-7s %-4s %-10s %s",
  3584. "protocol",
  3585. "size",
  3586. "sockets",
  3587. "memory",
  3588. "press",
  3589. "maxhdr",
  3590. "slab",
  3591. "module",
  3592. "cl co di ac io in de sh ss gs se re bi br ha uh gp em\n");
  3593. else
  3594. proto_seq_printf(seq, list_entry(v, struct proto, node));
  3595. return 0;
  3596. }
  3597. static const struct seq_operations proto_seq_ops = {
  3598. .start = proto_seq_start,
  3599. .next = proto_seq_next,
  3600. .stop = proto_seq_stop,
  3601. .show = proto_seq_show,
  3602. };
  3603. static __net_init int proto_init_net(struct net *net)
  3604. {
  3605. if (!proc_create_net("protocols", 0444, net->proc_net, &proto_seq_ops,
  3606. sizeof(struct seq_net_private)))
  3607. return -ENOMEM;
  3608. return 0;
  3609. }
  3610. static __net_exit void proto_exit_net(struct net *net)
  3611. {
  3612. remove_proc_entry("protocols", net->proc_net);
  3613. }
  3614. static __net_initdata struct pernet_operations proto_net_ops = {
  3615. .init = proto_init_net,
  3616. .exit = proto_exit_net,
  3617. };
  3618. static int __init proto_init(void)
  3619. {
  3620. return register_pernet_subsys(&proto_net_ops);
  3621. }
  3622. subsys_initcall(proto_init);
  3623. #endif /* PROC_FS */
  3624. #ifdef CONFIG_NET_RX_BUSY_POLL
  3625. bool sk_busy_loop_end(void *p, unsigned long start_time)
  3626. {
  3627. struct sock *sk = p;
  3628. if (!skb_queue_empty_lockless(&sk->sk_receive_queue))
  3629. return true;
  3630. if (sk_is_udp(sk) &&
  3631. !skb_queue_empty_lockless(&udp_sk(sk)->reader_queue))
  3632. return true;
  3633. return sk_busy_loop_timeout(sk, start_time);
  3634. }
  3635. EXPORT_SYMBOL(sk_busy_loop_end);
  3636. #endif /* CONFIG_NET_RX_BUSY_POLL */
  3637. int sock_bind_add(struct sock *sk, struct sockaddr *addr, int addr_len)
  3638. {
  3639. if (!sk->sk_prot->bind_add)
  3640. return -EOPNOTSUPP;
  3641. return sk->sk_prot->bind_add(sk, addr, addr_len);
  3642. }
  3643. EXPORT_SYMBOL(sock_bind_add);
  3644. /* Copy 'size' bytes from userspace and return `size` back to userspace */
  3645. int sock_ioctl_inout(struct sock *sk, unsigned int cmd,
  3646. void __user *arg, void *karg, size_t size)
  3647. {
  3648. int ret;
  3649. if (copy_from_user(karg, arg, size))
  3650. return -EFAULT;
  3651. ret = READ_ONCE(sk->sk_prot)->ioctl(sk, cmd, karg);
  3652. if (ret)
  3653. return ret;
  3654. if (copy_to_user(arg, karg, size))
  3655. return -EFAULT;
  3656. return 0;
  3657. }
  3658. EXPORT_SYMBOL(sock_ioctl_inout);
  3659. /* This is the most common ioctl prep function, where the result (4 bytes) is
  3660. * copied back to userspace if the ioctl() returns successfully. No input is
  3661. * copied from userspace as input argument.
  3662. */
  3663. static int sock_ioctl_out(struct sock *sk, unsigned int cmd, void __user *arg)
  3664. {
  3665. int ret, karg = 0;
  3666. ret = READ_ONCE(sk->sk_prot)->ioctl(sk, cmd, &karg);
  3667. if (ret)
  3668. return ret;
  3669. return put_user(karg, (int __user *)arg);
  3670. }
  3671. /* A wrapper around sock ioctls, which copies the data from userspace
  3672. * (depending on the protocol/ioctl), and copies back the result to userspace.
  3673. * The main motivation for this function is to pass kernel memory to the
  3674. * protocol ioctl callbacks, instead of userspace memory.
  3675. */
  3676. int sk_ioctl(struct sock *sk, unsigned int cmd, void __user *arg)
  3677. {
  3678. int rc = 1;
  3679. if (sk->sk_type == SOCK_RAW && sk->sk_family == AF_INET)
  3680. rc = ipmr_sk_ioctl(sk, cmd, arg);
  3681. else if (sk->sk_type == SOCK_RAW && sk->sk_family == AF_INET6)
  3682. rc = ip6mr_sk_ioctl(sk, cmd, arg);
  3683. else if (sk_is_phonet(sk))
  3684. rc = phonet_sk_ioctl(sk, cmd, arg);
  3685. /* If ioctl was processed, returns its value */
  3686. if (rc <= 0)
  3687. return rc;
  3688. /* Otherwise call the default handler */
  3689. return sock_ioctl_out(sk, cmd, arg);
  3690. }
  3691. EXPORT_SYMBOL(sk_ioctl);
  3692. static int __init sock_struct_check(void)
  3693. {
  3694. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rx, sk_drops);
  3695. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rx, sk_peek_off);
  3696. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rx, sk_error_queue);
  3697. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rx, sk_receive_queue);
  3698. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rx, sk_backlog);
  3699. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rx_dst);
  3700. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rx_dst_ifindex);
  3701. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rx_dst_cookie);
  3702. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rcvbuf);
  3703. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_filter);
  3704. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_wq);
  3705. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_data_ready);
  3706. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rcvtimeo);
  3707. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rcvlowat);
  3708. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rxtx, sk_err);
  3709. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rxtx, sk_socket);
  3710. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rxtx, sk_memcg);
  3711. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rxtx, sk_lock);
  3712. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rxtx, sk_reserved_mem);
  3713. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rxtx, sk_forward_alloc);
  3714. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rxtx, sk_tsflags);
  3715. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_omem_alloc);
  3716. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_omem_alloc);
  3717. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_sndbuf);
  3718. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_wmem_queued);
  3719. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_wmem_alloc);
  3720. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_tsq_flags);
  3721. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_send_head);
  3722. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_write_queue);
  3723. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_write_pending);
  3724. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_dst_pending_confirm);
  3725. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_pacing_status);
  3726. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_frag);
  3727. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_timer);
  3728. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_pacing_rate);
  3729. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_zckey);
  3730. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_tskey);
  3731. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_max_pacing_rate);
  3732. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_sndtimeo);
  3733. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_priority);
  3734. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_mark);
  3735. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_dst_cache);
  3736. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_route_caps);
  3737. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_gso_type);
  3738. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_gso_max_size);
  3739. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_allocation);
  3740. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_txhash);
  3741. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_gso_max_segs);
  3742. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_pacing_shift);
  3743. CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_use_task_frag);
  3744. return 0;
  3745. }
  3746. core_initcall(sock_struct_check);