sock.c 112 KB

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