udp.c 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * INET An implementation of the TCP/IP protocol suite for the LINUX
  4. * operating system. INET is implemented using the BSD Socket
  5. * interface as the means of communication with the user level.
  6. *
  7. * The User Datagram Protocol (UDP).
  8. *
  9. * Authors: Ross Biro
  10. * Fred N. van Kempen, <[email protected]>
  11. * Arnt Gulbrandsen, <[email protected]>
  12. * Alan Cox, <[email protected]>
  13. * Hirokazu Takahashi, <[email protected]>
  14. *
  15. * Fixes:
  16. * Alan Cox : verify_area() calls
  17. * Alan Cox : stopped close while in use off icmp
  18. * messages. Not a fix but a botch that
  19. * for udp at least is 'valid'.
  20. * Alan Cox : Fixed icmp handling properly
  21. * Alan Cox : Correct error for oversized datagrams
  22. * Alan Cox : Tidied select() semantics.
  23. * Alan Cox : udp_err() fixed properly, also now
  24. * select and read wake correctly on errors
  25. * Alan Cox : udp_send verify_area moved to avoid mem leak
  26. * Alan Cox : UDP can count its memory
  27. * Alan Cox : send to an unknown connection causes
  28. * an ECONNREFUSED off the icmp, but
  29. * does NOT close.
  30. * Alan Cox : Switched to new sk_buff handlers. No more backlog!
  31. * Alan Cox : Using generic datagram code. Even smaller and the PEEK
  32. * bug no longer crashes it.
  33. * Fred Van Kempen : Net2e support for sk->broadcast.
  34. * Alan Cox : Uses skb_free_datagram
  35. * Alan Cox : Added get/set sockopt support.
  36. * Alan Cox : Broadcasting without option set returns EACCES.
  37. * Alan Cox : No wakeup calls. Instead we now use the callbacks.
  38. * Alan Cox : Use ip_tos and ip_ttl
  39. * Alan Cox : SNMP Mibs
  40. * Alan Cox : MSG_DONTROUTE, and 0.0.0.0 support.
  41. * Matt Dillon : UDP length checks.
  42. * Alan Cox : Smarter af_inet used properly.
  43. * Alan Cox : Use new kernel side addressing.
  44. * Alan Cox : Incorrect return on truncated datagram receive.
  45. * Arnt Gulbrandsen : New udp_send and stuff
  46. * Alan Cox : Cache last socket
  47. * Alan Cox : Route cache
  48. * Jon Peatfield : Minor efficiency fix to sendto().
  49. * Mike Shaver : RFC1122 checks.
  50. * Alan Cox : Nonblocking error fix.
  51. * Willy Konynenberg : Transparent proxying support.
  52. * Mike McLagan : Routing by source
  53. * David S. Miller : New socket lookup architecture.
  54. * Last socket cache retained as it
  55. * does have a high hit rate.
  56. * Olaf Kirch : Don't linearise iovec on sendmsg.
  57. * Andi Kleen : Some cleanups, cache destination entry
  58. * for connect.
  59. * Vitaly E. Lavrov : Transparent proxy revived after year coma.
  60. * Melvin Smith : Check msg_name not msg_namelen in sendto(),
  61. * return ENOTCONN for unconnected sockets (POSIX)
  62. * Janos Farkas : don't deliver multi/broadcasts to a different
  63. * bound-to-device socket
  64. * Hirokazu Takahashi : HW checksumming for outgoing UDP
  65. * datagrams.
  66. * Hirokazu Takahashi : sendfile() on UDP works now.
  67. * Arnaldo C. Melo : convert /proc/net/udp to seq_file
  68. * YOSHIFUJI Hideaki @USAGI and: Support IPV6_V6ONLY socket option, which
  69. * Alexey Kuznetsov: allow both IPv4 and IPv6 sockets to bind
  70. * a single port at the same time.
  71. * Derek Atkins <[email protected]>: Add Encapulation Support
  72. * James Chapman : Add L2TP encapsulation type.
  73. */
  74. #define pr_fmt(fmt) "UDP: " fmt
  75. #include <linux/bpf-cgroup.h>
  76. #include <linux/uaccess.h>
  77. #include <asm/ioctls.h>
  78. #include <linux/memblock.h>
  79. #include <linux/highmem.h>
  80. #include <linux/types.h>
  81. #include <linux/fcntl.h>
  82. #include <linux/module.h>
  83. #include <linux/socket.h>
  84. #include <linux/sockios.h>
  85. #include <linux/igmp.h>
  86. #include <linux/inetdevice.h>
  87. #include <linux/in.h>
  88. #include <linux/errno.h>
  89. #include <linux/timer.h>
  90. #include <linux/mm.h>
  91. #include <linux/inet.h>
  92. #include <linux/netdevice.h>
  93. #include <linux/slab.h>
  94. #include <net/tcp_states.h>
  95. #include <linux/skbuff.h>
  96. #include <linux/proc_fs.h>
  97. #include <linux/seq_file.h>
  98. #include <net/net_namespace.h>
  99. #include <net/icmp.h>
  100. #include <net/inet_hashtables.h>
  101. #include <net/ip_tunnels.h>
  102. #include <net/route.h>
  103. #include <net/checksum.h>
  104. #include <net/xfrm.h>
  105. #include <trace/events/udp.h>
  106. #include <linux/static_key.h>
  107. #include <linux/btf_ids.h>
  108. #include <trace/events/skb.h>
  109. #include <net/busy_poll.h>
  110. #include "udp_impl.h"
  111. #include <net/sock_reuseport.h>
  112. #include <net/addrconf.h>
  113. #include <net/udp_tunnel.h>
  114. #if IS_ENABLED(CONFIG_IPV6)
  115. #include <net/ipv6_stubs.h>
  116. #endif
  117. struct udp_table udp_table __read_mostly;
  118. EXPORT_SYMBOL(udp_table);
  119. long sysctl_udp_mem[3] __read_mostly;
  120. EXPORT_SYMBOL(sysctl_udp_mem);
  121. atomic_long_t udp_memory_allocated ____cacheline_aligned_in_smp;
  122. EXPORT_SYMBOL(udp_memory_allocated);
  123. DEFINE_PER_CPU(int, udp_memory_per_cpu_fw_alloc);
  124. EXPORT_PER_CPU_SYMBOL_GPL(udp_memory_per_cpu_fw_alloc);
  125. #define MAX_UDP_PORTS 65536
  126. #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN)
  127. static int udp_lib_lport_inuse(struct net *net, __u16 num,
  128. const struct udp_hslot *hslot,
  129. unsigned long *bitmap,
  130. struct sock *sk, unsigned int log)
  131. {
  132. struct sock *sk2;
  133. kuid_t uid = sock_i_uid(sk);
  134. sk_for_each(sk2, &hslot->head) {
  135. if (net_eq(sock_net(sk2), net) &&
  136. sk2 != sk &&
  137. (bitmap || udp_sk(sk2)->udp_port_hash == num) &&
  138. (!sk2->sk_reuse || !sk->sk_reuse) &&
  139. (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
  140. sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
  141. inet_rcv_saddr_equal(sk, sk2, true)) {
  142. if (sk2->sk_reuseport && sk->sk_reuseport &&
  143. !rcu_access_pointer(sk->sk_reuseport_cb) &&
  144. uid_eq(uid, sock_i_uid(sk2))) {
  145. if (!bitmap)
  146. return 0;
  147. } else {
  148. if (!bitmap)
  149. return 1;
  150. __set_bit(udp_sk(sk2)->udp_port_hash >> log,
  151. bitmap);
  152. }
  153. }
  154. }
  155. return 0;
  156. }
  157. /*
  158. * Note: we still hold spinlock of primary hash chain, so no other writer
  159. * can insert/delete a socket with local_port == num
  160. */
  161. static int udp_lib_lport_inuse2(struct net *net, __u16 num,
  162. struct udp_hslot *hslot2,
  163. struct sock *sk)
  164. {
  165. struct sock *sk2;
  166. kuid_t uid = sock_i_uid(sk);
  167. int res = 0;
  168. spin_lock(&hslot2->lock);
  169. udp_portaddr_for_each_entry(sk2, &hslot2->head) {
  170. if (net_eq(sock_net(sk2), net) &&
  171. sk2 != sk &&
  172. (udp_sk(sk2)->udp_port_hash == num) &&
  173. (!sk2->sk_reuse || !sk->sk_reuse) &&
  174. (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
  175. sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
  176. inet_rcv_saddr_equal(sk, sk2, true)) {
  177. if (sk2->sk_reuseport && sk->sk_reuseport &&
  178. !rcu_access_pointer(sk->sk_reuseport_cb) &&
  179. uid_eq(uid, sock_i_uid(sk2))) {
  180. res = 0;
  181. } else {
  182. res = 1;
  183. }
  184. break;
  185. }
  186. }
  187. spin_unlock(&hslot2->lock);
  188. return res;
  189. }
  190. static int udp_reuseport_add_sock(struct sock *sk, struct udp_hslot *hslot)
  191. {
  192. struct net *net = sock_net(sk);
  193. kuid_t uid = sock_i_uid(sk);
  194. struct sock *sk2;
  195. sk_for_each(sk2, &hslot->head) {
  196. if (net_eq(sock_net(sk2), net) &&
  197. sk2 != sk &&
  198. sk2->sk_family == sk->sk_family &&
  199. ipv6_only_sock(sk2) == ipv6_only_sock(sk) &&
  200. (udp_sk(sk2)->udp_port_hash == udp_sk(sk)->udp_port_hash) &&
  201. (sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
  202. sk2->sk_reuseport && uid_eq(uid, sock_i_uid(sk2)) &&
  203. inet_rcv_saddr_equal(sk, sk2, false)) {
  204. return reuseport_add_sock(sk, sk2,
  205. inet_rcv_saddr_any(sk));
  206. }
  207. }
  208. return reuseport_alloc(sk, inet_rcv_saddr_any(sk));
  209. }
  210. /**
  211. * udp_lib_get_port - UDP/-Lite port lookup for IPv4 and IPv6
  212. *
  213. * @sk: socket struct in question
  214. * @snum: port number to look up
  215. * @hash2_nulladdr: AF-dependent hash value in secondary hash chains,
  216. * with NULL address
  217. */
  218. int udp_lib_get_port(struct sock *sk, unsigned short snum,
  219. unsigned int hash2_nulladdr)
  220. {
  221. struct udp_table *udptable = sk->sk_prot->h.udp_table;
  222. struct udp_hslot *hslot, *hslot2;
  223. struct net *net = sock_net(sk);
  224. int error = -EADDRINUSE;
  225. if (!snum) {
  226. DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN);
  227. unsigned short first, last;
  228. int low, high, remaining;
  229. unsigned int rand;
  230. inet_sk_get_local_port_range(sk, &low, &high);
  231. remaining = (high - low) + 1;
  232. rand = get_random_u32();
  233. first = reciprocal_scale(rand, remaining) + low;
  234. /*
  235. * force rand to be an odd multiple of UDP_HTABLE_SIZE
  236. */
  237. rand = (rand | 1) * (udptable->mask + 1);
  238. last = first + udptable->mask + 1;
  239. do {
  240. hslot = udp_hashslot(udptable, net, first);
  241. bitmap_zero(bitmap, PORTS_PER_CHAIN);
  242. spin_lock_bh(&hslot->lock);
  243. udp_lib_lport_inuse(net, snum, hslot, bitmap, sk,
  244. udptable->log);
  245. snum = first;
  246. /*
  247. * Iterate on all possible values of snum for this hash.
  248. * Using steps of an odd multiple of UDP_HTABLE_SIZE
  249. * give us randomization and full range coverage.
  250. */
  251. do {
  252. if (low <= snum && snum <= high &&
  253. !test_bit(snum >> udptable->log, bitmap) &&
  254. !inet_is_local_reserved_port(net, snum))
  255. goto found;
  256. snum += rand;
  257. } while (snum != first);
  258. spin_unlock_bh(&hslot->lock);
  259. cond_resched();
  260. } while (++first != last);
  261. goto fail;
  262. } else {
  263. hslot = udp_hashslot(udptable, net, snum);
  264. spin_lock_bh(&hslot->lock);
  265. if (hslot->count > 10) {
  266. int exist;
  267. unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum;
  268. slot2 &= udptable->mask;
  269. hash2_nulladdr &= udptable->mask;
  270. hslot2 = udp_hashslot2(udptable, slot2);
  271. if (hslot->count < hslot2->count)
  272. goto scan_primary_hash;
  273. exist = udp_lib_lport_inuse2(net, snum, hslot2, sk);
  274. if (!exist && (hash2_nulladdr != slot2)) {
  275. hslot2 = udp_hashslot2(udptable, hash2_nulladdr);
  276. exist = udp_lib_lport_inuse2(net, snum, hslot2,
  277. sk);
  278. }
  279. if (exist)
  280. goto fail_unlock;
  281. else
  282. goto found;
  283. }
  284. scan_primary_hash:
  285. if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk, 0))
  286. goto fail_unlock;
  287. }
  288. found:
  289. inet_sk(sk)->inet_num = snum;
  290. udp_sk(sk)->udp_port_hash = snum;
  291. udp_sk(sk)->udp_portaddr_hash ^= snum;
  292. if (sk_unhashed(sk)) {
  293. if (sk->sk_reuseport &&
  294. udp_reuseport_add_sock(sk, hslot)) {
  295. inet_sk(sk)->inet_num = 0;
  296. udp_sk(sk)->udp_port_hash = 0;
  297. udp_sk(sk)->udp_portaddr_hash ^= snum;
  298. goto fail_unlock;
  299. }
  300. sk_add_node_rcu(sk, &hslot->head);
  301. hslot->count++;
  302. sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
  303. hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
  304. spin_lock(&hslot2->lock);
  305. if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
  306. sk->sk_family == AF_INET6)
  307. hlist_add_tail_rcu(&udp_sk(sk)->udp_portaddr_node,
  308. &hslot2->head);
  309. else
  310. hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
  311. &hslot2->head);
  312. hslot2->count++;
  313. spin_unlock(&hslot2->lock);
  314. }
  315. sock_set_flag(sk, SOCK_RCU_FREE);
  316. error = 0;
  317. fail_unlock:
  318. spin_unlock_bh(&hslot->lock);
  319. fail:
  320. return error;
  321. }
  322. EXPORT_SYMBOL(udp_lib_get_port);
  323. int udp_v4_get_port(struct sock *sk, unsigned short snum)
  324. {
  325. unsigned int hash2_nulladdr =
  326. ipv4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum);
  327. unsigned int hash2_partial =
  328. ipv4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0);
  329. /* precompute partial secondary hash */
  330. udp_sk(sk)->udp_portaddr_hash = hash2_partial;
  331. return udp_lib_get_port(sk, snum, hash2_nulladdr);
  332. }
  333. static int compute_score(struct sock *sk, struct net *net,
  334. __be32 saddr, __be16 sport,
  335. __be32 daddr, unsigned short hnum,
  336. int dif, int sdif)
  337. {
  338. int score;
  339. struct inet_sock *inet;
  340. bool dev_match;
  341. if (!net_eq(sock_net(sk), net) ||
  342. udp_sk(sk)->udp_port_hash != hnum ||
  343. ipv6_only_sock(sk))
  344. return -1;
  345. if (sk->sk_rcv_saddr != daddr)
  346. return -1;
  347. score = (sk->sk_family == PF_INET) ? 2 : 1;
  348. inet = inet_sk(sk);
  349. if (inet->inet_daddr) {
  350. if (inet->inet_daddr != saddr)
  351. return -1;
  352. score += 4;
  353. }
  354. if (inet->inet_dport) {
  355. if (inet->inet_dport != sport)
  356. return -1;
  357. score += 4;
  358. }
  359. dev_match = udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if,
  360. dif, sdif);
  361. if (!dev_match)
  362. return -1;
  363. if (sk->sk_bound_dev_if)
  364. score += 4;
  365. if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id())
  366. score++;
  367. return score;
  368. }
  369. static u32 udp_ehashfn(const struct net *net, const __be32 laddr,
  370. const __u16 lport, const __be32 faddr,
  371. const __be16 fport)
  372. {
  373. static u32 udp_ehash_secret __read_mostly;
  374. net_get_random_once(&udp_ehash_secret, sizeof(udp_ehash_secret));
  375. return __inet_ehashfn(laddr, lport, faddr, fport,
  376. udp_ehash_secret + net_hash_mix(net));
  377. }
  378. static struct sock *lookup_reuseport(struct net *net, struct sock *sk,
  379. struct sk_buff *skb,
  380. __be32 saddr, __be16 sport,
  381. __be32 daddr, unsigned short hnum)
  382. {
  383. struct sock *reuse_sk = NULL;
  384. u32 hash;
  385. if (sk->sk_reuseport && sk->sk_state != TCP_ESTABLISHED) {
  386. hash = udp_ehashfn(net, daddr, hnum, saddr, sport);
  387. reuse_sk = reuseport_select_sock(sk, hash, skb,
  388. sizeof(struct udphdr));
  389. }
  390. return reuse_sk;
  391. }
  392. /* called with rcu_read_lock() */
  393. static struct sock *udp4_lib_lookup2(struct net *net,
  394. __be32 saddr, __be16 sport,
  395. __be32 daddr, unsigned int hnum,
  396. int dif, int sdif,
  397. struct udp_hslot *hslot2,
  398. struct sk_buff *skb)
  399. {
  400. struct sock *sk, *result;
  401. int score, badness;
  402. result = NULL;
  403. badness = 0;
  404. udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
  405. score = compute_score(sk, net, saddr, sport,
  406. daddr, hnum, dif, sdif);
  407. if (score > badness) {
  408. badness = score;
  409. result = lookup_reuseport(net, sk, skb, saddr, sport, daddr, hnum);
  410. if (!result) {
  411. result = sk;
  412. continue;
  413. }
  414. /* Fall back to scoring if group has connections */
  415. if (!reuseport_has_conns(sk))
  416. return result;
  417. /* Reuseport logic returned an error, keep original score. */
  418. if (IS_ERR(result))
  419. continue;
  420. badness = compute_score(result, net, saddr, sport,
  421. daddr, hnum, dif, sdif);
  422. }
  423. }
  424. return result;
  425. }
  426. static struct sock *udp4_lookup_run_bpf(struct net *net,
  427. struct udp_table *udptable,
  428. struct sk_buff *skb,
  429. __be32 saddr, __be16 sport,
  430. __be32 daddr, u16 hnum, const int dif)
  431. {
  432. struct sock *sk, *reuse_sk;
  433. bool no_reuseport;
  434. if (udptable != &udp_table)
  435. return NULL; /* only UDP is supported */
  436. no_reuseport = bpf_sk_lookup_run_v4(net, IPPROTO_UDP, saddr, sport,
  437. daddr, hnum, dif, &sk);
  438. if (no_reuseport || IS_ERR_OR_NULL(sk))
  439. return sk;
  440. reuse_sk = lookup_reuseport(net, sk, skb, saddr, sport, daddr, hnum);
  441. if (reuse_sk)
  442. sk = reuse_sk;
  443. return sk;
  444. }
  445. /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
  446. * harder than this. -DaveM
  447. */
  448. struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr,
  449. __be16 sport, __be32 daddr, __be16 dport, int dif,
  450. int sdif, struct udp_table *udptable, struct sk_buff *skb)
  451. {
  452. unsigned short hnum = ntohs(dport);
  453. unsigned int hash2, slot2;
  454. struct udp_hslot *hslot2;
  455. struct sock *result, *sk;
  456. hash2 = ipv4_portaddr_hash(net, daddr, hnum);
  457. slot2 = hash2 & udptable->mask;
  458. hslot2 = &udptable->hash2[slot2];
  459. /* Lookup connected or non-wildcard socket */
  460. result = udp4_lib_lookup2(net, saddr, sport,
  461. daddr, hnum, dif, sdif,
  462. hslot2, skb);
  463. if (!IS_ERR_OR_NULL(result) && result->sk_state == TCP_ESTABLISHED)
  464. goto done;
  465. /* Lookup redirect from BPF */
  466. if (static_branch_unlikely(&bpf_sk_lookup_enabled)) {
  467. sk = udp4_lookup_run_bpf(net, udptable, skb,
  468. saddr, sport, daddr, hnum, dif);
  469. if (sk) {
  470. result = sk;
  471. goto done;
  472. }
  473. }
  474. /* Got non-wildcard socket or error on first lookup */
  475. if (result)
  476. goto done;
  477. /* Lookup wildcard sockets */
  478. hash2 = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
  479. slot2 = hash2 & udptable->mask;
  480. hslot2 = &udptable->hash2[slot2];
  481. result = udp4_lib_lookup2(net, saddr, sport,
  482. htonl(INADDR_ANY), hnum, dif, sdif,
  483. hslot2, skb);
  484. done:
  485. if (IS_ERR(result))
  486. return NULL;
  487. return result;
  488. }
  489. EXPORT_SYMBOL_GPL(__udp4_lib_lookup);
  490. static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
  491. __be16 sport, __be16 dport,
  492. struct udp_table *udptable)
  493. {
  494. const struct iphdr *iph = ip_hdr(skb);
  495. return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
  496. iph->daddr, dport, inet_iif(skb),
  497. inet_sdif(skb), udptable, skb);
  498. }
  499. struct sock *udp4_lib_lookup_skb(const struct sk_buff *skb,
  500. __be16 sport, __be16 dport)
  501. {
  502. const struct iphdr *iph = ip_hdr(skb);
  503. return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
  504. iph->daddr, dport, inet_iif(skb),
  505. inet_sdif(skb), &udp_table, NULL);
  506. }
  507. /* Must be called under rcu_read_lock().
  508. * Does increment socket refcount.
  509. */
  510. #if IS_ENABLED(CONFIG_NF_TPROXY_IPV4) || IS_ENABLED(CONFIG_NF_SOCKET_IPV4)
  511. struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport,
  512. __be32 daddr, __be16 dport, int dif)
  513. {
  514. struct sock *sk;
  515. sk = __udp4_lib_lookup(net, saddr, sport, daddr, dport,
  516. dif, 0, &udp_table, NULL);
  517. if (sk && !refcount_inc_not_zero(&sk->sk_refcnt))
  518. sk = NULL;
  519. return sk;
  520. }
  521. EXPORT_SYMBOL_GPL(udp4_lib_lookup);
  522. #endif
  523. static inline bool __udp_is_mcast_sock(struct net *net, struct sock *sk,
  524. __be16 loc_port, __be32 loc_addr,
  525. __be16 rmt_port, __be32 rmt_addr,
  526. int dif, int sdif, unsigned short hnum)
  527. {
  528. struct inet_sock *inet = inet_sk(sk);
  529. if (!net_eq(sock_net(sk), net) ||
  530. udp_sk(sk)->udp_port_hash != hnum ||
  531. (inet->inet_daddr && inet->inet_daddr != rmt_addr) ||
  532. (inet->inet_dport != rmt_port && inet->inet_dport) ||
  533. (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) ||
  534. ipv6_only_sock(sk) ||
  535. !udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif))
  536. return false;
  537. if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif, sdif))
  538. return false;
  539. return true;
  540. }
  541. DEFINE_STATIC_KEY_FALSE(udp_encap_needed_key);
  542. void udp_encap_enable(void)
  543. {
  544. static_branch_inc(&udp_encap_needed_key);
  545. }
  546. EXPORT_SYMBOL(udp_encap_enable);
  547. void udp_encap_disable(void)
  548. {
  549. static_branch_dec(&udp_encap_needed_key);
  550. }
  551. EXPORT_SYMBOL(udp_encap_disable);
  552. /* Handler for tunnels with arbitrary destination ports: no socket lookup, go
  553. * through error handlers in encapsulations looking for a match.
  554. */
  555. static int __udp4_lib_err_encap_no_sk(struct sk_buff *skb, u32 info)
  556. {
  557. int i;
  558. for (i = 0; i < MAX_IPTUN_ENCAP_OPS; i++) {
  559. int (*handler)(struct sk_buff *skb, u32 info);
  560. const struct ip_tunnel_encap_ops *encap;
  561. encap = rcu_dereference(iptun_encaps[i]);
  562. if (!encap)
  563. continue;
  564. handler = encap->err_handler;
  565. if (handler && !handler(skb, info))
  566. return 0;
  567. }
  568. return -ENOENT;
  569. }
  570. /* Try to match ICMP errors to UDP tunnels by looking up a socket without
  571. * reversing source and destination port: this will match tunnels that force the
  572. * same destination port on both endpoints (e.g. VXLAN, GENEVE). Note that
  573. * lwtunnels might actually break this assumption by being configured with
  574. * different destination ports on endpoints, in this case we won't be able to
  575. * trace ICMP messages back to them.
  576. *
  577. * If this doesn't match any socket, probe tunnels with arbitrary destination
  578. * ports (e.g. FoU, GUE): there, the receiving socket is useless, as the port
  579. * we've sent packets to won't necessarily match the local destination port.
  580. *
  581. * Then ask the tunnel implementation to match the error against a valid
  582. * association.
  583. *
  584. * Return an error if we can't find a match, the socket if we need further
  585. * processing, zero otherwise.
  586. */
  587. static struct sock *__udp4_lib_err_encap(struct net *net,
  588. const struct iphdr *iph,
  589. struct udphdr *uh,
  590. struct udp_table *udptable,
  591. struct sock *sk,
  592. struct sk_buff *skb, u32 info)
  593. {
  594. int (*lookup)(struct sock *sk, struct sk_buff *skb);
  595. int network_offset, transport_offset;
  596. struct udp_sock *up;
  597. network_offset = skb_network_offset(skb);
  598. transport_offset = skb_transport_offset(skb);
  599. /* Network header needs to point to the outer IPv4 header inside ICMP */
  600. skb_reset_network_header(skb);
  601. /* Transport header needs to point to the UDP header */
  602. skb_set_transport_header(skb, iph->ihl << 2);
  603. if (sk) {
  604. up = udp_sk(sk);
  605. lookup = READ_ONCE(up->encap_err_lookup);
  606. if (lookup && lookup(sk, skb))
  607. sk = NULL;
  608. goto out;
  609. }
  610. sk = __udp4_lib_lookup(net, iph->daddr, uh->source,
  611. iph->saddr, uh->dest, skb->dev->ifindex, 0,
  612. udptable, NULL);
  613. if (sk) {
  614. up = udp_sk(sk);
  615. lookup = READ_ONCE(up->encap_err_lookup);
  616. if (!lookup || lookup(sk, skb))
  617. sk = NULL;
  618. }
  619. out:
  620. if (!sk)
  621. sk = ERR_PTR(__udp4_lib_err_encap_no_sk(skb, info));
  622. skb_set_transport_header(skb, transport_offset);
  623. skb_set_network_header(skb, network_offset);
  624. return sk;
  625. }
  626. /*
  627. * This routine is called by the ICMP module when it gets some
  628. * sort of error condition. If err < 0 then the socket should
  629. * be closed and the error returned to the user. If err > 0
  630. * it's just the icmp type << 8 | icmp code.
  631. * Header points to the ip header of the error packet. We move
  632. * on past this. Then (as it used to claim before adjustment)
  633. * header points to the first 8 bytes of the udp header. We need
  634. * to find the appropriate port.
  635. */
  636. int __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable)
  637. {
  638. struct inet_sock *inet;
  639. const struct iphdr *iph = (const struct iphdr *)skb->data;
  640. struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2));
  641. const int type = icmp_hdr(skb)->type;
  642. const int code = icmp_hdr(skb)->code;
  643. bool tunnel = false;
  644. struct sock *sk;
  645. int harderr;
  646. int err;
  647. struct net *net = dev_net(skb->dev);
  648. sk = __udp4_lib_lookup(net, iph->daddr, uh->dest,
  649. iph->saddr, uh->source, skb->dev->ifindex,
  650. inet_sdif(skb), udptable, NULL);
  651. if (!sk || udp_sk(sk)->encap_type) {
  652. /* No socket for error: try tunnels before discarding */
  653. if (static_branch_unlikely(&udp_encap_needed_key)) {
  654. sk = __udp4_lib_err_encap(net, iph, uh, udptable, sk, skb,
  655. info);
  656. if (!sk)
  657. return 0;
  658. } else
  659. sk = ERR_PTR(-ENOENT);
  660. if (IS_ERR(sk)) {
  661. __ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
  662. return PTR_ERR(sk);
  663. }
  664. tunnel = true;
  665. }
  666. err = 0;
  667. harderr = 0;
  668. inet = inet_sk(sk);
  669. switch (type) {
  670. default:
  671. case ICMP_TIME_EXCEEDED:
  672. err = EHOSTUNREACH;
  673. break;
  674. case ICMP_SOURCE_QUENCH:
  675. goto out;
  676. case ICMP_PARAMETERPROB:
  677. err = EPROTO;
  678. harderr = 1;
  679. break;
  680. case ICMP_DEST_UNREACH:
  681. if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
  682. ipv4_sk_update_pmtu(skb, sk, info);
  683. if (inet->pmtudisc != IP_PMTUDISC_DONT) {
  684. err = EMSGSIZE;
  685. harderr = 1;
  686. break;
  687. }
  688. goto out;
  689. }
  690. err = EHOSTUNREACH;
  691. if (code <= NR_ICMP_UNREACH) {
  692. harderr = icmp_err_convert[code].fatal;
  693. err = icmp_err_convert[code].errno;
  694. }
  695. break;
  696. case ICMP_REDIRECT:
  697. ipv4_sk_redirect(skb, sk);
  698. goto out;
  699. }
  700. /*
  701. * RFC1122: OK. Passes ICMP errors back to application, as per
  702. * 4.1.3.3.
  703. */
  704. if (tunnel) {
  705. /* ...not for tunnels though: we don't have a sending socket */
  706. if (udp_sk(sk)->encap_err_rcv)
  707. udp_sk(sk)->encap_err_rcv(sk, skb, iph->ihl << 2);
  708. goto out;
  709. }
  710. if (!inet->recverr) {
  711. if (!harderr || sk->sk_state != TCP_ESTABLISHED)
  712. goto out;
  713. } else
  714. ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1));
  715. sk->sk_err = err;
  716. sk_error_report(sk);
  717. out:
  718. return 0;
  719. }
  720. int udp_err(struct sk_buff *skb, u32 info)
  721. {
  722. return __udp4_lib_err(skb, info, &udp_table);
  723. }
  724. /*
  725. * Throw away all pending data and cancel the corking. Socket is locked.
  726. */
  727. void udp_flush_pending_frames(struct sock *sk)
  728. {
  729. struct udp_sock *up = udp_sk(sk);
  730. if (up->pending) {
  731. up->len = 0;
  732. up->pending = 0;
  733. ip_flush_pending_frames(sk);
  734. }
  735. }
  736. EXPORT_SYMBOL(udp_flush_pending_frames);
  737. /**
  738. * udp4_hwcsum - handle outgoing HW checksumming
  739. * @skb: sk_buff containing the filled-in UDP header
  740. * (checksum field must be zeroed out)
  741. * @src: source IP address
  742. * @dst: destination IP address
  743. */
  744. void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst)
  745. {
  746. struct udphdr *uh = udp_hdr(skb);
  747. int offset = skb_transport_offset(skb);
  748. int len = skb->len - offset;
  749. int hlen = len;
  750. __wsum csum = 0;
  751. if (!skb_has_frag_list(skb)) {
  752. /*
  753. * Only one fragment on the socket.
  754. */
  755. skb->csum_start = skb_transport_header(skb) - skb->head;
  756. skb->csum_offset = offsetof(struct udphdr, check);
  757. uh->check = ~csum_tcpudp_magic(src, dst, len,
  758. IPPROTO_UDP, 0);
  759. } else {
  760. struct sk_buff *frags;
  761. /*
  762. * HW-checksum won't work as there are two or more
  763. * fragments on the socket so that all csums of sk_buffs
  764. * should be together
  765. */
  766. skb_walk_frags(skb, frags) {
  767. csum = csum_add(csum, frags->csum);
  768. hlen -= frags->len;
  769. }
  770. csum = skb_checksum(skb, offset, hlen, csum);
  771. skb->ip_summed = CHECKSUM_NONE;
  772. uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);
  773. if (uh->check == 0)
  774. uh->check = CSUM_MANGLED_0;
  775. }
  776. }
  777. EXPORT_SYMBOL_GPL(udp4_hwcsum);
  778. /* Function to set UDP checksum for an IPv4 UDP packet. This is intended
  779. * for the simple case like when setting the checksum for a UDP tunnel.
  780. */
  781. void udp_set_csum(bool nocheck, struct sk_buff *skb,
  782. __be32 saddr, __be32 daddr, int len)
  783. {
  784. struct udphdr *uh = udp_hdr(skb);
  785. if (nocheck) {
  786. uh->check = 0;
  787. } else if (skb_is_gso(skb)) {
  788. uh->check = ~udp_v4_check(len, saddr, daddr, 0);
  789. } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
  790. uh->check = 0;
  791. uh->check = udp_v4_check(len, saddr, daddr, lco_csum(skb));
  792. if (uh->check == 0)
  793. uh->check = CSUM_MANGLED_0;
  794. } else {
  795. skb->ip_summed = CHECKSUM_PARTIAL;
  796. skb->csum_start = skb_transport_header(skb) - skb->head;
  797. skb->csum_offset = offsetof(struct udphdr, check);
  798. uh->check = ~udp_v4_check(len, saddr, daddr, 0);
  799. }
  800. }
  801. EXPORT_SYMBOL(udp_set_csum);
  802. static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4,
  803. struct inet_cork *cork)
  804. {
  805. struct sock *sk = skb->sk;
  806. struct inet_sock *inet = inet_sk(sk);
  807. struct udphdr *uh;
  808. int err;
  809. int is_udplite = IS_UDPLITE(sk);
  810. int offset = skb_transport_offset(skb);
  811. int len = skb->len - offset;
  812. int datalen = len - sizeof(*uh);
  813. __wsum csum = 0;
  814. /*
  815. * Create a UDP header
  816. */
  817. uh = udp_hdr(skb);
  818. uh->source = inet->inet_sport;
  819. uh->dest = fl4->fl4_dport;
  820. uh->len = htons(len);
  821. uh->check = 0;
  822. if (cork->gso_size) {
  823. const int hlen = skb_network_header_len(skb) +
  824. sizeof(struct udphdr);
  825. if (hlen + cork->gso_size > cork->fragsize) {
  826. kfree_skb(skb);
  827. return -EINVAL;
  828. }
  829. if (datalen > cork->gso_size * UDP_MAX_SEGMENTS) {
  830. kfree_skb(skb);
  831. return -EINVAL;
  832. }
  833. if (sk->sk_no_check_tx) {
  834. kfree_skb(skb);
  835. return -EINVAL;
  836. }
  837. if (skb->ip_summed != CHECKSUM_PARTIAL || is_udplite ||
  838. dst_xfrm(skb_dst(skb))) {
  839. kfree_skb(skb);
  840. return -EIO;
  841. }
  842. if (datalen > cork->gso_size) {
  843. skb_shinfo(skb)->gso_size = cork->gso_size;
  844. skb_shinfo(skb)->gso_type = SKB_GSO_UDP_L4;
  845. skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(datalen,
  846. cork->gso_size);
  847. }
  848. goto csum_partial;
  849. }
  850. if (is_udplite) /* UDP-Lite */
  851. csum = udplite_csum(skb);
  852. else if (sk->sk_no_check_tx) { /* UDP csum off */
  853. skb->ip_summed = CHECKSUM_NONE;
  854. goto send;
  855. } else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
  856. csum_partial:
  857. udp4_hwcsum(skb, fl4->saddr, fl4->daddr);
  858. goto send;
  859. } else
  860. csum = udp_csum(skb);
  861. /* add protocol-dependent pseudo-header */
  862. uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len,
  863. sk->sk_protocol, csum);
  864. if (uh->check == 0)
  865. uh->check = CSUM_MANGLED_0;
  866. send:
  867. err = ip_send_skb(sock_net(sk), skb);
  868. if (err) {
  869. if (err == -ENOBUFS && !inet->recverr) {
  870. UDP_INC_STATS(sock_net(sk),
  871. UDP_MIB_SNDBUFERRORS, is_udplite);
  872. err = 0;
  873. }
  874. } else
  875. UDP_INC_STATS(sock_net(sk),
  876. UDP_MIB_OUTDATAGRAMS, is_udplite);
  877. return err;
  878. }
  879. /*
  880. * Push out all pending data as one UDP datagram. Socket is locked.
  881. */
  882. int udp_push_pending_frames(struct sock *sk)
  883. {
  884. struct udp_sock *up = udp_sk(sk);
  885. struct inet_sock *inet = inet_sk(sk);
  886. struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
  887. struct sk_buff *skb;
  888. int err = 0;
  889. skb = ip_finish_skb(sk, fl4);
  890. if (!skb)
  891. goto out;
  892. err = udp_send_skb(skb, fl4, &inet->cork.base);
  893. out:
  894. up->len = 0;
  895. up->pending = 0;
  896. return err;
  897. }
  898. EXPORT_SYMBOL(udp_push_pending_frames);
  899. static int __udp_cmsg_send(struct cmsghdr *cmsg, u16 *gso_size)
  900. {
  901. switch (cmsg->cmsg_type) {
  902. case UDP_SEGMENT:
  903. if (cmsg->cmsg_len != CMSG_LEN(sizeof(__u16)))
  904. return -EINVAL;
  905. *gso_size = *(__u16 *)CMSG_DATA(cmsg);
  906. return 0;
  907. default:
  908. return -EINVAL;
  909. }
  910. }
  911. int udp_cmsg_send(struct sock *sk, struct msghdr *msg, u16 *gso_size)
  912. {
  913. struct cmsghdr *cmsg;
  914. bool need_ip = false;
  915. int err;
  916. for_each_cmsghdr(cmsg, msg) {
  917. if (!CMSG_OK(msg, cmsg))
  918. return -EINVAL;
  919. if (cmsg->cmsg_level != SOL_UDP) {
  920. need_ip = true;
  921. continue;
  922. }
  923. err = __udp_cmsg_send(cmsg, gso_size);
  924. if (err)
  925. return err;
  926. }
  927. return need_ip;
  928. }
  929. EXPORT_SYMBOL_GPL(udp_cmsg_send);
  930. int udp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
  931. {
  932. struct inet_sock *inet = inet_sk(sk);
  933. struct udp_sock *up = udp_sk(sk);
  934. DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
  935. struct flowi4 fl4_stack;
  936. struct flowi4 *fl4;
  937. int ulen = len;
  938. struct ipcm_cookie ipc;
  939. struct rtable *rt = NULL;
  940. int free = 0;
  941. int connected = 0;
  942. __be32 daddr, faddr, saddr;
  943. __be16 dport;
  944. u8 tos;
  945. int err, is_udplite = IS_UDPLITE(sk);
  946. int corkreq = READ_ONCE(up->corkflag) || msg->msg_flags&MSG_MORE;
  947. int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
  948. struct sk_buff *skb;
  949. struct ip_options_data opt_copy;
  950. if (len > 0xFFFF)
  951. return -EMSGSIZE;
  952. /*
  953. * Check the flags.
  954. */
  955. if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
  956. return -EOPNOTSUPP;
  957. getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
  958. fl4 = &inet->cork.fl.u.ip4;
  959. if (up->pending) {
  960. /*
  961. * There are pending frames.
  962. * The socket lock must be held while it's corked.
  963. */
  964. lock_sock(sk);
  965. if (likely(up->pending)) {
  966. if (unlikely(up->pending != AF_INET)) {
  967. release_sock(sk);
  968. return -EINVAL;
  969. }
  970. goto do_append_data;
  971. }
  972. release_sock(sk);
  973. }
  974. ulen += sizeof(struct udphdr);
  975. /*
  976. * Get and verify the address.
  977. */
  978. if (usin) {
  979. if (msg->msg_namelen < sizeof(*usin))
  980. return -EINVAL;
  981. if (usin->sin_family != AF_INET) {
  982. if (usin->sin_family != AF_UNSPEC)
  983. return -EAFNOSUPPORT;
  984. }
  985. daddr = usin->sin_addr.s_addr;
  986. dport = usin->sin_port;
  987. if (dport == 0)
  988. return -EINVAL;
  989. } else {
  990. if (sk->sk_state != TCP_ESTABLISHED)
  991. return -EDESTADDRREQ;
  992. daddr = inet->inet_daddr;
  993. dport = inet->inet_dport;
  994. /* Open fast path for connected socket.
  995. Route will not be used, if at least one option is set.
  996. */
  997. connected = 1;
  998. }
  999. ipcm_init_sk(&ipc, inet);
  1000. ipc.gso_size = READ_ONCE(up->gso_size);
  1001. if (msg->msg_controllen) {
  1002. err = udp_cmsg_send(sk, msg, &ipc.gso_size);
  1003. if (err > 0)
  1004. err = ip_cmsg_send(sk, msg, &ipc,
  1005. sk->sk_family == AF_INET6);
  1006. if (unlikely(err < 0)) {
  1007. kfree(ipc.opt);
  1008. return err;
  1009. }
  1010. if (ipc.opt)
  1011. free = 1;
  1012. connected = 0;
  1013. }
  1014. if (!ipc.opt) {
  1015. struct ip_options_rcu *inet_opt;
  1016. rcu_read_lock();
  1017. inet_opt = rcu_dereference(inet->inet_opt);
  1018. if (inet_opt) {
  1019. memcpy(&opt_copy, inet_opt,
  1020. sizeof(*inet_opt) + inet_opt->opt.optlen);
  1021. ipc.opt = &opt_copy.opt;
  1022. }
  1023. rcu_read_unlock();
  1024. }
  1025. if (cgroup_bpf_enabled(CGROUP_UDP4_SENDMSG) && !connected) {
  1026. err = BPF_CGROUP_RUN_PROG_UDP4_SENDMSG_LOCK(sk,
  1027. (struct sockaddr *)usin, &ipc.addr);
  1028. if (err)
  1029. goto out_free;
  1030. if (usin) {
  1031. if (usin->sin_port == 0) {
  1032. /* BPF program set invalid port. Reject it. */
  1033. err = -EINVAL;
  1034. goto out_free;
  1035. }
  1036. daddr = usin->sin_addr.s_addr;
  1037. dport = usin->sin_port;
  1038. }
  1039. }
  1040. saddr = ipc.addr;
  1041. ipc.addr = faddr = daddr;
  1042. if (ipc.opt && ipc.opt->opt.srr) {
  1043. if (!daddr) {
  1044. err = -EINVAL;
  1045. goto out_free;
  1046. }
  1047. faddr = ipc.opt->opt.faddr;
  1048. connected = 0;
  1049. }
  1050. tos = get_rttos(&ipc, inet);
  1051. if (sock_flag(sk, SOCK_LOCALROUTE) ||
  1052. (msg->msg_flags & MSG_DONTROUTE) ||
  1053. (ipc.opt && ipc.opt->opt.is_strictroute)) {
  1054. tos |= RTO_ONLINK;
  1055. connected = 0;
  1056. }
  1057. if (ipv4_is_multicast(daddr)) {
  1058. if (!ipc.oif || netif_index_is_l3_master(sock_net(sk), ipc.oif))
  1059. ipc.oif = inet->mc_index;
  1060. if (!saddr)
  1061. saddr = inet->mc_addr;
  1062. connected = 0;
  1063. } else if (!ipc.oif) {
  1064. ipc.oif = inet->uc_index;
  1065. } else if (ipv4_is_lbcast(daddr) && inet->uc_index) {
  1066. /* oif is set, packet is to local broadcast and
  1067. * uc_index is set. oif is most likely set
  1068. * by sk_bound_dev_if. If uc_index != oif check if the
  1069. * oif is an L3 master and uc_index is an L3 slave.
  1070. * If so, we want to allow the send using the uc_index.
  1071. */
  1072. if (ipc.oif != inet->uc_index &&
  1073. ipc.oif == l3mdev_master_ifindex_by_index(sock_net(sk),
  1074. inet->uc_index)) {
  1075. ipc.oif = inet->uc_index;
  1076. }
  1077. }
  1078. if (connected)
  1079. rt = (struct rtable *)sk_dst_check(sk, 0);
  1080. if (!rt) {
  1081. struct net *net = sock_net(sk);
  1082. __u8 flow_flags = inet_sk_flowi_flags(sk);
  1083. fl4 = &fl4_stack;
  1084. flowi4_init_output(fl4, ipc.oif, ipc.sockc.mark, tos,
  1085. RT_SCOPE_UNIVERSE, sk->sk_protocol,
  1086. flow_flags,
  1087. faddr, saddr, dport, inet->inet_sport,
  1088. sk->sk_uid);
  1089. security_sk_classify_flow(sk, flowi4_to_flowi_common(fl4));
  1090. rt = ip_route_output_flow(net, fl4, sk);
  1091. if (IS_ERR(rt)) {
  1092. err = PTR_ERR(rt);
  1093. rt = NULL;
  1094. if (err == -ENETUNREACH)
  1095. IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
  1096. goto out;
  1097. }
  1098. err = -EACCES;
  1099. if ((rt->rt_flags & RTCF_BROADCAST) &&
  1100. !sock_flag(sk, SOCK_BROADCAST))
  1101. goto out;
  1102. if (connected)
  1103. sk_dst_set(sk, dst_clone(&rt->dst));
  1104. }
  1105. if (msg->msg_flags&MSG_CONFIRM)
  1106. goto do_confirm;
  1107. back_from_confirm:
  1108. saddr = fl4->saddr;
  1109. if (!ipc.addr)
  1110. daddr = ipc.addr = fl4->daddr;
  1111. /* Lockless fast path for the non-corking case. */
  1112. if (!corkreq) {
  1113. struct inet_cork cork;
  1114. skb = ip_make_skb(sk, fl4, getfrag, msg, ulen,
  1115. sizeof(struct udphdr), &ipc, &rt,
  1116. &cork, msg->msg_flags);
  1117. err = PTR_ERR(skb);
  1118. if (!IS_ERR_OR_NULL(skb))
  1119. err = udp_send_skb(skb, fl4, &cork);
  1120. goto out;
  1121. }
  1122. lock_sock(sk);
  1123. if (unlikely(up->pending)) {
  1124. /* The socket is already corked while preparing it. */
  1125. /* ... which is an evident application bug. --ANK */
  1126. release_sock(sk);
  1127. net_dbg_ratelimited("socket already corked\n");
  1128. err = -EINVAL;
  1129. goto out;
  1130. }
  1131. /*
  1132. * Now cork the socket to pend data.
  1133. */
  1134. fl4 = &inet->cork.fl.u.ip4;
  1135. fl4->daddr = daddr;
  1136. fl4->saddr = saddr;
  1137. fl4->fl4_dport = dport;
  1138. fl4->fl4_sport = inet->inet_sport;
  1139. up->pending = AF_INET;
  1140. do_append_data:
  1141. up->len += ulen;
  1142. err = ip_append_data(sk, fl4, getfrag, msg, ulen,
  1143. sizeof(struct udphdr), &ipc, &rt,
  1144. corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
  1145. if (err)
  1146. udp_flush_pending_frames(sk);
  1147. else if (!corkreq)
  1148. err = udp_push_pending_frames(sk);
  1149. else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
  1150. up->pending = 0;
  1151. release_sock(sk);
  1152. out:
  1153. ip_rt_put(rt);
  1154. out_free:
  1155. if (free)
  1156. kfree(ipc.opt);
  1157. if (!err)
  1158. return len;
  1159. /*
  1160. * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting
  1161. * ENOBUFS might not be good (it's not tunable per se), but otherwise
  1162. * we don't have a good statistic (IpOutDiscards but it can be too many
  1163. * things). We could add another new stat but at least for now that
  1164. * seems like overkill.
  1165. */
  1166. if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
  1167. UDP_INC_STATS(sock_net(sk),
  1168. UDP_MIB_SNDBUFERRORS, is_udplite);
  1169. }
  1170. return err;
  1171. do_confirm:
  1172. if (msg->msg_flags & MSG_PROBE)
  1173. dst_confirm_neigh(&rt->dst, &fl4->daddr);
  1174. if (!(msg->msg_flags&MSG_PROBE) || len)
  1175. goto back_from_confirm;
  1176. err = 0;
  1177. goto out;
  1178. }
  1179. EXPORT_SYMBOL(udp_sendmsg);
  1180. int udp_sendpage(struct sock *sk, struct page *page, int offset,
  1181. size_t size, int flags)
  1182. {
  1183. struct inet_sock *inet = inet_sk(sk);
  1184. struct udp_sock *up = udp_sk(sk);
  1185. int ret;
  1186. if (flags & MSG_SENDPAGE_NOTLAST)
  1187. flags |= MSG_MORE;
  1188. if (!up->pending) {
  1189. struct msghdr msg = { .msg_flags = flags|MSG_MORE };
  1190. /* Call udp_sendmsg to specify destination address which
  1191. * sendpage interface can't pass.
  1192. * This will succeed only when the socket is connected.
  1193. */
  1194. ret = udp_sendmsg(sk, &msg, 0);
  1195. if (ret < 0)
  1196. return ret;
  1197. }
  1198. lock_sock(sk);
  1199. if (unlikely(!up->pending)) {
  1200. release_sock(sk);
  1201. net_dbg_ratelimited("cork failed\n");
  1202. return -EINVAL;
  1203. }
  1204. ret = ip_append_page(sk, &inet->cork.fl.u.ip4,
  1205. page, offset, size, flags);
  1206. if (ret == -EOPNOTSUPP) {
  1207. release_sock(sk);
  1208. return sock_no_sendpage(sk->sk_socket, page, offset,
  1209. size, flags);
  1210. }
  1211. if (ret < 0) {
  1212. udp_flush_pending_frames(sk);
  1213. goto out;
  1214. }
  1215. up->len += size;
  1216. if (!(READ_ONCE(up->corkflag) || (flags&MSG_MORE)))
  1217. ret = udp_push_pending_frames(sk);
  1218. if (!ret)
  1219. ret = size;
  1220. out:
  1221. release_sock(sk);
  1222. return ret;
  1223. }
  1224. #define UDP_SKB_IS_STATELESS 0x80000000
  1225. /* all head states (dst, sk, nf conntrack) except skb extensions are
  1226. * cleared by udp_rcv().
  1227. *
  1228. * We need to preserve secpath, if present, to eventually process
  1229. * IP_CMSG_PASSSEC at recvmsg() time.
  1230. *
  1231. * Other extensions can be cleared.
  1232. */
  1233. static bool udp_try_make_stateless(struct sk_buff *skb)
  1234. {
  1235. if (!skb_has_extensions(skb))
  1236. return true;
  1237. if (!secpath_exists(skb)) {
  1238. skb_ext_reset(skb);
  1239. return true;
  1240. }
  1241. return false;
  1242. }
  1243. static void udp_set_dev_scratch(struct sk_buff *skb)
  1244. {
  1245. struct udp_dev_scratch *scratch = udp_skb_scratch(skb);
  1246. BUILD_BUG_ON(sizeof(struct udp_dev_scratch) > sizeof(long));
  1247. scratch->_tsize_state = skb->truesize;
  1248. #if BITS_PER_LONG == 64
  1249. scratch->len = skb->len;
  1250. scratch->csum_unnecessary = !!skb_csum_unnecessary(skb);
  1251. scratch->is_linear = !skb_is_nonlinear(skb);
  1252. #endif
  1253. if (udp_try_make_stateless(skb))
  1254. scratch->_tsize_state |= UDP_SKB_IS_STATELESS;
  1255. }
  1256. static void udp_skb_csum_unnecessary_set(struct sk_buff *skb)
  1257. {
  1258. /* We come here after udp_lib_checksum_complete() returned 0.
  1259. * This means that __skb_checksum_complete() might have
  1260. * set skb->csum_valid to 1.
  1261. * On 64bit platforms, we can set csum_unnecessary
  1262. * to true, but only if the skb is not shared.
  1263. */
  1264. #if BITS_PER_LONG == 64
  1265. if (!skb_shared(skb))
  1266. udp_skb_scratch(skb)->csum_unnecessary = true;
  1267. #endif
  1268. }
  1269. static int udp_skb_truesize(struct sk_buff *skb)
  1270. {
  1271. return udp_skb_scratch(skb)->_tsize_state & ~UDP_SKB_IS_STATELESS;
  1272. }
  1273. static bool udp_skb_has_head_state(struct sk_buff *skb)
  1274. {
  1275. return !(udp_skb_scratch(skb)->_tsize_state & UDP_SKB_IS_STATELESS);
  1276. }
  1277. /* fully reclaim rmem/fwd memory allocated for skb */
  1278. static void udp_rmem_release(struct sock *sk, int size, int partial,
  1279. bool rx_queue_lock_held)
  1280. {
  1281. struct udp_sock *up = udp_sk(sk);
  1282. struct sk_buff_head *sk_queue;
  1283. int amt;
  1284. if (likely(partial)) {
  1285. up->forward_deficit += size;
  1286. size = up->forward_deficit;
  1287. if (size < (sk->sk_rcvbuf >> 2) &&
  1288. !skb_queue_empty(&up->reader_queue))
  1289. return;
  1290. } else {
  1291. size += up->forward_deficit;
  1292. }
  1293. up->forward_deficit = 0;
  1294. /* acquire the sk_receive_queue for fwd allocated memory scheduling,
  1295. * if the called don't held it already
  1296. */
  1297. sk_queue = &sk->sk_receive_queue;
  1298. if (!rx_queue_lock_held)
  1299. spin_lock(&sk_queue->lock);
  1300. sk_forward_alloc_add(sk, size);
  1301. amt = (sk->sk_forward_alloc - partial) & ~(PAGE_SIZE - 1);
  1302. sk_forward_alloc_add(sk, -amt);
  1303. if (amt)
  1304. __sk_mem_reduce_allocated(sk, amt >> PAGE_SHIFT);
  1305. atomic_sub(size, &sk->sk_rmem_alloc);
  1306. /* this can save us from acquiring the rx queue lock on next receive */
  1307. skb_queue_splice_tail_init(sk_queue, &up->reader_queue);
  1308. if (!rx_queue_lock_held)
  1309. spin_unlock(&sk_queue->lock);
  1310. }
  1311. /* Note: called with reader_queue.lock held.
  1312. * Instead of using skb->truesize here, find a copy of it in skb->dev_scratch
  1313. * This avoids a cache line miss while receive_queue lock is held.
  1314. * Look at __udp_enqueue_schedule_skb() to find where this copy is done.
  1315. */
  1316. void udp_skb_destructor(struct sock *sk, struct sk_buff *skb)
  1317. {
  1318. prefetch(&skb->data);
  1319. udp_rmem_release(sk, udp_skb_truesize(skb), 1, false);
  1320. }
  1321. EXPORT_SYMBOL(udp_skb_destructor);
  1322. /* as above, but the caller held the rx queue lock, too */
  1323. static void udp_skb_dtor_locked(struct sock *sk, struct sk_buff *skb)
  1324. {
  1325. prefetch(&skb->data);
  1326. udp_rmem_release(sk, udp_skb_truesize(skb), 1, true);
  1327. }
  1328. /* Idea of busylocks is to let producers grab an extra spinlock
  1329. * to relieve pressure on the receive_queue spinlock shared by consumer.
  1330. * Under flood, this means that only one producer can be in line
  1331. * trying to acquire the receive_queue spinlock.
  1332. * These busylock can be allocated on a per cpu manner, instead of a
  1333. * per socket one (that would consume a cache line per socket)
  1334. */
  1335. static int udp_busylocks_log __read_mostly;
  1336. static spinlock_t *udp_busylocks __read_mostly;
  1337. static spinlock_t *busylock_acquire(void *ptr)
  1338. {
  1339. spinlock_t *busy;
  1340. busy = udp_busylocks + hash_ptr(ptr, udp_busylocks_log);
  1341. spin_lock(busy);
  1342. return busy;
  1343. }
  1344. static void busylock_release(spinlock_t *busy)
  1345. {
  1346. if (busy)
  1347. spin_unlock(busy);
  1348. }
  1349. int __udp_enqueue_schedule_skb(struct sock *sk, struct sk_buff *skb)
  1350. {
  1351. struct sk_buff_head *list = &sk->sk_receive_queue;
  1352. int rmem, delta, amt, err = -ENOMEM;
  1353. spinlock_t *busy = NULL;
  1354. int size;
  1355. /* try to avoid the costly atomic add/sub pair when the receive
  1356. * queue is full; always allow at least a packet
  1357. */
  1358. rmem = atomic_read(&sk->sk_rmem_alloc);
  1359. if (rmem > sk->sk_rcvbuf)
  1360. goto drop;
  1361. /* Under mem pressure, it might be helpful to help udp_recvmsg()
  1362. * having linear skbs :
  1363. * - Reduce memory overhead and thus increase receive queue capacity
  1364. * - Less cache line misses at copyout() time
  1365. * - Less work at consume_skb() (less alien page frag freeing)
  1366. */
  1367. if (rmem > (sk->sk_rcvbuf >> 1)) {
  1368. skb_condense(skb);
  1369. busy = busylock_acquire(sk);
  1370. }
  1371. size = skb->truesize;
  1372. udp_set_dev_scratch(skb);
  1373. /* we drop only if the receive buf is full and the receive
  1374. * queue contains some other skb
  1375. */
  1376. rmem = atomic_add_return(size, &sk->sk_rmem_alloc);
  1377. if (rmem > (size + (unsigned int)sk->sk_rcvbuf))
  1378. goto uncharge_drop;
  1379. spin_lock(&list->lock);
  1380. if (size >= sk->sk_forward_alloc) {
  1381. amt = sk_mem_pages(size);
  1382. delta = amt << PAGE_SHIFT;
  1383. if (!__sk_mem_raise_allocated(sk, delta, amt, SK_MEM_RECV)) {
  1384. err = -ENOBUFS;
  1385. spin_unlock(&list->lock);
  1386. goto uncharge_drop;
  1387. }
  1388. sk->sk_forward_alloc += delta;
  1389. }
  1390. sk_forward_alloc_add(sk, -size);
  1391. /* no need to setup a destructor, we will explicitly release the
  1392. * forward allocated memory on dequeue
  1393. */
  1394. sock_skb_set_dropcount(sk, skb);
  1395. __skb_queue_tail(list, skb);
  1396. spin_unlock(&list->lock);
  1397. if (!sock_flag(sk, SOCK_DEAD))
  1398. sk->sk_data_ready(sk);
  1399. busylock_release(busy);
  1400. return 0;
  1401. uncharge_drop:
  1402. atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
  1403. drop:
  1404. atomic_inc(&sk->sk_drops);
  1405. busylock_release(busy);
  1406. return err;
  1407. }
  1408. EXPORT_SYMBOL_GPL(__udp_enqueue_schedule_skb);
  1409. void udp_destruct_common(struct sock *sk)
  1410. {
  1411. /* reclaim completely the forward allocated memory */
  1412. struct udp_sock *up = udp_sk(sk);
  1413. unsigned int total = 0;
  1414. struct sk_buff *skb;
  1415. skb_queue_splice_tail_init(&sk->sk_receive_queue, &up->reader_queue);
  1416. while ((skb = __skb_dequeue(&up->reader_queue)) != NULL) {
  1417. total += skb->truesize;
  1418. kfree_skb(skb);
  1419. }
  1420. udp_rmem_release(sk, total, 0, true);
  1421. }
  1422. EXPORT_SYMBOL_GPL(udp_destruct_common);
  1423. static void udp_destruct_sock(struct sock *sk)
  1424. {
  1425. udp_destruct_common(sk);
  1426. inet_sock_destruct(sk);
  1427. }
  1428. int udp_init_sock(struct sock *sk)
  1429. {
  1430. skb_queue_head_init(&udp_sk(sk)->reader_queue);
  1431. sk->sk_destruct = udp_destruct_sock;
  1432. set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
  1433. return 0;
  1434. }
  1435. void skb_consume_udp(struct sock *sk, struct sk_buff *skb, int len)
  1436. {
  1437. if (unlikely(READ_ONCE(sk->sk_peek_off) >= 0)) {
  1438. bool slow = lock_sock_fast(sk);
  1439. sk_peek_offset_bwd(sk, len);
  1440. unlock_sock_fast(sk, slow);
  1441. }
  1442. if (!skb_unref(skb))
  1443. return;
  1444. /* In the more common cases we cleared the head states previously,
  1445. * see __udp_queue_rcv_skb().
  1446. */
  1447. if (unlikely(udp_skb_has_head_state(skb)))
  1448. skb_release_head_state(skb);
  1449. __consume_stateless_skb(skb);
  1450. }
  1451. EXPORT_SYMBOL_GPL(skb_consume_udp);
  1452. static struct sk_buff *__first_packet_length(struct sock *sk,
  1453. struct sk_buff_head *rcvq,
  1454. int *total)
  1455. {
  1456. struct sk_buff *skb;
  1457. while ((skb = skb_peek(rcvq)) != NULL) {
  1458. if (udp_lib_checksum_complete(skb)) {
  1459. __UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS,
  1460. IS_UDPLITE(sk));
  1461. __UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS,
  1462. IS_UDPLITE(sk));
  1463. atomic_inc(&sk->sk_drops);
  1464. __skb_unlink(skb, rcvq);
  1465. *total += skb->truesize;
  1466. kfree_skb(skb);
  1467. } else {
  1468. udp_skb_csum_unnecessary_set(skb);
  1469. break;
  1470. }
  1471. }
  1472. return skb;
  1473. }
  1474. /**
  1475. * first_packet_length - return length of first packet in receive queue
  1476. * @sk: socket
  1477. *
  1478. * Drops all bad checksum frames, until a valid one is found.
  1479. * Returns the length of found skb, or -1 if none is found.
  1480. */
  1481. static int first_packet_length(struct sock *sk)
  1482. {
  1483. struct sk_buff_head *rcvq = &udp_sk(sk)->reader_queue;
  1484. struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
  1485. struct sk_buff *skb;
  1486. int total = 0;
  1487. int res;
  1488. spin_lock_bh(&rcvq->lock);
  1489. skb = __first_packet_length(sk, rcvq, &total);
  1490. if (!skb && !skb_queue_empty_lockless(sk_queue)) {
  1491. spin_lock(&sk_queue->lock);
  1492. skb_queue_splice_tail_init(sk_queue, rcvq);
  1493. spin_unlock(&sk_queue->lock);
  1494. skb = __first_packet_length(sk, rcvq, &total);
  1495. }
  1496. res = skb ? skb->len : -1;
  1497. if (total)
  1498. udp_rmem_release(sk, total, 1, false);
  1499. spin_unlock_bh(&rcvq->lock);
  1500. return res;
  1501. }
  1502. /*
  1503. * IOCTL requests applicable to the UDP protocol
  1504. */
  1505. int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
  1506. {
  1507. switch (cmd) {
  1508. case SIOCOUTQ:
  1509. {
  1510. int amount = sk_wmem_alloc_get(sk);
  1511. return put_user(amount, (int __user *)arg);
  1512. }
  1513. case SIOCINQ:
  1514. {
  1515. int amount = max_t(int, 0, first_packet_length(sk));
  1516. return put_user(amount, (int __user *)arg);
  1517. }
  1518. default:
  1519. return -ENOIOCTLCMD;
  1520. }
  1521. return 0;
  1522. }
  1523. EXPORT_SYMBOL(udp_ioctl);
  1524. struct sk_buff *__skb_recv_udp(struct sock *sk, unsigned int flags,
  1525. int *off, int *err)
  1526. {
  1527. struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
  1528. struct sk_buff_head *queue;
  1529. struct sk_buff *last;
  1530. long timeo;
  1531. int error;
  1532. queue = &udp_sk(sk)->reader_queue;
  1533. timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
  1534. do {
  1535. struct sk_buff *skb;
  1536. error = sock_error(sk);
  1537. if (error)
  1538. break;
  1539. error = -EAGAIN;
  1540. do {
  1541. spin_lock_bh(&queue->lock);
  1542. skb = __skb_try_recv_from_queue(sk, queue, flags, off,
  1543. err, &last);
  1544. if (skb) {
  1545. if (!(flags & MSG_PEEK))
  1546. udp_skb_destructor(sk, skb);
  1547. spin_unlock_bh(&queue->lock);
  1548. return skb;
  1549. }
  1550. if (skb_queue_empty_lockless(sk_queue)) {
  1551. spin_unlock_bh(&queue->lock);
  1552. goto busy_check;
  1553. }
  1554. /* refill the reader queue and walk it again
  1555. * keep both queues locked to avoid re-acquiring
  1556. * the sk_receive_queue lock if fwd memory scheduling
  1557. * is needed.
  1558. */
  1559. spin_lock(&sk_queue->lock);
  1560. skb_queue_splice_tail_init(sk_queue, queue);
  1561. skb = __skb_try_recv_from_queue(sk, queue, flags, off,
  1562. err, &last);
  1563. if (skb && !(flags & MSG_PEEK))
  1564. udp_skb_dtor_locked(sk, skb);
  1565. spin_unlock(&sk_queue->lock);
  1566. spin_unlock_bh(&queue->lock);
  1567. if (skb)
  1568. return skb;
  1569. busy_check:
  1570. if (!sk_can_busy_loop(sk))
  1571. break;
  1572. sk_busy_loop(sk, flags & MSG_DONTWAIT);
  1573. } while (!skb_queue_empty_lockless(sk_queue));
  1574. /* sk_queue is empty, reader_queue may contain peeked packets */
  1575. } while (timeo &&
  1576. !__skb_wait_for_more_packets(sk, &sk->sk_receive_queue,
  1577. &error, &timeo,
  1578. (struct sk_buff *)sk_queue));
  1579. *err = error;
  1580. return NULL;
  1581. }
  1582. EXPORT_SYMBOL(__skb_recv_udp);
  1583. int udp_read_skb(struct sock *sk, skb_read_actor_t recv_actor)
  1584. {
  1585. struct sk_buff *skb;
  1586. int err;
  1587. try_again:
  1588. skb = skb_recv_udp(sk, MSG_DONTWAIT, &err);
  1589. if (!skb)
  1590. return err;
  1591. if (udp_lib_checksum_complete(skb)) {
  1592. int is_udplite = IS_UDPLITE(sk);
  1593. struct net *net = sock_net(sk);
  1594. __UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, is_udplite);
  1595. __UDP_INC_STATS(net, UDP_MIB_INERRORS, is_udplite);
  1596. atomic_inc(&sk->sk_drops);
  1597. kfree_skb(skb);
  1598. goto try_again;
  1599. }
  1600. WARN_ON_ONCE(!skb_set_owner_sk_safe(skb, sk));
  1601. return recv_actor(sk, skb);
  1602. }
  1603. EXPORT_SYMBOL(udp_read_skb);
  1604. /*
  1605. * This should be easy, if there is something there we
  1606. * return it, otherwise we block.
  1607. */
  1608. int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags,
  1609. int *addr_len)
  1610. {
  1611. struct inet_sock *inet = inet_sk(sk);
  1612. DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
  1613. struct sk_buff *skb;
  1614. unsigned int ulen, copied;
  1615. int off, err, peeking = flags & MSG_PEEK;
  1616. int is_udplite = IS_UDPLITE(sk);
  1617. bool checksum_valid = false;
  1618. if (flags & MSG_ERRQUEUE)
  1619. return ip_recv_error(sk, msg, len, addr_len);
  1620. try_again:
  1621. off = sk_peek_offset(sk, flags);
  1622. skb = __skb_recv_udp(sk, flags, &off, &err);
  1623. if (!skb)
  1624. return err;
  1625. ulen = udp_skb_len(skb);
  1626. copied = len;
  1627. if (copied > ulen - off)
  1628. copied = ulen - off;
  1629. else if (copied < ulen)
  1630. msg->msg_flags |= MSG_TRUNC;
  1631. /*
  1632. * If checksum is needed at all, try to do it while copying the
  1633. * data. If the data is truncated, or if we only want a partial
  1634. * coverage checksum (UDP-Lite), do it before the copy.
  1635. */
  1636. if (copied < ulen || peeking ||
  1637. (is_udplite && UDP_SKB_CB(skb)->partial_cov)) {
  1638. checksum_valid = udp_skb_csum_unnecessary(skb) ||
  1639. !__udp_lib_checksum_complete(skb);
  1640. if (!checksum_valid)
  1641. goto csum_copy_err;
  1642. }
  1643. if (checksum_valid || udp_skb_csum_unnecessary(skb)) {
  1644. if (udp_skb_is_linear(skb))
  1645. err = copy_linear_skb(skb, copied, off, &msg->msg_iter);
  1646. else
  1647. err = skb_copy_datagram_msg(skb, off, msg, copied);
  1648. } else {
  1649. err = skb_copy_and_csum_datagram_msg(skb, off, msg);
  1650. if (err == -EINVAL)
  1651. goto csum_copy_err;
  1652. }
  1653. if (unlikely(err)) {
  1654. if (!peeking) {
  1655. atomic_inc(&sk->sk_drops);
  1656. UDP_INC_STATS(sock_net(sk),
  1657. UDP_MIB_INERRORS, is_udplite);
  1658. }
  1659. kfree_skb(skb);
  1660. return err;
  1661. }
  1662. if (!peeking)
  1663. UDP_INC_STATS(sock_net(sk),
  1664. UDP_MIB_INDATAGRAMS, is_udplite);
  1665. sock_recv_cmsgs(msg, sk, skb);
  1666. /* Copy the address. */
  1667. if (sin) {
  1668. sin->sin_family = AF_INET;
  1669. sin->sin_port = udp_hdr(skb)->source;
  1670. sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
  1671. memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
  1672. *addr_len = sizeof(*sin);
  1673. BPF_CGROUP_RUN_PROG_UDP4_RECVMSG_LOCK(sk,
  1674. (struct sockaddr *)sin);
  1675. }
  1676. if (udp_sk(sk)->gro_enabled)
  1677. udp_cmsg_recv(msg, sk, skb);
  1678. if (inet->cmsg_flags)
  1679. ip_cmsg_recv_offset(msg, sk, skb, sizeof(struct udphdr), off);
  1680. err = copied;
  1681. if (flags & MSG_TRUNC)
  1682. err = ulen;
  1683. skb_consume_udp(sk, skb, peeking ? -err : err);
  1684. return err;
  1685. csum_copy_err:
  1686. if (!__sk_queue_drop_skb(sk, &udp_sk(sk)->reader_queue, skb, flags,
  1687. udp_skb_destructor)) {
  1688. UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
  1689. UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
  1690. }
  1691. kfree_skb(skb);
  1692. /* starting over for a new packet, but check if we need to yield */
  1693. cond_resched();
  1694. msg->msg_flags &= ~MSG_TRUNC;
  1695. goto try_again;
  1696. }
  1697. int udp_pre_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
  1698. {
  1699. /* This check is replicated from __ip4_datagram_connect() and
  1700. * intended to prevent BPF program called below from accessing bytes
  1701. * that are out of the bound specified by user in addr_len.
  1702. */
  1703. if (addr_len < sizeof(struct sockaddr_in))
  1704. return -EINVAL;
  1705. return BPF_CGROUP_RUN_PROG_INET4_CONNECT_LOCK(sk, uaddr);
  1706. }
  1707. EXPORT_SYMBOL(udp_pre_connect);
  1708. int __udp_disconnect(struct sock *sk, int flags)
  1709. {
  1710. struct inet_sock *inet = inet_sk(sk);
  1711. /*
  1712. * 1003.1g - break association.
  1713. */
  1714. sk->sk_state = TCP_CLOSE;
  1715. inet->inet_daddr = 0;
  1716. inet->inet_dport = 0;
  1717. sock_rps_reset_rxhash(sk);
  1718. sk->sk_bound_dev_if = 0;
  1719. if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) {
  1720. inet_reset_saddr(sk);
  1721. if (sk->sk_prot->rehash &&
  1722. (sk->sk_userlocks & SOCK_BINDPORT_LOCK))
  1723. sk->sk_prot->rehash(sk);
  1724. }
  1725. if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
  1726. sk->sk_prot->unhash(sk);
  1727. inet->inet_sport = 0;
  1728. }
  1729. sk_dst_reset(sk);
  1730. return 0;
  1731. }
  1732. EXPORT_SYMBOL(__udp_disconnect);
  1733. int udp_disconnect(struct sock *sk, int flags)
  1734. {
  1735. lock_sock(sk);
  1736. __udp_disconnect(sk, flags);
  1737. release_sock(sk);
  1738. return 0;
  1739. }
  1740. EXPORT_SYMBOL(udp_disconnect);
  1741. void udp_lib_unhash(struct sock *sk)
  1742. {
  1743. if (sk_hashed(sk)) {
  1744. struct udp_table *udptable = sk->sk_prot->h.udp_table;
  1745. struct udp_hslot *hslot, *hslot2;
  1746. hslot = udp_hashslot(udptable, sock_net(sk),
  1747. udp_sk(sk)->udp_port_hash);
  1748. hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
  1749. spin_lock_bh(&hslot->lock);
  1750. if (rcu_access_pointer(sk->sk_reuseport_cb))
  1751. reuseport_detach_sock(sk);
  1752. if (sk_del_node_init_rcu(sk)) {
  1753. hslot->count--;
  1754. inet_sk(sk)->inet_num = 0;
  1755. sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
  1756. spin_lock(&hslot2->lock);
  1757. hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
  1758. hslot2->count--;
  1759. spin_unlock(&hslot2->lock);
  1760. }
  1761. spin_unlock_bh(&hslot->lock);
  1762. }
  1763. }
  1764. EXPORT_SYMBOL(udp_lib_unhash);
  1765. /*
  1766. * inet_rcv_saddr was changed, we must rehash secondary hash
  1767. */
  1768. void udp_lib_rehash(struct sock *sk, u16 newhash)
  1769. {
  1770. if (sk_hashed(sk)) {
  1771. struct udp_table *udptable = sk->sk_prot->h.udp_table;
  1772. struct udp_hslot *hslot, *hslot2, *nhslot2;
  1773. hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
  1774. nhslot2 = udp_hashslot2(udptable, newhash);
  1775. udp_sk(sk)->udp_portaddr_hash = newhash;
  1776. if (hslot2 != nhslot2 ||
  1777. rcu_access_pointer(sk->sk_reuseport_cb)) {
  1778. hslot = udp_hashslot(udptable, sock_net(sk),
  1779. udp_sk(sk)->udp_port_hash);
  1780. /* we must lock primary chain too */
  1781. spin_lock_bh(&hslot->lock);
  1782. if (rcu_access_pointer(sk->sk_reuseport_cb))
  1783. reuseport_detach_sock(sk);
  1784. if (hslot2 != nhslot2) {
  1785. spin_lock(&hslot2->lock);
  1786. hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
  1787. hslot2->count--;
  1788. spin_unlock(&hslot2->lock);
  1789. spin_lock(&nhslot2->lock);
  1790. hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
  1791. &nhslot2->head);
  1792. nhslot2->count++;
  1793. spin_unlock(&nhslot2->lock);
  1794. }
  1795. spin_unlock_bh(&hslot->lock);
  1796. }
  1797. }
  1798. }
  1799. EXPORT_SYMBOL(udp_lib_rehash);
  1800. void udp_v4_rehash(struct sock *sk)
  1801. {
  1802. u16 new_hash = ipv4_portaddr_hash(sock_net(sk),
  1803. inet_sk(sk)->inet_rcv_saddr,
  1804. inet_sk(sk)->inet_num);
  1805. udp_lib_rehash(sk, new_hash);
  1806. }
  1807. static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
  1808. {
  1809. int rc;
  1810. if (inet_sk(sk)->inet_daddr) {
  1811. sock_rps_save_rxhash(sk, skb);
  1812. sk_mark_napi_id(sk, skb);
  1813. sk_incoming_cpu_update(sk);
  1814. } else {
  1815. sk_mark_napi_id_once(sk, skb);
  1816. }
  1817. rc = __udp_enqueue_schedule_skb(sk, skb);
  1818. if (rc < 0) {
  1819. int is_udplite = IS_UDPLITE(sk);
  1820. int drop_reason;
  1821. /* Note that an ENOMEM error is charged twice */
  1822. if (rc == -ENOMEM) {
  1823. UDP_INC_STATS(sock_net(sk), UDP_MIB_RCVBUFERRORS,
  1824. is_udplite);
  1825. drop_reason = SKB_DROP_REASON_SOCKET_RCVBUFF;
  1826. } else {
  1827. UDP_INC_STATS(sock_net(sk), UDP_MIB_MEMERRORS,
  1828. is_udplite);
  1829. drop_reason = SKB_DROP_REASON_PROTO_MEM;
  1830. }
  1831. UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
  1832. kfree_skb_reason(skb, drop_reason);
  1833. trace_udp_fail_queue_rcv_skb(rc, sk);
  1834. return -1;
  1835. }
  1836. return 0;
  1837. }
  1838. /* returns:
  1839. * -1: error
  1840. * 0: success
  1841. * >0: "udp encap" protocol resubmission
  1842. *
  1843. * Note that in the success and error cases, the skb is assumed to
  1844. * have either been requeued or freed.
  1845. */
  1846. static int udp_queue_rcv_one_skb(struct sock *sk, struct sk_buff *skb)
  1847. {
  1848. int drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
  1849. struct udp_sock *up = udp_sk(sk);
  1850. int is_udplite = IS_UDPLITE(sk);
  1851. /*
  1852. * Charge it to the socket, dropping if the queue is full.
  1853. */
  1854. if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
  1855. drop_reason = SKB_DROP_REASON_XFRM_POLICY;
  1856. goto drop;
  1857. }
  1858. nf_reset_ct(skb);
  1859. if (static_branch_unlikely(&udp_encap_needed_key) && up->encap_type) {
  1860. int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
  1861. /*
  1862. * This is an encapsulation socket so pass the skb to
  1863. * the socket's udp_encap_rcv() hook. Otherwise, just
  1864. * fall through and pass this up the UDP socket.
  1865. * up->encap_rcv() returns the following value:
  1866. * =0 if skb was successfully passed to the encap
  1867. * handler or was discarded by it.
  1868. * >0 if skb should be passed on to UDP.
  1869. * <0 if skb should be resubmitted as proto -N
  1870. */
  1871. /* if we're overly short, let UDP handle it */
  1872. encap_rcv = READ_ONCE(up->encap_rcv);
  1873. if (encap_rcv) {
  1874. int ret;
  1875. /* Verify checksum before giving to encap */
  1876. if (udp_lib_checksum_complete(skb))
  1877. goto csum_error;
  1878. ret = encap_rcv(sk, skb);
  1879. if (ret <= 0) {
  1880. __UDP_INC_STATS(sock_net(sk),
  1881. UDP_MIB_INDATAGRAMS,
  1882. is_udplite);
  1883. return -ret;
  1884. }
  1885. }
  1886. /* FALLTHROUGH -- it's a UDP Packet */
  1887. }
  1888. /*
  1889. * UDP-Lite specific tests, ignored on UDP sockets
  1890. */
  1891. if ((up->pcflag & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) {
  1892. /*
  1893. * MIB statistics other than incrementing the error count are
  1894. * disabled for the following two types of errors: these depend
  1895. * on the application settings, not on the functioning of the
  1896. * protocol stack as such.
  1897. *
  1898. * RFC 3828 here recommends (sec 3.3): "There should also be a
  1899. * way ... to ... at least let the receiving application block
  1900. * delivery of packets with coverage values less than a value
  1901. * provided by the application."
  1902. */
  1903. if (up->pcrlen == 0) { /* full coverage was set */
  1904. net_dbg_ratelimited("UDPLite: partial coverage %d while full coverage %d requested\n",
  1905. UDP_SKB_CB(skb)->cscov, skb->len);
  1906. goto drop;
  1907. }
  1908. /* The next case involves violating the min. coverage requested
  1909. * by the receiver. This is subtle: if receiver wants x and x is
  1910. * greater than the buffersize/MTU then receiver will complain
  1911. * that it wants x while sender emits packets of smaller size y.
  1912. * Therefore the above ...()->partial_cov statement is essential.
  1913. */
  1914. if (UDP_SKB_CB(skb)->cscov < up->pcrlen) {
  1915. net_dbg_ratelimited("UDPLite: coverage %d too small, need min %d\n",
  1916. UDP_SKB_CB(skb)->cscov, up->pcrlen);
  1917. goto drop;
  1918. }
  1919. }
  1920. prefetch(&sk->sk_rmem_alloc);
  1921. if (rcu_access_pointer(sk->sk_filter) &&
  1922. udp_lib_checksum_complete(skb))
  1923. goto csum_error;
  1924. if (sk_filter_trim_cap(sk, skb, sizeof(struct udphdr))) {
  1925. drop_reason = SKB_DROP_REASON_SOCKET_FILTER;
  1926. goto drop;
  1927. }
  1928. udp_csum_pull_header(skb);
  1929. ipv4_pktinfo_prepare(sk, skb);
  1930. return __udp_queue_rcv_skb(sk, skb);
  1931. csum_error:
  1932. drop_reason = SKB_DROP_REASON_UDP_CSUM;
  1933. __UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
  1934. drop:
  1935. __UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
  1936. atomic_inc(&sk->sk_drops);
  1937. kfree_skb_reason(skb, drop_reason);
  1938. return -1;
  1939. }
  1940. static int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
  1941. {
  1942. struct sk_buff *next, *segs;
  1943. int ret;
  1944. if (likely(!udp_unexpected_gso(sk, skb)))
  1945. return udp_queue_rcv_one_skb(sk, skb);
  1946. BUILD_BUG_ON(sizeof(struct udp_skb_cb) > SKB_GSO_CB_OFFSET);
  1947. __skb_push(skb, -skb_mac_offset(skb));
  1948. segs = udp_rcv_segment(sk, skb, true);
  1949. skb_list_walk_safe(segs, skb, next) {
  1950. __skb_pull(skb, skb_transport_offset(skb));
  1951. udp_post_segment_fix_csum(skb);
  1952. ret = udp_queue_rcv_one_skb(sk, skb);
  1953. if (ret > 0)
  1954. ip_protocol_deliver_rcu(dev_net(skb->dev), skb, ret);
  1955. }
  1956. return 0;
  1957. }
  1958. /* For TCP sockets, sk_rx_dst is protected by socket lock
  1959. * For UDP, we use xchg() to guard against concurrent changes.
  1960. */
  1961. bool udp_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst)
  1962. {
  1963. struct dst_entry *old;
  1964. if (dst_hold_safe(dst)) {
  1965. old = xchg((__force struct dst_entry **)&sk->sk_rx_dst, dst);
  1966. dst_release(old);
  1967. return old != dst;
  1968. }
  1969. return false;
  1970. }
  1971. EXPORT_SYMBOL(udp_sk_rx_dst_set);
  1972. /*
  1973. * Multicasts and broadcasts go to each listener.
  1974. *
  1975. * Note: called only from the BH handler context.
  1976. */
  1977. static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
  1978. struct udphdr *uh,
  1979. __be32 saddr, __be32 daddr,
  1980. struct udp_table *udptable,
  1981. int proto)
  1982. {
  1983. struct sock *sk, *first = NULL;
  1984. unsigned short hnum = ntohs(uh->dest);
  1985. struct udp_hslot *hslot = udp_hashslot(udptable, net, hnum);
  1986. unsigned int hash2 = 0, hash2_any = 0, use_hash2 = (hslot->count > 10);
  1987. unsigned int offset = offsetof(typeof(*sk), sk_node);
  1988. int dif = skb->dev->ifindex;
  1989. int sdif = inet_sdif(skb);
  1990. struct hlist_node *node;
  1991. struct sk_buff *nskb;
  1992. if (use_hash2) {
  1993. hash2_any = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum) &
  1994. udptable->mask;
  1995. hash2 = ipv4_portaddr_hash(net, daddr, hnum) & udptable->mask;
  1996. start_lookup:
  1997. hslot = &udptable->hash2[hash2];
  1998. offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node);
  1999. }
  2000. sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) {
  2001. if (!__udp_is_mcast_sock(net, sk, uh->dest, daddr,
  2002. uh->source, saddr, dif, sdif, hnum))
  2003. continue;
  2004. if (!first) {
  2005. first = sk;
  2006. continue;
  2007. }
  2008. nskb = skb_clone(skb, GFP_ATOMIC);
  2009. if (unlikely(!nskb)) {
  2010. atomic_inc(&sk->sk_drops);
  2011. __UDP_INC_STATS(net, UDP_MIB_RCVBUFERRORS,
  2012. IS_UDPLITE(sk));
  2013. __UDP_INC_STATS(net, UDP_MIB_INERRORS,
  2014. IS_UDPLITE(sk));
  2015. continue;
  2016. }
  2017. if (udp_queue_rcv_skb(sk, nskb) > 0)
  2018. consume_skb(nskb);
  2019. }
  2020. /* Also lookup *:port if we are using hash2 and haven't done so yet. */
  2021. if (use_hash2 && hash2 != hash2_any) {
  2022. hash2 = hash2_any;
  2023. goto start_lookup;
  2024. }
  2025. if (first) {
  2026. if (udp_queue_rcv_skb(first, skb) > 0)
  2027. consume_skb(skb);
  2028. } else {
  2029. kfree_skb(skb);
  2030. __UDP_INC_STATS(net, UDP_MIB_IGNOREDMULTI,
  2031. proto == IPPROTO_UDPLITE);
  2032. }
  2033. return 0;
  2034. }
  2035. /* Initialize UDP checksum. If exited with zero value (success),
  2036. * CHECKSUM_UNNECESSARY means, that no more checks are required.
  2037. * Otherwise, csum completion requires checksumming packet body,
  2038. * including udp header and folding it to skb->csum.
  2039. */
  2040. static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh,
  2041. int proto)
  2042. {
  2043. int err;
  2044. UDP_SKB_CB(skb)->partial_cov = 0;
  2045. UDP_SKB_CB(skb)->cscov = skb->len;
  2046. if (proto == IPPROTO_UDPLITE) {
  2047. err = udplite_checksum_init(skb, uh);
  2048. if (err)
  2049. return err;
  2050. if (UDP_SKB_CB(skb)->partial_cov) {
  2051. skb->csum = inet_compute_pseudo(skb, proto);
  2052. return 0;
  2053. }
  2054. }
  2055. /* Note, we are only interested in != 0 or == 0, thus the
  2056. * force to int.
  2057. */
  2058. err = (__force int)skb_checksum_init_zero_check(skb, proto, uh->check,
  2059. inet_compute_pseudo);
  2060. if (err)
  2061. return err;
  2062. if (skb->ip_summed == CHECKSUM_COMPLETE && !skb->csum_valid) {
  2063. /* If SW calculated the value, we know it's bad */
  2064. if (skb->csum_complete_sw)
  2065. return 1;
  2066. /* HW says the value is bad. Let's validate that.
  2067. * skb->csum is no longer the full packet checksum,
  2068. * so don't treat it as such.
  2069. */
  2070. skb_checksum_complete_unset(skb);
  2071. }
  2072. return 0;
  2073. }
  2074. /* wrapper for udp_queue_rcv_skb tacking care of csum conversion and
  2075. * return code conversion for ip layer consumption
  2076. */
  2077. static int udp_unicast_rcv_skb(struct sock *sk, struct sk_buff *skb,
  2078. struct udphdr *uh)
  2079. {
  2080. int ret;
  2081. if (inet_get_convert_csum(sk) && uh->check && !IS_UDPLITE(sk))
  2082. skb_checksum_try_convert(skb, IPPROTO_UDP, inet_compute_pseudo);
  2083. ret = udp_queue_rcv_skb(sk, skb);
  2084. /* a return value > 0 means to resubmit the input, but
  2085. * it wants the return to be -protocol, or 0
  2086. */
  2087. if (ret > 0)
  2088. return -ret;
  2089. return 0;
  2090. }
  2091. /*
  2092. * All we need to do is get the socket, and then do a checksum.
  2093. */
  2094. // SEC_PRODUCT_FEATURE_KNOX_SUPPORT_NPA {
  2095. #ifdef CONFIG_KNOX_NCM
  2096. #include <net/ncm.h>
  2097. #endif
  2098. // SEC_PRODUCT_FEATURE_KNOX_SUPPORT_NPA }
  2099. int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
  2100. int proto)
  2101. {
  2102. struct sock *sk;
  2103. struct udphdr *uh;
  2104. unsigned short ulen;
  2105. struct rtable *rt = skb_rtable(skb);
  2106. __be32 saddr, daddr;
  2107. struct net *net = dev_net(skb->dev);
  2108. bool refcounted;
  2109. int drop_reason;
  2110. drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
  2111. /*
  2112. * Validate the packet.
  2113. */
  2114. if (!pskb_may_pull(skb, sizeof(struct udphdr)))
  2115. goto drop; /* No space for header. */
  2116. uh = udp_hdr(skb);
  2117. ulen = ntohs(uh->len);
  2118. saddr = ip_hdr(skb)->saddr;
  2119. daddr = ip_hdr(skb)->daddr;
  2120. if (ulen > skb->len)
  2121. goto short_packet;
  2122. if (proto == IPPROTO_UDP) {
  2123. /* UDP validates ulen. */
  2124. if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
  2125. goto short_packet;
  2126. uh = udp_hdr(skb);
  2127. }
  2128. if (udp4_csum_init(skb, uh, proto))
  2129. goto csum_error;
  2130. sk = skb_steal_sock(skb, &refcounted);
  2131. if (sk) {
  2132. struct dst_entry *dst = skb_dst(skb);
  2133. int ret;
  2134. // SEC_PRODUCT_FEATURE_KNOX_SUPPORT_NPA {
  2135. #ifdef CONFIG_KNOX_NCM
  2136. struct nf_conn *ct = NULL;
  2137. enum ip_conntrack_info ctinfo;
  2138. struct nf_conntrack_tuple *tuple = NULL;
  2139. char srcaddr[INET6_ADDRSTRLEN_NAP];
  2140. char dstaddr[INET6_ADDRSTRLEN_NAP];
  2141. #endif
  2142. // SEC_PRODUCT_FEATURE_KNOX_SUPPORT_NPA }
  2143. if (unlikely(rcu_dereference(sk->sk_rx_dst) != dst))
  2144. udp_sk_rx_dst_set(sk, dst);
  2145. // SEC_PRODUCT_FEATURE_KNOX_SUPPORT_NPA {
  2146. #ifdef CONFIG_KNOX_NCM
  2147. /* function to handle open flows with incoming udp packets */
  2148. if (check_ncm_flag()) {
  2149. if ( (sk) && (sk->sk_protocol == IPPROTO_UDP) && (SOCK_NPA_VENDOR_DATA_GET(sk) != NULL) ) {
  2150. ct = nf_ct_get(skb, &ctinfo);
  2151. if ( (ct) && (NF_CONN_NPA_VENDOR_DATA_GET(ct) != NULL) && (!atomic_read(&NF_CONN_NPA_VENDOR_DATA_GET(ct)->startFlow)) && (!nf_ct_is_dying(ct)) ) {
  2152. tuple = &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple;
  2153. if (tuple) {
  2154. sprintf(srcaddr,"%pI4",(void *)&tuple->src.u3.ip);
  2155. sprintf(dstaddr,"%pI4",(void *)&tuple->dst.u3.ip);
  2156. if ( !isIpv4AddressEqualsNull(srcaddr, dstaddr) ) {
  2157. atomic_set(&NF_CONN_NPA_VENDOR_DATA_GET(ct)->startFlow, 1);
  2158. if ( check_intermediate_flag() ) {
  2159. NF_CONN_NPA_VENDOR_DATA_GET(ct)->npa_timeout = ((u32)(jiffies)) + (get_intermediate_timeout() * HZ);
  2160. atomic_set(&NF_CONN_NPA_VENDOR_DATA_GET(ct)->intermediateFlow, 1);
  2161. }
  2162. NF_CONN_NPA_VENDOR_DATA_GET(ct)->knox_uid = SOCK_NPA_VENDOR_DATA_GET(sk)->knox_uid;
  2163. NF_CONN_NPA_VENDOR_DATA_GET(ct)->knox_pid = SOCK_NPA_VENDOR_DATA_GET(sk)->knox_pid;
  2164. memcpy(NF_CONN_NPA_VENDOR_DATA_GET(ct)->process_name, SOCK_NPA_VENDOR_DATA_GET(sk)->process_name, sizeof(NF_CONN_NPA_VENDOR_DATA_GET(ct)->process_name)-1);
  2165. NF_CONN_NPA_VENDOR_DATA_GET(ct)->knox_puid = SOCK_NPA_VENDOR_DATA_GET(sk)->knox_puid;
  2166. NF_CONN_NPA_VENDOR_DATA_GET(ct)->knox_ppid = SOCK_NPA_VENDOR_DATA_GET(sk)->knox_ppid;
  2167. memcpy(NF_CONN_NPA_VENDOR_DATA_GET(ct)->parent_process_name, SOCK_NPA_VENDOR_DATA_GET(sk)->parent_process_name, sizeof(NF_CONN_NPA_VENDOR_DATA_GET(ct)->parent_process_name)-1);
  2168. memcpy(NF_CONN_NPA_VENDOR_DATA_GET(ct)->domain_name, SOCK_NPA_VENDOR_DATA_GET(sk)->domain_name, sizeof(NF_CONN_NPA_VENDOR_DATA_GET(ct)->domain_name)-1);
  2169. if ( (skb->dev) ) {
  2170. memcpy(NF_CONN_NPA_VENDOR_DATA_GET(ct)->interface_name, skb->dev->name, sizeof(NF_CONN_NPA_VENDOR_DATA_GET(ct)->interface_name)-1);
  2171. } else {
  2172. sprintf(NF_CONN_NPA_VENDOR_DATA_GET(ct)->interface_name,"%s","null");
  2173. }
  2174. if ( (tuple != NULL) && (ntohs(tuple->dst.u.udp.port) == DNS_PORT_NAP) && (NF_CONN_NPA_VENDOR_DATA_GET(ct)->knox_uid == INIT_UID_NAP) && (SOCK_NPA_VENDOR_DATA_GET(sk)->knox_dns_uid > INIT_UID_NAP) ) {
  2175. NF_CONN_NPA_VENDOR_DATA_GET(ct)->knox_puid = SOCK_NPA_VENDOR_DATA_GET(sk)->knox_dns_uid;
  2176. NF_CONN_NPA_VENDOR_DATA_GET(ct)->knox_ppid = SOCK_NPA_VENDOR_DATA_GET(sk)->knox_dns_pid;
  2177. memcpy(NF_CONN_NPA_VENDOR_DATA_GET(ct)->parent_process_name, SOCK_NPA_VENDOR_DATA_GET(sk)->dns_process_name, sizeof(NF_CONN_NPA_VENDOR_DATA_GET(ct)->parent_process_name)-1);
  2178. }
  2179. knox_collect_conntrack_data(ct, NCM_FLOW_TYPE_OPEN, 3);
  2180. }
  2181. }
  2182. }
  2183. }
  2184. }
  2185. #endif
  2186. // SEC_PRODUCT_FEATURE_KNOX_SUPPORT_NPA }
  2187. ret = udp_unicast_rcv_skb(sk, skb, uh);
  2188. if (refcounted)
  2189. sock_put(sk);
  2190. return ret;
  2191. }
  2192. if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
  2193. return __udp4_lib_mcast_deliver(net, skb, uh,
  2194. saddr, daddr, udptable, proto);
  2195. sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
  2196. if (sk) {
  2197. // SEC_PRODUCT_FEATURE_KNOX_SUPPORT_NPA {
  2198. #ifdef CONFIG_KNOX_NCM
  2199. struct nf_conn *ct = NULL;
  2200. enum ip_conntrack_info ctinfo;
  2201. struct nf_conntrack_tuple *tuple = NULL;
  2202. char srcaddr[INET6_ADDRSTRLEN_NAP];
  2203. char dstaddr[INET6_ADDRSTRLEN_NAP];
  2204. /* function to handle open flows with incoming udp packets */
  2205. if (check_ncm_flag()) {
  2206. if ( (sk) && (sk->sk_protocol == IPPROTO_UDP) && (SOCK_NPA_VENDOR_DATA_GET(sk) != NULL) ) {
  2207. ct = nf_ct_get(skb, &ctinfo);
  2208. if ( (ct) && (NF_CONN_NPA_VENDOR_DATA_GET(ct) != NULL) && (!atomic_read(&NF_CONN_NPA_VENDOR_DATA_GET(ct)->startFlow)) && (!nf_ct_is_dying(ct)) ) {
  2209. tuple = &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple;
  2210. if (tuple) {
  2211. sprintf(srcaddr,"%pI4",(void *)&tuple->src.u3.ip);
  2212. sprintf(dstaddr,"%pI4",(void *)&tuple->dst.u3.ip);
  2213. if ( !isIpv4AddressEqualsNull(srcaddr, dstaddr) ) {
  2214. atomic_set(&NF_CONN_NPA_VENDOR_DATA_GET(ct)->startFlow, 1);
  2215. if ( check_intermediate_flag() ) {
  2216. NF_CONN_NPA_VENDOR_DATA_GET(ct)->npa_timeout = ((u32)(jiffies)) + (get_intermediate_timeout() * HZ);
  2217. atomic_set(&NF_CONN_NPA_VENDOR_DATA_GET(ct)->intermediateFlow, 1);
  2218. }
  2219. NF_CONN_NPA_VENDOR_DATA_GET(ct)->knox_uid = SOCK_NPA_VENDOR_DATA_GET(sk)->knox_uid;
  2220. NF_CONN_NPA_VENDOR_DATA_GET(ct)->knox_pid = SOCK_NPA_VENDOR_DATA_GET(sk)->knox_pid;
  2221. memcpy(NF_CONN_NPA_VENDOR_DATA_GET(ct)->process_name, SOCK_NPA_VENDOR_DATA_GET(sk)->process_name, sizeof(NF_CONN_NPA_VENDOR_DATA_GET(ct)->process_name)-1);
  2222. NF_CONN_NPA_VENDOR_DATA_GET(ct)->knox_puid = SOCK_NPA_VENDOR_DATA_GET(sk)->knox_puid;
  2223. NF_CONN_NPA_VENDOR_DATA_GET(ct)->knox_ppid = SOCK_NPA_VENDOR_DATA_GET(sk)->knox_ppid;
  2224. memcpy(NF_CONN_NPA_VENDOR_DATA_GET(ct)->parent_process_name, SOCK_NPA_VENDOR_DATA_GET(sk)->parent_process_name, sizeof(NF_CONN_NPA_VENDOR_DATA_GET(ct)->parent_process_name)-1);
  2225. memcpy(NF_CONN_NPA_VENDOR_DATA_GET(ct)->domain_name, SOCK_NPA_VENDOR_DATA_GET(sk)->domain_name, sizeof(NF_CONN_NPA_VENDOR_DATA_GET(ct)->domain_name)-1);
  2226. if ( (skb->dev) ) {
  2227. memcpy(NF_CONN_NPA_VENDOR_DATA_GET(ct)->interface_name, skb->dev->name, sizeof(NF_CONN_NPA_VENDOR_DATA_GET(ct)->interface_name)-1);
  2228. } else {
  2229. sprintf(NF_CONN_NPA_VENDOR_DATA_GET(ct)->interface_name,"%s","null");
  2230. }
  2231. if ( (tuple != NULL) && (ntohs(tuple->dst.u.udp.port) == DNS_PORT_NAP) && (NF_CONN_NPA_VENDOR_DATA_GET(ct)->knox_uid == INIT_UID_NAP) && (SOCK_NPA_VENDOR_DATA_GET(sk)->knox_dns_uid > INIT_UID_NAP) ) {
  2232. NF_CONN_NPA_VENDOR_DATA_GET(ct)->knox_puid = SOCK_NPA_VENDOR_DATA_GET(sk)->knox_dns_uid;
  2233. NF_CONN_NPA_VENDOR_DATA_GET(ct)->knox_ppid = SOCK_NPA_VENDOR_DATA_GET(sk)->knox_dns_pid;
  2234. memcpy(NF_CONN_NPA_VENDOR_DATA_GET(ct)->parent_process_name, SOCK_NPA_VENDOR_DATA_GET(sk)->dns_process_name, sizeof(NF_CONN_NPA_VENDOR_DATA_GET(ct)->parent_process_name)-1);
  2235. }
  2236. knox_collect_conntrack_data(ct, NCM_FLOW_TYPE_OPEN, 3);
  2237. }
  2238. }
  2239. }
  2240. }
  2241. }
  2242. #endif
  2243. // SEC_PRODUCT_FEATURE_KNOX_SUPPORT_NPA }
  2244. return udp_unicast_rcv_skb(sk, skb, uh);
  2245. }
  2246. if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
  2247. goto drop;
  2248. nf_reset_ct(skb);
  2249. /* No socket. Drop packet silently, if checksum is wrong */
  2250. if (udp_lib_checksum_complete(skb))
  2251. goto csum_error;
  2252. drop_reason = SKB_DROP_REASON_NO_SOCKET;
  2253. __UDP_INC_STATS(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
  2254. icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
  2255. /*
  2256. * Hmm. We got an UDP packet to a port to which we
  2257. * don't wanna listen. Ignore it.
  2258. */
  2259. kfree_skb_reason(skb, drop_reason);
  2260. return 0;
  2261. short_packet:
  2262. drop_reason = SKB_DROP_REASON_PKT_TOO_SMALL;
  2263. net_dbg_ratelimited("UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
  2264. proto == IPPROTO_UDPLITE ? "Lite" : "",
  2265. &saddr, ntohs(uh->source),
  2266. ulen, skb->len,
  2267. &daddr, ntohs(uh->dest));
  2268. goto drop;
  2269. csum_error:
  2270. /*
  2271. * RFC1122: OK. Discards the bad packet silently (as far as
  2272. * the network is concerned, anyway) as per 4.1.3.4 (MUST).
  2273. */
  2274. drop_reason = SKB_DROP_REASON_UDP_CSUM;
  2275. net_dbg_ratelimited("UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
  2276. proto == IPPROTO_UDPLITE ? "Lite" : "",
  2277. &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
  2278. ulen);
  2279. __UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
  2280. drop:
  2281. __UDP_INC_STATS(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
  2282. kfree_skb_reason(skb, drop_reason);
  2283. return 0;
  2284. }
  2285. /* We can only early demux multicast if there is a single matching socket.
  2286. * If more than one socket found returns NULL
  2287. */
  2288. static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net,
  2289. __be16 loc_port, __be32 loc_addr,
  2290. __be16 rmt_port, __be32 rmt_addr,
  2291. int dif, int sdif)
  2292. {
  2293. unsigned short hnum = ntohs(loc_port);
  2294. struct sock *sk, *result;
  2295. struct udp_hslot *hslot;
  2296. unsigned int slot;
  2297. slot = udp_hashfn(net, hnum, udp_table.mask);
  2298. hslot = &udp_table.hash[slot];
  2299. /* Do not bother scanning a too big list */
  2300. if (hslot->count > 10)
  2301. return NULL;
  2302. result = NULL;
  2303. sk_for_each_rcu(sk, &hslot->head) {
  2304. if (__udp_is_mcast_sock(net, sk, loc_port, loc_addr,
  2305. rmt_port, rmt_addr, dif, sdif, hnum)) {
  2306. if (result)
  2307. return NULL;
  2308. result = sk;
  2309. }
  2310. }
  2311. return result;
  2312. }
  2313. /* For unicast we should only early demux connected sockets or we can
  2314. * break forwarding setups. The chains here can be long so only check
  2315. * if the first socket is an exact match and if not move on.
  2316. */
  2317. static struct sock *__udp4_lib_demux_lookup(struct net *net,
  2318. __be16 loc_port, __be32 loc_addr,
  2319. __be16 rmt_port, __be32 rmt_addr,
  2320. int dif, int sdif)
  2321. {
  2322. INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr);
  2323. unsigned short hnum = ntohs(loc_port);
  2324. unsigned int hash2, slot2;
  2325. struct udp_hslot *hslot2;
  2326. __portpair ports;
  2327. struct sock *sk;
  2328. hash2 = ipv4_portaddr_hash(net, loc_addr, hnum);
  2329. slot2 = hash2 & udp_table.mask;
  2330. hslot2 = &udp_table.hash2[slot2];
  2331. ports = INET_COMBINED_PORTS(rmt_port, hnum);
  2332. udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
  2333. if (inet_match(net, sk, acookie, ports, dif, sdif))
  2334. return sk;
  2335. /* Only check first socket in chain */
  2336. break;
  2337. }
  2338. return NULL;
  2339. }
  2340. int udp_v4_early_demux(struct sk_buff *skb)
  2341. {
  2342. struct net *net = dev_net(skb->dev);
  2343. struct in_device *in_dev = NULL;
  2344. const struct iphdr *iph;
  2345. const struct udphdr *uh;
  2346. struct sock *sk = NULL;
  2347. struct dst_entry *dst;
  2348. int dif = skb->dev->ifindex;
  2349. int sdif = inet_sdif(skb);
  2350. int ours;
  2351. /* validate the packet */
  2352. if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr)))
  2353. return 0;
  2354. iph = ip_hdr(skb);
  2355. uh = udp_hdr(skb);
  2356. if (skb->pkt_type == PACKET_MULTICAST) {
  2357. in_dev = __in_dev_get_rcu(skb->dev);
  2358. if (!in_dev)
  2359. return 0;
  2360. ours = ip_check_mc_rcu(in_dev, iph->daddr, iph->saddr,
  2361. iph->protocol);
  2362. if (!ours)
  2363. return 0;
  2364. sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr,
  2365. uh->source, iph->saddr,
  2366. dif, sdif);
  2367. } else if (skb->pkt_type == PACKET_HOST) {
  2368. sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr,
  2369. uh->source, iph->saddr, dif, sdif);
  2370. }
  2371. if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
  2372. return 0;
  2373. skb->sk = sk;
  2374. skb->destructor = sock_efree;
  2375. dst = rcu_dereference(sk->sk_rx_dst);
  2376. if (dst)
  2377. dst = dst_check(dst, 0);
  2378. if (dst) {
  2379. u32 itag = 0;
  2380. /* set noref for now.
  2381. * any place which wants to hold dst has to call
  2382. * dst_hold_safe()
  2383. */
  2384. skb_dst_set_noref(skb, dst);
  2385. /* for unconnected multicast sockets we need to validate
  2386. * the source on each packet
  2387. */
  2388. if (!inet_sk(sk)->inet_daddr && in_dev)
  2389. return ip_mc_validate_source(skb, iph->daddr,
  2390. iph->saddr,
  2391. iph->tos & IPTOS_RT_MASK,
  2392. skb->dev, in_dev, &itag);
  2393. }
  2394. return 0;
  2395. }
  2396. int udp_rcv(struct sk_buff *skb)
  2397. {
  2398. return __udp4_lib_rcv(skb, &udp_table, IPPROTO_UDP);
  2399. }
  2400. void udp_destroy_sock(struct sock *sk)
  2401. {
  2402. struct udp_sock *up = udp_sk(sk);
  2403. bool slow = lock_sock_fast(sk);
  2404. /* protects from races with udp_abort() */
  2405. sock_set_flag(sk, SOCK_DEAD);
  2406. udp_flush_pending_frames(sk);
  2407. unlock_sock_fast(sk, slow);
  2408. if (static_branch_unlikely(&udp_encap_needed_key)) {
  2409. if (up->encap_type) {
  2410. void (*encap_destroy)(struct sock *sk);
  2411. encap_destroy = READ_ONCE(up->encap_destroy);
  2412. if (encap_destroy)
  2413. encap_destroy(sk);
  2414. }
  2415. if (up->encap_enabled)
  2416. static_branch_dec(&udp_encap_needed_key);
  2417. }
  2418. }
  2419. /*
  2420. * Socket option code for UDP
  2421. */
  2422. int udp_lib_setsockopt(struct sock *sk, int level, int optname,
  2423. sockptr_t optval, unsigned int optlen,
  2424. int (*push_pending_frames)(struct sock *))
  2425. {
  2426. struct udp_sock *up = udp_sk(sk);
  2427. int val, valbool;
  2428. int err = 0;
  2429. int is_udplite = IS_UDPLITE(sk);
  2430. if (optlen < sizeof(int))
  2431. return -EINVAL;
  2432. if (copy_from_sockptr(&val, optval, sizeof(val)))
  2433. return -EFAULT;
  2434. valbool = val ? 1 : 0;
  2435. switch (optname) {
  2436. case UDP_CORK:
  2437. if (val != 0) {
  2438. WRITE_ONCE(up->corkflag, 1);
  2439. } else {
  2440. WRITE_ONCE(up->corkflag, 0);
  2441. lock_sock(sk);
  2442. push_pending_frames(sk);
  2443. release_sock(sk);
  2444. }
  2445. break;
  2446. case UDP_ENCAP:
  2447. switch (val) {
  2448. case 0:
  2449. #ifdef CONFIG_XFRM
  2450. case UDP_ENCAP_ESPINUDP:
  2451. case UDP_ENCAP_ESPINUDP_NON_IKE:
  2452. #if IS_ENABLED(CONFIG_IPV6)
  2453. if (sk->sk_family == AF_INET6)
  2454. WRITE_ONCE(up->encap_rcv,
  2455. ipv6_stub->xfrm6_udp_encap_rcv);
  2456. else
  2457. #endif
  2458. WRITE_ONCE(up->encap_rcv,
  2459. xfrm4_udp_encap_rcv);
  2460. #endif
  2461. fallthrough;
  2462. case UDP_ENCAP_L2TPINUDP:
  2463. up->encap_type = val;
  2464. lock_sock(sk);
  2465. udp_tunnel_encap_enable(sk->sk_socket);
  2466. release_sock(sk);
  2467. break;
  2468. default:
  2469. err = -ENOPROTOOPT;
  2470. break;
  2471. }
  2472. break;
  2473. case UDP_NO_CHECK6_TX:
  2474. up->no_check6_tx = valbool;
  2475. break;
  2476. case UDP_NO_CHECK6_RX:
  2477. up->no_check6_rx = valbool;
  2478. break;
  2479. case UDP_SEGMENT:
  2480. if (val < 0 || val > USHRT_MAX)
  2481. return -EINVAL;
  2482. WRITE_ONCE(up->gso_size, val);
  2483. break;
  2484. case UDP_GRO:
  2485. lock_sock(sk);
  2486. /* when enabling GRO, accept the related GSO packet type */
  2487. if (valbool)
  2488. udp_tunnel_encap_enable(sk->sk_socket);
  2489. up->gro_enabled = valbool;
  2490. up->accept_udp_l4 = valbool;
  2491. release_sock(sk);
  2492. break;
  2493. /*
  2494. * UDP-Lite's partial checksum coverage (RFC 3828).
  2495. */
  2496. /* The sender sets actual checksum coverage length via this option.
  2497. * The case coverage > packet length is handled by send module. */
  2498. case UDPLITE_SEND_CSCOV:
  2499. if (!is_udplite) /* Disable the option on UDP sockets */
  2500. return -ENOPROTOOPT;
  2501. if (val != 0 && val < 8) /* Illegal coverage: use default (8) */
  2502. val = 8;
  2503. else if (val > USHRT_MAX)
  2504. val = USHRT_MAX;
  2505. up->pcslen = val;
  2506. up->pcflag |= UDPLITE_SEND_CC;
  2507. break;
  2508. /* The receiver specifies a minimum checksum coverage value. To make
  2509. * sense, this should be set to at least 8 (as done below). If zero is
  2510. * used, this again means full checksum coverage. */
  2511. case UDPLITE_RECV_CSCOV:
  2512. if (!is_udplite) /* Disable the option on UDP sockets */
  2513. return -ENOPROTOOPT;
  2514. if (val != 0 && val < 8) /* Avoid silly minimal values. */
  2515. val = 8;
  2516. else if (val > USHRT_MAX)
  2517. val = USHRT_MAX;
  2518. up->pcrlen = val;
  2519. up->pcflag |= UDPLITE_RECV_CC;
  2520. break;
  2521. default:
  2522. err = -ENOPROTOOPT;
  2523. break;
  2524. }
  2525. return err;
  2526. }
  2527. EXPORT_SYMBOL(udp_lib_setsockopt);
  2528. int udp_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval,
  2529. unsigned int optlen)
  2530. {
  2531. if (level == SOL_UDP || level == SOL_UDPLITE)
  2532. return udp_lib_setsockopt(sk, level, optname,
  2533. optval, optlen,
  2534. udp_push_pending_frames);
  2535. return ip_setsockopt(sk, level, optname, optval, optlen);
  2536. }
  2537. int udp_lib_getsockopt(struct sock *sk, int level, int optname,
  2538. char __user *optval, int __user *optlen)
  2539. {
  2540. struct udp_sock *up = udp_sk(sk);
  2541. int val, len;
  2542. if (get_user(len, optlen))
  2543. return -EFAULT;
  2544. len = min_t(unsigned int, len, sizeof(int));
  2545. if (len < 0)
  2546. return -EINVAL;
  2547. switch (optname) {
  2548. case UDP_CORK:
  2549. val = READ_ONCE(up->corkflag);
  2550. break;
  2551. case UDP_ENCAP:
  2552. val = up->encap_type;
  2553. break;
  2554. case UDP_NO_CHECK6_TX:
  2555. val = up->no_check6_tx;
  2556. break;
  2557. case UDP_NO_CHECK6_RX:
  2558. val = up->no_check6_rx;
  2559. break;
  2560. case UDP_SEGMENT:
  2561. val = READ_ONCE(up->gso_size);
  2562. break;
  2563. case UDP_GRO:
  2564. val = up->gro_enabled;
  2565. break;
  2566. /* The following two cannot be changed on UDP sockets, the return is
  2567. * always 0 (which corresponds to the full checksum coverage of UDP). */
  2568. case UDPLITE_SEND_CSCOV:
  2569. val = up->pcslen;
  2570. break;
  2571. case UDPLITE_RECV_CSCOV:
  2572. val = up->pcrlen;
  2573. break;
  2574. default:
  2575. return -ENOPROTOOPT;
  2576. }
  2577. if (put_user(len, optlen))
  2578. return -EFAULT;
  2579. if (copy_to_user(optval, &val, len))
  2580. return -EFAULT;
  2581. return 0;
  2582. }
  2583. EXPORT_SYMBOL(udp_lib_getsockopt);
  2584. int udp_getsockopt(struct sock *sk, int level, int optname,
  2585. char __user *optval, int __user *optlen)
  2586. {
  2587. if (level == SOL_UDP || level == SOL_UDPLITE)
  2588. return udp_lib_getsockopt(sk, level, optname, optval, optlen);
  2589. return ip_getsockopt(sk, level, optname, optval, optlen);
  2590. }
  2591. /**
  2592. * udp_poll - wait for a UDP event.
  2593. * @file: - file struct
  2594. * @sock: - socket
  2595. * @wait: - poll table
  2596. *
  2597. * This is same as datagram poll, except for the special case of
  2598. * blocking sockets. If application is using a blocking fd
  2599. * and a packet with checksum error is in the queue;
  2600. * then it could get return from select indicating data available
  2601. * but then block when reading it. Add special case code
  2602. * to work around these arguably broken applications.
  2603. */
  2604. __poll_t udp_poll(struct file *file, struct socket *sock, poll_table *wait)
  2605. {
  2606. __poll_t mask = datagram_poll(file, sock, wait);
  2607. struct sock *sk = sock->sk;
  2608. if (!skb_queue_empty_lockless(&udp_sk(sk)->reader_queue))
  2609. mask |= EPOLLIN | EPOLLRDNORM;
  2610. /* Check for false positives due to checksum errors */
  2611. if ((mask & EPOLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
  2612. !(sk->sk_shutdown & RCV_SHUTDOWN) && first_packet_length(sk) == -1)
  2613. mask &= ~(EPOLLIN | EPOLLRDNORM);
  2614. /* psock ingress_msg queue should not contain any bad checksum frames */
  2615. if (sk_is_readable(sk))
  2616. mask |= EPOLLIN | EPOLLRDNORM;
  2617. return mask;
  2618. }
  2619. EXPORT_SYMBOL(udp_poll);
  2620. int udp_abort(struct sock *sk, int err)
  2621. {
  2622. lock_sock(sk);
  2623. /* udp{v6}_destroy_sock() sets it under the sk lock, avoid racing
  2624. * with close()
  2625. */
  2626. if (sock_flag(sk, SOCK_DEAD))
  2627. goto out;
  2628. sk->sk_err = err;
  2629. sk_error_report(sk);
  2630. __udp_disconnect(sk, 0);
  2631. out:
  2632. release_sock(sk);
  2633. return 0;
  2634. }
  2635. EXPORT_SYMBOL_GPL(udp_abort);
  2636. struct proto udp_prot = {
  2637. .name = "UDP",
  2638. .owner = THIS_MODULE,
  2639. .close = udp_lib_close,
  2640. .pre_connect = udp_pre_connect,
  2641. .connect = ip4_datagram_connect,
  2642. .disconnect = udp_disconnect,
  2643. .ioctl = udp_ioctl,
  2644. .init = udp_init_sock,
  2645. .destroy = udp_destroy_sock,
  2646. .setsockopt = udp_setsockopt,
  2647. .getsockopt = udp_getsockopt,
  2648. .sendmsg = udp_sendmsg,
  2649. .recvmsg = udp_recvmsg,
  2650. .sendpage = udp_sendpage,
  2651. .release_cb = ip4_datagram_release_cb,
  2652. .hash = udp_lib_hash,
  2653. .unhash = udp_lib_unhash,
  2654. .rehash = udp_v4_rehash,
  2655. .get_port = udp_v4_get_port,
  2656. .put_port = udp_lib_unhash,
  2657. #ifdef CONFIG_BPF_SYSCALL
  2658. .psock_update_sk_prot = udp_bpf_update_proto,
  2659. #endif
  2660. .memory_allocated = &udp_memory_allocated,
  2661. .per_cpu_fw_alloc = &udp_memory_per_cpu_fw_alloc,
  2662. .sysctl_mem = sysctl_udp_mem,
  2663. .sysctl_wmem_offset = offsetof(struct net, ipv4.sysctl_udp_wmem_min),
  2664. .sysctl_rmem_offset = offsetof(struct net, ipv4.sysctl_udp_rmem_min),
  2665. .obj_size = sizeof(struct udp_sock),
  2666. .h.udp_table = &udp_table,
  2667. .diag_destroy = udp_abort,
  2668. };
  2669. EXPORT_SYMBOL(udp_prot);
  2670. /* ------------------------------------------------------------------------ */
  2671. #ifdef CONFIG_PROC_FS
  2672. static struct sock *udp_get_first(struct seq_file *seq, int start)
  2673. {
  2674. struct udp_iter_state *state = seq->private;
  2675. struct net *net = seq_file_net(seq);
  2676. struct udp_seq_afinfo *afinfo;
  2677. struct sock *sk;
  2678. if (state->bpf_seq_afinfo)
  2679. afinfo = state->bpf_seq_afinfo;
  2680. else
  2681. afinfo = pde_data(file_inode(seq->file));
  2682. for (state->bucket = start; state->bucket <= afinfo->udp_table->mask;
  2683. ++state->bucket) {
  2684. struct udp_hslot *hslot = &afinfo->udp_table->hash[state->bucket];
  2685. if (hlist_empty(&hslot->head))
  2686. continue;
  2687. spin_lock_bh(&hslot->lock);
  2688. sk_for_each(sk, &hslot->head) {
  2689. if (!net_eq(sock_net(sk), net))
  2690. continue;
  2691. if (afinfo->family == AF_UNSPEC ||
  2692. sk->sk_family == afinfo->family)
  2693. goto found;
  2694. }
  2695. spin_unlock_bh(&hslot->lock);
  2696. }
  2697. sk = NULL;
  2698. found:
  2699. return sk;
  2700. }
  2701. static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
  2702. {
  2703. struct udp_iter_state *state = seq->private;
  2704. struct net *net = seq_file_net(seq);
  2705. struct udp_seq_afinfo *afinfo;
  2706. if (state->bpf_seq_afinfo)
  2707. afinfo = state->bpf_seq_afinfo;
  2708. else
  2709. afinfo = pde_data(file_inode(seq->file));
  2710. do {
  2711. sk = sk_next(sk);
  2712. } while (sk && (!net_eq(sock_net(sk), net) ||
  2713. (afinfo->family != AF_UNSPEC &&
  2714. sk->sk_family != afinfo->family)));
  2715. if (!sk) {
  2716. if (state->bucket <= afinfo->udp_table->mask)
  2717. spin_unlock_bh(&afinfo->udp_table->hash[state->bucket].lock);
  2718. return udp_get_first(seq, state->bucket + 1);
  2719. }
  2720. return sk;
  2721. }
  2722. static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
  2723. {
  2724. struct sock *sk = udp_get_first(seq, 0);
  2725. if (sk)
  2726. while (pos && (sk = udp_get_next(seq, sk)) != NULL)
  2727. --pos;
  2728. return pos ? NULL : sk;
  2729. }
  2730. void *udp_seq_start(struct seq_file *seq, loff_t *pos)
  2731. {
  2732. struct udp_iter_state *state = seq->private;
  2733. state->bucket = MAX_UDP_PORTS;
  2734. return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
  2735. }
  2736. EXPORT_SYMBOL(udp_seq_start);
  2737. void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
  2738. {
  2739. struct sock *sk;
  2740. if (v == SEQ_START_TOKEN)
  2741. sk = udp_get_idx(seq, 0);
  2742. else
  2743. sk = udp_get_next(seq, v);
  2744. ++*pos;
  2745. return sk;
  2746. }
  2747. EXPORT_SYMBOL(udp_seq_next);
  2748. void udp_seq_stop(struct seq_file *seq, void *v)
  2749. {
  2750. struct udp_iter_state *state = seq->private;
  2751. struct udp_seq_afinfo *afinfo;
  2752. if (state->bpf_seq_afinfo)
  2753. afinfo = state->bpf_seq_afinfo;
  2754. else
  2755. afinfo = pde_data(file_inode(seq->file));
  2756. if (state->bucket <= afinfo->udp_table->mask)
  2757. spin_unlock_bh(&afinfo->udp_table->hash[state->bucket].lock);
  2758. }
  2759. EXPORT_SYMBOL(udp_seq_stop);
  2760. /* ------------------------------------------------------------------------ */
  2761. static void udp4_format_sock(struct sock *sp, struct seq_file *f,
  2762. int bucket)
  2763. {
  2764. struct inet_sock *inet = inet_sk(sp);
  2765. __be32 dest = inet->inet_daddr;
  2766. __be32 src = inet->inet_rcv_saddr;
  2767. __u16 destp = ntohs(inet->inet_dport);
  2768. __u16 srcp = ntohs(inet->inet_sport);
  2769. seq_printf(f, "%5d: %08X:%04X %08X:%04X"
  2770. " %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %u",
  2771. bucket, src, srcp, dest, destp, sp->sk_state,
  2772. sk_wmem_alloc_get(sp),
  2773. udp_rqueue_get(sp),
  2774. 0, 0L, 0,
  2775. from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
  2776. 0, sock_i_ino(sp),
  2777. refcount_read(&sp->sk_refcnt), sp,
  2778. atomic_read(&sp->sk_drops));
  2779. }
  2780. int udp4_seq_show(struct seq_file *seq, void *v)
  2781. {
  2782. seq_setwidth(seq, 127);
  2783. if (v == SEQ_START_TOKEN)
  2784. seq_puts(seq, " sl local_address rem_address st tx_queue "
  2785. "rx_queue tr tm->when retrnsmt uid timeout "
  2786. "inode ref pointer drops");
  2787. else {
  2788. struct udp_iter_state *state = seq->private;
  2789. udp4_format_sock(v, seq, state->bucket);
  2790. }
  2791. seq_pad(seq, '\n');
  2792. return 0;
  2793. }
  2794. #ifdef CONFIG_BPF_SYSCALL
  2795. struct bpf_iter__udp {
  2796. __bpf_md_ptr(struct bpf_iter_meta *, meta);
  2797. __bpf_md_ptr(struct udp_sock *, udp_sk);
  2798. uid_t uid __aligned(8);
  2799. int bucket __aligned(8);
  2800. };
  2801. static int udp_prog_seq_show(struct bpf_prog *prog, struct bpf_iter_meta *meta,
  2802. struct udp_sock *udp_sk, uid_t uid, int bucket)
  2803. {
  2804. struct bpf_iter__udp ctx;
  2805. meta->seq_num--; /* skip SEQ_START_TOKEN */
  2806. ctx.meta = meta;
  2807. ctx.udp_sk = udp_sk;
  2808. ctx.uid = uid;
  2809. ctx.bucket = bucket;
  2810. return bpf_iter_run_prog(prog, &ctx);
  2811. }
  2812. static int bpf_iter_udp_seq_show(struct seq_file *seq, void *v)
  2813. {
  2814. struct udp_iter_state *state = seq->private;
  2815. struct bpf_iter_meta meta;
  2816. struct bpf_prog *prog;
  2817. struct sock *sk = v;
  2818. uid_t uid;
  2819. if (v == SEQ_START_TOKEN)
  2820. return 0;
  2821. uid = from_kuid_munged(seq_user_ns(seq), sock_i_uid(sk));
  2822. meta.seq = seq;
  2823. prog = bpf_iter_get_info(&meta, false);
  2824. return udp_prog_seq_show(prog, &meta, v, uid, state->bucket);
  2825. }
  2826. static void bpf_iter_udp_seq_stop(struct seq_file *seq, void *v)
  2827. {
  2828. struct bpf_iter_meta meta;
  2829. struct bpf_prog *prog;
  2830. if (!v) {
  2831. meta.seq = seq;
  2832. prog = bpf_iter_get_info(&meta, true);
  2833. if (prog)
  2834. (void)udp_prog_seq_show(prog, &meta, v, 0, 0);
  2835. }
  2836. udp_seq_stop(seq, v);
  2837. }
  2838. static const struct seq_operations bpf_iter_udp_seq_ops = {
  2839. .start = udp_seq_start,
  2840. .next = udp_seq_next,
  2841. .stop = bpf_iter_udp_seq_stop,
  2842. .show = bpf_iter_udp_seq_show,
  2843. };
  2844. #endif
  2845. const struct seq_operations udp_seq_ops = {
  2846. .start = udp_seq_start,
  2847. .next = udp_seq_next,
  2848. .stop = udp_seq_stop,
  2849. .show = udp4_seq_show,
  2850. };
  2851. EXPORT_SYMBOL(udp_seq_ops);
  2852. static struct udp_seq_afinfo udp4_seq_afinfo = {
  2853. .family = AF_INET,
  2854. .udp_table = &udp_table,
  2855. };
  2856. static int __net_init udp4_proc_init_net(struct net *net)
  2857. {
  2858. if (!proc_create_net_data("udp", 0444, net->proc_net, &udp_seq_ops,
  2859. sizeof(struct udp_iter_state), &udp4_seq_afinfo))
  2860. return -ENOMEM;
  2861. return 0;
  2862. }
  2863. static void __net_exit udp4_proc_exit_net(struct net *net)
  2864. {
  2865. remove_proc_entry("udp", net->proc_net);
  2866. }
  2867. static struct pernet_operations udp4_net_ops = {
  2868. .init = udp4_proc_init_net,
  2869. .exit = udp4_proc_exit_net,
  2870. };
  2871. int __init udp4_proc_init(void)
  2872. {
  2873. return register_pernet_subsys(&udp4_net_ops);
  2874. }
  2875. void udp4_proc_exit(void)
  2876. {
  2877. unregister_pernet_subsys(&udp4_net_ops);
  2878. }
  2879. #endif /* CONFIG_PROC_FS */
  2880. static __initdata unsigned long uhash_entries;
  2881. static int __init set_uhash_entries(char *str)
  2882. {
  2883. ssize_t ret;
  2884. if (!str)
  2885. return 0;
  2886. ret = kstrtoul(str, 0, &uhash_entries);
  2887. if (ret)
  2888. return 0;
  2889. if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
  2890. uhash_entries = UDP_HTABLE_SIZE_MIN;
  2891. return 1;
  2892. }
  2893. __setup("uhash_entries=", set_uhash_entries);
  2894. void __init udp_table_init(struct udp_table *table, const char *name)
  2895. {
  2896. unsigned int i;
  2897. table->hash = alloc_large_system_hash(name,
  2898. 2 * sizeof(struct udp_hslot),
  2899. uhash_entries,
  2900. 21, /* one slot per 2 MB */
  2901. 0,
  2902. &table->log,
  2903. &table->mask,
  2904. UDP_HTABLE_SIZE_MIN,
  2905. 64 * 1024);
  2906. table->hash2 = table->hash + (table->mask + 1);
  2907. for (i = 0; i <= table->mask; i++) {
  2908. INIT_HLIST_HEAD(&table->hash[i].head);
  2909. table->hash[i].count = 0;
  2910. spin_lock_init(&table->hash[i].lock);
  2911. }
  2912. for (i = 0; i <= table->mask; i++) {
  2913. INIT_HLIST_HEAD(&table->hash2[i].head);
  2914. table->hash2[i].count = 0;
  2915. spin_lock_init(&table->hash2[i].lock);
  2916. }
  2917. }
  2918. u32 udp_flow_hashrnd(void)
  2919. {
  2920. static u32 hashrnd __read_mostly;
  2921. net_get_random_once(&hashrnd, sizeof(hashrnd));
  2922. return hashrnd;
  2923. }
  2924. EXPORT_SYMBOL(udp_flow_hashrnd);
  2925. static int __net_init udp_sysctl_init(struct net *net)
  2926. {
  2927. net->ipv4.sysctl_udp_rmem_min = PAGE_SIZE;
  2928. net->ipv4.sysctl_udp_wmem_min = PAGE_SIZE;
  2929. #ifdef CONFIG_NET_L3_MASTER_DEV
  2930. net->ipv4.sysctl_udp_l3mdev_accept = 0;
  2931. #endif
  2932. return 0;
  2933. }
  2934. static struct pernet_operations __net_initdata udp_sysctl_ops = {
  2935. .init = udp_sysctl_init,
  2936. };
  2937. #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
  2938. DEFINE_BPF_ITER_FUNC(udp, struct bpf_iter_meta *meta,
  2939. struct udp_sock *udp_sk, uid_t uid, int bucket)
  2940. static int bpf_iter_init_udp(void *priv_data, struct bpf_iter_aux_info *aux)
  2941. {
  2942. struct udp_iter_state *st = priv_data;
  2943. struct udp_seq_afinfo *afinfo;
  2944. int ret;
  2945. afinfo = kmalloc(sizeof(*afinfo), GFP_USER | __GFP_NOWARN);
  2946. if (!afinfo)
  2947. return -ENOMEM;
  2948. afinfo->family = AF_UNSPEC;
  2949. afinfo->udp_table = &udp_table;
  2950. st->bpf_seq_afinfo = afinfo;
  2951. ret = bpf_iter_init_seq_net(priv_data, aux);
  2952. if (ret)
  2953. kfree(afinfo);
  2954. return ret;
  2955. }
  2956. static void bpf_iter_fini_udp(void *priv_data)
  2957. {
  2958. struct udp_iter_state *st = priv_data;
  2959. kfree(st->bpf_seq_afinfo);
  2960. bpf_iter_fini_seq_net(priv_data);
  2961. }
  2962. static const struct bpf_iter_seq_info udp_seq_info = {
  2963. .seq_ops = &bpf_iter_udp_seq_ops,
  2964. .init_seq_private = bpf_iter_init_udp,
  2965. .fini_seq_private = bpf_iter_fini_udp,
  2966. .seq_priv_size = sizeof(struct udp_iter_state),
  2967. };
  2968. static struct bpf_iter_reg udp_reg_info = {
  2969. .target = "udp",
  2970. .ctx_arg_info_size = 1,
  2971. .ctx_arg_info = {
  2972. { offsetof(struct bpf_iter__udp, udp_sk),
  2973. PTR_TO_BTF_ID_OR_NULL },
  2974. },
  2975. .seq_info = &udp_seq_info,
  2976. };
  2977. static void __init bpf_iter_register(void)
  2978. {
  2979. udp_reg_info.ctx_arg_info[0].btf_id = btf_sock_ids[BTF_SOCK_TYPE_UDP];
  2980. if (bpf_iter_reg_target(&udp_reg_info))
  2981. pr_warn("Warning: could not register bpf iterator udp\n");
  2982. }
  2983. #endif
  2984. void __init udp_init(void)
  2985. {
  2986. unsigned long limit;
  2987. unsigned int i;
  2988. udp_table_init(&udp_table, "UDP");
  2989. limit = nr_free_buffer_pages() / 8;
  2990. limit = max(limit, 128UL);
  2991. sysctl_udp_mem[0] = limit / 4 * 3;
  2992. sysctl_udp_mem[1] = limit;
  2993. sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
  2994. /* 16 spinlocks per cpu */
  2995. udp_busylocks_log = ilog2(nr_cpu_ids) + 4;
  2996. udp_busylocks = kmalloc(sizeof(spinlock_t) << udp_busylocks_log,
  2997. GFP_KERNEL);
  2998. if (!udp_busylocks)
  2999. panic("UDP: failed to alloc udp_busylocks\n");
  3000. for (i = 0; i < (1U << udp_busylocks_log); i++)
  3001. spin_lock_init(udp_busylocks + i);
  3002. if (register_pernet_subsys(&udp_sysctl_ops))
  3003. panic("UDP: failed to init sysctl parameters.\n");
  3004. #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
  3005. bpf_iter_register();
  3006. #endif
  3007. }