sock.c 86 KB

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