sock.c 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517
  1. /*
  2. * INET An implementation of the TCP/IP protocol suite for the LINUX
  3. * operating system. INET is implemented using the BSD Socket
  4. * interface as the means of communication with the user level.
  5. *
  6. * Generic socket support routines. Memory allocators, socket lock/release
  7. * handler for protocols to use and generic option handler.
  8. *
  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. *
  86. * This program is free software; you can redistribute it and/or
  87. * modify it under the terms of the GNU General Public License
  88. * as published by the Free Software Foundation; either version
  89. * 2 of the License, or (at your option) any later version.
  90. */
  91. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  92. #include <asm/unaligned.h>
  93. #include <linux/capability.h>
  94. #include <linux/errno.h>
  95. #include <linux/errqueue.h>
  96. #include <linux/types.h>
  97. #include <linux/socket.h>
  98. #include <linux/in.h>
  99. #include <linux/kernel.h>
  100. #include <linux/module.h>
  101. #include <linux/proc_fs.h>
  102. #include <linux/seq_file.h>
  103. #include <linux/sched.h>
  104. #include <linux/sched/mm.h>
  105. #include <linux/timer.h>
  106. #include <linux/string.h>
  107. #include <linux/sockios.h>
  108. #include <linux/net.h>
  109. #include <linux/mm.h>
  110. #include <linux/slab.h>
  111. #include <linux/interrupt.h>
  112. #include <linux/poll.h>
  113. #include <linux/tcp.h>
  114. #include <linux/init.h>
  115. #include <linux/highmem.h>
  116. #include <linux/user_namespace.h>
  117. #include <linux/static_key.h>
  118. #include <linux/memcontrol.h>
  119. #include <linux/prefetch.h>
  120. #include <linux/uaccess.h>
  121. #include <linux/netdevice.h>
  122. #include <net/protocol.h>
  123. #include <linux/skbuff.h>
  124. #include <net/net_namespace.h>
  125. #include <net/request_sock.h>
  126. #include <net/sock.h>
  127. #include <linux/net_tstamp.h>
  128. #include <net/xfrm.h>
  129. #include <linux/ipsec.h>
  130. #include <net/cls_cgroup.h>
  131. #include <net/netprio_cgroup.h>
  132. #include <linux/sock_diag.h>
  133. #include <linux/filter.h>
  134. #include <net/sock_reuseport.h>
  135. #include <trace/events/sock.h>
  136. #include <net/tcp.h>
  137. #include <net/busy_poll.h>
  138. static DEFINE_MUTEX(proto_list_mutex);
  139. static LIST_HEAD(proto_list);
  140. static void sock_inuse_add(struct net *net, int val);
  141. /**
  142. * sk_ns_capable - General socket capability test
  143. * @sk: Socket to use a capability on or through
  144. * @user_ns: The user namespace of the capability to use
  145. * @cap: The capability to use
  146. *
  147. * Test to see if the opener of the socket had when the socket was
  148. * created and the current process has the capability @cap in the user
  149. * namespace @user_ns.
  150. */
  151. bool sk_ns_capable(const struct sock *sk,
  152. struct user_namespace *user_ns, int cap)
  153. {
  154. return file_ns_capable(sk->sk_socket->file, user_ns, cap) &&
  155. ns_capable(user_ns, cap);
  156. }
  157. EXPORT_SYMBOL(sk_ns_capable);
  158. /**
  159. * sk_capable - Socket global capability test
  160. * @sk: Socket to use a capability on or through
  161. * @cap: The global capability to use
  162. *
  163. * Test to see if the opener of the socket had when the socket was
  164. * created and the current process has the capability @cap in all user
  165. * namespaces.
  166. */
  167. bool sk_capable(const struct sock *sk, int cap)
  168. {
  169. return sk_ns_capable(sk, &init_user_ns, cap);
  170. }
  171. EXPORT_SYMBOL(sk_capable);
  172. /**
  173. * sk_net_capable - Network namespace socket capability test
  174. * @sk: Socket to use a capability on or through
  175. * @cap: The capability to use
  176. *
  177. * Test to see if the opener of the socket had when the socket was created
  178. * and the current process has the capability @cap over the network namespace
  179. * the socket is a member of.
  180. */
  181. bool sk_net_capable(const struct sock *sk, int cap)
  182. {
  183. return sk_ns_capable(sk, sock_net(sk)->user_ns, cap);
  184. }
  185. EXPORT_SYMBOL(sk_net_capable);
  186. /*
  187. * Each address family might have different locking rules, so we have
  188. * one slock key per address family and separate keys for internal and
  189. * userspace sockets.
  190. */
  191. static struct lock_class_key af_family_keys[AF_MAX];
  192. static struct lock_class_key af_family_kern_keys[AF_MAX];
  193. static struct lock_class_key af_family_slock_keys[AF_MAX];
  194. static struct lock_class_key af_family_kern_slock_keys[AF_MAX];
  195. /*
  196. * Make lock validator output more readable. (we pre-construct these
  197. * strings build-time, so that runtime initialization of socket
  198. * locks is fast):
  199. */
  200. #define _sock_locks(x) \
  201. x "AF_UNSPEC", x "AF_UNIX" , x "AF_INET" , \
  202. x "AF_AX25" , x "AF_IPX" , x "AF_APPLETALK", \
  203. x "AF_NETROM", x "AF_BRIDGE" , x "AF_ATMPVC" , \
  204. x "AF_X25" , x "AF_INET6" , x "AF_ROSE" , \
  205. x "AF_DECnet", x "AF_NETBEUI" , x "AF_SECURITY" , \
  206. x "AF_KEY" , x "AF_NETLINK" , x "AF_PACKET" , \
  207. x "AF_ASH" , x "AF_ECONET" , x "AF_ATMSVC" , \
  208. x "AF_RDS" , x "AF_SNA" , x "AF_IRDA" , \
  209. x "AF_PPPOX" , x "AF_WANPIPE" , x "AF_LLC" , \
  210. x "27" , x "28" , x "AF_CAN" , \
  211. x "AF_TIPC" , x "AF_BLUETOOTH", x "IUCV" , \
  212. x "AF_RXRPC" , x "AF_ISDN" , x "AF_PHONET" , \
  213. x "AF_IEEE802154", x "AF_CAIF" , x "AF_ALG" , \
  214. x "AF_NFC" , x "AF_VSOCK" , x "AF_KCM" , \
  215. x "AF_QIPCRTR", x "AF_SMC" , x "AF_XDP" , \
  216. x "AF_MAX"
  217. static const char *const af_family_key_strings[AF_MAX+1] = {
  218. _sock_locks("sk_lock-")
  219. };
  220. static const char *const af_family_slock_key_strings[AF_MAX+1] = {
  221. _sock_locks("slock-")
  222. };
  223. static const char *const af_family_clock_key_strings[AF_MAX+1] = {
  224. _sock_locks("clock-")
  225. };
  226. static const char *const af_family_kern_key_strings[AF_MAX+1] = {
  227. _sock_locks("k-sk_lock-")
  228. };
  229. static const char *const af_family_kern_slock_key_strings[AF_MAX+1] = {
  230. _sock_locks("k-slock-")
  231. };
  232. static const char *const af_family_kern_clock_key_strings[AF_MAX+1] = {
  233. _sock_locks("k-clock-")
  234. };
  235. static const char *const af_family_rlock_key_strings[AF_MAX+1] = {
  236. _sock_locks("rlock-")
  237. };
  238. static const char *const af_family_wlock_key_strings[AF_MAX+1] = {
  239. _sock_locks("wlock-")
  240. };
  241. static const char *const af_family_elock_key_strings[AF_MAX+1] = {
  242. _sock_locks("elock-")
  243. };
  244. /*
  245. * sk_callback_lock and sk queues locking rules are per-address-family,
  246. * so split the lock classes by using a per-AF key:
  247. */
  248. static struct lock_class_key af_callback_keys[AF_MAX];
  249. static struct lock_class_key af_rlock_keys[AF_MAX];
  250. static struct lock_class_key af_wlock_keys[AF_MAX];
  251. static struct lock_class_key af_elock_keys[AF_MAX];
  252. static struct lock_class_key af_kern_callback_keys[AF_MAX];
  253. /* Run time adjustable parameters. */
  254. __u32 sysctl_wmem_max __read_mostly = SK_WMEM_MAX;
  255. EXPORT_SYMBOL(sysctl_wmem_max);
  256. __u32 sysctl_rmem_max __read_mostly = SK_RMEM_MAX;
  257. EXPORT_SYMBOL(sysctl_rmem_max);
  258. __u32 sysctl_wmem_default __read_mostly = SK_WMEM_MAX;
  259. __u32 sysctl_rmem_default __read_mostly = SK_RMEM_MAX;
  260. /* Maximal space eaten by iovec or ancillary data plus some space */
  261. int sysctl_optmem_max __read_mostly = sizeof(unsigned long)*(2*UIO_MAXIOV+512);
  262. EXPORT_SYMBOL(sysctl_optmem_max);
  263. int sysctl_tstamp_allow_data __read_mostly = 1;
  264. DEFINE_STATIC_KEY_FALSE(memalloc_socks_key);
  265. EXPORT_SYMBOL_GPL(memalloc_socks_key);
  266. /**
  267. * sk_set_memalloc - sets %SOCK_MEMALLOC
  268. * @sk: socket to set it on
  269. *
  270. * Set %SOCK_MEMALLOC on a socket for access to emergency reserves.
  271. * It's the responsibility of the admin to adjust min_free_kbytes
  272. * to meet the requirements
  273. */
  274. void sk_set_memalloc(struct sock *sk)
  275. {
  276. sock_set_flag(sk, SOCK_MEMALLOC);
  277. sk->sk_allocation |= __GFP_MEMALLOC;
  278. static_branch_inc(&memalloc_socks_key);
  279. }
  280. EXPORT_SYMBOL_GPL(sk_set_memalloc);
  281. void sk_clear_memalloc(struct sock *sk)
  282. {
  283. sock_reset_flag(sk, SOCK_MEMALLOC);
  284. sk->sk_allocation &= ~__GFP_MEMALLOC;
  285. static_branch_dec(&memalloc_socks_key);
  286. /*
  287. * SOCK_MEMALLOC is allowed to ignore rmem limits to ensure forward
  288. * progress of swapping. SOCK_MEMALLOC may be cleared while
  289. * it has rmem allocations due to the last swapfile being deactivated
  290. * but there is a risk that the socket is unusable due to exceeding
  291. * the rmem limits. Reclaim the reserves and obey rmem limits again.
  292. */
  293. sk_mem_reclaim(sk);
  294. }
  295. EXPORT_SYMBOL_GPL(sk_clear_memalloc);
  296. int __sk_backlog_rcv(struct sock *sk, struct sk_buff *skb)
  297. {
  298. int ret;
  299. unsigned int noreclaim_flag;
  300. /* these should have been dropped before queueing */
  301. BUG_ON(!sock_flag(sk, SOCK_MEMALLOC));
  302. noreclaim_flag = memalloc_noreclaim_save();
  303. ret = sk->sk_backlog_rcv(sk, skb);
  304. memalloc_noreclaim_restore(noreclaim_flag);
  305. return ret;
  306. }
  307. EXPORT_SYMBOL(__sk_backlog_rcv);
  308. static int sock_set_timeout(long *timeo_p, char __user *optval, int optlen)
  309. {
  310. struct timeval tv;
  311. if (optlen < sizeof(tv))
  312. return -EINVAL;
  313. if (copy_from_user(&tv, optval, sizeof(tv)))
  314. return -EFAULT;
  315. if (tv.tv_usec < 0 || tv.tv_usec >= USEC_PER_SEC)
  316. return -EDOM;
  317. if (tv.tv_sec < 0) {
  318. static int warned __read_mostly;
  319. *timeo_p = 0;
  320. if (warned < 10 && net_ratelimit()) {
  321. warned++;
  322. pr_info("%s: `%s' (pid %d) tries to set negative timeout\n",
  323. __func__, current->comm, task_pid_nr(current));
  324. }
  325. return 0;
  326. }
  327. *timeo_p = MAX_SCHEDULE_TIMEOUT;
  328. if (tv.tv_sec == 0 && tv.tv_usec == 0)
  329. return 0;
  330. if (tv.tv_sec < (MAX_SCHEDULE_TIMEOUT/HZ - 1))
  331. *timeo_p = tv.tv_sec * HZ + DIV_ROUND_UP(tv.tv_usec, USEC_PER_SEC / HZ);
  332. return 0;
  333. }
  334. static void sock_warn_obsolete_bsdism(const char *name)
  335. {
  336. static int warned;
  337. static char warncomm[TASK_COMM_LEN];
  338. if (strcmp(warncomm, current->comm) && warned < 5) {
  339. strcpy(warncomm, current->comm);
  340. pr_warn("process `%s' is using obsolete %s SO_BSDCOMPAT\n",
  341. warncomm, name);
  342. warned++;
  343. }
  344. }
  345. static bool sock_needs_netstamp(const struct sock *sk)
  346. {
  347. switch (sk->sk_family) {
  348. case AF_UNSPEC:
  349. case AF_UNIX:
  350. return false;
  351. default:
  352. return true;
  353. }
  354. }
  355. static void sock_disable_timestamp(struct sock *sk, unsigned long flags)
  356. {
  357. if (sk->sk_flags & flags) {
  358. sk->sk_flags &= ~flags;
  359. if (sock_needs_netstamp(sk) &&
  360. !(sk->sk_flags & SK_FLAGS_TIMESTAMP))
  361. net_disable_timestamp();
  362. }
  363. }
  364. int __sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
  365. {
  366. unsigned long flags;
  367. struct sk_buff_head *list = &sk->sk_receive_queue;
  368. if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) {
  369. atomic_inc(&sk->sk_drops);
  370. trace_sock_rcvqueue_full(sk, skb);
  371. return -ENOMEM;
  372. }
  373. if (!sk_rmem_schedule(sk, skb, skb->truesize)) {
  374. atomic_inc(&sk->sk_drops);
  375. return -ENOBUFS;
  376. }
  377. skb->dev = NULL;
  378. skb_set_owner_r(skb, sk);
  379. /* we escape from rcu protected region, make sure we dont leak
  380. * a norefcounted dst
  381. */
  382. skb_dst_force(skb);
  383. spin_lock_irqsave(&list->lock, flags);
  384. sock_skb_set_dropcount(sk, skb);
  385. __skb_queue_tail(list, skb);
  386. spin_unlock_irqrestore(&list->lock, flags);
  387. if (!sock_flag(sk, SOCK_DEAD))
  388. sk->sk_data_ready(sk);
  389. return 0;
  390. }
  391. EXPORT_SYMBOL(__sock_queue_rcv_skb);
  392. int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
  393. {
  394. int err;
  395. err = sk_filter(sk, skb);
  396. if (err)
  397. return err;
  398. return __sock_queue_rcv_skb(sk, skb);
  399. }
  400. EXPORT_SYMBOL(sock_queue_rcv_skb);
  401. int __sk_receive_skb(struct sock *sk, struct sk_buff *skb,
  402. const int nested, unsigned int trim_cap, bool refcounted)
  403. {
  404. int rc = NET_RX_SUCCESS;
  405. if (sk_filter_trim_cap(sk, skb, trim_cap))
  406. goto discard_and_relse;
  407. skb->dev = NULL;
  408. if (sk_rcvqueues_full(sk, sk->sk_rcvbuf)) {
  409. atomic_inc(&sk->sk_drops);
  410. goto discard_and_relse;
  411. }
  412. if (nested)
  413. bh_lock_sock_nested(sk);
  414. else
  415. bh_lock_sock(sk);
  416. if (!sock_owned_by_user(sk)) {
  417. /*
  418. * trylock + unlock semantics:
  419. */
  420. mutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_);
  421. rc = sk_backlog_rcv(sk, skb);
  422. mutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_);
  423. } else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) {
  424. bh_unlock_sock(sk);
  425. atomic_inc(&sk->sk_drops);
  426. goto discard_and_relse;
  427. }
  428. bh_unlock_sock(sk);
  429. out:
  430. if (refcounted)
  431. sock_put(sk);
  432. return rc;
  433. discard_and_relse:
  434. kfree_skb(skb);
  435. goto out;
  436. }
  437. EXPORT_SYMBOL(__sk_receive_skb);
  438. struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie)
  439. {
  440. struct dst_entry *dst = __sk_dst_get(sk);
  441. if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) {
  442. sk_tx_queue_clear(sk);
  443. sk->sk_dst_pending_confirm = 0;
  444. RCU_INIT_POINTER(sk->sk_dst_cache, NULL);
  445. dst_release(dst);
  446. return NULL;
  447. }
  448. return dst;
  449. }
  450. EXPORT_SYMBOL(__sk_dst_check);
  451. struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie)
  452. {
  453. struct dst_entry *dst = sk_dst_get(sk);
  454. if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) {
  455. sk_dst_reset(sk);
  456. dst_release(dst);
  457. return NULL;
  458. }
  459. return dst;
  460. }
  461. EXPORT_SYMBOL(sk_dst_check);
  462. static int sock_setbindtodevice(struct sock *sk, char __user *optval,
  463. int optlen)
  464. {
  465. int ret = -ENOPROTOOPT;
  466. #ifdef CONFIG_NETDEVICES
  467. struct net *net = sock_net(sk);
  468. char devname[IFNAMSIZ];
  469. int index;
  470. /* Sorry... */
  471. ret = -EPERM;
  472. if (!ns_capable(net->user_ns, CAP_NET_RAW))
  473. goto out;
  474. ret = -EINVAL;
  475. if (optlen < 0)
  476. goto out;
  477. /* Bind this socket to a particular device like "eth0",
  478. * as specified in the passed interface name. If the
  479. * name is "" or the option length is zero the socket
  480. * is not bound.
  481. */
  482. if (optlen > IFNAMSIZ - 1)
  483. optlen = IFNAMSIZ - 1;
  484. memset(devname, 0, sizeof(devname));
  485. ret = -EFAULT;
  486. if (copy_from_user(devname, optval, optlen))
  487. goto out;
  488. index = 0;
  489. if (devname[0] != '\0') {
  490. struct net_device *dev;
  491. rcu_read_lock();
  492. dev = dev_get_by_name_rcu(net, devname);
  493. if (dev)
  494. index = dev->ifindex;
  495. rcu_read_unlock();
  496. ret = -ENODEV;
  497. if (!dev)
  498. goto out;
  499. }
  500. lock_sock(sk);
  501. sk->sk_bound_dev_if = index;
  502. sk_dst_reset(sk);
  503. release_sock(sk);
  504. ret = 0;
  505. out:
  506. #endif
  507. return ret;
  508. }
  509. static int sock_getbindtodevice(struct sock *sk, char __user *optval,
  510. int __user *optlen, int len)
  511. {
  512. int ret = -ENOPROTOOPT;
  513. #ifdef CONFIG_NETDEVICES
  514. struct net *net = sock_net(sk);
  515. char devname[IFNAMSIZ];
  516. if (sk->sk_bound_dev_if == 0) {
  517. len = 0;
  518. goto zero;
  519. }
  520. ret = -EINVAL;
  521. if (len < IFNAMSIZ)
  522. goto out;
  523. ret = netdev_get_name(net, devname, sk->sk_bound_dev_if);
  524. if (ret)
  525. goto out;
  526. len = strlen(devname) + 1;
  527. ret = -EFAULT;
  528. if (copy_to_user(optval, devname, len))
  529. goto out;
  530. zero:
  531. ret = -EFAULT;
  532. if (put_user(len, optlen))
  533. goto out;
  534. ret = 0;
  535. out:
  536. #endif
  537. return ret;
  538. }
  539. static inline void sock_valbool_flag(struct sock *sk, int bit, int valbool)
  540. {
  541. if (valbool)
  542. sock_set_flag(sk, bit);
  543. else
  544. sock_reset_flag(sk, bit);
  545. }
  546. bool sk_mc_loop(struct sock *sk)
  547. {
  548. if (dev_recursion_level())
  549. return false;
  550. if (!sk)
  551. return true;
  552. switch (sk->sk_family) {
  553. case AF_INET:
  554. return inet_sk(sk)->mc_loop;
  555. #if IS_ENABLED(CONFIG_IPV6)
  556. case AF_INET6:
  557. return inet6_sk(sk)->mc_loop;
  558. #endif
  559. }
  560. WARN_ON_ONCE(1);
  561. return true;
  562. }
  563. EXPORT_SYMBOL(sk_mc_loop);
  564. /*
  565. * This is meant for all protocols to use and covers goings on
  566. * at the socket level. Everything here is generic.
  567. */
  568. int sock_setsockopt(struct socket *sock, int level, int optname,
  569. char __user *optval, unsigned int optlen)
  570. {
  571. struct sock_txtime sk_txtime;
  572. struct sock *sk = sock->sk;
  573. int val;
  574. int valbool;
  575. struct linger ling;
  576. int ret = 0;
  577. /*
  578. * Options without arguments
  579. */
  580. if (optname == SO_BINDTODEVICE)
  581. return sock_setbindtodevice(sk, optval, optlen);
  582. if (optlen < sizeof(int))
  583. return -EINVAL;
  584. if (get_user(val, (int __user *)optval))
  585. return -EFAULT;
  586. valbool = val ? 1 : 0;
  587. lock_sock(sk);
  588. switch (optname) {
  589. case SO_DEBUG:
  590. if (val && !capable(CAP_NET_ADMIN))
  591. ret = -EACCES;
  592. else
  593. sock_valbool_flag(sk, SOCK_DBG, valbool);
  594. break;
  595. case SO_REUSEADDR:
  596. sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE);
  597. break;
  598. case SO_REUSEPORT:
  599. sk->sk_reuseport = valbool;
  600. break;
  601. case SO_TYPE:
  602. case SO_PROTOCOL:
  603. case SO_DOMAIN:
  604. case SO_ERROR:
  605. ret = -ENOPROTOOPT;
  606. break;
  607. case SO_DONTROUTE:
  608. sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool);
  609. sk_dst_reset(sk);
  610. break;
  611. case SO_BROADCAST:
  612. sock_valbool_flag(sk, SOCK_BROADCAST, valbool);
  613. break;
  614. case SO_SNDBUF:
  615. /* Don't error on this BSD doesn't and if you think
  616. * about it this is right. Otherwise apps have to
  617. * play 'guess the biggest size' games. RCVBUF/SNDBUF
  618. * are treated in BSD as hints
  619. */
  620. val = min_t(u32, val, sysctl_wmem_max);
  621. set_sndbuf:
  622. sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
  623. sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF);
  624. /* Wake up sending tasks if we upped the value. */
  625. sk->sk_write_space(sk);
  626. break;
  627. case SO_SNDBUFFORCE:
  628. if (!capable(CAP_NET_ADMIN)) {
  629. ret = -EPERM;
  630. break;
  631. }
  632. goto set_sndbuf;
  633. case SO_RCVBUF:
  634. /* Don't error on this BSD doesn't and if you think
  635. * about it this is right. Otherwise apps have to
  636. * play 'guess the biggest size' games. RCVBUF/SNDBUF
  637. * are treated in BSD as hints
  638. */
  639. val = min_t(u32, val, sysctl_rmem_max);
  640. set_rcvbuf:
  641. sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
  642. /*
  643. * We double it on the way in to account for
  644. * "struct sk_buff" etc. overhead. Applications
  645. * assume that the SO_RCVBUF setting they make will
  646. * allow that much actual data to be received on that
  647. * socket.
  648. *
  649. * Applications are unaware that "struct sk_buff" and
  650. * other overheads allocate from the receive buffer
  651. * during socket buffer allocation.
  652. *
  653. * And after considering the possible alternatives,
  654. * returning the value we actually used in getsockopt
  655. * is the most desirable behavior.
  656. */
  657. sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF);
  658. break;
  659. case SO_RCVBUFFORCE:
  660. if (!capable(CAP_NET_ADMIN)) {
  661. ret = -EPERM;
  662. break;
  663. }
  664. goto set_rcvbuf;
  665. case SO_KEEPALIVE:
  666. if (sk->sk_prot->keepalive)
  667. sk->sk_prot->keepalive(sk, valbool);
  668. sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool);
  669. break;
  670. case SO_OOBINLINE:
  671. sock_valbool_flag(sk, SOCK_URGINLINE, valbool);
  672. break;
  673. case SO_NO_CHECK:
  674. sk->sk_no_check_tx = valbool;
  675. break;
  676. case SO_PRIORITY:
  677. if ((val >= 0 && val <= 6) ||
  678. ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
  679. sk->sk_priority = val;
  680. else
  681. ret = -EPERM;
  682. break;
  683. case SO_LINGER:
  684. if (optlen < sizeof(ling)) {
  685. ret = -EINVAL; /* 1003.1g */
  686. break;
  687. }
  688. if (copy_from_user(&ling, optval, sizeof(ling))) {
  689. ret = -EFAULT;
  690. break;
  691. }
  692. if (!ling.l_onoff)
  693. sock_reset_flag(sk, SOCK_LINGER);
  694. else {
  695. #if (BITS_PER_LONG == 32)
  696. if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ)
  697. sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT;
  698. else
  699. #endif
  700. sk->sk_lingertime = (unsigned int)ling.l_linger * HZ;
  701. sock_set_flag(sk, SOCK_LINGER);
  702. }
  703. break;
  704. case SO_BSDCOMPAT:
  705. sock_warn_obsolete_bsdism("setsockopt");
  706. break;
  707. case SO_PASSCRED:
  708. if (valbool)
  709. set_bit(SOCK_PASSCRED, &sock->flags);
  710. else
  711. clear_bit(SOCK_PASSCRED, &sock->flags);
  712. break;
  713. case SO_TIMESTAMP:
  714. case SO_TIMESTAMPNS:
  715. if (valbool) {
  716. if (optname == SO_TIMESTAMP)
  717. sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
  718. else
  719. sock_set_flag(sk, SOCK_RCVTSTAMPNS);
  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. break;
  727. case SO_TIMESTAMPING:
  728. if (val & ~SOF_TIMESTAMPING_MASK) {
  729. ret = -EINVAL;
  730. break;
  731. }
  732. if (val & SOF_TIMESTAMPING_OPT_ID &&
  733. !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) {
  734. if (sk->sk_protocol == IPPROTO_TCP &&
  735. sk->sk_type == SOCK_STREAM) {
  736. if ((1 << sk->sk_state) &
  737. (TCPF_CLOSE | TCPF_LISTEN)) {
  738. ret = -EINVAL;
  739. break;
  740. }
  741. sk->sk_tskey = tcp_sk(sk)->snd_una;
  742. } else {
  743. sk->sk_tskey = 0;
  744. }
  745. }
  746. if (val & SOF_TIMESTAMPING_OPT_STATS &&
  747. !(val & SOF_TIMESTAMPING_OPT_TSONLY)) {
  748. ret = -EINVAL;
  749. break;
  750. }
  751. sk->sk_tsflags = val;
  752. if (val & SOF_TIMESTAMPING_RX_SOFTWARE)
  753. sock_enable_timestamp(sk,
  754. SOCK_TIMESTAMPING_RX_SOFTWARE);
  755. else
  756. sock_disable_timestamp(sk,
  757. (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE));
  758. break;
  759. case SO_RCVLOWAT:
  760. if (val < 0)
  761. val = INT_MAX;
  762. if (sock->ops->set_rcvlowat)
  763. ret = sock->ops->set_rcvlowat(sk, val);
  764. else
  765. sk->sk_rcvlowat = val ? : 1;
  766. break;
  767. case SO_RCVTIMEO:
  768. ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen);
  769. break;
  770. case SO_SNDTIMEO:
  771. ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen);
  772. break;
  773. case SO_ATTACH_FILTER:
  774. ret = -EINVAL;
  775. if (optlen == sizeof(struct sock_fprog)) {
  776. struct sock_fprog fprog;
  777. ret = -EFAULT;
  778. if (copy_from_user(&fprog, optval, sizeof(fprog)))
  779. break;
  780. ret = sk_attach_filter(&fprog, sk);
  781. }
  782. break;
  783. case SO_ATTACH_BPF:
  784. ret = -EINVAL;
  785. if (optlen == sizeof(u32)) {
  786. u32 ufd;
  787. ret = -EFAULT;
  788. if (copy_from_user(&ufd, optval, sizeof(ufd)))
  789. break;
  790. ret = sk_attach_bpf(ufd, sk);
  791. }
  792. break;
  793. case SO_ATTACH_REUSEPORT_CBPF:
  794. ret = -EINVAL;
  795. if (optlen == sizeof(struct sock_fprog)) {
  796. struct sock_fprog fprog;
  797. ret = -EFAULT;
  798. if (copy_from_user(&fprog, optval, sizeof(fprog)))
  799. break;
  800. ret = sk_reuseport_attach_filter(&fprog, sk);
  801. }
  802. break;
  803. case SO_ATTACH_REUSEPORT_EBPF:
  804. ret = -EINVAL;
  805. if (optlen == sizeof(u32)) {
  806. u32 ufd;
  807. ret = -EFAULT;
  808. if (copy_from_user(&ufd, optval, sizeof(ufd)))
  809. break;
  810. ret = sk_reuseport_attach_bpf(ufd, sk);
  811. }
  812. break;
  813. case SO_DETACH_FILTER:
  814. ret = sk_detach_filter(sk);
  815. break;
  816. case SO_LOCK_FILTER:
  817. if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool)
  818. ret = -EPERM;
  819. else
  820. sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool);
  821. break;
  822. case SO_PASSSEC:
  823. if (valbool)
  824. set_bit(SOCK_PASSSEC, &sock->flags);
  825. else
  826. clear_bit(SOCK_PASSSEC, &sock->flags);
  827. break;
  828. case SO_MARK:
  829. if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
  830. ret = -EPERM;
  831. else
  832. sk->sk_mark = val;
  833. break;
  834. case SO_RXQ_OVFL:
  835. sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool);
  836. break;
  837. case SO_WIFI_STATUS:
  838. sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool);
  839. break;
  840. case SO_PEEK_OFF:
  841. if (sock->ops->set_peek_off)
  842. ret = sock->ops->set_peek_off(sk, val);
  843. else
  844. ret = -EOPNOTSUPP;
  845. break;
  846. case SO_NOFCS:
  847. sock_valbool_flag(sk, SOCK_NOFCS, valbool);
  848. break;
  849. case SO_SELECT_ERR_QUEUE:
  850. sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool);
  851. break;
  852. #ifdef CONFIG_NET_RX_BUSY_POLL
  853. case SO_BUSY_POLL:
  854. /* allow unprivileged users to decrease the value */
  855. if ((val > sk->sk_ll_usec) && !capable(CAP_NET_ADMIN))
  856. ret = -EPERM;
  857. else {
  858. if (val < 0)
  859. ret = -EINVAL;
  860. else
  861. sk->sk_ll_usec = val;
  862. }
  863. break;
  864. #endif
  865. case SO_MAX_PACING_RATE:
  866. if (val != ~0U)
  867. cmpxchg(&sk->sk_pacing_status,
  868. SK_PACING_NONE,
  869. SK_PACING_NEEDED);
  870. sk->sk_max_pacing_rate = val;
  871. sk->sk_pacing_rate = min(sk->sk_pacing_rate,
  872. sk->sk_max_pacing_rate);
  873. break;
  874. case SO_INCOMING_CPU:
  875. WRITE_ONCE(sk->sk_incoming_cpu, val);
  876. break;
  877. case SO_CNX_ADVICE:
  878. if (val == 1)
  879. dst_negative_advice(sk);
  880. break;
  881. case SO_ZEROCOPY:
  882. if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6) {
  883. if (sk->sk_protocol != IPPROTO_TCP)
  884. ret = -ENOTSUPP;
  885. } else if (sk->sk_family != PF_RDS) {
  886. ret = -ENOTSUPP;
  887. }
  888. if (!ret) {
  889. if (val < 0 || val > 1)
  890. ret = -EINVAL;
  891. else
  892. sock_valbool_flag(sk, SOCK_ZEROCOPY, valbool);
  893. }
  894. break;
  895. case SO_TXTIME:
  896. if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) {
  897. ret = -EPERM;
  898. } else if (optlen != sizeof(struct sock_txtime)) {
  899. ret = -EINVAL;
  900. } else if (copy_from_user(&sk_txtime, optval,
  901. sizeof(struct sock_txtime))) {
  902. ret = -EFAULT;
  903. } else if (sk_txtime.flags & ~SOF_TXTIME_FLAGS_MASK) {
  904. ret = -EINVAL;
  905. } else {
  906. sock_valbool_flag(sk, SOCK_TXTIME, true);
  907. sk->sk_clockid = sk_txtime.clockid;
  908. sk->sk_txtime_deadline_mode =
  909. !!(sk_txtime.flags & SOF_TXTIME_DEADLINE_MODE);
  910. sk->sk_txtime_report_errors =
  911. !!(sk_txtime.flags & SOF_TXTIME_REPORT_ERRORS);
  912. }
  913. break;
  914. default:
  915. ret = -ENOPROTOOPT;
  916. break;
  917. }
  918. release_sock(sk);
  919. return ret;
  920. }
  921. EXPORT_SYMBOL(sock_setsockopt);
  922. static void cred_to_ucred(struct pid *pid, const struct cred *cred,
  923. struct ucred *ucred)
  924. {
  925. ucred->pid = pid_vnr(pid);
  926. ucred->uid = ucred->gid = -1;
  927. if (cred) {
  928. struct user_namespace *current_ns = current_user_ns();
  929. ucred->uid = from_kuid_munged(current_ns, cred->euid);
  930. ucred->gid = from_kgid_munged(current_ns, cred->egid);
  931. }
  932. }
  933. static int groups_to_user(gid_t __user *dst, const struct group_info *src)
  934. {
  935. struct user_namespace *user_ns = current_user_ns();
  936. int i;
  937. for (i = 0; i < src->ngroups; i++)
  938. if (put_user(from_kgid_munged(user_ns, src->gid[i]), dst + i))
  939. return -EFAULT;
  940. return 0;
  941. }
  942. int sock_getsockopt(struct socket *sock, int level, int optname,
  943. char __user *optval, int __user *optlen)
  944. {
  945. struct sock *sk = sock->sk;
  946. union {
  947. int val;
  948. u64 val64;
  949. struct linger ling;
  950. struct timeval tm;
  951. struct sock_txtime txtime;
  952. } v;
  953. int lv = sizeof(int);
  954. int len;
  955. if (get_user(len, optlen))
  956. return -EFAULT;
  957. if (len < 0)
  958. return -EINVAL;
  959. memset(&v, 0, sizeof(v));
  960. switch (optname) {
  961. case SO_DEBUG:
  962. v.val = sock_flag(sk, SOCK_DBG);
  963. break;
  964. case SO_DONTROUTE:
  965. v.val = sock_flag(sk, SOCK_LOCALROUTE);
  966. break;
  967. case SO_BROADCAST:
  968. v.val = sock_flag(sk, SOCK_BROADCAST);
  969. break;
  970. case SO_SNDBUF:
  971. v.val = sk->sk_sndbuf;
  972. break;
  973. case SO_RCVBUF:
  974. v.val = sk->sk_rcvbuf;
  975. break;
  976. case SO_REUSEADDR:
  977. v.val = sk->sk_reuse;
  978. break;
  979. case SO_REUSEPORT:
  980. v.val = sk->sk_reuseport;
  981. break;
  982. case SO_KEEPALIVE:
  983. v.val = sock_flag(sk, SOCK_KEEPOPEN);
  984. break;
  985. case SO_TYPE:
  986. v.val = sk->sk_type;
  987. break;
  988. case SO_PROTOCOL:
  989. v.val = sk->sk_protocol;
  990. break;
  991. case SO_DOMAIN:
  992. v.val = sk->sk_family;
  993. break;
  994. case SO_ERROR:
  995. v.val = -sock_error(sk);
  996. if (v.val == 0)
  997. v.val = xchg(&sk->sk_err_soft, 0);
  998. break;
  999. case SO_OOBINLINE:
  1000. v.val = sock_flag(sk, SOCK_URGINLINE);
  1001. break;
  1002. case SO_NO_CHECK:
  1003. v.val = sk->sk_no_check_tx;
  1004. break;
  1005. case SO_PRIORITY:
  1006. v.val = sk->sk_priority;
  1007. break;
  1008. case SO_LINGER:
  1009. lv = sizeof(v.ling);
  1010. v.ling.l_onoff = sock_flag(sk, SOCK_LINGER);
  1011. v.ling.l_linger = sk->sk_lingertime / HZ;
  1012. break;
  1013. case SO_BSDCOMPAT:
  1014. sock_warn_obsolete_bsdism("getsockopt");
  1015. break;
  1016. case SO_TIMESTAMP:
  1017. v.val = sock_flag(sk, SOCK_RCVTSTAMP) &&
  1018. !sock_flag(sk, SOCK_RCVTSTAMPNS);
  1019. break;
  1020. case SO_TIMESTAMPNS:
  1021. v.val = sock_flag(sk, SOCK_RCVTSTAMPNS);
  1022. break;
  1023. case SO_TIMESTAMPING:
  1024. v.val = sk->sk_tsflags;
  1025. break;
  1026. case SO_RCVTIMEO:
  1027. lv = sizeof(struct timeval);
  1028. if (sk->sk_rcvtimeo == MAX_SCHEDULE_TIMEOUT) {
  1029. v.tm.tv_sec = 0;
  1030. v.tm.tv_usec = 0;
  1031. } else {
  1032. v.tm.tv_sec = sk->sk_rcvtimeo / HZ;
  1033. v.tm.tv_usec = ((sk->sk_rcvtimeo % HZ) * USEC_PER_SEC) / HZ;
  1034. }
  1035. break;
  1036. case SO_SNDTIMEO:
  1037. lv = sizeof(struct timeval);
  1038. if (sk->sk_sndtimeo == MAX_SCHEDULE_TIMEOUT) {
  1039. v.tm.tv_sec = 0;
  1040. v.tm.tv_usec = 0;
  1041. } else {
  1042. v.tm.tv_sec = sk->sk_sndtimeo / HZ;
  1043. v.tm.tv_usec = ((sk->sk_sndtimeo % HZ) * USEC_PER_SEC) / HZ;
  1044. }
  1045. break;
  1046. case SO_RCVLOWAT:
  1047. v.val = sk->sk_rcvlowat;
  1048. break;
  1049. case SO_SNDLOWAT:
  1050. v.val = 1;
  1051. break;
  1052. case SO_PASSCRED:
  1053. v.val = !!test_bit(SOCK_PASSCRED, &sock->flags);
  1054. break;
  1055. case SO_PEERCRED:
  1056. {
  1057. struct ucred peercred;
  1058. if (len > sizeof(peercred))
  1059. len = sizeof(peercred);
  1060. cred_to_ucred(sk->sk_peer_pid, sk->sk_peer_cred, &peercred);
  1061. if (copy_to_user(optval, &peercred, len))
  1062. return -EFAULT;
  1063. goto lenout;
  1064. }
  1065. case SO_PEERGROUPS:
  1066. {
  1067. int ret, n;
  1068. if (!sk->sk_peer_cred)
  1069. return -ENODATA;
  1070. n = sk->sk_peer_cred->group_info->ngroups;
  1071. if (len < n * sizeof(gid_t)) {
  1072. len = n * sizeof(gid_t);
  1073. return put_user(len, optlen) ? -EFAULT : -ERANGE;
  1074. }
  1075. len = n * sizeof(gid_t);
  1076. ret = groups_to_user((gid_t __user *)optval,
  1077. sk->sk_peer_cred->group_info);
  1078. if (ret)
  1079. return ret;
  1080. goto lenout;
  1081. }
  1082. case SO_PEERNAME:
  1083. {
  1084. char address[128];
  1085. lv = sock->ops->getname(sock, (struct sockaddr *)address, 2);
  1086. if (lv < 0)
  1087. return -ENOTCONN;
  1088. if (lv < len)
  1089. return -EINVAL;
  1090. if (copy_to_user(optval, address, len))
  1091. return -EFAULT;
  1092. goto lenout;
  1093. }
  1094. /* Dubious BSD thing... Probably nobody even uses it, but
  1095. * the UNIX standard wants it for whatever reason... -DaveM
  1096. */
  1097. case SO_ACCEPTCONN:
  1098. v.val = sk->sk_state == TCP_LISTEN;
  1099. break;
  1100. case SO_PASSSEC:
  1101. v.val = !!test_bit(SOCK_PASSSEC, &sock->flags);
  1102. break;
  1103. case SO_PEERSEC:
  1104. return security_socket_getpeersec_stream(sock, optval, optlen, len);
  1105. case SO_MARK:
  1106. v.val = sk->sk_mark;
  1107. break;
  1108. case SO_RXQ_OVFL:
  1109. v.val = sock_flag(sk, SOCK_RXQ_OVFL);
  1110. break;
  1111. case SO_WIFI_STATUS:
  1112. v.val = sock_flag(sk, SOCK_WIFI_STATUS);
  1113. break;
  1114. case SO_PEEK_OFF:
  1115. if (!sock->ops->set_peek_off)
  1116. return -EOPNOTSUPP;
  1117. v.val = sk->sk_peek_off;
  1118. break;
  1119. case SO_NOFCS:
  1120. v.val = sock_flag(sk, SOCK_NOFCS);
  1121. break;
  1122. case SO_BINDTODEVICE:
  1123. return sock_getbindtodevice(sk, optval, optlen, len);
  1124. case SO_GET_FILTER:
  1125. len = sk_get_filter(sk, (struct sock_filter __user *)optval, len);
  1126. if (len < 0)
  1127. return len;
  1128. goto lenout;
  1129. case SO_LOCK_FILTER:
  1130. v.val = sock_flag(sk, SOCK_FILTER_LOCKED);
  1131. break;
  1132. case SO_BPF_EXTENSIONS:
  1133. v.val = bpf_tell_extensions();
  1134. break;
  1135. case SO_SELECT_ERR_QUEUE:
  1136. v.val = sock_flag(sk, SOCK_SELECT_ERR_QUEUE);
  1137. break;
  1138. #ifdef CONFIG_NET_RX_BUSY_POLL
  1139. case SO_BUSY_POLL:
  1140. v.val = sk->sk_ll_usec;
  1141. break;
  1142. #endif
  1143. case SO_MAX_PACING_RATE:
  1144. v.val = sk->sk_max_pacing_rate;
  1145. break;
  1146. case SO_INCOMING_CPU:
  1147. v.val = READ_ONCE(sk->sk_incoming_cpu);
  1148. break;
  1149. case SO_MEMINFO:
  1150. {
  1151. u32 meminfo[SK_MEMINFO_VARS];
  1152. sk_get_meminfo(sk, meminfo);
  1153. len = min_t(unsigned int, len, sizeof(meminfo));
  1154. if (copy_to_user(optval, &meminfo, len))
  1155. return -EFAULT;
  1156. goto lenout;
  1157. }
  1158. #ifdef CONFIG_NET_RX_BUSY_POLL
  1159. case SO_INCOMING_NAPI_ID:
  1160. v.val = READ_ONCE(sk->sk_napi_id);
  1161. /* aggregate non-NAPI IDs down to 0 */
  1162. if (v.val < MIN_NAPI_ID)
  1163. v.val = 0;
  1164. break;
  1165. #endif
  1166. case SO_COOKIE:
  1167. lv = sizeof(u64);
  1168. if (len < lv)
  1169. return -EINVAL;
  1170. v.val64 = sock_gen_cookie(sk);
  1171. break;
  1172. case SO_ZEROCOPY:
  1173. v.val = sock_flag(sk, SOCK_ZEROCOPY);
  1174. break;
  1175. case SO_TXTIME:
  1176. lv = sizeof(v.txtime);
  1177. v.txtime.clockid = sk->sk_clockid;
  1178. v.txtime.flags |= sk->sk_txtime_deadline_mode ?
  1179. SOF_TXTIME_DEADLINE_MODE : 0;
  1180. v.txtime.flags |= sk->sk_txtime_report_errors ?
  1181. SOF_TXTIME_REPORT_ERRORS : 0;
  1182. break;
  1183. default:
  1184. /* We implement the SO_SNDLOWAT etc to not be settable
  1185. * (1003.1g 7).
  1186. */
  1187. return -ENOPROTOOPT;
  1188. }
  1189. if (len > lv)
  1190. len = lv;
  1191. if (copy_to_user(optval, &v, len))
  1192. return -EFAULT;
  1193. lenout:
  1194. if (put_user(len, optlen))
  1195. return -EFAULT;
  1196. return 0;
  1197. }
  1198. /*
  1199. * Initialize an sk_lock.
  1200. *
  1201. * (We also register the sk_lock with the lock validator.)
  1202. */
  1203. static inline void sock_lock_init(struct sock *sk)
  1204. {
  1205. if (sk->sk_kern_sock)
  1206. sock_lock_init_class_and_name(
  1207. sk,
  1208. af_family_kern_slock_key_strings[sk->sk_family],
  1209. af_family_kern_slock_keys + sk->sk_family,
  1210. af_family_kern_key_strings[sk->sk_family],
  1211. af_family_kern_keys + sk->sk_family);
  1212. else
  1213. sock_lock_init_class_and_name(
  1214. sk,
  1215. af_family_slock_key_strings[sk->sk_family],
  1216. af_family_slock_keys + sk->sk_family,
  1217. af_family_key_strings[sk->sk_family],
  1218. af_family_keys + sk->sk_family);
  1219. }
  1220. /*
  1221. * Copy all fields from osk to nsk but nsk->sk_refcnt must not change yet,
  1222. * even temporarly, because of RCU lookups. sk_node should also be left as is.
  1223. * We must not copy fields between sk_dontcopy_begin and sk_dontcopy_end
  1224. */
  1225. static void sock_copy(struct sock *nsk, const struct sock *osk)
  1226. {
  1227. #ifdef CONFIG_SECURITY_NETWORK
  1228. void *sptr = nsk->sk_security;
  1229. #endif
  1230. memcpy(nsk, osk, offsetof(struct sock, sk_dontcopy_begin));
  1231. memcpy(&nsk->sk_dontcopy_end, &osk->sk_dontcopy_end,
  1232. osk->sk_prot->obj_size - offsetof(struct sock, sk_dontcopy_end));
  1233. #ifdef CONFIG_SECURITY_NETWORK
  1234. nsk->sk_security = sptr;
  1235. security_sk_clone(osk, nsk);
  1236. #endif
  1237. }
  1238. static struct sock *sk_prot_alloc(struct proto *prot, gfp_t priority,
  1239. int family)
  1240. {
  1241. struct sock *sk;
  1242. struct kmem_cache *slab;
  1243. slab = prot->slab;
  1244. if (slab != NULL) {
  1245. sk = kmem_cache_alloc(slab, priority & ~__GFP_ZERO);
  1246. if (!sk)
  1247. return sk;
  1248. if (priority & __GFP_ZERO)
  1249. sk_prot_clear_nulls(sk, prot->obj_size);
  1250. } else
  1251. sk = kmalloc(prot->obj_size, priority);
  1252. if (sk != NULL) {
  1253. if (security_sk_alloc(sk, family, priority))
  1254. goto out_free;
  1255. if (!try_module_get(prot->owner))
  1256. goto out_free_sec;
  1257. sk_tx_queue_clear(sk);
  1258. }
  1259. return sk;
  1260. out_free_sec:
  1261. security_sk_free(sk);
  1262. out_free:
  1263. if (slab != NULL)
  1264. kmem_cache_free(slab, sk);
  1265. else
  1266. kfree(sk);
  1267. return NULL;
  1268. }
  1269. static void sk_prot_free(struct proto *prot, struct sock *sk)
  1270. {
  1271. struct kmem_cache *slab;
  1272. struct module *owner;
  1273. owner = prot->owner;
  1274. slab = prot->slab;
  1275. cgroup_sk_free(&sk->sk_cgrp_data);
  1276. mem_cgroup_sk_free(sk);
  1277. security_sk_free(sk);
  1278. if (slab != NULL)
  1279. kmem_cache_free(slab, sk);
  1280. else
  1281. kfree(sk);
  1282. module_put(owner);
  1283. }
  1284. /**
  1285. * sk_alloc - All socket objects are allocated here
  1286. * @net: the applicable net namespace
  1287. * @family: protocol family
  1288. * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
  1289. * @prot: struct proto associated with this new sock instance
  1290. * @kern: is this to be a kernel socket?
  1291. */
  1292. struct sock *sk_alloc(struct net *net, int family, gfp_t priority,
  1293. struct proto *prot, int kern)
  1294. {
  1295. struct sock *sk;
  1296. sk = sk_prot_alloc(prot, priority | __GFP_ZERO, family);
  1297. if (sk) {
  1298. sk->sk_family = family;
  1299. /*
  1300. * See comment in struct sock definition to understand
  1301. * why we need sk_prot_creator -acme
  1302. */
  1303. sk->sk_prot = sk->sk_prot_creator = prot;
  1304. sk->sk_kern_sock = kern;
  1305. sock_lock_init(sk);
  1306. sk->sk_net_refcnt = kern ? 0 : 1;
  1307. if (likely(sk->sk_net_refcnt)) {
  1308. get_net(net);
  1309. sock_inuse_add(net, 1);
  1310. }
  1311. sock_net_set(sk, net);
  1312. refcount_set(&sk->sk_wmem_alloc, 1);
  1313. mem_cgroup_sk_alloc(sk);
  1314. cgroup_sk_alloc(&sk->sk_cgrp_data);
  1315. sock_update_classid(&sk->sk_cgrp_data);
  1316. sock_update_netprioidx(&sk->sk_cgrp_data);
  1317. sk_tx_queue_clear(sk);
  1318. }
  1319. return sk;
  1320. }
  1321. EXPORT_SYMBOL(sk_alloc);
  1322. /* Sockets having SOCK_RCU_FREE will call this function after one RCU
  1323. * grace period. This is the case for UDP sockets and TCP listeners.
  1324. */
  1325. static void __sk_destruct(struct rcu_head *head)
  1326. {
  1327. struct sock *sk = container_of(head, struct sock, sk_rcu);
  1328. struct sk_filter *filter;
  1329. if (sk->sk_destruct)
  1330. sk->sk_destruct(sk);
  1331. filter = rcu_dereference_check(sk->sk_filter,
  1332. refcount_read(&sk->sk_wmem_alloc) == 0);
  1333. if (filter) {
  1334. sk_filter_uncharge(sk, filter);
  1335. RCU_INIT_POINTER(sk->sk_filter, NULL);
  1336. }
  1337. sock_disable_timestamp(sk, SK_FLAGS_TIMESTAMP);
  1338. if (atomic_read(&sk->sk_omem_alloc))
  1339. pr_debug("%s: optmem leakage (%d bytes) detected\n",
  1340. __func__, atomic_read(&sk->sk_omem_alloc));
  1341. if (sk->sk_frag.page) {
  1342. put_page(sk->sk_frag.page);
  1343. sk->sk_frag.page = NULL;
  1344. }
  1345. if (sk->sk_peer_cred)
  1346. put_cred(sk->sk_peer_cred);
  1347. put_pid(sk->sk_peer_pid);
  1348. if (likely(sk->sk_net_refcnt))
  1349. put_net(sock_net(sk));
  1350. sk_prot_free(sk->sk_prot_creator, sk);
  1351. }
  1352. void sk_destruct(struct sock *sk)
  1353. {
  1354. bool use_call_rcu = sock_flag(sk, SOCK_RCU_FREE);
  1355. if (rcu_access_pointer(sk->sk_reuseport_cb)) {
  1356. reuseport_detach_sock(sk);
  1357. use_call_rcu = true;
  1358. }
  1359. if (use_call_rcu)
  1360. call_rcu(&sk->sk_rcu, __sk_destruct);
  1361. else
  1362. __sk_destruct(&sk->sk_rcu);
  1363. }
  1364. static void __sk_free(struct sock *sk)
  1365. {
  1366. if (likely(sk->sk_net_refcnt))
  1367. sock_inuse_add(sock_net(sk), -1);
  1368. if (unlikely(sk->sk_net_refcnt && sock_diag_has_destroy_listeners(sk)))
  1369. sock_diag_broadcast_destroy(sk);
  1370. else
  1371. sk_destruct(sk);
  1372. }
  1373. void sk_free(struct sock *sk)
  1374. {
  1375. /*
  1376. * We subtract one from sk_wmem_alloc and can know if
  1377. * some packets are still in some tx queue.
  1378. * If not null, sock_wfree() will call __sk_free(sk) later
  1379. */
  1380. if (refcount_dec_and_test(&sk->sk_wmem_alloc))
  1381. __sk_free(sk);
  1382. }
  1383. EXPORT_SYMBOL(sk_free);
  1384. static void sk_init_common(struct sock *sk)
  1385. {
  1386. skb_queue_head_init(&sk->sk_receive_queue);
  1387. skb_queue_head_init(&sk->sk_write_queue);
  1388. skb_queue_head_init(&sk->sk_error_queue);
  1389. rwlock_init(&sk->sk_callback_lock);
  1390. lockdep_set_class_and_name(&sk->sk_receive_queue.lock,
  1391. af_rlock_keys + sk->sk_family,
  1392. af_family_rlock_key_strings[sk->sk_family]);
  1393. lockdep_set_class_and_name(&sk->sk_write_queue.lock,
  1394. af_wlock_keys + sk->sk_family,
  1395. af_family_wlock_key_strings[sk->sk_family]);
  1396. lockdep_set_class_and_name(&sk->sk_error_queue.lock,
  1397. af_elock_keys + sk->sk_family,
  1398. af_family_elock_key_strings[sk->sk_family]);
  1399. lockdep_set_class_and_name(&sk->sk_callback_lock,
  1400. af_callback_keys + sk->sk_family,
  1401. af_family_clock_key_strings[sk->sk_family]);
  1402. }
  1403. /**
  1404. * sk_clone_lock - clone a socket, and lock its clone
  1405. * @sk: the socket to clone
  1406. * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
  1407. *
  1408. * Caller must unlock socket even in error path (bh_unlock_sock(newsk))
  1409. */
  1410. struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority)
  1411. {
  1412. struct sock *newsk;
  1413. bool is_charged = true;
  1414. newsk = sk_prot_alloc(sk->sk_prot, priority, sk->sk_family);
  1415. if (newsk != NULL) {
  1416. struct sk_filter *filter;
  1417. sock_copy(newsk, sk);
  1418. newsk->sk_prot_creator = sk->sk_prot;
  1419. /* SANITY */
  1420. if (likely(newsk->sk_net_refcnt))
  1421. get_net(sock_net(newsk));
  1422. sk_node_init(&newsk->sk_node);
  1423. sock_lock_init(newsk);
  1424. bh_lock_sock(newsk);
  1425. newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL;
  1426. newsk->sk_backlog.len = 0;
  1427. atomic_set(&newsk->sk_rmem_alloc, 0);
  1428. /*
  1429. * sk_wmem_alloc set to one (see sk_free() and sock_wfree())
  1430. */
  1431. refcount_set(&newsk->sk_wmem_alloc, 1);
  1432. atomic_set(&newsk->sk_omem_alloc, 0);
  1433. sk_init_common(newsk);
  1434. newsk->sk_dst_cache = NULL;
  1435. newsk->sk_dst_pending_confirm = 0;
  1436. newsk->sk_wmem_queued = 0;
  1437. newsk->sk_forward_alloc = 0;
  1438. atomic_set(&newsk->sk_drops, 0);
  1439. newsk->sk_send_head = NULL;
  1440. newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK;
  1441. atomic_set(&newsk->sk_zckey, 0);
  1442. sock_reset_flag(newsk, SOCK_DONE);
  1443. /* sk->sk_memcg will be populated at accept() time */
  1444. newsk->sk_memcg = NULL;
  1445. cgroup_sk_clone(&newsk->sk_cgrp_data);
  1446. rcu_read_lock();
  1447. filter = rcu_dereference(sk->sk_filter);
  1448. if (filter != NULL)
  1449. /* though it's an empty new sock, the charging may fail
  1450. * if sysctl_optmem_max was changed between creation of
  1451. * original socket and cloning
  1452. */
  1453. is_charged = sk_filter_charge(newsk, filter);
  1454. RCU_INIT_POINTER(newsk->sk_filter, filter);
  1455. rcu_read_unlock();
  1456. if (unlikely(!is_charged || xfrm_sk_clone_policy(newsk, sk))) {
  1457. /* We need to make sure that we don't uncharge the new
  1458. * socket if we couldn't charge it in the first place
  1459. * as otherwise we uncharge the parent's filter.
  1460. */
  1461. if (!is_charged)
  1462. RCU_INIT_POINTER(newsk->sk_filter, NULL);
  1463. sk_free_unlock_clone(newsk);
  1464. newsk = NULL;
  1465. goto out;
  1466. }
  1467. RCU_INIT_POINTER(newsk->sk_reuseport_cb, NULL);
  1468. newsk->sk_err = 0;
  1469. newsk->sk_err_soft = 0;
  1470. newsk->sk_priority = 0;
  1471. newsk->sk_incoming_cpu = raw_smp_processor_id();
  1472. atomic64_set(&newsk->sk_cookie, 0);
  1473. if (likely(newsk->sk_net_refcnt))
  1474. sock_inuse_add(sock_net(newsk), 1);
  1475. /*
  1476. * Before updating sk_refcnt, we must commit prior changes to memory
  1477. * (Documentation/RCU/rculist_nulls.txt for details)
  1478. */
  1479. smp_wmb();
  1480. refcount_set(&newsk->sk_refcnt, 2);
  1481. /*
  1482. * Increment the counter in the same struct proto as the master
  1483. * sock (sk_refcnt_debug_inc uses newsk->sk_prot->socks, that
  1484. * is the same as sk->sk_prot->socks, as this field was copied
  1485. * with memcpy).
  1486. *
  1487. * This _changes_ the previous behaviour, where
  1488. * tcp_create_openreq_child always was incrementing the
  1489. * equivalent to tcp_prot->socks (inet_sock_nr), so this have
  1490. * to be taken into account in all callers. -acme
  1491. */
  1492. sk_refcnt_debug_inc(newsk);
  1493. sk_set_socket(newsk, NULL);
  1494. sk_tx_queue_clear(newsk);
  1495. newsk->sk_wq = NULL;
  1496. if (newsk->sk_prot->sockets_allocated)
  1497. sk_sockets_allocated_inc(newsk);
  1498. if (sock_needs_netstamp(sk) &&
  1499. newsk->sk_flags & SK_FLAGS_TIMESTAMP)
  1500. net_enable_timestamp();
  1501. }
  1502. out:
  1503. return newsk;
  1504. }
  1505. EXPORT_SYMBOL_GPL(sk_clone_lock);
  1506. void sk_free_unlock_clone(struct sock *sk)
  1507. {
  1508. /* It is still raw copy of parent, so invalidate
  1509. * destructor and make plain sk_free() */
  1510. sk->sk_destruct = NULL;
  1511. bh_unlock_sock(sk);
  1512. sk_free(sk);
  1513. }
  1514. EXPORT_SYMBOL_GPL(sk_free_unlock_clone);
  1515. void sk_setup_caps(struct sock *sk, struct dst_entry *dst)
  1516. {
  1517. u32 max_segs = 1;
  1518. sk_dst_set(sk, dst);
  1519. sk->sk_route_caps = dst->dev->features | sk->sk_route_forced_caps;
  1520. if (sk->sk_route_caps & NETIF_F_GSO)
  1521. sk->sk_route_caps |= NETIF_F_GSO_SOFTWARE;
  1522. sk->sk_route_caps &= ~sk->sk_route_nocaps;
  1523. if (sk_can_gso(sk)) {
  1524. if (dst->header_len && !xfrm_dst_offload_ok(dst)) {
  1525. sk->sk_route_caps &= ~NETIF_F_GSO_MASK;
  1526. } else {
  1527. sk->sk_route_caps |= NETIF_F_SG | NETIF_F_HW_CSUM;
  1528. sk->sk_gso_max_size = dst->dev->gso_max_size;
  1529. max_segs = max_t(u32, dst->dev->gso_max_segs, 1);
  1530. }
  1531. }
  1532. sk->sk_gso_max_segs = max_segs;
  1533. }
  1534. EXPORT_SYMBOL_GPL(sk_setup_caps);
  1535. /*
  1536. * Simple resource managers for sockets.
  1537. */
  1538. /*
  1539. * Write buffer destructor automatically called from kfree_skb.
  1540. */
  1541. void sock_wfree(struct sk_buff *skb)
  1542. {
  1543. struct sock *sk = skb->sk;
  1544. unsigned int len = skb->truesize;
  1545. if (!sock_flag(sk, SOCK_USE_WRITE_QUEUE)) {
  1546. /*
  1547. * Keep a reference on sk_wmem_alloc, this will be released
  1548. * after sk_write_space() call
  1549. */
  1550. WARN_ON(refcount_sub_and_test(len - 1, &sk->sk_wmem_alloc));
  1551. sk->sk_write_space(sk);
  1552. len = 1;
  1553. }
  1554. /*
  1555. * if sk_wmem_alloc reaches 0, we must finish what sk_free()
  1556. * could not do because of in-flight packets
  1557. */
  1558. if (refcount_sub_and_test(len, &sk->sk_wmem_alloc))
  1559. __sk_free(sk);
  1560. }
  1561. EXPORT_SYMBOL(sock_wfree);
  1562. /* This variant of sock_wfree() is used by TCP,
  1563. * since it sets SOCK_USE_WRITE_QUEUE.
  1564. */
  1565. void __sock_wfree(struct sk_buff *skb)
  1566. {
  1567. struct sock *sk = skb->sk;
  1568. if (refcount_sub_and_test(skb->truesize, &sk->sk_wmem_alloc))
  1569. __sk_free(sk);
  1570. }
  1571. void skb_set_owner_w(struct sk_buff *skb, struct sock *sk)
  1572. {
  1573. skb_orphan(skb);
  1574. skb->sk = sk;
  1575. #ifdef CONFIG_INET
  1576. if (unlikely(!sk_fullsock(sk))) {
  1577. skb->destructor = sock_edemux;
  1578. sock_hold(sk);
  1579. return;
  1580. }
  1581. #endif
  1582. skb->destructor = sock_wfree;
  1583. skb_set_hash_from_sk(skb, sk);
  1584. /*
  1585. * We used to take a refcount on sk, but following operation
  1586. * is enough to guarantee sk_free() wont free this sock until
  1587. * all in-flight packets are completed
  1588. */
  1589. refcount_add(skb->truesize, &sk->sk_wmem_alloc);
  1590. }
  1591. EXPORT_SYMBOL(skb_set_owner_w);
  1592. /* This helper is used by netem, as it can hold packets in its
  1593. * delay queue. We want to allow the owner socket to send more
  1594. * packets, as if they were already TX completed by a typical driver.
  1595. * But we also want to keep skb->sk set because some packet schedulers
  1596. * rely on it (sch_fq for example).
  1597. */
  1598. void skb_orphan_partial(struct sk_buff *skb)
  1599. {
  1600. if (skb_is_tcp_pure_ack(skb))
  1601. return;
  1602. if (skb->destructor == sock_wfree
  1603. #ifdef CONFIG_INET
  1604. || skb->destructor == tcp_wfree
  1605. #endif
  1606. ) {
  1607. struct sock *sk = skb->sk;
  1608. if (refcount_inc_not_zero(&sk->sk_refcnt)) {
  1609. WARN_ON(refcount_sub_and_test(skb->truesize, &sk->sk_wmem_alloc));
  1610. skb->destructor = sock_efree;
  1611. }
  1612. } else {
  1613. skb_orphan(skb);
  1614. }
  1615. }
  1616. EXPORT_SYMBOL(skb_orphan_partial);
  1617. /*
  1618. * Read buffer destructor automatically called from kfree_skb.
  1619. */
  1620. void sock_rfree(struct sk_buff *skb)
  1621. {
  1622. struct sock *sk = skb->sk;
  1623. unsigned int len = skb->truesize;
  1624. atomic_sub(len, &sk->sk_rmem_alloc);
  1625. sk_mem_uncharge(sk, len);
  1626. }
  1627. EXPORT_SYMBOL(sock_rfree);
  1628. /*
  1629. * Buffer destructor for skbs that are not used directly in read or write
  1630. * path, e.g. for error handler skbs. Automatically called from kfree_skb.
  1631. */
  1632. void sock_efree(struct sk_buff *skb)
  1633. {
  1634. sock_put(skb->sk);
  1635. }
  1636. EXPORT_SYMBOL(sock_efree);
  1637. kuid_t sock_i_uid(struct sock *sk)
  1638. {
  1639. kuid_t uid;
  1640. read_lock_bh(&sk->sk_callback_lock);
  1641. uid = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_uid : GLOBAL_ROOT_UID;
  1642. read_unlock_bh(&sk->sk_callback_lock);
  1643. return uid;
  1644. }
  1645. EXPORT_SYMBOL(sock_i_uid);
  1646. unsigned long sock_i_ino(struct sock *sk)
  1647. {
  1648. unsigned long ino;
  1649. read_lock_bh(&sk->sk_callback_lock);
  1650. ino = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_ino : 0;
  1651. read_unlock_bh(&sk->sk_callback_lock);
  1652. return ino;
  1653. }
  1654. EXPORT_SYMBOL(sock_i_ino);
  1655. /*
  1656. * Allocate a skb from the socket's send buffer.
  1657. */
  1658. struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force,
  1659. gfp_t priority)
  1660. {
  1661. if (force || refcount_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) {
  1662. struct sk_buff *skb = alloc_skb(size, priority);
  1663. if (skb) {
  1664. skb_set_owner_w(skb, sk);
  1665. return skb;
  1666. }
  1667. }
  1668. return NULL;
  1669. }
  1670. EXPORT_SYMBOL(sock_wmalloc);
  1671. static void sock_ofree(struct sk_buff *skb)
  1672. {
  1673. struct sock *sk = skb->sk;
  1674. atomic_sub(skb->truesize, &sk->sk_omem_alloc);
  1675. }
  1676. struct sk_buff *sock_omalloc(struct sock *sk, unsigned long size,
  1677. gfp_t priority)
  1678. {
  1679. struct sk_buff *skb;
  1680. /* small safe race: SKB_TRUESIZE may differ from final skb->truesize */
  1681. if (atomic_read(&sk->sk_omem_alloc) + SKB_TRUESIZE(size) >
  1682. sysctl_optmem_max)
  1683. return NULL;
  1684. skb = alloc_skb(size, priority);
  1685. if (!skb)
  1686. return NULL;
  1687. atomic_add(skb->truesize, &sk->sk_omem_alloc);
  1688. skb->sk = sk;
  1689. skb->destructor = sock_ofree;
  1690. return skb;
  1691. }
  1692. /*
  1693. * Allocate a memory block from the socket's option memory buffer.
  1694. */
  1695. void *sock_kmalloc(struct sock *sk, int size, gfp_t priority)
  1696. {
  1697. if ((unsigned int)size <= sysctl_optmem_max &&
  1698. atomic_read(&sk->sk_omem_alloc) + size < sysctl_optmem_max) {
  1699. void *mem;
  1700. /* First do the add, to avoid the race if kmalloc
  1701. * might sleep.
  1702. */
  1703. atomic_add(size, &sk->sk_omem_alloc);
  1704. mem = kmalloc(size, priority);
  1705. if (mem)
  1706. return mem;
  1707. atomic_sub(size, &sk->sk_omem_alloc);
  1708. }
  1709. return NULL;
  1710. }
  1711. EXPORT_SYMBOL(sock_kmalloc);
  1712. /* Free an option memory block. Note, we actually want the inline
  1713. * here as this allows gcc to detect the nullify and fold away the
  1714. * condition entirely.
  1715. */
  1716. static inline void __sock_kfree_s(struct sock *sk, void *mem, int size,
  1717. const bool nullify)
  1718. {
  1719. if (WARN_ON_ONCE(!mem))
  1720. return;
  1721. if (nullify)
  1722. kzfree(mem);
  1723. else
  1724. kfree(mem);
  1725. atomic_sub(size, &sk->sk_omem_alloc);
  1726. }
  1727. void sock_kfree_s(struct sock *sk, void *mem, int size)
  1728. {
  1729. __sock_kfree_s(sk, mem, size, false);
  1730. }
  1731. EXPORT_SYMBOL(sock_kfree_s);
  1732. void sock_kzfree_s(struct sock *sk, void *mem, int size)
  1733. {
  1734. __sock_kfree_s(sk, mem, size, true);
  1735. }
  1736. EXPORT_SYMBOL(sock_kzfree_s);
  1737. /* It is almost wait_for_tcp_memory minus release_sock/lock_sock.
  1738. I think, these locks should be removed for datagram sockets.
  1739. */
  1740. static long sock_wait_for_wmem(struct sock *sk, long timeo)
  1741. {
  1742. DEFINE_WAIT(wait);
  1743. sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
  1744. for (;;) {
  1745. if (!timeo)
  1746. break;
  1747. if (signal_pending(current))
  1748. break;
  1749. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  1750. prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
  1751. if (refcount_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf)
  1752. break;
  1753. if (sk->sk_shutdown & SEND_SHUTDOWN)
  1754. break;
  1755. if (sk->sk_err)
  1756. break;
  1757. timeo = schedule_timeout(timeo);
  1758. }
  1759. finish_wait(sk_sleep(sk), &wait);
  1760. return timeo;
  1761. }
  1762. /*
  1763. * Generic send/receive buffer handlers
  1764. */
  1765. struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
  1766. unsigned long data_len, int noblock,
  1767. int *errcode, int max_page_order)
  1768. {
  1769. struct sk_buff *skb;
  1770. long timeo;
  1771. int err;
  1772. timeo = sock_sndtimeo(sk, noblock);
  1773. for (;;) {
  1774. err = sock_error(sk);
  1775. if (err != 0)
  1776. goto failure;
  1777. err = -EPIPE;
  1778. if (sk->sk_shutdown & SEND_SHUTDOWN)
  1779. goto failure;
  1780. if (sk_wmem_alloc_get(sk) < sk->sk_sndbuf)
  1781. break;
  1782. sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
  1783. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  1784. err = -EAGAIN;
  1785. if (!timeo)
  1786. goto failure;
  1787. if (signal_pending(current))
  1788. goto interrupted;
  1789. timeo = sock_wait_for_wmem(sk, timeo);
  1790. }
  1791. skb = alloc_skb_with_frags(header_len, data_len, max_page_order,
  1792. errcode, sk->sk_allocation);
  1793. if (skb)
  1794. skb_set_owner_w(skb, sk);
  1795. return skb;
  1796. interrupted:
  1797. err = sock_intr_errno(timeo);
  1798. failure:
  1799. *errcode = err;
  1800. return NULL;
  1801. }
  1802. EXPORT_SYMBOL(sock_alloc_send_pskb);
  1803. struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size,
  1804. int noblock, int *errcode)
  1805. {
  1806. return sock_alloc_send_pskb(sk, size, 0, noblock, errcode, 0);
  1807. }
  1808. EXPORT_SYMBOL(sock_alloc_send_skb);
  1809. int __sock_cmsg_send(struct sock *sk, struct msghdr *msg, struct cmsghdr *cmsg,
  1810. struct sockcm_cookie *sockc)
  1811. {
  1812. u32 tsflags;
  1813. switch (cmsg->cmsg_type) {
  1814. case SO_MARK:
  1815. if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
  1816. return -EPERM;
  1817. if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32)))
  1818. return -EINVAL;
  1819. sockc->mark = *(u32 *)CMSG_DATA(cmsg);
  1820. break;
  1821. case SO_TIMESTAMPING:
  1822. if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32)))
  1823. return -EINVAL;
  1824. tsflags = *(u32 *)CMSG_DATA(cmsg);
  1825. if (tsflags & ~SOF_TIMESTAMPING_TX_RECORD_MASK)
  1826. return -EINVAL;
  1827. sockc->tsflags &= ~SOF_TIMESTAMPING_TX_RECORD_MASK;
  1828. sockc->tsflags |= tsflags;
  1829. break;
  1830. case SCM_TXTIME:
  1831. if (!sock_flag(sk, SOCK_TXTIME))
  1832. return -EINVAL;
  1833. if (cmsg->cmsg_len != CMSG_LEN(sizeof(u64)))
  1834. return -EINVAL;
  1835. sockc->transmit_time = get_unaligned((u64 *)CMSG_DATA(cmsg));
  1836. break;
  1837. /* SCM_RIGHTS and SCM_CREDENTIALS are semantically in SOL_UNIX. */
  1838. case SCM_RIGHTS:
  1839. case SCM_CREDENTIALS:
  1840. break;
  1841. default:
  1842. return -EINVAL;
  1843. }
  1844. return 0;
  1845. }
  1846. EXPORT_SYMBOL(__sock_cmsg_send);
  1847. int sock_cmsg_send(struct sock *sk, struct msghdr *msg,
  1848. struct sockcm_cookie *sockc)
  1849. {
  1850. struct cmsghdr *cmsg;
  1851. int ret;
  1852. for_each_cmsghdr(cmsg, msg) {
  1853. if (!CMSG_OK(msg, cmsg))
  1854. return -EINVAL;
  1855. if (cmsg->cmsg_level != SOL_SOCKET)
  1856. continue;
  1857. ret = __sock_cmsg_send(sk, msg, cmsg, sockc);
  1858. if (ret)
  1859. return ret;
  1860. }
  1861. return 0;
  1862. }
  1863. EXPORT_SYMBOL(sock_cmsg_send);
  1864. static void sk_enter_memory_pressure(struct sock *sk)
  1865. {
  1866. if (!sk->sk_prot->enter_memory_pressure)
  1867. return;
  1868. sk->sk_prot->enter_memory_pressure(sk);
  1869. }
  1870. static void sk_leave_memory_pressure(struct sock *sk)
  1871. {
  1872. if (sk->sk_prot->leave_memory_pressure) {
  1873. sk->sk_prot->leave_memory_pressure(sk);
  1874. } else {
  1875. unsigned long *memory_pressure = sk->sk_prot->memory_pressure;
  1876. if (memory_pressure && READ_ONCE(*memory_pressure))
  1877. WRITE_ONCE(*memory_pressure, 0);
  1878. }
  1879. }
  1880. /* On 32bit arches, an skb frag is limited to 2^15 */
  1881. #define SKB_FRAG_PAGE_ORDER get_order(32768)
  1882. /**
  1883. * skb_page_frag_refill - check that a page_frag contains enough room
  1884. * @sz: minimum size of the fragment we want to get
  1885. * @pfrag: pointer to page_frag
  1886. * @gfp: priority for memory allocation
  1887. *
  1888. * Note: While this allocator tries to use high order pages, there is
  1889. * no guarantee that allocations succeed. Therefore, @sz MUST be
  1890. * less or equal than PAGE_SIZE.
  1891. */
  1892. bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp)
  1893. {
  1894. if (pfrag->page) {
  1895. if (page_ref_count(pfrag->page) == 1) {
  1896. pfrag->offset = 0;
  1897. return true;
  1898. }
  1899. if (pfrag->offset + sz <= pfrag->size)
  1900. return true;
  1901. put_page(pfrag->page);
  1902. }
  1903. pfrag->offset = 0;
  1904. if (SKB_FRAG_PAGE_ORDER) {
  1905. /* Avoid direct reclaim but allow kswapd to wake */
  1906. pfrag->page = alloc_pages((gfp & ~__GFP_DIRECT_RECLAIM) |
  1907. __GFP_COMP | __GFP_NOWARN |
  1908. __GFP_NORETRY,
  1909. SKB_FRAG_PAGE_ORDER);
  1910. if (likely(pfrag->page)) {
  1911. pfrag->size = PAGE_SIZE << SKB_FRAG_PAGE_ORDER;
  1912. return true;
  1913. }
  1914. }
  1915. pfrag->page = alloc_page(gfp);
  1916. if (likely(pfrag->page)) {
  1917. pfrag->size = PAGE_SIZE;
  1918. return true;
  1919. }
  1920. return false;
  1921. }
  1922. EXPORT_SYMBOL(skb_page_frag_refill);
  1923. bool sk_page_frag_refill(struct sock *sk, struct page_frag *pfrag)
  1924. {
  1925. if (likely(skb_page_frag_refill(32U, pfrag, sk->sk_allocation)))
  1926. return true;
  1927. sk_enter_memory_pressure(sk);
  1928. sk_stream_moderate_sndbuf(sk);
  1929. return false;
  1930. }
  1931. EXPORT_SYMBOL(sk_page_frag_refill);
  1932. int sk_alloc_sg(struct sock *sk, int len, struct scatterlist *sg,
  1933. int sg_start, int *sg_curr_index, unsigned int *sg_curr_size,
  1934. int first_coalesce)
  1935. {
  1936. int sg_curr = *sg_curr_index, use = 0, rc = 0;
  1937. unsigned int size = *sg_curr_size;
  1938. struct page_frag *pfrag;
  1939. struct scatterlist *sge;
  1940. len -= size;
  1941. pfrag = sk_page_frag(sk);
  1942. while (len > 0) {
  1943. unsigned int orig_offset;
  1944. if (!sk_page_frag_refill(sk, pfrag)) {
  1945. rc = -ENOMEM;
  1946. goto out;
  1947. }
  1948. use = min_t(int, len, pfrag->size - pfrag->offset);
  1949. if (!sk_wmem_schedule(sk, use)) {
  1950. rc = -ENOMEM;
  1951. goto out;
  1952. }
  1953. sk_mem_charge(sk, use);
  1954. size += use;
  1955. orig_offset = pfrag->offset;
  1956. pfrag->offset += use;
  1957. sge = sg + sg_curr - 1;
  1958. if (sg_curr > first_coalesce && sg_page(sge) == pfrag->page &&
  1959. sge->offset + sge->length == orig_offset) {
  1960. sge->length += use;
  1961. } else {
  1962. sge = sg + sg_curr;
  1963. sg_unmark_end(sge);
  1964. sg_set_page(sge, pfrag->page, use, orig_offset);
  1965. get_page(pfrag->page);
  1966. sg_curr++;
  1967. if (sg_curr == MAX_SKB_FRAGS)
  1968. sg_curr = 0;
  1969. if (sg_curr == sg_start) {
  1970. rc = -ENOSPC;
  1971. break;
  1972. }
  1973. }
  1974. len -= use;
  1975. }
  1976. out:
  1977. *sg_curr_size = size;
  1978. *sg_curr_index = sg_curr;
  1979. return rc;
  1980. }
  1981. EXPORT_SYMBOL(sk_alloc_sg);
  1982. static void __lock_sock(struct sock *sk)
  1983. __releases(&sk->sk_lock.slock)
  1984. __acquires(&sk->sk_lock.slock)
  1985. {
  1986. DEFINE_WAIT(wait);
  1987. for (;;) {
  1988. prepare_to_wait_exclusive(&sk->sk_lock.wq, &wait,
  1989. TASK_UNINTERRUPTIBLE);
  1990. spin_unlock_bh(&sk->sk_lock.slock);
  1991. schedule();
  1992. spin_lock_bh(&sk->sk_lock.slock);
  1993. if (!sock_owned_by_user(sk))
  1994. break;
  1995. }
  1996. finish_wait(&sk->sk_lock.wq, &wait);
  1997. }
  1998. void __release_sock(struct sock *sk)
  1999. __releases(&sk->sk_lock.slock)
  2000. __acquires(&sk->sk_lock.slock)
  2001. {
  2002. struct sk_buff *skb, *next;
  2003. while ((skb = sk->sk_backlog.head) != NULL) {
  2004. sk->sk_backlog.head = sk->sk_backlog.tail = NULL;
  2005. spin_unlock_bh(&sk->sk_lock.slock);
  2006. do {
  2007. next = skb->next;
  2008. prefetch(next);
  2009. WARN_ON_ONCE(skb_dst_is_noref(skb));
  2010. skb->next = NULL;
  2011. sk_backlog_rcv(sk, skb);
  2012. cond_resched();
  2013. skb = next;
  2014. } while (skb != NULL);
  2015. spin_lock_bh(&sk->sk_lock.slock);
  2016. }
  2017. /*
  2018. * Doing the zeroing here guarantee we can not loop forever
  2019. * while a wild producer attempts to flood us.
  2020. */
  2021. sk->sk_backlog.len = 0;
  2022. }
  2023. void __sk_flush_backlog(struct sock *sk)
  2024. {
  2025. spin_lock_bh(&sk->sk_lock.slock);
  2026. __release_sock(sk);
  2027. spin_unlock_bh(&sk->sk_lock.slock);
  2028. }
  2029. /**
  2030. * sk_wait_data - wait for data to arrive at sk_receive_queue
  2031. * @sk: sock to wait on
  2032. * @timeo: for how long
  2033. * @skb: last skb seen on sk_receive_queue
  2034. *
  2035. * Now socket state including sk->sk_err is changed only under lock,
  2036. * hence we may omit checks after joining wait queue.
  2037. * We check receive queue before schedule() only as optimization;
  2038. * it is very likely that release_sock() added new data.
  2039. */
  2040. int sk_wait_data(struct sock *sk, long *timeo, const struct sk_buff *skb)
  2041. {
  2042. DEFINE_WAIT_FUNC(wait, woken_wake_function);
  2043. int rc;
  2044. add_wait_queue(sk_sleep(sk), &wait);
  2045. sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
  2046. rc = sk_wait_event(sk, timeo, skb_peek_tail(&sk->sk_receive_queue) != skb, &wait);
  2047. sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
  2048. remove_wait_queue(sk_sleep(sk), &wait);
  2049. return rc;
  2050. }
  2051. EXPORT_SYMBOL(sk_wait_data);
  2052. /**
  2053. * __sk_mem_raise_allocated - increase memory_allocated
  2054. * @sk: socket
  2055. * @size: memory size to allocate
  2056. * @amt: pages to allocate
  2057. * @kind: allocation type
  2058. *
  2059. * Similar to __sk_mem_schedule(), but does not update sk_forward_alloc
  2060. */
  2061. int __sk_mem_raise_allocated(struct sock *sk, int size, int amt, int kind)
  2062. {
  2063. struct proto *prot = sk->sk_prot;
  2064. long allocated = sk_memory_allocated_add(sk, amt);
  2065. bool charged = true;
  2066. if (mem_cgroup_sockets_enabled && sk->sk_memcg &&
  2067. !(charged = mem_cgroup_charge_skmem(sk->sk_memcg, amt)))
  2068. goto suppress_allocation;
  2069. /* Under limit. */
  2070. if (allocated <= sk_prot_mem_limits(sk, 0)) {
  2071. sk_leave_memory_pressure(sk);
  2072. return 1;
  2073. }
  2074. /* Under pressure. */
  2075. if (allocated > sk_prot_mem_limits(sk, 1))
  2076. sk_enter_memory_pressure(sk);
  2077. /* Over hard limit. */
  2078. if (allocated > sk_prot_mem_limits(sk, 2))
  2079. goto suppress_allocation;
  2080. /* guarantee minimum buffer size under pressure */
  2081. if (kind == SK_MEM_RECV) {
  2082. if (atomic_read(&sk->sk_rmem_alloc) < sk_get_rmem0(sk, prot))
  2083. return 1;
  2084. } else { /* SK_MEM_SEND */
  2085. int wmem0 = sk_get_wmem0(sk, prot);
  2086. if (sk->sk_type == SOCK_STREAM) {
  2087. if (sk->sk_wmem_queued < wmem0)
  2088. return 1;
  2089. } else if (refcount_read(&sk->sk_wmem_alloc) < wmem0) {
  2090. return 1;
  2091. }
  2092. }
  2093. if (sk_has_memory_pressure(sk)) {
  2094. u64 alloc;
  2095. if (!sk_under_memory_pressure(sk))
  2096. return 1;
  2097. alloc = sk_sockets_allocated_read_positive(sk);
  2098. if (sk_prot_mem_limits(sk, 2) > alloc *
  2099. sk_mem_pages(sk->sk_wmem_queued +
  2100. atomic_read(&sk->sk_rmem_alloc) +
  2101. sk->sk_forward_alloc))
  2102. return 1;
  2103. }
  2104. suppress_allocation:
  2105. if (kind == SK_MEM_SEND && sk->sk_type == SOCK_STREAM) {
  2106. sk_stream_moderate_sndbuf(sk);
  2107. /* Fail only if socket is _under_ its sndbuf.
  2108. * In this case we cannot block, so that we have to fail.
  2109. */
  2110. if (sk->sk_wmem_queued + size >= sk->sk_sndbuf)
  2111. return 1;
  2112. }
  2113. if (kind == SK_MEM_SEND || (kind == SK_MEM_RECV && charged))
  2114. trace_sock_exceed_buf_limit(sk, prot, allocated, kind);
  2115. sk_memory_allocated_sub(sk, amt);
  2116. if (mem_cgroup_sockets_enabled && sk->sk_memcg)
  2117. mem_cgroup_uncharge_skmem(sk->sk_memcg, amt);
  2118. return 0;
  2119. }
  2120. EXPORT_SYMBOL(__sk_mem_raise_allocated);
  2121. /**
  2122. * __sk_mem_schedule - increase sk_forward_alloc and memory_allocated
  2123. * @sk: socket
  2124. * @size: memory size to allocate
  2125. * @kind: allocation type
  2126. *
  2127. * If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means
  2128. * rmem allocation. This function assumes that protocols which have
  2129. * memory_pressure use sk_wmem_queued as write buffer accounting.
  2130. */
  2131. int __sk_mem_schedule(struct sock *sk, int size, int kind)
  2132. {
  2133. int ret, amt = sk_mem_pages(size);
  2134. sk->sk_forward_alloc += amt << SK_MEM_QUANTUM_SHIFT;
  2135. ret = __sk_mem_raise_allocated(sk, size, amt, kind);
  2136. if (!ret)
  2137. sk->sk_forward_alloc -= amt << SK_MEM_QUANTUM_SHIFT;
  2138. return ret;
  2139. }
  2140. EXPORT_SYMBOL(__sk_mem_schedule);
  2141. /**
  2142. * __sk_mem_reduce_allocated - reclaim memory_allocated
  2143. * @sk: socket
  2144. * @amount: number of quanta
  2145. *
  2146. * Similar to __sk_mem_reclaim(), but does not update sk_forward_alloc
  2147. */
  2148. void __sk_mem_reduce_allocated(struct sock *sk, int amount)
  2149. {
  2150. sk_memory_allocated_sub(sk, amount);
  2151. if (mem_cgroup_sockets_enabled && sk->sk_memcg)
  2152. mem_cgroup_uncharge_skmem(sk->sk_memcg, amount);
  2153. if (sk_under_memory_pressure(sk) &&
  2154. (sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)))
  2155. sk_leave_memory_pressure(sk);
  2156. }
  2157. EXPORT_SYMBOL(__sk_mem_reduce_allocated);
  2158. /**
  2159. * __sk_mem_reclaim - reclaim sk_forward_alloc and memory_allocated
  2160. * @sk: socket
  2161. * @amount: number of bytes (rounded down to a SK_MEM_QUANTUM multiple)
  2162. */
  2163. void __sk_mem_reclaim(struct sock *sk, int amount)
  2164. {
  2165. amount >>= SK_MEM_QUANTUM_SHIFT;
  2166. sk->sk_forward_alloc -= amount << SK_MEM_QUANTUM_SHIFT;
  2167. __sk_mem_reduce_allocated(sk, amount);
  2168. }
  2169. EXPORT_SYMBOL(__sk_mem_reclaim);
  2170. int sk_set_peek_off(struct sock *sk, int val)
  2171. {
  2172. sk->sk_peek_off = val;
  2173. return 0;
  2174. }
  2175. EXPORT_SYMBOL_GPL(sk_set_peek_off);
  2176. /*
  2177. * Set of default routines for initialising struct proto_ops when
  2178. * the protocol does not support a particular function. In certain
  2179. * cases where it makes no sense for a protocol to have a "do nothing"
  2180. * function, some default processing is provided.
  2181. */
  2182. int sock_no_bind(struct socket *sock, struct sockaddr *saddr, int len)
  2183. {
  2184. return -EOPNOTSUPP;
  2185. }
  2186. EXPORT_SYMBOL(sock_no_bind);
  2187. int sock_no_connect(struct socket *sock, struct sockaddr *saddr,
  2188. int len, int flags)
  2189. {
  2190. return -EOPNOTSUPP;
  2191. }
  2192. EXPORT_SYMBOL(sock_no_connect);
  2193. int sock_no_socketpair(struct socket *sock1, struct socket *sock2)
  2194. {
  2195. return -EOPNOTSUPP;
  2196. }
  2197. EXPORT_SYMBOL(sock_no_socketpair);
  2198. int sock_no_accept(struct socket *sock, struct socket *newsock, int flags,
  2199. bool kern)
  2200. {
  2201. return -EOPNOTSUPP;
  2202. }
  2203. EXPORT_SYMBOL(sock_no_accept);
  2204. int sock_no_getname(struct socket *sock, struct sockaddr *saddr,
  2205. int peer)
  2206. {
  2207. return -EOPNOTSUPP;
  2208. }
  2209. EXPORT_SYMBOL(sock_no_getname);
  2210. int sock_no_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
  2211. {
  2212. return -EOPNOTSUPP;
  2213. }
  2214. EXPORT_SYMBOL(sock_no_ioctl);
  2215. int sock_no_listen(struct socket *sock, int backlog)
  2216. {
  2217. return -EOPNOTSUPP;
  2218. }
  2219. EXPORT_SYMBOL(sock_no_listen);
  2220. int sock_no_shutdown(struct socket *sock, int how)
  2221. {
  2222. return -EOPNOTSUPP;
  2223. }
  2224. EXPORT_SYMBOL(sock_no_shutdown);
  2225. int sock_no_setsockopt(struct socket *sock, int level, int optname,
  2226. char __user *optval, unsigned int optlen)
  2227. {
  2228. return -EOPNOTSUPP;
  2229. }
  2230. EXPORT_SYMBOL(sock_no_setsockopt);
  2231. int sock_no_getsockopt(struct socket *sock, int level, int optname,
  2232. char __user *optval, int __user *optlen)
  2233. {
  2234. return -EOPNOTSUPP;
  2235. }
  2236. EXPORT_SYMBOL(sock_no_getsockopt);
  2237. int sock_no_sendmsg(struct socket *sock, struct msghdr *m, size_t len)
  2238. {
  2239. return -EOPNOTSUPP;
  2240. }
  2241. EXPORT_SYMBOL(sock_no_sendmsg);
  2242. int sock_no_sendmsg_locked(struct sock *sk, struct msghdr *m, size_t len)
  2243. {
  2244. return -EOPNOTSUPP;
  2245. }
  2246. EXPORT_SYMBOL(sock_no_sendmsg_locked);
  2247. int sock_no_recvmsg(struct socket *sock, struct msghdr *m, size_t len,
  2248. int flags)
  2249. {
  2250. return -EOPNOTSUPP;
  2251. }
  2252. EXPORT_SYMBOL(sock_no_recvmsg);
  2253. int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma)
  2254. {
  2255. /* Mirror missing mmap method error code */
  2256. return -ENODEV;
  2257. }
  2258. EXPORT_SYMBOL(sock_no_mmap);
  2259. /*
  2260. * When a file is received (via SCM_RIGHTS, etc), we must bump the
  2261. * various sock-based usage counts.
  2262. */
  2263. void __receive_sock(struct file *file)
  2264. {
  2265. struct socket *sock;
  2266. int error;
  2267. /*
  2268. * The resulting value of "error" is ignored here since we only
  2269. * need to take action when the file is a socket and testing
  2270. * "sock" for NULL is sufficient.
  2271. */
  2272. sock = sock_from_file(file, &error);
  2273. if (sock) {
  2274. sock_update_netprioidx(&sock->sk->sk_cgrp_data);
  2275. sock_update_classid(&sock->sk->sk_cgrp_data);
  2276. }
  2277. }
  2278. ssize_t sock_no_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags)
  2279. {
  2280. ssize_t res;
  2281. struct msghdr msg = {.msg_flags = flags};
  2282. struct kvec iov;
  2283. char *kaddr = kmap(page);
  2284. iov.iov_base = kaddr + offset;
  2285. iov.iov_len = size;
  2286. res = kernel_sendmsg(sock, &msg, &iov, 1, size);
  2287. kunmap(page);
  2288. return res;
  2289. }
  2290. EXPORT_SYMBOL(sock_no_sendpage);
  2291. ssize_t sock_no_sendpage_locked(struct sock *sk, struct page *page,
  2292. int offset, size_t size, int flags)
  2293. {
  2294. ssize_t res;
  2295. struct msghdr msg = {.msg_flags = flags};
  2296. struct kvec iov;
  2297. char *kaddr = kmap(page);
  2298. iov.iov_base = kaddr + offset;
  2299. iov.iov_len = size;
  2300. res = kernel_sendmsg_locked(sk, &msg, &iov, 1, size);
  2301. kunmap(page);
  2302. return res;
  2303. }
  2304. EXPORT_SYMBOL(sock_no_sendpage_locked);
  2305. /*
  2306. * Default Socket Callbacks
  2307. */
  2308. static void sock_def_wakeup(struct sock *sk)
  2309. {
  2310. struct socket_wq *wq;
  2311. rcu_read_lock();
  2312. wq = rcu_dereference(sk->sk_wq);
  2313. if (skwq_has_sleeper(wq))
  2314. wake_up_interruptible_all(&wq->wait);
  2315. rcu_read_unlock();
  2316. }
  2317. static void sock_def_error_report(struct sock *sk)
  2318. {
  2319. struct socket_wq *wq;
  2320. rcu_read_lock();
  2321. wq = rcu_dereference(sk->sk_wq);
  2322. if (skwq_has_sleeper(wq))
  2323. wake_up_interruptible_poll(&wq->wait, EPOLLERR);
  2324. sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR);
  2325. rcu_read_unlock();
  2326. }
  2327. static void sock_def_readable(struct sock *sk)
  2328. {
  2329. struct socket_wq *wq;
  2330. rcu_read_lock();
  2331. wq = rcu_dereference(sk->sk_wq);
  2332. if (skwq_has_sleeper(wq))
  2333. wake_up_interruptible_sync_poll(&wq->wait, EPOLLIN | EPOLLPRI |
  2334. EPOLLRDNORM | EPOLLRDBAND);
  2335. sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
  2336. rcu_read_unlock();
  2337. }
  2338. static void sock_def_write_space(struct sock *sk)
  2339. {
  2340. struct socket_wq *wq;
  2341. rcu_read_lock();
  2342. /* Do not wake up a writer until he can make "significant"
  2343. * progress. --DaveM
  2344. */
  2345. if ((refcount_read(&sk->sk_wmem_alloc) << 1) <= sk->sk_sndbuf) {
  2346. wq = rcu_dereference(sk->sk_wq);
  2347. if (skwq_has_sleeper(wq))
  2348. wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT |
  2349. EPOLLWRNORM | EPOLLWRBAND);
  2350. /* Should agree with poll, otherwise some programs break */
  2351. if (sock_writeable(sk))
  2352. sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
  2353. }
  2354. rcu_read_unlock();
  2355. }
  2356. static void sock_def_destruct(struct sock *sk)
  2357. {
  2358. }
  2359. void sk_send_sigurg(struct sock *sk)
  2360. {
  2361. if (sk->sk_socket && sk->sk_socket->file)
  2362. if (send_sigurg(&sk->sk_socket->file->f_owner))
  2363. sk_wake_async(sk, SOCK_WAKE_URG, POLL_PRI);
  2364. }
  2365. EXPORT_SYMBOL(sk_send_sigurg);
  2366. void sk_reset_timer(struct sock *sk, struct timer_list* timer,
  2367. unsigned long expires)
  2368. {
  2369. if (!mod_timer(timer, expires))
  2370. sock_hold(sk);
  2371. }
  2372. EXPORT_SYMBOL(sk_reset_timer);
  2373. void sk_stop_timer(struct sock *sk, struct timer_list* timer)
  2374. {
  2375. if (del_timer(timer))
  2376. __sock_put(sk);
  2377. }
  2378. EXPORT_SYMBOL(sk_stop_timer);
  2379. void sock_init_data(struct socket *sock, struct sock *sk)
  2380. {
  2381. sk_init_common(sk);
  2382. sk->sk_send_head = NULL;
  2383. timer_setup(&sk->sk_timer, NULL, 0);
  2384. sk->sk_allocation = GFP_KERNEL;
  2385. sk->sk_rcvbuf = sysctl_rmem_default;
  2386. sk->sk_sndbuf = sysctl_wmem_default;
  2387. sk->sk_state = TCP_CLOSE;
  2388. sk_set_socket(sk, sock);
  2389. sock_set_flag(sk, SOCK_ZAPPED);
  2390. if (sock) {
  2391. sk->sk_type = sock->type;
  2392. sk->sk_wq = sock->wq;
  2393. sock->sk = sk;
  2394. sk->sk_uid = SOCK_INODE(sock)->i_uid;
  2395. } else {
  2396. sk->sk_wq = NULL;
  2397. sk->sk_uid = make_kuid(sock_net(sk)->user_ns, 0);
  2398. }
  2399. rwlock_init(&sk->sk_callback_lock);
  2400. if (sk->sk_kern_sock)
  2401. lockdep_set_class_and_name(
  2402. &sk->sk_callback_lock,
  2403. af_kern_callback_keys + sk->sk_family,
  2404. af_family_kern_clock_key_strings[sk->sk_family]);
  2405. else
  2406. lockdep_set_class_and_name(
  2407. &sk->sk_callback_lock,
  2408. af_callback_keys + sk->sk_family,
  2409. af_family_clock_key_strings[sk->sk_family]);
  2410. sk->sk_state_change = sock_def_wakeup;
  2411. sk->sk_data_ready = sock_def_readable;
  2412. sk->sk_write_space = sock_def_write_space;
  2413. sk->sk_error_report = sock_def_error_report;
  2414. sk->sk_destruct = sock_def_destruct;
  2415. sk->sk_frag.page = NULL;
  2416. sk->sk_frag.offset = 0;
  2417. sk->sk_peek_off = -1;
  2418. sk->sk_peer_pid = NULL;
  2419. sk->sk_peer_cred = NULL;
  2420. sk->sk_write_pending = 0;
  2421. sk->sk_rcvlowat = 1;
  2422. sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT;
  2423. sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
  2424. sk->sk_stamp = SK_DEFAULT_STAMP;
  2425. #if BITS_PER_LONG==32
  2426. seqlock_init(&sk->sk_stamp_seq);
  2427. #endif
  2428. atomic_set(&sk->sk_zckey, 0);
  2429. #ifdef CONFIG_NET_RX_BUSY_POLL
  2430. sk->sk_napi_id = 0;
  2431. sk->sk_ll_usec = sysctl_net_busy_read;
  2432. #endif
  2433. sk->sk_max_pacing_rate = ~0U;
  2434. sk->sk_pacing_rate = ~0U;
  2435. sk->sk_pacing_shift = 10;
  2436. sk->sk_incoming_cpu = -1;
  2437. sk_rx_queue_clear(sk);
  2438. /*
  2439. * Before updating sk_refcnt, we must commit prior changes to memory
  2440. * (Documentation/RCU/rculist_nulls.txt for details)
  2441. */
  2442. smp_wmb();
  2443. refcount_set(&sk->sk_refcnt, 1);
  2444. atomic_set(&sk->sk_drops, 0);
  2445. }
  2446. EXPORT_SYMBOL(sock_init_data);
  2447. void lock_sock_nested(struct sock *sk, int subclass)
  2448. {
  2449. might_sleep();
  2450. spin_lock_bh(&sk->sk_lock.slock);
  2451. if (sk->sk_lock.owned)
  2452. __lock_sock(sk);
  2453. sk->sk_lock.owned = 1;
  2454. spin_unlock(&sk->sk_lock.slock);
  2455. /*
  2456. * The sk_lock has mutex_lock() semantics here:
  2457. */
  2458. mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_);
  2459. local_bh_enable();
  2460. }
  2461. EXPORT_SYMBOL(lock_sock_nested);
  2462. void release_sock(struct sock *sk)
  2463. {
  2464. spin_lock_bh(&sk->sk_lock.slock);
  2465. if (sk->sk_backlog.tail)
  2466. __release_sock(sk);
  2467. /* Warning : release_cb() might need to release sk ownership,
  2468. * ie call sock_release_ownership(sk) before us.
  2469. */
  2470. if (sk->sk_prot->release_cb)
  2471. sk->sk_prot->release_cb(sk);
  2472. sock_release_ownership(sk);
  2473. if (waitqueue_active(&sk->sk_lock.wq))
  2474. wake_up(&sk->sk_lock.wq);
  2475. spin_unlock_bh(&sk->sk_lock.slock);
  2476. }
  2477. EXPORT_SYMBOL(release_sock);
  2478. /**
  2479. * lock_sock_fast - fast version of lock_sock
  2480. * @sk: socket
  2481. *
  2482. * This version should be used for very small section, where process wont block
  2483. * return false if fast path is taken:
  2484. *
  2485. * sk_lock.slock locked, owned = 0, BH disabled
  2486. *
  2487. * return true if slow path is taken:
  2488. *
  2489. * sk_lock.slock unlocked, owned = 1, BH enabled
  2490. */
  2491. bool lock_sock_fast(struct sock *sk)
  2492. {
  2493. might_sleep();
  2494. spin_lock_bh(&sk->sk_lock.slock);
  2495. if (!sk->sk_lock.owned)
  2496. /*
  2497. * Note : We must disable BH
  2498. */
  2499. return false;
  2500. __lock_sock(sk);
  2501. sk->sk_lock.owned = 1;
  2502. spin_unlock(&sk->sk_lock.slock);
  2503. /*
  2504. * The sk_lock has mutex_lock() semantics here:
  2505. */
  2506. mutex_acquire(&sk->sk_lock.dep_map, 0, 0, _RET_IP_);
  2507. local_bh_enable();
  2508. return true;
  2509. }
  2510. EXPORT_SYMBOL(lock_sock_fast);
  2511. int sock_get_timestamp(struct sock *sk, struct timeval __user *userstamp)
  2512. {
  2513. struct timeval tv;
  2514. sock_enable_timestamp(sk, SOCK_TIMESTAMP);
  2515. tv = ktime_to_timeval(sock_read_timestamp(sk));
  2516. if (tv.tv_sec == -1)
  2517. return -ENOENT;
  2518. if (tv.tv_sec == 0) {
  2519. ktime_t kt = ktime_get_real();
  2520. sock_write_timestamp(sk, kt);
  2521. tv = ktime_to_timeval(kt);
  2522. }
  2523. return copy_to_user(userstamp, &tv, sizeof(tv)) ? -EFAULT : 0;
  2524. }
  2525. EXPORT_SYMBOL(sock_get_timestamp);
  2526. int sock_get_timestampns(struct sock *sk, struct timespec __user *userstamp)
  2527. {
  2528. struct timespec ts;
  2529. sock_enable_timestamp(sk, SOCK_TIMESTAMP);
  2530. ts = ktime_to_timespec(sock_read_timestamp(sk));
  2531. if (ts.tv_sec == -1)
  2532. return -ENOENT;
  2533. if (ts.tv_sec == 0) {
  2534. ktime_t kt = ktime_get_real();
  2535. sock_write_timestamp(sk, kt);
  2536. ts = ktime_to_timespec(sk->sk_stamp);
  2537. }
  2538. return copy_to_user(userstamp, &ts, sizeof(ts)) ? -EFAULT : 0;
  2539. }
  2540. EXPORT_SYMBOL(sock_get_timestampns);
  2541. void sock_enable_timestamp(struct sock *sk, int flag)
  2542. {
  2543. if (!sock_flag(sk, flag)) {
  2544. unsigned long previous_flags = sk->sk_flags;
  2545. sock_set_flag(sk, flag);
  2546. /*
  2547. * we just set one of the two flags which require net
  2548. * time stamping, but time stamping might have been on
  2549. * already because of the other one
  2550. */
  2551. if (sock_needs_netstamp(sk) &&
  2552. !(previous_flags & SK_FLAGS_TIMESTAMP))
  2553. net_enable_timestamp();
  2554. }
  2555. }
  2556. int sock_recv_errqueue(struct sock *sk, struct msghdr *msg, int len,
  2557. int level, int type)
  2558. {
  2559. struct sock_exterr_skb *serr;
  2560. struct sk_buff *skb;
  2561. int copied, err;
  2562. err = -EAGAIN;
  2563. skb = sock_dequeue_err_skb(sk);
  2564. if (skb == NULL)
  2565. goto out;
  2566. copied = skb->len;
  2567. if (copied > len) {
  2568. msg->msg_flags |= MSG_TRUNC;
  2569. copied = len;
  2570. }
  2571. err = skb_copy_datagram_msg(skb, 0, msg, copied);
  2572. if (err)
  2573. goto out_free_skb;
  2574. sock_recv_timestamp(msg, sk, skb);
  2575. serr = SKB_EXT_ERR(skb);
  2576. put_cmsg(msg, level, type, sizeof(serr->ee), &serr->ee);
  2577. msg->msg_flags |= MSG_ERRQUEUE;
  2578. err = copied;
  2579. out_free_skb:
  2580. kfree_skb(skb);
  2581. out:
  2582. return err;
  2583. }
  2584. EXPORT_SYMBOL(sock_recv_errqueue);
  2585. /*
  2586. * Get a socket option on an socket.
  2587. *
  2588. * FIX: POSIX 1003.1g is very ambiguous here. It states that
  2589. * asynchronous errors should be reported by getsockopt. We assume
  2590. * this means if you specify SO_ERROR (otherwise whats the point of it).
  2591. */
  2592. int sock_common_getsockopt(struct socket *sock, int level, int optname,
  2593. char __user *optval, int __user *optlen)
  2594. {
  2595. struct sock *sk = sock->sk;
  2596. return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen);
  2597. }
  2598. EXPORT_SYMBOL(sock_common_getsockopt);
  2599. #ifdef CONFIG_COMPAT
  2600. int compat_sock_common_getsockopt(struct socket *sock, int level, int optname,
  2601. char __user *optval, int __user *optlen)
  2602. {
  2603. struct sock *sk = sock->sk;
  2604. if (sk->sk_prot->compat_getsockopt != NULL)
  2605. return sk->sk_prot->compat_getsockopt(sk, level, optname,
  2606. optval, optlen);
  2607. return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen);
  2608. }
  2609. EXPORT_SYMBOL(compat_sock_common_getsockopt);
  2610. #endif
  2611. int sock_common_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
  2612. int flags)
  2613. {
  2614. struct sock *sk = sock->sk;
  2615. int addr_len = 0;
  2616. int err;
  2617. err = sk->sk_prot->recvmsg(sk, msg, size, flags & MSG_DONTWAIT,
  2618. flags & ~MSG_DONTWAIT, &addr_len);
  2619. if (err >= 0)
  2620. msg->msg_namelen = addr_len;
  2621. return err;
  2622. }
  2623. EXPORT_SYMBOL(sock_common_recvmsg);
  2624. /*
  2625. * Set socket options on an inet socket.
  2626. */
  2627. int sock_common_setsockopt(struct socket *sock, int level, int optname,
  2628. char __user *optval, unsigned int optlen)
  2629. {
  2630. struct sock *sk = sock->sk;
  2631. return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen);
  2632. }
  2633. EXPORT_SYMBOL(sock_common_setsockopt);
  2634. #ifdef CONFIG_COMPAT
  2635. int compat_sock_common_setsockopt(struct socket *sock, int level, int optname,
  2636. char __user *optval, unsigned int optlen)
  2637. {
  2638. struct sock *sk = sock->sk;
  2639. if (sk->sk_prot->compat_setsockopt != NULL)
  2640. return sk->sk_prot->compat_setsockopt(sk, level, optname,
  2641. optval, optlen);
  2642. return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen);
  2643. }
  2644. EXPORT_SYMBOL(compat_sock_common_setsockopt);
  2645. #endif
  2646. void sk_common_release(struct sock *sk)
  2647. {
  2648. if (sk->sk_prot->destroy)
  2649. sk->sk_prot->destroy(sk);
  2650. /*
  2651. * Observation: when sock_common_release is called, processes have
  2652. * no access to socket. But net still has.
  2653. * Step one, detach it from networking:
  2654. *
  2655. * A. Remove from hash tables.
  2656. */
  2657. sk->sk_prot->unhash(sk);
  2658. /*
  2659. * In this point socket cannot receive new packets, but it is possible
  2660. * that some packets are in flight because some CPU runs receiver and
  2661. * did hash table lookup before we unhashed socket. They will achieve
  2662. * receive queue and will be purged by socket destructor.
  2663. *
  2664. * Also we still have packets pending on receive queue and probably,
  2665. * our own packets waiting in device queues. sock_destroy will drain
  2666. * receive queue, but transmitted packets will delay socket destruction
  2667. * until the last reference will be released.
  2668. */
  2669. sock_orphan(sk);
  2670. xfrm_sk_free_policy(sk);
  2671. sk_refcnt_debug_release(sk);
  2672. sock_put(sk);
  2673. }
  2674. EXPORT_SYMBOL(sk_common_release);
  2675. void sk_get_meminfo(const struct sock *sk, u32 *mem)
  2676. {
  2677. memset(mem, 0, sizeof(*mem) * SK_MEMINFO_VARS);
  2678. mem[SK_MEMINFO_RMEM_ALLOC] = sk_rmem_alloc_get(sk);
  2679. mem[SK_MEMINFO_RCVBUF] = sk->sk_rcvbuf;
  2680. mem[SK_MEMINFO_WMEM_ALLOC] = sk_wmem_alloc_get(sk);
  2681. mem[SK_MEMINFO_SNDBUF] = sk->sk_sndbuf;
  2682. mem[SK_MEMINFO_FWD_ALLOC] = sk->sk_forward_alloc;
  2683. mem[SK_MEMINFO_WMEM_QUEUED] = sk->sk_wmem_queued;
  2684. mem[SK_MEMINFO_OPTMEM] = atomic_read(&sk->sk_omem_alloc);
  2685. mem[SK_MEMINFO_BACKLOG] = sk->sk_backlog.len;
  2686. mem[SK_MEMINFO_DROPS] = atomic_read(&sk->sk_drops);
  2687. }
  2688. #ifdef CONFIG_PROC_FS
  2689. #define PROTO_INUSE_NR 64 /* should be enough for the first time */
  2690. struct prot_inuse {
  2691. int val[PROTO_INUSE_NR];
  2692. };
  2693. static DECLARE_BITMAP(proto_inuse_idx, PROTO_INUSE_NR);
  2694. void sock_prot_inuse_add(struct net *net, struct proto *prot, int val)
  2695. {
  2696. __this_cpu_add(net->core.prot_inuse->val[prot->inuse_idx], val);
  2697. }
  2698. EXPORT_SYMBOL_GPL(sock_prot_inuse_add);
  2699. int sock_prot_inuse_get(struct net *net, struct proto *prot)
  2700. {
  2701. int cpu, idx = prot->inuse_idx;
  2702. int res = 0;
  2703. for_each_possible_cpu(cpu)
  2704. res += per_cpu_ptr(net->core.prot_inuse, cpu)->val[idx];
  2705. return res >= 0 ? res : 0;
  2706. }
  2707. EXPORT_SYMBOL_GPL(sock_prot_inuse_get);
  2708. static void sock_inuse_add(struct net *net, int val)
  2709. {
  2710. this_cpu_add(*net->core.sock_inuse, val);
  2711. }
  2712. int sock_inuse_get(struct net *net)
  2713. {
  2714. int cpu, res = 0;
  2715. for_each_possible_cpu(cpu)
  2716. res += *per_cpu_ptr(net->core.sock_inuse, cpu);
  2717. return res;
  2718. }
  2719. EXPORT_SYMBOL_GPL(sock_inuse_get);
  2720. static int __net_init sock_inuse_init_net(struct net *net)
  2721. {
  2722. net->core.prot_inuse = alloc_percpu(struct prot_inuse);
  2723. if (net->core.prot_inuse == NULL)
  2724. return -ENOMEM;
  2725. net->core.sock_inuse = alloc_percpu(int);
  2726. if (net->core.sock_inuse == NULL)
  2727. goto out;
  2728. return 0;
  2729. out:
  2730. free_percpu(net->core.prot_inuse);
  2731. return -ENOMEM;
  2732. }
  2733. static void __net_exit sock_inuse_exit_net(struct net *net)
  2734. {
  2735. free_percpu(net->core.prot_inuse);
  2736. free_percpu(net->core.sock_inuse);
  2737. }
  2738. static struct pernet_operations net_inuse_ops = {
  2739. .init = sock_inuse_init_net,
  2740. .exit = sock_inuse_exit_net,
  2741. };
  2742. static __init int net_inuse_init(void)
  2743. {
  2744. if (register_pernet_subsys(&net_inuse_ops))
  2745. panic("Cannot initialize net inuse counters");
  2746. return 0;
  2747. }
  2748. core_initcall(net_inuse_init);
  2749. static void assign_proto_idx(struct proto *prot)
  2750. {
  2751. prot->inuse_idx = find_first_zero_bit(proto_inuse_idx, PROTO_INUSE_NR);
  2752. if (unlikely(prot->inuse_idx == PROTO_INUSE_NR - 1)) {
  2753. pr_err("PROTO_INUSE_NR exhausted\n");
  2754. return;
  2755. }
  2756. set_bit(prot->inuse_idx, proto_inuse_idx);
  2757. }
  2758. static void release_proto_idx(struct proto *prot)
  2759. {
  2760. if (prot->inuse_idx != PROTO_INUSE_NR - 1)
  2761. clear_bit(prot->inuse_idx, proto_inuse_idx);
  2762. }
  2763. #else
  2764. static inline void assign_proto_idx(struct proto *prot)
  2765. {
  2766. }
  2767. static inline void release_proto_idx(struct proto *prot)
  2768. {
  2769. }
  2770. static void sock_inuse_add(struct net *net, int val)
  2771. {
  2772. }
  2773. #endif
  2774. static void req_prot_cleanup(struct request_sock_ops *rsk_prot)
  2775. {
  2776. if (!rsk_prot)
  2777. return;
  2778. kfree(rsk_prot->slab_name);
  2779. rsk_prot->slab_name = NULL;
  2780. kmem_cache_destroy(rsk_prot->slab);
  2781. rsk_prot->slab = NULL;
  2782. }
  2783. static int req_prot_init(const struct proto *prot)
  2784. {
  2785. struct request_sock_ops *rsk_prot = prot->rsk_prot;
  2786. if (!rsk_prot)
  2787. return 0;
  2788. rsk_prot->slab_name = kasprintf(GFP_KERNEL, "request_sock_%s",
  2789. prot->name);
  2790. if (!rsk_prot->slab_name)
  2791. return -ENOMEM;
  2792. rsk_prot->slab = kmem_cache_create(rsk_prot->slab_name,
  2793. rsk_prot->obj_size, 0,
  2794. SLAB_ACCOUNT | prot->slab_flags,
  2795. NULL);
  2796. if (!rsk_prot->slab) {
  2797. pr_crit("%s: Can't create request sock SLAB cache!\n",
  2798. prot->name);
  2799. return -ENOMEM;
  2800. }
  2801. return 0;
  2802. }
  2803. int proto_register(struct proto *prot, int alloc_slab)
  2804. {
  2805. if (alloc_slab) {
  2806. prot->slab = kmem_cache_create_usercopy(prot->name,
  2807. prot->obj_size, 0,
  2808. SLAB_HWCACHE_ALIGN | SLAB_ACCOUNT |
  2809. prot->slab_flags,
  2810. prot->useroffset, prot->usersize,
  2811. NULL);
  2812. if (prot->slab == NULL) {
  2813. pr_crit("%s: Can't create sock SLAB cache!\n",
  2814. prot->name);
  2815. goto out;
  2816. }
  2817. if (req_prot_init(prot))
  2818. goto out_free_request_sock_slab;
  2819. if (prot->twsk_prot != NULL) {
  2820. prot->twsk_prot->twsk_slab_name = kasprintf(GFP_KERNEL, "tw_sock_%s", prot->name);
  2821. if (prot->twsk_prot->twsk_slab_name == NULL)
  2822. goto out_free_request_sock_slab;
  2823. prot->twsk_prot->twsk_slab =
  2824. kmem_cache_create(prot->twsk_prot->twsk_slab_name,
  2825. prot->twsk_prot->twsk_obj_size,
  2826. 0,
  2827. SLAB_ACCOUNT |
  2828. prot->slab_flags,
  2829. NULL);
  2830. if (prot->twsk_prot->twsk_slab == NULL)
  2831. goto out_free_timewait_sock_slab_name;
  2832. }
  2833. }
  2834. mutex_lock(&proto_list_mutex);
  2835. list_add(&prot->node, &proto_list);
  2836. assign_proto_idx(prot);
  2837. mutex_unlock(&proto_list_mutex);
  2838. return 0;
  2839. out_free_timewait_sock_slab_name:
  2840. kfree(prot->twsk_prot->twsk_slab_name);
  2841. out_free_request_sock_slab:
  2842. req_prot_cleanup(prot->rsk_prot);
  2843. kmem_cache_destroy(prot->slab);
  2844. prot->slab = NULL;
  2845. out:
  2846. return -ENOBUFS;
  2847. }
  2848. EXPORT_SYMBOL(proto_register);
  2849. void proto_unregister(struct proto *prot)
  2850. {
  2851. mutex_lock(&proto_list_mutex);
  2852. release_proto_idx(prot);
  2853. list_del(&prot->node);
  2854. mutex_unlock(&proto_list_mutex);
  2855. kmem_cache_destroy(prot->slab);
  2856. prot->slab = NULL;
  2857. req_prot_cleanup(prot->rsk_prot);
  2858. if (prot->twsk_prot != NULL && prot->twsk_prot->twsk_slab != NULL) {
  2859. kmem_cache_destroy(prot->twsk_prot->twsk_slab);
  2860. kfree(prot->twsk_prot->twsk_slab_name);
  2861. prot->twsk_prot->twsk_slab = NULL;
  2862. }
  2863. }
  2864. EXPORT_SYMBOL(proto_unregister);
  2865. int sock_load_diag_module(int family, int protocol)
  2866. {
  2867. if (!protocol) {
  2868. if (!sock_is_registered(family))
  2869. return -ENOENT;
  2870. return request_module("net-pf-%d-proto-%d-type-%d", PF_NETLINK,
  2871. NETLINK_SOCK_DIAG, family);
  2872. }
  2873. #ifdef CONFIG_INET
  2874. if (family == AF_INET &&
  2875. protocol != IPPROTO_RAW &&
  2876. !rcu_access_pointer(inet_protos[protocol]))
  2877. return -ENOENT;
  2878. #endif
  2879. return request_module("net-pf-%d-proto-%d-type-%d-%d", PF_NETLINK,
  2880. NETLINK_SOCK_DIAG, family, protocol);
  2881. }
  2882. EXPORT_SYMBOL(sock_load_diag_module);
  2883. #ifdef CONFIG_PROC_FS
  2884. static void *proto_seq_start(struct seq_file *seq, loff_t *pos)
  2885. __acquires(proto_list_mutex)
  2886. {
  2887. mutex_lock(&proto_list_mutex);
  2888. return seq_list_start_head(&proto_list, *pos);
  2889. }
  2890. static void *proto_seq_next(struct seq_file *seq, void *v, loff_t *pos)
  2891. {
  2892. return seq_list_next(v, &proto_list, pos);
  2893. }
  2894. static void proto_seq_stop(struct seq_file *seq, void *v)
  2895. __releases(proto_list_mutex)
  2896. {
  2897. mutex_unlock(&proto_list_mutex);
  2898. }
  2899. static char proto_method_implemented(const void *method)
  2900. {
  2901. return method == NULL ? 'n' : 'y';
  2902. }
  2903. static long sock_prot_memory_allocated(struct proto *proto)
  2904. {
  2905. return proto->memory_allocated != NULL ? proto_memory_allocated(proto) : -1L;
  2906. }
  2907. static char *sock_prot_memory_pressure(struct proto *proto)
  2908. {
  2909. return proto->memory_pressure != NULL ?
  2910. proto_memory_pressure(proto) ? "yes" : "no" : "NI";
  2911. }
  2912. static void proto_seq_printf(struct seq_file *seq, struct proto *proto)
  2913. {
  2914. seq_printf(seq, "%-9s %4u %6d %6ld %-3s %6u %-3s %-10s "
  2915. "%2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c\n",
  2916. proto->name,
  2917. proto->obj_size,
  2918. sock_prot_inuse_get(seq_file_net(seq), proto),
  2919. sock_prot_memory_allocated(proto),
  2920. sock_prot_memory_pressure(proto),
  2921. proto->max_header,
  2922. proto->slab == NULL ? "no" : "yes",
  2923. module_name(proto->owner),
  2924. proto_method_implemented(proto->close),
  2925. proto_method_implemented(proto->connect),
  2926. proto_method_implemented(proto->disconnect),
  2927. proto_method_implemented(proto->accept),
  2928. proto_method_implemented(proto->ioctl),
  2929. proto_method_implemented(proto->init),
  2930. proto_method_implemented(proto->destroy),
  2931. proto_method_implemented(proto->shutdown),
  2932. proto_method_implemented(proto->setsockopt),
  2933. proto_method_implemented(proto->getsockopt),
  2934. proto_method_implemented(proto->sendmsg),
  2935. proto_method_implemented(proto->recvmsg),
  2936. proto_method_implemented(proto->sendpage),
  2937. proto_method_implemented(proto->bind),
  2938. proto_method_implemented(proto->backlog_rcv),
  2939. proto_method_implemented(proto->hash),
  2940. proto_method_implemented(proto->unhash),
  2941. proto_method_implemented(proto->get_port),
  2942. proto_method_implemented(proto->enter_memory_pressure));
  2943. }
  2944. static int proto_seq_show(struct seq_file *seq, void *v)
  2945. {
  2946. if (v == &proto_list)
  2947. seq_printf(seq, "%-9s %-4s %-8s %-6s %-5s %-7s %-4s %-10s %s",
  2948. "protocol",
  2949. "size",
  2950. "sockets",
  2951. "memory",
  2952. "press",
  2953. "maxhdr",
  2954. "slab",
  2955. "module",
  2956. "cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\n");
  2957. else
  2958. proto_seq_printf(seq, list_entry(v, struct proto, node));
  2959. return 0;
  2960. }
  2961. static const struct seq_operations proto_seq_ops = {
  2962. .start = proto_seq_start,
  2963. .next = proto_seq_next,
  2964. .stop = proto_seq_stop,
  2965. .show = proto_seq_show,
  2966. };
  2967. static __net_init int proto_init_net(struct net *net)
  2968. {
  2969. if (!proc_create_net("protocols", 0444, net->proc_net, &proto_seq_ops,
  2970. sizeof(struct seq_net_private)))
  2971. return -ENOMEM;
  2972. return 0;
  2973. }
  2974. static __net_exit void proto_exit_net(struct net *net)
  2975. {
  2976. remove_proc_entry("protocols", net->proc_net);
  2977. }
  2978. static __net_initdata struct pernet_operations proto_net_ops = {
  2979. .init = proto_init_net,
  2980. .exit = proto_exit_net,
  2981. };
  2982. static int __init proto_init(void)
  2983. {
  2984. return register_pernet_subsys(&proto_net_ops);
  2985. }
  2986. subsys_initcall(proto_init);
  2987. #endif /* PROC_FS */
  2988. #ifdef CONFIG_NET_RX_BUSY_POLL
  2989. bool sk_busy_loop_end(void *p, unsigned long start_time)
  2990. {
  2991. struct sock *sk = p;
  2992. return !skb_queue_empty_lockless(&sk->sk_receive_queue) ||
  2993. sk_busy_loop_timeout(sk, start_time);
  2994. }
  2995. EXPORT_SYMBOL(sk_busy_loop_end);
  2996. #endif /* CONFIG_NET_RX_BUSY_POLL */