sock.c 83 KB

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