sock.c 108 KB

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