af_packet.c 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768
  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. * PACKET - implements raw packet sockets.
  8. *
  9. * Authors: Ross Biro
  10. * Fred N. van Kempen, <[email protected]>
  11. * Alan Cox, <[email protected]>
  12. *
  13. * Fixes:
  14. * Alan Cox : verify_area() now used correctly
  15. * Alan Cox : new skbuff lists, look ma no backlogs!
  16. * Alan Cox : tidied skbuff lists.
  17. * Alan Cox : Now uses generic datagram routines I
  18. * added. Also fixed the peek/read crash
  19. * from all old Linux datagram code.
  20. * Alan Cox : Uses the improved datagram code.
  21. * Alan Cox : Added NULL's for socket options.
  22. * Alan Cox : Re-commented the code.
  23. * Alan Cox : Use new kernel side addressing
  24. * Rob Janssen : Correct MTU usage.
  25. * Dave Platt : Counter leaks caused by incorrect
  26. * interrupt locking and some slightly
  27. * dubious gcc output. Can you read
  28. * compiler: it said _VOLATILE_
  29. * Richard Kooijman : Timestamp fixes.
  30. * Alan Cox : New buffers. Use sk->mac.raw.
  31. * Alan Cox : sendmsg/recvmsg support.
  32. * Alan Cox : Protocol setting support
  33. * Alexey Kuznetsov : Untied from IPv4 stack.
  34. * Cyrus Durgin : Fixed kerneld for kmod.
  35. * Michal Ostrowski : Module initialization cleanup.
  36. * Ulises Alonso : Frame number limit removal and
  37. * packet_set_ring memory leak.
  38. * Eric Biederman : Allow for > 8 byte hardware addresses.
  39. * The convention is that longer addresses
  40. * will simply extend the hardware address
  41. * byte arrays at the end of sockaddr_ll
  42. * and packet_mreq.
  43. * Johann Baudy : Added TX RING.
  44. * Chetan Loke : Implemented TPACKET_V3 block abstraction
  45. * layer.
  46. * Copyright (C) 2011, <[email protected]>
  47. */
  48. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  49. #include <linux/ethtool.h>
  50. #include <linux/filter.h>
  51. #include <linux/types.h>
  52. #include <linux/mm.h>
  53. #include <linux/capability.h>
  54. #include <linux/fcntl.h>
  55. #include <linux/socket.h>
  56. #include <linux/in.h>
  57. #include <linux/inet.h>
  58. #include <linux/netdevice.h>
  59. #include <linux/if_packet.h>
  60. #include <linux/wireless.h>
  61. #include <linux/kernel.h>
  62. #include <linux/kmod.h>
  63. #include <linux/slab.h>
  64. #include <linux/vmalloc.h>
  65. #include <net/net_namespace.h>
  66. #include <net/ip.h>
  67. #include <net/protocol.h>
  68. #include <linux/skbuff.h>
  69. #include <net/sock.h>
  70. #include <linux/errno.h>
  71. #include <linux/timer.h>
  72. #include <linux/uaccess.h>
  73. #include <asm/ioctls.h>
  74. #include <asm/page.h>
  75. #include <asm/cacheflush.h>
  76. #include <asm/io.h>
  77. #include <linux/proc_fs.h>
  78. #include <linux/seq_file.h>
  79. #include <linux/poll.h>
  80. #include <linux/module.h>
  81. #include <linux/init.h>
  82. #include <linux/mutex.h>
  83. #include <linux/if_vlan.h>
  84. #include <linux/virtio_net.h>
  85. #include <linux/errqueue.h>
  86. #include <linux/net_tstamp.h>
  87. #include <linux/percpu.h>
  88. #ifdef CONFIG_INET
  89. #include <net/inet_common.h>
  90. #endif
  91. #include <linux/bpf.h>
  92. #include <net/compat.h>
  93. #include <linux/netfilter_netdev.h>
  94. #include "internal.h"
  95. /*
  96. Assumptions:
  97. - If the device has no dev->header_ops->create, there is no LL header
  98. visible above the device. In this case, its hard_header_len should be 0.
  99. The device may prepend its own header internally. In this case, its
  100. needed_headroom should be set to the space needed for it to add its
  101. internal header.
  102. For example, a WiFi driver pretending to be an Ethernet driver should
  103. set its hard_header_len to be the Ethernet header length, and set its
  104. needed_headroom to be (the real WiFi header length - the fake Ethernet
  105. header length).
  106. - packet socket receives packets with pulled ll header,
  107. so that SOCK_RAW should push it back.
  108. On receive:
  109. -----------
  110. Incoming, dev_has_header(dev) == true
  111. mac_header -> ll header
  112. data -> data
  113. Outgoing, dev_has_header(dev) == true
  114. mac_header -> ll header
  115. data -> ll header
  116. Incoming, dev_has_header(dev) == false
  117. mac_header -> data
  118. However drivers often make it point to the ll header.
  119. This is incorrect because the ll header should be invisible to us.
  120. data -> data
  121. Outgoing, dev_has_header(dev) == false
  122. mac_header -> data. ll header is invisible to us.
  123. data -> data
  124. Resume
  125. If dev_has_header(dev) == false we are unable to restore the ll header,
  126. because it is invisible to us.
  127. On transmit:
  128. ------------
  129. dev_has_header(dev) == true
  130. mac_header -> ll header
  131. data -> ll header
  132. dev_has_header(dev) == false (ll header is invisible to us)
  133. mac_header -> data
  134. data -> data
  135. We should set network_header on output to the correct position,
  136. packet classifier depends on it.
  137. */
  138. /* Private packet socket structures. */
  139. /* identical to struct packet_mreq except it has
  140. * a longer address field.
  141. */
  142. struct packet_mreq_max {
  143. int mr_ifindex;
  144. unsigned short mr_type;
  145. unsigned short mr_alen;
  146. unsigned char mr_address[MAX_ADDR_LEN];
  147. };
  148. union tpacket_uhdr {
  149. struct tpacket_hdr *h1;
  150. struct tpacket2_hdr *h2;
  151. struct tpacket3_hdr *h3;
  152. void *raw;
  153. };
  154. static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
  155. int closing, int tx_ring);
  156. #define V3_ALIGNMENT (8)
  157. #define BLK_HDR_LEN (ALIGN(sizeof(struct tpacket_block_desc), V3_ALIGNMENT))
  158. #define BLK_PLUS_PRIV(sz_of_priv) \
  159. (BLK_HDR_LEN + ALIGN((sz_of_priv), V3_ALIGNMENT))
  160. #define BLOCK_STATUS(x) ((x)->hdr.bh1.block_status)
  161. #define BLOCK_NUM_PKTS(x) ((x)->hdr.bh1.num_pkts)
  162. #define BLOCK_O2FP(x) ((x)->hdr.bh1.offset_to_first_pkt)
  163. #define BLOCK_LEN(x) ((x)->hdr.bh1.blk_len)
  164. #define BLOCK_SNUM(x) ((x)->hdr.bh1.seq_num)
  165. #define BLOCK_O2PRIV(x) ((x)->offset_to_priv)
  166. struct packet_sock;
  167. static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
  168. struct packet_type *pt, struct net_device *orig_dev);
  169. static void *packet_previous_frame(struct packet_sock *po,
  170. struct packet_ring_buffer *rb,
  171. int status);
  172. static void packet_increment_head(struct packet_ring_buffer *buff);
  173. static int prb_curr_blk_in_use(struct tpacket_block_desc *);
  174. static void *prb_dispatch_next_block(struct tpacket_kbdq_core *,
  175. struct packet_sock *);
  176. static void prb_retire_current_block(struct tpacket_kbdq_core *,
  177. struct packet_sock *, unsigned int status);
  178. static int prb_queue_frozen(struct tpacket_kbdq_core *);
  179. static void prb_open_block(struct tpacket_kbdq_core *,
  180. struct tpacket_block_desc *);
  181. static void prb_retire_rx_blk_timer_expired(struct timer_list *);
  182. static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *);
  183. static void prb_fill_rxhash(struct tpacket_kbdq_core *, struct tpacket3_hdr *);
  184. static void prb_clear_rxhash(struct tpacket_kbdq_core *,
  185. struct tpacket3_hdr *);
  186. static void prb_fill_vlan_info(struct tpacket_kbdq_core *,
  187. struct tpacket3_hdr *);
  188. static void packet_flush_mclist(struct sock *sk);
  189. static u16 packet_pick_tx_queue(struct sk_buff *skb);
  190. struct packet_skb_cb {
  191. union {
  192. struct sockaddr_pkt pkt;
  193. union {
  194. /* Trick: alias skb original length with
  195. * ll.sll_family and ll.protocol in order
  196. * to save room.
  197. */
  198. unsigned int origlen;
  199. struct sockaddr_ll ll;
  200. };
  201. } sa;
  202. };
  203. #define vio_le() virtio_legacy_is_little_endian()
  204. #define PACKET_SKB_CB(__skb) ((struct packet_skb_cb *)((__skb)->cb))
  205. #define GET_PBDQC_FROM_RB(x) ((struct tpacket_kbdq_core *)(&(x)->prb_bdqc))
  206. #define GET_PBLOCK_DESC(x, bid) \
  207. ((struct tpacket_block_desc *)((x)->pkbdq[(bid)].buffer))
  208. #define GET_CURR_PBLOCK_DESC_FROM_CORE(x) \
  209. ((struct tpacket_block_desc *)((x)->pkbdq[(x)->kactive_blk_num].buffer))
  210. #define GET_NEXT_PRB_BLK_NUM(x) \
  211. (((x)->kactive_blk_num < ((x)->knum_blocks-1)) ? \
  212. ((x)->kactive_blk_num+1) : 0)
  213. static void __fanout_unlink(struct sock *sk, struct packet_sock *po);
  214. static void __fanout_link(struct sock *sk, struct packet_sock *po);
  215. #ifdef CONFIG_NETFILTER_EGRESS
  216. static noinline struct sk_buff *nf_hook_direct_egress(struct sk_buff *skb)
  217. {
  218. struct sk_buff *next, *head = NULL, *tail;
  219. int rc;
  220. rcu_read_lock();
  221. for (; skb != NULL; skb = next) {
  222. next = skb->next;
  223. skb_mark_not_on_list(skb);
  224. if (!nf_hook_egress(skb, &rc, skb->dev))
  225. continue;
  226. if (!head)
  227. head = skb;
  228. else
  229. tail->next = skb;
  230. tail = skb;
  231. }
  232. rcu_read_unlock();
  233. return head;
  234. }
  235. #endif
  236. static int packet_direct_xmit(struct sk_buff *skb)
  237. {
  238. #ifdef CONFIG_NETFILTER_EGRESS
  239. if (nf_hook_egress_active()) {
  240. skb = nf_hook_direct_egress(skb);
  241. if (!skb)
  242. return NET_XMIT_DROP;
  243. }
  244. #endif
  245. return dev_direct_xmit(skb, packet_pick_tx_queue(skb));
  246. }
  247. static struct net_device *packet_cached_dev_get(struct packet_sock *po)
  248. {
  249. struct net_device *dev;
  250. rcu_read_lock();
  251. dev = rcu_dereference(po->cached_dev);
  252. dev_hold(dev);
  253. rcu_read_unlock();
  254. return dev;
  255. }
  256. static void packet_cached_dev_assign(struct packet_sock *po,
  257. struct net_device *dev)
  258. {
  259. rcu_assign_pointer(po->cached_dev, dev);
  260. }
  261. static void packet_cached_dev_reset(struct packet_sock *po)
  262. {
  263. RCU_INIT_POINTER(po->cached_dev, NULL);
  264. }
  265. static bool packet_use_direct_xmit(const struct packet_sock *po)
  266. {
  267. /* Paired with WRITE_ONCE() in packet_setsockopt() */
  268. return READ_ONCE(po->xmit) == packet_direct_xmit;
  269. }
  270. static u16 packet_pick_tx_queue(struct sk_buff *skb)
  271. {
  272. struct net_device *dev = skb->dev;
  273. const struct net_device_ops *ops = dev->netdev_ops;
  274. int cpu = raw_smp_processor_id();
  275. u16 queue_index;
  276. #ifdef CONFIG_XPS
  277. skb->sender_cpu = cpu + 1;
  278. #endif
  279. skb_record_rx_queue(skb, cpu % dev->real_num_tx_queues);
  280. if (ops->ndo_select_queue) {
  281. queue_index = ops->ndo_select_queue(dev, skb, NULL);
  282. queue_index = netdev_cap_txqueue(dev, queue_index);
  283. } else {
  284. queue_index = netdev_pick_tx(dev, skb, NULL);
  285. }
  286. return queue_index;
  287. }
  288. /* __register_prot_hook must be invoked through register_prot_hook
  289. * or from a context in which asynchronous accesses to the packet
  290. * socket is not possible (packet_create()).
  291. */
  292. static void __register_prot_hook(struct sock *sk)
  293. {
  294. struct packet_sock *po = pkt_sk(sk);
  295. if (!po->running) {
  296. if (po->fanout)
  297. __fanout_link(sk, po);
  298. else
  299. dev_add_pack(&po->prot_hook);
  300. sock_hold(sk);
  301. po->running = 1;
  302. }
  303. }
  304. static void register_prot_hook(struct sock *sk)
  305. {
  306. lockdep_assert_held_once(&pkt_sk(sk)->bind_lock);
  307. __register_prot_hook(sk);
  308. }
  309. /* If the sync parameter is true, we will temporarily drop
  310. * the po->bind_lock and do a synchronize_net to make sure no
  311. * asynchronous packet processing paths still refer to the elements
  312. * of po->prot_hook. If the sync parameter is false, it is the
  313. * callers responsibility to take care of this.
  314. */
  315. static void __unregister_prot_hook(struct sock *sk, bool sync)
  316. {
  317. struct packet_sock *po = pkt_sk(sk);
  318. lockdep_assert_held_once(&po->bind_lock);
  319. po->running = 0;
  320. if (po->fanout)
  321. __fanout_unlink(sk, po);
  322. else
  323. __dev_remove_pack(&po->prot_hook);
  324. __sock_put(sk);
  325. if (sync) {
  326. spin_unlock(&po->bind_lock);
  327. synchronize_net();
  328. spin_lock(&po->bind_lock);
  329. }
  330. }
  331. static void unregister_prot_hook(struct sock *sk, bool sync)
  332. {
  333. struct packet_sock *po = pkt_sk(sk);
  334. if (po->running)
  335. __unregister_prot_hook(sk, sync);
  336. }
  337. static inline struct page * __pure pgv_to_page(void *addr)
  338. {
  339. if (is_vmalloc_addr(addr))
  340. return vmalloc_to_page(addr);
  341. return virt_to_page(addr);
  342. }
  343. static void __packet_set_status(struct packet_sock *po, void *frame, int status)
  344. {
  345. union tpacket_uhdr h;
  346. /* WRITE_ONCE() are paired with READ_ONCE() in __packet_get_status */
  347. h.raw = frame;
  348. switch (po->tp_version) {
  349. case TPACKET_V1:
  350. WRITE_ONCE(h.h1->tp_status, status);
  351. flush_dcache_page(pgv_to_page(&h.h1->tp_status));
  352. break;
  353. case TPACKET_V2:
  354. WRITE_ONCE(h.h2->tp_status, status);
  355. flush_dcache_page(pgv_to_page(&h.h2->tp_status));
  356. break;
  357. case TPACKET_V3:
  358. WRITE_ONCE(h.h3->tp_status, status);
  359. flush_dcache_page(pgv_to_page(&h.h3->tp_status));
  360. break;
  361. default:
  362. WARN(1, "TPACKET version not supported.\n");
  363. BUG();
  364. }
  365. smp_wmb();
  366. }
  367. static int __packet_get_status(const struct packet_sock *po, void *frame)
  368. {
  369. union tpacket_uhdr h;
  370. smp_rmb();
  371. /* READ_ONCE() are paired with WRITE_ONCE() in __packet_set_status */
  372. h.raw = frame;
  373. switch (po->tp_version) {
  374. case TPACKET_V1:
  375. flush_dcache_page(pgv_to_page(&h.h1->tp_status));
  376. return READ_ONCE(h.h1->tp_status);
  377. case TPACKET_V2:
  378. flush_dcache_page(pgv_to_page(&h.h2->tp_status));
  379. return READ_ONCE(h.h2->tp_status);
  380. case TPACKET_V3:
  381. flush_dcache_page(pgv_to_page(&h.h3->tp_status));
  382. return READ_ONCE(h.h3->tp_status);
  383. default:
  384. WARN(1, "TPACKET version not supported.\n");
  385. BUG();
  386. return 0;
  387. }
  388. }
  389. static __u32 tpacket_get_timestamp(struct sk_buff *skb, struct timespec64 *ts,
  390. unsigned int flags)
  391. {
  392. struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
  393. if (shhwtstamps &&
  394. (flags & SOF_TIMESTAMPING_RAW_HARDWARE) &&
  395. ktime_to_timespec64_cond(shhwtstamps->hwtstamp, ts))
  396. return TP_STATUS_TS_RAW_HARDWARE;
  397. if ((flags & SOF_TIMESTAMPING_SOFTWARE) &&
  398. ktime_to_timespec64_cond(skb_tstamp(skb), ts))
  399. return TP_STATUS_TS_SOFTWARE;
  400. return 0;
  401. }
  402. static __u32 __packet_set_timestamp(struct packet_sock *po, void *frame,
  403. struct sk_buff *skb)
  404. {
  405. union tpacket_uhdr h;
  406. struct timespec64 ts;
  407. __u32 ts_status;
  408. if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
  409. return 0;
  410. h.raw = frame;
  411. /*
  412. * versions 1 through 3 overflow the timestamps in y2106, since they
  413. * all store the seconds in a 32-bit unsigned integer.
  414. * If we create a version 4, that should have a 64-bit timestamp,
  415. * either 64-bit seconds + 32-bit nanoseconds, or just 64-bit
  416. * nanoseconds.
  417. */
  418. switch (po->tp_version) {
  419. case TPACKET_V1:
  420. h.h1->tp_sec = ts.tv_sec;
  421. h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
  422. break;
  423. case TPACKET_V2:
  424. h.h2->tp_sec = ts.tv_sec;
  425. h.h2->tp_nsec = ts.tv_nsec;
  426. break;
  427. case TPACKET_V3:
  428. h.h3->tp_sec = ts.tv_sec;
  429. h.h3->tp_nsec = ts.tv_nsec;
  430. break;
  431. default:
  432. WARN(1, "TPACKET version not supported.\n");
  433. BUG();
  434. }
  435. /* one flush is safe, as both fields always lie on the same cacheline */
  436. flush_dcache_page(pgv_to_page(&h.h1->tp_sec));
  437. smp_wmb();
  438. return ts_status;
  439. }
  440. static void *packet_lookup_frame(const struct packet_sock *po,
  441. const struct packet_ring_buffer *rb,
  442. unsigned int position,
  443. int status)
  444. {
  445. unsigned int pg_vec_pos, frame_offset;
  446. union tpacket_uhdr h;
  447. pg_vec_pos = position / rb->frames_per_block;
  448. frame_offset = position % rb->frames_per_block;
  449. h.raw = rb->pg_vec[pg_vec_pos].buffer +
  450. (frame_offset * rb->frame_size);
  451. if (status != __packet_get_status(po, h.raw))
  452. return NULL;
  453. return h.raw;
  454. }
  455. static void *packet_current_frame(struct packet_sock *po,
  456. struct packet_ring_buffer *rb,
  457. int status)
  458. {
  459. return packet_lookup_frame(po, rb, rb->head, status);
  460. }
  461. static void prb_del_retire_blk_timer(struct tpacket_kbdq_core *pkc)
  462. {
  463. del_timer_sync(&pkc->retire_blk_timer);
  464. }
  465. static void prb_shutdown_retire_blk_timer(struct packet_sock *po,
  466. struct sk_buff_head *rb_queue)
  467. {
  468. struct tpacket_kbdq_core *pkc;
  469. pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
  470. spin_lock_bh(&rb_queue->lock);
  471. pkc->delete_blk_timer = 1;
  472. spin_unlock_bh(&rb_queue->lock);
  473. prb_del_retire_blk_timer(pkc);
  474. }
  475. static void prb_setup_retire_blk_timer(struct packet_sock *po)
  476. {
  477. struct tpacket_kbdq_core *pkc;
  478. pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
  479. timer_setup(&pkc->retire_blk_timer, prb_retire_rx_blk_timer_expired,
  480. 0);
  481. pkc->retire_blk_timer.expires = jiffies;
  482. }
  483. static int prb_calc_retire_blk_tmo(struct packet_sock *po,
  484. int blk_size_in_bytes)
  485. {
  486. struct net_device *dev;
  487. unsigned int mbits, div;
  488. struct ethtool_link_ksettings ecmd;
  489. int err;
  490. rtnl_lock();
  491. dev = __dev_get_by_index(sock_net(&po->sk), po->ifindex);
  492. if (unlikely(!dev)) {
  493. rtnl_unlock();
  494. return DEFAULT_PRB_RETIRE_TOV;
  495. }
  496. err = __ethtool_get_link_ksettings(dev, &ecmd);
  497. rtnl_unlock();
  498. if (err)
  499. return DEFAULT_PRB_RETIRE_TOV;
  500. /* If the link speed is so slow you don't really
  501. * need to worry about perf anyways
  502. */
  503. if (ecmd.base.speed < SPEED_1000 ||
  504. ecmd.base.speed == SPEED_UNKNOWN)
  505. return DEFAULT_PRB_RETIRE_TOV;
  506. div = ecmd.base.speed / 1000;
  507. mbits = (blk_size_in_bytes * 8) / (1024 * 1024);
  508. if (div)
  509. mbits /= div;
  510. if (div)
  511. return mbits + 1;
  512. return mbits;
  513. }
  514. static void prb_init_ft_ops(struct tpacket_kbdq_core *p1,
  515. union tpacket_req_u *req_u)
  516. {
  517. p1->feature_req_word = req_u->req3.tp_feature_req_word;
  518. }
  519. static void init_prb_bdqc(struct packet_sock *po,
  520. struct packet_ring_buffer *rb,
  521. struct pgv *pg_vec,
  522. union tpacket_req_u *req_u)
  523. {
  524. struct tpacket_kbdq_core *p1 = GET_PBDQC_FROM_RB(rb);
  525. struct tpacket_block_desc *pbd;
  526. memset(p1, 0x0, sizeof(*p1));
  527. p1->knxt_seq_num = 1;
  528. p1->pkbdq = pg_vec;
  529. pbd = (struct tpacket_block_desc *)pg_vec[0].buffer;
  530. p1->pkblk_start = pg_vec[0].buffer;
  531. p1->kblk_size = req_u->req3.tp_block_size;
  532. p1->knum_blocks = req_u->req3.tp_block_nr;
  533. p1->hdrlen = po->tp_hdrlen;
  534. p1->version = po->tp_version;
  535. p1->last_kactive_blk_num = 0;
  536. po->stats.stats3.tp_freeze_q_cnt = 0;
  537. if (req_u->req3.tp_retire_blk_tov)
  538. p1->retire_blk_tov = req_u->req3.tp_retire_blk_tov;
  539. else
  540. p1->retire_blk_tov = prb_calc_retire_blk_tmo(po,
  541. req_u->req3.tp_block_size);
  542. p1->tov_in_jiffies = msecs_to_jiffies(p1->retire_blk_tov);
  543. p1->blk_sizeof_priv = req_u->req3.tp_sizeof_priv;
  544. rwlock_init(&p1->blk_fill_in_prog_lock);
  545. p1->max_frame_len = p1->kblk_size - BLK_PLUS_PRIV(p1->blk_sizeof_priv);
  546. prb_init_ft_ops(p1, req_u);
  547. prb_setup_retire_blk_timer(po);
  548. prb_open_block(p1, pbd);
  549. }
  550. /* Do NOT update the last_blk_num first.
  551. * Assumes sk_buff_head lock is held.
  552. */
  553. static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *pkc)
  554. {
  555. mod_timer(&pkc->retire_blk_timer,
  556. jiffies + pkc->tov_in_jiffies);
  557. pkc->last_kactive_blk_num = pkc->kactive_blk_num;
  558. }
  559. /*
  560. * Timer logic:
  561. * 1) We refresh the timer only when we open a block.
  562. * By doing this we don't waste cycles refreshing the timer
  563. * on packet-by-packet basis.
  564. *
  565. * With a 1MB block-size, on a 1Gbps line, it will take
  566. * i) ~8 ms to fill a block + ii) memcpy etc.
  567. * In this cut we are not accounting for the memcpy time.
  568. *
  569. * So, if the user sets the 'tmo' to 10ms then the timer
  570. * will never fire while the block is still getting filled
  571. * (which is what we want). However, the user could choose
  572. * to close a block early and that's fine.
  573. *
  574. * But when the timer does fire, we check whether or not to refresh it.
  575. * Since the tmo granularity is in msecs, it is not too expensive
  576. * to refresh the timer, lets say every '8' msecs.
  577. * Either the user can set the 'tmo' or we can derive it based on
  578. * a) line-speed and b) block-size.
  579. * prb_calc_retire_blk_tmo() calculates the tmo.
  580. *
  581. */
  582. static void prb_retire_rx_blk_timer_expired(struct timer_list *t)
  583. {
  584. struct packet_sock *po =
  585. from_timer(po, t, rx_ring.prb_bdqc.retire_blk_timer);
  586. struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
  587. unsigned int frozen;
  588. struct tpacket_block_desc *pbd;
  589. spin_lock(&po->sk.sk_receive_queue.lock);
  590. frozen = prb_queue_frozen(pkc);
  591. pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
  592. if (unlikely(pkc->delete_blk_timer))
  593. goto out;
  594. /* We only need to plug the race when the block is partially filled.
  595. * tpacket_rcv:
  596. * lock(); increment BLOCK_NUM_PKTS; unlock()
  597. * copy_bits() is in progress ...
  598. * timer fires on other cpu:
  599. * we can't retire the current block because copy_bits
  600. * is in progress.
  601. *
  602. */
  603. if (BLOCK_NUM_PKTS(pbd)) {
  604. /* Waiting for skb_copy_bits to finish... */
  605. write_lock(&pkc->blk_fill_in_prog_lock);
  606. write_unlock(&pkc->blk_fill_in_prog_lock);
  607. }
  608. if (pkc->last_kactive_blk_num == pkc->kactive_blk_num) {
  609. if (!frozen) {
  610. if (!BLOCK_NUM_PKTS(pbd)) {
  611. /* An empty block. Just refresh the timer. */
  612. goto refresh_timer;
  613. }
  614. prb_retire_current_block(pkc, po, TP_STATUS_BLK_TMO);
  615. if (!prb_dispatch_next_block(pkc, po))
  616. goto refresh_timer;
  617. else
  618. goto out;
  619. } else {
  620. /* Case 1. Queue was frozen because user-space was
  621. * lagging behind.
  622. */
  623. if (prb_curr_blk_in_use(pbd)) {
  624. /*
  625. * Ok, user-space is still behind.
  626. * So just refresh the timer.
  627. */
  628. goto refresh_timer;
  629. } else {
  630. /* Case 2. queue was frozen,user-space caught up,
  631. * now the link went idle && the timer fired.
  632. * We don't have a block to close.So we open this
  633. * block and restart the timer.
  634. * opening a block thaws the queue,restarts timer
  635. * Thawing/timer-refresh is a side effect.
  636. */
  637. prb_open_block(pkc, pbd);
  638. goto out;
  639. }
  640. }
  641. }
  642. refresh_timer:
  643. _prb_refresh_rx_retire_blk_timer(pkc);
  644. out:
  645. spin_unlock(&po->sk.sk_receive_queue.lock);
  646. }
  647. static void prb_flush_block(struct tpacket_kbdq_core *pkc1,
  648. struct tpacket_block_desc *pbd1, __u32 status)
  649. {
  650. /* Flush everything minus the block header */
  651. #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
  652. u8 *start, *end;
  653. start = (u8 *)pbd1;
  654. /* Skip the block header(we know header WILL fit in 4K) */
  655. start += PAGE_SIZE;
  656. end = (u8 *)PAGE_ALIGN((unsigned long)pkc1->pkblk_end);
  657. for (; start < end; start += PAGE_SIZE)
  658. flush_dcache_page(pgv_to_page(start));
  659. smp_wmb();
  660. #endif
  661. /* Now update the block status. */
  662. BLOCK_STATUS(pbd1) = status;
  663. /* Flush the block header */
  664. #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
  665. start = (u8 *)pbd1;
  666. flush_dcache_page(pgv_to_page(start));
  667. smp_wmb();
  668. #endif
  669. }
  670. /*
  671. * Side effect:
  672. *
  673. * 1) flush the block
  674. * 2) Increment active_blk_num
  675. *
  676. * Note:We DONT refresh the timer on purpose.
  677. * Because almost always the next block will be opened.
  678. */
  679. static void prb_close_block(struct tpacket_kbdq_core *pkc1,
  680. struct tpacket_block_desc *pbd1,
  681. struct packet_sock *po, unsigned int stat)
  682. {
  683. __u32 status = TP_STATUS_USER | stat;
  684. struct tpacket3_hdr *last_pkt;
  685. struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
  686. struct sock *sk = &po->sk;
  687. if (atomic_read(&po->tp_drops))
  688. status |= TP_STATUS_LOSING;
  689. last_pkt = (struct tpacket3_hdr *)pkc1->prev;
  690. last_pkt->tp_next_offset = 0;
  691. /* Get the ts of the last pkt */
  692. if (BLOCK_NUM_PKTS(pbd1)) {
  693. h1->ts_last_pkt.ts_sec = last_pkt->tp_sec;
  694. h1->ts_last_pkt.ts_nsec = last_pkt->tp_nsec;
  695. } else {
  696. /* Ok, we tmo'd - so get the current time.
  697. *
  698. * It shouldn't really happen as we don't close empty
  699. * blocks. See prb_retire_rx_blk_timer_expired().
  700. */
  701. struct timespec64 ts;
  702. ktime_get_real_ts64(&ts);
  703. h1->ts_last_pkt.ts_sec = ts.tv_sec;
  704. h1->ts_last_pkt.ts_nsec = ts.tv_nsec;
  705. }
  706. smp_wmb();
  707. /* Flush the block */
  708. prb_flush_block(pkc1, pbd1, status);
  709. sk->sk_data_ready(sk);
  710. pkc1->kactive_blk_num = GET_NEXT_PRB_BLK_NUM(pkc1);
  711. }
  712. static void prb_thaw_queue(struct tpacket_kbdq_core *pkc)
  713. {
  714. pkc->reset_pending_on_curr_blk = 0;
  715. }
  716. /*
  717. * Side effect of opening a block:
  718. *
  719. * 1) prb_queue is thawed.
  720. * 2) retire_blk_timer is refreshed.
  721. *
  722. */
  723. static void prb_open_block(struct tpacket_kbdq_core *pkc1,
  724. struct tpacket_block_desc *pbd1)
  725. {
  726. struct timespec64 ts;
  727. struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
  728. smp_rmb();
  729. /* We could have just memset this but we will lose the
  730. * flexibility of making the priv area sticky
  731. */
  732. BLOCK_SNUM(pbd1) = pkc1->knxt_seq_num++;
  733. BLOCK_NUM_PKTS(pbd1) = 0;
  734. BLOCK_LEN(pbd1) = BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
  735. ktime_get_real_ts64(&ts);
  736. h1->ts_first_pkt.ts_sec = ts.tv_sec;
  737. h1->ts_first_pkt.ts_nsec = ts.tv_nsec;
  738. pkc1->pkblk_start = (char *)pbd1;
  739. pkc1->nxt_offset = pkc1->pkblk_start + BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
  740. BLOCK_O2FP(pbd1) = (__u32)BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
  741. BLOCK_O2PRIV(pbd1) = BLK_HDR_LEN;
  742. pbd1->version = pkc1->version;
  743. pkc1->prev = pkc1->nxt_offset;
  744. pkc1->pkblk_end = pkc1->pkblk_start + pkc1->kblk_size;
  745. prb_thaw_queue(pkc1);
  746. _prb_refresh_rx_retire_blk_timer(pkc1);
  747. smp_wmb();
  748. }
  749. /*
  750. * Queue freeze logic:
  751. * 1) Assume tp_block_nr = 8 blocks.
  752. * 2) At time 't0', user opens Rx ring.
  753. * 3) Some time past 't0', kernel starts filling blocks starting from 0 .. 7
  754. * 4) user-space is either sleeping or processing block '0'.
  755. * 5) tpacket_rcv is currently filling block '7', since there is no space left,
  756. * it will close block-7,loop around and try to fill block '0'.
  757. * call-flow:
  758. * __packet_lookup_frame_in_block
  759. * prb_retire_current_block()
  760. * prb_dispatch_next_block()
  761. * |->(BLOCK_STATUS == USER) evaluates to true
  762. * 5.1) Since block-0 is currently in-use, we just freeze the queue.
  763. * 6) Now there are two cases:
  764. * 6.1) Link goes idle right after the queue is frozen.
  765. * But remember, the last open_block() refreshed the timer.
  766. * When this timer expires,it will refresh itself so that we can
  767. * re-open block-0 in near future.
  768. * 6.2) Link is busy and keeps on receiving packets. This is a simple
  769. * case and __packet_lookup_frame_in_block will check if block-0
  770. * is free and can now be re-used.
  771. */
  772. static void prb_freeze_queue(struct tpacket_kbdq_core *pkc,
  773. struct packet_sock *po)
  774. {
  775. pkc->reset_pending_on_curr_blk = 1;
  776. po->stats.stats3.tp_freeze_q_cnt++;
  777. }
  778. #define TOTAL_PKT_LEN_INCL_ALIGN(length) (ALIGN((length), V3_ALIGNMENT))
  779. /*
  780. * If the next block is free then we will dispatch it
  781. * and return a good offset.
  782. * Else, we will freeze the queue.
  783. * So, caller must check the return value.
  784. */
  785. static void *prb_dispatch_next_block(struct tpacket_kbdq_core *pkc,
  786. struct packet_sock *po)
  787. {
  788. struct tpacket_block_desc *pbd;
  789. smp_rmb();
  790. /* 1. Get current block num */
  791. pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
  792. /* 2. If this block is currently in_use then freeze the queue */
  793. if (TP_STATUS_USER & BLOCK_STATUS(pbd)) {
  794. prb_freeze_queue(pkc, po);
  795. return NULL;
  796. }
  797. /*
  798. * 3.
  799. * open this block and return the offset where the first packet
  800. * needs to get stored.
  801. */
  802. prb_open_block(pkc, pbd);
  803. return (void *)pkc->nxt_offset;
  804. }
  805. static void prb_retire_current_block(struct tpacket_kbdq_core *pkc,
  806. struct packet_sock *po, unsigned int status)
  807. {
  808. struct tpacket_block_desc *pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
  809. /* retire/close the current block */
  810. if (likely(TP_STATUS_KERNEL == BLOCK_STATUS(pbd))) {
  811. /*
  812. * Plug the case where copy_bits() is in progress on
  813. * cpu-0 and tpacket_rcv() got invoked on cpu-1, didn't
  814. * have space to copy the pkt in the current block and
  815. * called prb_retire_current_block()
  816. *
  817. * We don't need to worry about the TMO case because
  818. * the timer-handler already handled this case.
  819. */
  820. if (!(status & TP_STATUS_BLK_TMO)) {
  821. /* Waiting for skb_copy_bits to finish... */
  822. write_lock(&pkc->blk_fill_in_prog_lock);
  823. write_unlock(&pkc->blk_fill_in_prog_lock);
  824. }
  825. prb_close_block(pkc, pbd, po, status);
  826. return;
  827. }
  828. }
  829. static int prb_curr_blk_in_use(struct tpacket_block_desc *pbd)
  830. {
  831. return TP_STATUS_USER & BLOCK_STATUS(pbd);
  832. }
  833. static int prb_queue_frozen(struct tpacket_kbdq_core *pkc)
  834. {
  835. return pkc->reset_pending_on_curr_blk;
  836. }
  837. static void prb_clear_blk_fill_status(struct packet_ring_buffer *rb)
  838. __releases(&pkc->blk_fill_in_prog_lock)
  839. {
  840. struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
  841. read_unlock(&pkc->blk_fill_in_prog_lock);
  842. }
  843. static void prb_fill_rxhash(struct tpacket_kbdq_core *pkc,
  844. struct tpacket3_hdr *ppd)
  845. {
  846. ppd->hv1.tp_rxhash = skb_get_hash(pkc->skb);
  847. }
  848. static void prb_clear_rxhash(struct tpacket_kbdq_core *pkc,
  849. struct tpacket3_hdr *ppd)
  850. {
  851. ppd->hv1.tp_rxhash = 0;
  852. }
  853. static void prb_fill_vlan_info(struct tpacket_kbdq_core *pkc,
  854. struct tpacket3_hdr *ppd)
  855. {
  856. if (skb_vlan_tag_present(pkc->skb)) {
  857. ppd->hv1.tp_vlan_tci = skb_vlan_tag_get(pkc->skb);
  858. ppd->hv1.tp_vlan_tpid = ntohs(pkc->skb->vlan_proto);
  859. ppd->tp_status = TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
  860. } else {
  861. ppd->hv1.tp_vlan_tci = 0;
  862. ppd->hv1.tp_vlan_tpid = 0;
  863. ppd->tp_status = TP_STATUS_AVAILABLE;
  864. }
  865. }
  866. static void prb_run_all_ft_ops(struct tpacket_kbdq_core *pkc,
  867. struct tpacket3_hdr *ppd)
  868. {
  869. ppd->hv1.tp_padding = 0;
  870. prb_fill_vlan_info(pkc, ppd);
  871. if (pkc->feature_req_word & TP_FT_REQ_FILL_RXHASH)
  872. prb_fill_rxhash(pkc, ppd);
  873. else
  874. prb_clear_rxhash(pkc, ppd);
  875. }
  876. static void prb_fill_curr_block(char *curr,
  877. struct tpacket_kbdq_core *pkc,
  878. struct tpacket_block_desc *pbd,
  879. unsigned int len)
  880. __acquires(&pkc->blk_fill_in_prog_lock)
  881. {
  882. struct tpacket3_hdr *ppd;
  883. ppd = (struct tpacket3_hdr *)curr;
  884. ppd->tp_next_offset = TOTAL_PKT_LEN_INCL_ALIGN(len);
  885. pkc->prev = curr;
  886. pkc->nxt_offset += TOTAL_PKT_LEN_INCL_ALIGN(len);
  887. BLOCK_LEN(pbd) += TOTAL_PKT_LEN_INCL_ALIGN(len);
  888. BLOCK_NUM_PKTS(pbd) += 1;
  889. read_lock(&pkc->blk_fill_in_prog_lock);
  890. prb_run_all_ft_ops(pkc, ppd);
  891. }
  892. /* Assumes caller has the sk->rx_queue.lock */
  893. static void *__packet_lookup_frame_in_block(struct packet_sock *po,
  894. struct sk_buff *skb,
  895. unsigned int len
  896. )
  897. {
  898. struct tpacket_kbdq_core *pkc;
  899. struct tpacket_block_desc *pbd;
  900. char *curr, *end;
  901. pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
  902. pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
  903. /* Queue is frozen when user space is lagging behind */
  904. if (prb_queue_frozen(pkc)) {
  905. /*
  906. * Check if that last block which caused the queue to freeze,
  907. * is still in_use by user-space.
  908. */
  909. if (prb_curr_blk_in_use(pbd)) {
  910. /* Can't record this packet */
  911. return NULL;
  912. } else {
  913. /*
  914. * Ok, the block was released by user-space.
  915. * Now let's open that block.
  916. * opening a block also thaws the queue.
  917. * Thawing is a side effect.
  918. */
  919. prb_open_block(pkc, pbd);
  920. }
  921. }
  922. smp_mb();
  923. curr = pkc->nxt_offset;
  924. pkc->skb = skb;
  925. end = (char *)pbd + pkc->kblk_size;
  926. /* first try the current block */
  927. if (curr+TOTAL_PKT_LEN_INCL_ALIGN(len) < end) {
  928. prb_fill_curr_block(curr, pkc, pbd, len);
  929. return (void *)curr;
  930. }
  931. /* Ok, close the current block */
  932. prb_retire_current_block(pkc, po, 0);
  933. /* Now, try to dispatch the next block */
  934. curr = (char *)prb_dispatch_next_block(pkc, po);
  935. if (curr) {
  936. pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
  937. prb_fill_curr_block(curr, pkc, pbd, len);
  938. return (void *)curr;
  939. }
  940. /*
  941. * No free blocks are available.user_space hasn't caught up yet.
  942. * Queue was just frozen and now this packet will get dropped.
  943. */
  944. return NULL;
  945. }
  946. static void *packet_current_rx_frame(struct packet_sock *po,
  947. struct sk_buff *skb,
  948. int status, unsigned int len)
  949. {
  950. char *curr = NULL;
  951. switch (po->tp_version) {
  952. case TPACKET_V1:
  953. case TPACKET_V2:
  954. curr = packet_lookup_frame(po, &po->rx_ring,
  955. po->rx_ring.head, status);
  956. return curr;
  957. case TPACKET_V3:
  958. return __packet_lookup_frame_in_block(po, skb, len);
  959. default:
  960. WARN(1, "TPACKET version not supported\n");
  961. BUG();
  962. return NULL;
  963. }
  964. }
  965. static void *prb_lookup_block(const struct packet_sock *po,
  966. const struct packet_ring_buffer *rb,
  967. unsigned int idx,
  968. int status)
  969. {
  970. struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
  971. struct tpacket_block_desc *pbd = GET_PBLOCK_DESC(pkc, idx);
  972. if (status != BLOCK_STATUS(pbd))
  973. return NULL;
  974. return pbd;
  975. }
  976. static int prb_previous_blk_num(struct packet_ring_buffer *rb)
  977. {
  978. unsigned int prev;
  979. if (rb->prb_bdqc.kactive_blk_num)
  980. prev = rb->prb_bdqc.kactive_blk_num-1;
  981. else
  982. prev = rb->prb_bdqc.knum_blocks-1;
  983. return prev;
  984. }
  985. /* Assumes caller has held the rx_queue.lock */
  986. static void *__prb_previous_block(struct packet_sock *po,
  987. struct packet_ring_buffer *rb,
  988. int status)
  989. {
  990. unsigned int previous = prb_previous_blk_num(rb);
  991. return prb_lookup_block(po, rb, previous, status);
  992. }
  993. static void *packet_previous_rx_frame(struct packet_sock *po,
  994. struct packet_ring_buffer *rb,
  995. int status)
  996. {
  997. if (po->tp_version <= TPACKET_V2)
  998. return packet_previous_frame(po, rb, status);
  999. return __prb_previous_block(po, rb, status);
  1000. }
  1001. static void packet_increment_rx_head(struct packet_sock *po,
  1002. struct packet_ring_buffer *rb)
  1003. {
  1004. switch (po->tp_version) {
  1005. case TPACKET_V1:
  1006. case TPACKET_V2:
  1007. return packet_increment_head(rb);
  1008. case TPACKET_V3:
  1009. default:
  1010. WARN(1, "TPACKET version not supported.\n");
  1011. BUG();
  1012. return;
  1013. }
  1014. }
  1015. static void *packet_previous_frame(struct packet_sock *po,
  1016. struct packet_ring_buffer *rb,
  1017. int status)
  1018. {
  1019. unsigned int previous = rb->head ? rb->head - 1 : rb->frame_max;
  1020. return packet_lookup_frame(po, rb, previous, status);
  1021. }
  1022. static void packet_increment_head(struct packet_ring_buffer *buff)
  1023. {
  1024. buff->head = buff->head != buff->frame_max ? buff->head+1 : 0;
  1025. }
  1026. static void packet_inc_pending(struct packet_ring_buffer *rb)
  1027. {
  1028. this_cpu_inc(*rb->pending_refcnt);
  1029. }
  1030. static void packet_dec_pending(struct packet_ring_buffer *rb)
  1031. {
  1032. this_cpu_dec(*rb->pending_refcnt);
  1033. }
  1034. static unsigned int packet_read_pending(const struct packet_ring_buffer *rb)
  1035. {
  1036. unsigned int refcnt = 0;
  1037. int cpu;
  1038. /* We don't use pending refcount in rx_ring. */
  1039. if (rb->pending_refcnt == NULL)
  1040. return 0;
  1041. for_each_possible_cpu(cpu)
  1042. refcnt += *per_cpu_ptr(rb->pending_refcnt, cpu);
  1043. return refcnt;
  1044. }
  1045. static int packet_alloc_pending(struct packet_sock *po)
  1046. {
  1047. po->rx_ring.pending_refcnt = NULL;
  1048. po->tx_ring.pending_refcnt = alloc_percpu(unsigned int);
  1049. if (unlikely(po->tx_ring.pending_refcnt == NULL))
  1050. return -ENOBUFS;
  1051. return 0;
  1052. }
  1053. static void packet_free_pending(struct packet_sock *po)
  1054. {
  1055. free_percpu(po->tx_ring.pending_refcnt);
  1056. }
  1057. #define ROOM_POW_OFF 2
  1058. #define ROOM_NONE 0x0
  1059. #define ROOM_LOW 0x1
  1060. #define ROOM_NORMAL 0x2
  1061. static bool __tpacket_has_room(const struct packet_sock *po, int pow_off)
  1062. {
  1063. int idx, len;
  1064. len = READ_ONCE(po->rx_ring.frame_max) + 1;
  1065. idx = READ_ONCE(po->rx_ring.head);
  1066. if (pow_off)
  1067. idx += len >> pow_off;
  1068. if (idx >= len)
  1069. idx -= len;
  1070. return packet_lookup_frame(po, &po->rx_ring, idx, TP_STATUS_KERNEL);
  1071. }
  1072. static bool __tpacket_v3_has_room(const struct packet_sock *po, int pow_off)
  1073. {
  1074. int idx, len;
  1075. len = READ_ONCE(po->rx_ring.prb_bdqc.knum_blocks);
  1076. idx = READ_ONCE(po->rx_ring.prb_bdqc.kactive_blk_num);
  1077. if (pow_off)
  1078. idx += len >> pow_off;
  1079. if (idx >= len)
  1080. idx -= len;
  1081. return prb_lookup_block(po, &po->rx_ring, idx, TP_STATUS_KERNEL);
  1082. }
  1083. static int __packet_rcv_has_room(const struct packet_sock *po,
  1084. const struct sk_buff *skb)
  1085. {
  1086. const struct sock *sk = &po->sk;
  1087. int ret = ROOM_NONE;
  1088. if (po->prot_hook.func != tpacket_rcv) {
  1089. int rcvbuf = READ_ONCE(sk->sk_rcvbuf);
  1090. int avail = rcvbuf - atomic_read(&sk->sk_rmem_alloc)
  1091. - (skb ? skb->truesize : 0);
  1092. if (avail > (rcvbuf >> ROOM_POW_OFF))
  1093. return ROOM_NORMAL;
  1094. else if (avail > 0)
  1095. return ROOM_LOW;
  1096. else
  1097. return ROOM_NONE;
  1098. }
  1099. if (po->tp_version == TPACKET_V3) {
  1100. if (__tpacket_v3_has_room(po, ROOM_POW_OFF))
  1101. ret = ROOM_NORMAL;
  1102. else if (__tpacket_v3_has_room(po, 0))
  1103. ret = ROOM_LOW;
  1104. } else {
  1105. if (__tpacket_has_room(po, ROOM_POW_OFF))
  1106. ret = ROOM_NORMAL;
  1107. else if (__tpacket_has_room(po, 0))
  1108. ret = ROOM_LOW;
  1109. }
  1110. return ret;
  1111. }
  1112. static int packet_rcv_has_room(struct packet_sock *po, struct sk_buff *skb)
  1113. {
  1114. int pressure, ret;
  1115. ret = __packet_rcv_has_room(po, skb);
  1116. pressure = ret != ROOM_NORMAL;
  1117. if (READ_ONCE(po->pressure) != pressure)
  1118. WRITE_ONCE(po->pressure, pressure);
  1119. return ret;
  1120. }
  1121. static void packet_rcv_try_clear_pressure(struct packet_sock *po)
  1122. {
  1123. if (READ_ONCE(po->pressure) &&
  1124. __packet_rcv_has_room(po, NULL) == ROOM_NORMAL)
  1125. WRITE_ONCE(po->pressure, 0);
  1126. }
  1127. static void packet_sock_destruct(struct sock *sk)
  1128. {
  1129. skb_queue_purge(&sk->sk_error_queue);
  1130. WARN_ON(atomic_read(&sk->sk_rmem_alloc));
  1131. WARN_ON(refcount_read(&sk->sk_wmem_alloc));
  1132. if (!sock_flag(sk, SOCK_DEAD)) {
  1133. pr_err("Attempt to release alive packet socket: %p\n", sk);
  1134. return;
  1135. }
  1136. sk_refcnt_debug_dec(sk);
  1137. }
  1138. static bool fanout_flow_is_huge(struct packet_sock *po, struct sk_buff *skb)
  1139. {
  1140. u32 *history = po->rollover->history;
  1141. u32 victim, rxhash;
  1142. int i, count = 0;
  1143. rxhash = skb_get_hash(skb);
  1144. for (i = 0; i < ROLLOVER_HLEN; i++)
  1145. if (READ_ONCE(history[i]) == rxhash)
  1146. count++;
  1147. victim = prandom_u32_max(ROLLOVER_HLEN);
  1148. /* Avoid dirtying the cache line if possible */
  1149. if (READ_ONCE(history[victim]) != rxhash)
  1150. WRITE_ONCE(history[victim], rxhash);
  1151. return count > (ROLLOVER_HLEN >> 1);
  1152. }
  1153. static unsigned int fanout_demux_hash(struct packet_fanout *f,
  1154. struct sk_buff *skb,
  1155. unsigned int num)
  1156. {
  1157. return reciprocal_scale(__skb_get_hash_symmetric(skb), num);
  1158. }
  1159. static unsigned int fanout_demux_lb(struct packet_fanout *f,
  1160. struct sk_buff *skb,
  1161. unsigned int num)
  1162. {
  1163. unsigned int val = atomic_inc_return(&f->rr_cur);
  1164. return val % num;
  1165. }
  1166. static unsigned int fanout_demux_cpu(struct packet_fanout *f,
  1167. struct sk_buff *skb,
  1168. unsigned int num)
  1169. {
  1170. return smp_processor_id() % num;
  1171. }
  1172. static unsigned int fanout_demux_rnd(struct packet_fanout *f,
  1173. struct sk_buff *skb,
  1174. unsigned int num)
  1175. {
  1176. return prandom_u32_max(num);
  1177. }
  1178. static unsigned int fanout_demux_rollover(struct packet_fanout *f,
  1179. struct sk_buff *skb,
  1180. unsigned int idx, bool try_self,
  1181. unsigned int num)
  1182. {
  1183. struct packet_sock *po, *po_next, *po_skip = NULL;
  1184. unsigned int i, j, room = ROOM_NONE;
  1185. po = pkt_sk(rcu_dereference(f->arr[idx]));
  1186. if (try_self) {
  1187. room = packet_rcv_has_room(po, skb);
  1188. if (room == ROOM_NORMAL ||
  1189. (room == ROOM_LOW && !fanout_flow_is_huge(po, skb)))
  1190. return idx;
  1191. po_skip = po;
  1192. }
  1193. i = j = min_t(int, po->rollover->sock, num - 1);
  1194. do {
  1195. po_next = pkt_sk(rcu_dereference(f->arr[i]));
  1196. if (po_next != po_skip && !READ_ONCE(po_next->pressure) &&
  1197. packet_rcv_has_room(po_next, skb) == ROOM_NORMAL) {
  1198. if (i != j)
  1199. po->rollover->sock = i;
  1200. atomic_long_inc(&po->rollover->num);
  1201. if (room == ROOM_LOW)
  1202. atomic_long_inc(&po->rollover->num_huge);
  1203. return i;
  1204. }
  1205. if (++i == num)
  1206. i = 0;
  1207. } while (i != j);
  1208. atomic_long_inc(&po->rollover->num_failed);
  1209. return idx;
  1210. }
  1211. static unsigned int fanout_demux_qm(struct packet_fanout *f,
  1212. struct sk_buff *skb,
  1213. unsigned int num)
  1214. {
  1215. return skb_get_queue_mapping(skb) % num;
  1216. }
  1217. static unsigned int fanout_demux_bpf(struct packet_fanout *f,
  1218. struct sk_buff *skb,
  1219. unsigned int num)
  1220. {
  1221. struct bpf_prog *prog;
  1222. unsigned int ret = 0;
  1223. rcu_read_lock();
  1224. prog = rcu_dereference(f->bpf_prog);
  1225. if (prog)
  1226. ret = bpf_prog_run_clear_cb(prog, skb) % num;
  1227. rcu_read_unlock();
  1228. return ret;
  1229. }
  1230. static bool fanout_has_flag(struct packet_fanout *f, u16 flag)
  1231. {
  1232. return f->flags & (flag >> 8);
  1233. }
  1234. static int packet_rcv_fanout(struct sk_buff *skb, struct net_device *dev,
  1235. struct packet_type *pt, struct net_device *orig_dev)
  1236. {
  1237. struct packet_fanout *f = pt->af_packet_priv;
  1238. unsigned int num = READ_ONCE(f->num_members);
  1239. struct net *net = read_pnet(&f->net);
  1240. struct packet_sock *po;
  1241. unsigned int idx;
  1242. if (!net_eq(dev_net(dev), net) || !num) {
  1243. kfree_skb(skb);
  1244. return 0;
  1245. }
  1246. if (fanout_has_flag(f, PACKET_FANOUT_FLAG_DEFRAG)) {
  1247. skb = ip_check_defrag(net, skb, IP_DEFRAG_AF_PACKET);
  1248. if (!skb)
  1249. return 0;
  1250. }
  1251. switch (f->type) {
  1252. case PACKET_FANOUT_HASH:
  1253. default:
  1254. idx = fanout_demux_hash(f, skb, num);
  1255. break;
  1256. case PACKET_FANOUT_LB:
  1257. idx = fanout_demux_lb(f, skb, num);
  1258. break;
  1259. case PACKET_FANOUT_CPU:
  1260. idx = fanout_demux_cpu(f, skb, num);
  1261. break;
  1262. case PACKET_FANOUT_RND:
  1263. idx = fanout_demux_rnd(f, skb, num);
  1264. break;
  1265. case PACKET_FANOUT_QM:
  1266. idx = fanout_demux_qm(f, skb, num);
  1267. break;
  1268. case PACKET_FANOUT_ROLLOVER:
  1269. idx = fanout_demux_rollover(f, skb, 0, false, num);
  1270. break;
  1271. case PACKET_FANOUT_CBPF:
  1272. case PACKET_FANOUT_EBPF:
  1273. idx = fanout_demux_bpf(f, skb, num);
  1274. break;
  1275. }
  1276. if (fanout_has_flag(f, PACKET_FANOUT_FLAG_ROLLOVER))
  1277. idx = fanout_demux_rollover(f, skb, idx, true, num);
  1278. po = pkt_sk(rcu_dereference(f->arr[idx]));
  1279. return po->prot_hook.func(skb, dev, &po->prot_hook, orig_dev);
  1280. }
  1281. DEFINE_MUTEX(fanout_mutex);
  1282. EXPORT_SYMBOL_GPL(fanout_mutex);
  1283. static LIST_HEAD(fanout_list);
  1284. static u16 fanout_next_id;
  1285. static void __fanout_link(struct sock *sk, struct packet_sock *po)
  1286. {
  1287. struct packet_fanout *f = po->fanout;
  1288. spin_lock(&f->lock);
  1289. rcu_assign_pointer(f->arr[f->num_members], sk);
  1290. smp_wmb();
  1291. f->num_members++;
  1292. if (f->num_members == 1)
  1293. dev_add_pack(&f->prot_hook);
  1294. spin_unlock(&f->lock);
  1295. }
  1296. static void __fanout_unlink(struct sock *sk, struct packet_sock *po)
  1297. {
  1298. struct packet_fanout *f = po->fanout;
  1299. int i;
  1300. spin_lock(&f->lock);
  1301. for (i = 0; i < f->num_members; i++) {
  1302. if (rcu_dereference_protected(f->arr[i],
  1303. lockdep_is_held(&f->lock)) == sk)
  1304. break;
  1305. }
  1306. BUG_ON(i >= f->num_members);
  1307. rcu_assign_pointer(f->arr[i],
  1308. rcu_dereference_protected(f->arr[f->num_members - 1],
  1309. lockdep_is_held(&f->lock)));
  1310. f->num_members--;
  1311. if (f->num_members == 0)
  1312. __dev_remove_pack(&f->prot_hook);
  1313. spin_unlock(&f->lock);
  1314. }
  1315. static bool match_fanout_group(struct packet_type *ptype, struct sock *sk)
  1316. {
  1317. if (sk->sk_family != PF_PACKET)
  1318. return false;
  1319. return ptype->af_packet_priv == pkt_sk(sk)->fanout;
  1320. }
  1321. static void fanout_init_data(struct packet_fanout *f)
  1322. {
  1323. switch (f->type) {
  1324. case PACKET_FANOUT_LB:
  1325. atomic_set(&f->rr_cur, 0);
  1326. break;
  1327. case PACKET_FANOUT_CBPF:
  1328. case PACKET_FANOUT_EBPF:
  1329. RCU_INIT_POINTER(f->bpf_prog, NULL);
  1330. break;
  1331. }
  1332. }
  1333. static void __fanout_set_data_bpf(struct packet_fanout *f, struct bpf_prog *new)
  1334. {
  1335. struct bpf_prog *old;
  1336. spin_lock(&f->lock);
  1337. old = rcu_dereference_protected(f->bpf_prog, lockdep_is_held(&f->lock));
  1338. rcu_assign_pointer(f->bpf_prog, new);
  1339. spin_unlock(&f->lock);
  1340. if (old) {
  1341. synchronize_net();
  1342. bpf_prog_destroy(old);
  1343. }
  1344. }
  1345. static int fanout_set_data_cbpf(struct packet_sock *po, sockptr_t data,
  1346. unsigned int len)
  1347. {
  1348. struct bpf_prog *new;
  1349. struct sock_fprog fprog;
  1350. int ret;
  1351. if (sock_flag(&po->sk, SOCK_FILTER_LOCKED))
  1352. return -EPERM;
  1353. ret = copy_bpf_fprog_from_user(&fprog, data, len);
  1354. if (ret)
  1355. return ret;
  1356. ret = bpf_prog_create_from_user(&new, &fprog, NULL, false);
  1357. if (ret)
  1358. return ret;
  1359. __fanout_set_data_bpf(po->fanout, new);
  1360. return 0;
  1361. }
  1362. static int fanout_set_data_ebpf(struct packet_sock *po, sockptr_t data,
  1363. unsigned int len)
  1364. {
  1365. struct bpf_prog *new;
  1366. u32 fd;
  1367. if (sock_flag(&po->sk, SOCK_FILTER_LOCKED))
  1368. return -EPERM;
  1369. if (len != sizeof(fd))
  1370. return -EINVAL;
  1371. if (copy_from_sockptr(&fd, data, len))
  1372. return -EFAULT;
  1373. new = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
  1374. if (IS_ERR(new))
  1375. return PTR_ERR(new);
  1376. __fanout_set_data_bpf(po->fanout, new);
  1377. return 0;
  1378. }
  1379. static int fanout_set_data(struct packet_sock *po, sockptr_t data,
  1380. unsigned int len)
  1381. {
  1382. switch (po->fanout->type) {
  1383. case PACKET_FANOUT_CBPF:
  1384. return fanout_set_data_cbpf(po, data, len);
  1385. case PACKET_FANOUT_EBPF:
  1386. return fanout_set_data_ebpf(po, data, len);
  1387. default:
  1388. return -EINVAL;
  1389. }
  1390. }
  1391. static void fanout_release_data(struct packet_fanout *f)
  1392. {
  1393. switch (f->type) {
  1394. case PACKET_FANOUT_CBPF:
  1395. case PACKET_FANOUT_EBPF:
  1396. __fanout_set_data_bpf(f, NULL);
  1397. }
  1398. }
  1399. static bool __fanout_id_is_free(struct sock *sk, u16 candidate_id)
  1400. {
  1401. struct packet_fanout *f;
  1402. list_for_each_entry(f, &fanout_list, list) {
  1403. if (f->id == candidate_id &&
  1404. read_pnet(&f->net) == sock_net(sk)) {
  1405. return false;
  1406. }
  1407. }
  1408. return true;
  1409. }
  1410. static bool fanout_find_new_id(struct sock *sk, u16 *new_id)
  1411. {
  1412. u16 id = fanout_next_id;
  1413. do {
  1414. if (__fanout_id_is_free(sk, id)) {
  1415. *new_id = id;
  1416. fanout_next_id = id + 1;
  1417. return true;
  1418. }
  1419. id++;
  1420. } while (id != fanout_next_id);
  1421. return false;
  1422. }
  1423. static int fanout_add(struct sock *sk, struct fanout_args *args)
  1424. {
  1425. struct packet_rollover *rollover = NULL;
  1426. struct packet_sock *po = pkt_sk(sk);
  1427. u16 type_flags = args->type_flags;
  1428. struct packet_fanout *f, *match;
  1429. u8 type = type_flags & 0xff;
  1430. u8 flags = type_flags >> 8;
  1431. u16 id = args->id;
  1432. int err;
  1433. switch (type) {
  1434. case PACKET_FANOUT_ROLLOVER:
  1435. if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
  1436. return -EINVAL;
  1437. break;
  1438. case PACKET_FANOUT_HASH:
  1439. case PACKET_FANOUT_LB:
  1440. case PACKET_FANOUT_CPU:
  1441. case PACKET_FANOUT_RND:
  1442. case PACKET_FANOUT_QM:
  1443. case PACKET_FANOUT_CBPF:
  1444. case PACKET_FANOUT_EBPF:
  1445. break;
  1446. default:
  1447. return -EINVAL;
  1448. }
  1449. mutex_lock(&fanout_mutex);
  1450. err = -EALREADY;
  1451. if (po->fanout)
  1452. goto out;
  1453. if (type == PACKET_FANOUT_ROLLOVER ||
  1454. (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) {
  1455. err = -ENOMEM;
  1456. rollover = kzalloc(sizeof(*rollover), GFP_KERNEL);
  1457. if (!rollover)
  1458. goto out;
  1459. atomic_long_set(&rollover->num, 0);
  1460. atomic_long_set(&rollover->num_huge, 0);
  1461. atomic_long_set(&rollover->num_failed, 0);
  1462. }
  1463. if (type_flags & PACKET_FANOUT_FLAG_UNIQUEID) {
  1464. if (id != 0) {
  1465. err = -EINVAL;
  1466. goto out;
  1467. }
  1468. if (!fanout_find_new_id(sk, &id)) {
  1469. err = -ENOMEM;
  1470. goto out;
  1471. }
  1472. /* ephemeral flag for the first socket in the group: drop it */
  1473. flags &= ~(PACKET_FANOUT_FLAG_UNIQUEID >> 8);
  1474. }
  1475. match = NULL;
  1476. list_for_each_entry(f, &fanout_list, list) {
  1477. if (f->id == id &&
  1478. read_pnet(&f->net) == sock_net(sk)) {
  1479. match = f;
  1480. break;
  1481. }
  1482. }
  1483. err = -EINVAL;
  1484. if (match) {
  1485. if (match->flags != flags)
  1486. goto out;
  1487. if (args->max_num_members &&
  1488. args->max_num_members != match->max_num_members)
  1489. goto out;
  1490. } else {
  1491. if (args->max_num_members > PACKET_FANOUT_MAX)
  1492. goto out;
  1493. if (!args->max_num_members)
  1494. /* legacy PACKET_FANOUT_MAX */
  1495. args->max_num_members = 256;
  1496. err = -ENOMEM;
  1497. match = kvzalloc(struct_size(match, arr, args->max_num_members),
  1498. GFP_KERNEL);
  1499. if (!match)
  1500. goto out;
  1501. write_pnet(&match->net, sock_net(sk));
  1502. match->id = id;
  1503. match->type = type;
  1504. match->flags = flags;
  1505. INIT_LIST_HEAD(&match->list);
  1506. spin_lock_init(&match->lock);
  1507. refcount_set(&match->sk_ref, 0);
  1508. fanout_init_data(match);
  1509. match->prot_hook.type = po->prot_hook.type;
  1510. match->prot_hook.dev = po->prot_hook.dev;
  1511. match->prot_hook.func = packet_rcv_fanout;
  1512. match->prot_hook.af_packet_priv = match;
  1513. match->prot_hook.af_packet_net = read_pnet(&match->net);
  1514. match->prot_hook.id_match = match_fanout_group;
  1515. match->max_num_members = args->max_num_members;
  1516. list_add(&match->list, &fanout_list);
  1517. }
  1518. err = -EINVAL;
  1519. spin_lock(&po->bind_lock);
  1520. if (po->running &&
  1521. match->type == type &&
  1522. match->prot_hook.type == po->prot_hook.type &&
  1523. match->prot_hook.dev == po->prot_hook.dev) {
  1524. err = -ENOSPC;
  1525. if (refcount_read(&match->sk_ref) < match->max_num_members) {
  1526. __dev_remove_pack(&po->prot_hook);
  1527. /* Paired with packet_setsockopt(PACKET_FANOUT_DATA) */
  1528. WRITE_ONCE(po->fanout, match);
  1529. po->rollover = rollover;
  1530. rollover = NULL;
  1531. refcount_set(&match->sk_ref, refcount_read(&match->sk_ref) + 1);
  1532. __fanout_link(sk, po);
  1533. err = 0;
  1534. }
  1535. }
  1536. spin_unlock(&po->bind_lock);
  1537. if (err && !refcount_read(&match->sk_ref)) {
  1538. list_del(&match->list);
  1539. kvfree(match);
  1540. }
  1541. out:
  1542. kfree(rollover);
  1543. mutex_unlock(&fanout_mutex);
  1544. return err;
  1545. }
  1546. /* If pkt_sk(sk)->fanout->sk_ref is zero, this function removes
  1547. * pkt_sk(sk)->fanout from fanout_list and returns pkt_sk(sk)->fanout.
  1548. * It is the responsibility of the caller to call fanout_release_data() and
  1549. * free the returned packet_fanout (after synchronize_net())
  1550. */
  1551. static struct packet_fanout *fanout_release(struct sock *sk)
  1552. {
  1553. struct packet_sock *po = pkt_sk(sk);
  1554. struct packet_fanout *f;
  1555. mutex_lock(&fanout_mutex);
  1556. f = po->fanout;
  1557. if (f) {
  1558. po->fanout = NULL;
  1559. if (refcount_dec_and_test(&f->sk_ref))
  1560. list_del(&f->list);
  1561. else
  1562. f = NULL;
  1563. }
  1564. mutex_unlock(&fanout_mutex);
  1565. return f;
  1566. }
  1567. static bool packet_extra_vlan_len_allowed(const struct net_device *dev,
  1568. struct sk_buff *skb)
  1569. {
  1570. /* Earlier code assumed this would be a VLAN pkt, double-check
  1571. * this now that we have the actual packet in hand. We can only
  1572. * do this check on Ethernet devices.
  1573. */
  1574. if (unlikely(dev->type != ARPHRD_ETHER))
  1575. return false;
  1576. skb_reset_mac_header(skb);
  1577. return likely(eth_hdr(skb)->h_proto == htons(ETH_P_8021Q));
  1578. }
  1579. static const struct proto_ops packet_ops;
  1580. static const struct proto_ops packet_ops_spkt;
  1581. static int packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev,
  1582. struct packet_type *pt, struct net_device *orig_dev)
  1583. {
  1584. struct sock *sk;
  1585. struct sockaddr_pkt *spkt;
  1586. /*
  1587. * When we registered the protocol we saved the socket in the data
  1588. * field for just this event.
  1589. */
  1590. sk = pt->af_packet_priv;
  1591. /*
  1592. * Yank back the headers [hope the device set this
  1593. * right or kerboom...]
  1594. *
  1595. * Incoming packets have ll header pulled,
  1596. * push it back.
  1597. *
  1598. * For outgoing ones skb->data == skb_mac_header(skb)
  1599. * so that this procedure is noop.
  1600. */
  1601. if (skb->pkt_type == PACKET_LOOPBACK)
  1602. goto out;
  1603. if (!net_eq(dev_net(dev), sock_net(sk)))
  1604. goto out;
  1605. skb = skb_share_check(skb, GFP_ATOMIC);
  1606. if (skb == NULL)
  1607. goto oom;
  1608. /* drop any routing info */
  1609. skb_dst_drop(skb);
  1610. /* drop conntrack reference */
  1611. nf_reset_ct(skb);
  1612. spkt = &PACKET_SKB_CB(skb)->sa.pkt;
  1613. skb_push(skb, skb->data - skb_mac_header(skb));
  1614. /*
  1615. * The SOCK_PACKET socket receives _all_ frames.
  1616. */
  1617. spkt->spkt_family = dev->type;
  1618. strscpy(spkt->spkt_device, dev->name, sizeof(spkt->spkt_device));
  1619. spkt->spkt_protocol = skb->protocol;
  1620. /*
  1621. * Charge the memory to the socket. This is done specifically
  1622. * to prevent sockets using all the memory up.
  1623. */
  1624. if (sock_queue_rcv_skb(sk, skb) == 0)
  1625. return 0;
  1626. out:
  1627. kfree_skb(skb);
  1628. oom:
  1629. return 0;
  1630. }
  1631. static void packet_parse_headers(struct sk_buff *skb, struct socket *sock)
  1632. {
  1633. int depth;
  1634. if ((!skb->protocol || skb->protocol == htons(ETH_P_ALL)) &&
  1635. sock->type == SOCK_RAW) {
  1636. skb_reset_mac_header(skb);
  1637. skb->protocol = dev_parse_header_protocol(skb);
  1638. }
  1639. /* Move network header to the right position for VLAN tagged packets */
  1640. if (likely(skb->dev->type == ARPHRD_ETHER) &&
  1641. eth_type_vlan(skb->protocol) &&
  1642. vlan_get_protocol_and_depth(skb, skb->protocol, &depth) != 0)
  1643. skb_set_network_header(skb, depth);
  1644. skb_probe_transport_header(skb);
  1645. }
  1646. /*
  1647. * Output a raw packet to a device layer. This bypasses all the other
  1648. * protocol layers and you must therefore supply it with a complete frame
  1649. */
  1650. static int packet_sendmsg_spkt(struct socket *sock, struct msghdr *msg,
  1651. size_t len)
  1652. {
  1653. struct sock *sk = sock->sk;
  1654. DECLARE_SOCKADDR(struct sockaddr_pkt *, saddr, msg->msg_name);
  1655. struct sk_buff *skb = NULL;
  1656. struct net_device *dev;
  1657. struct sockcm_cookie sockc;
  1658. __be16 proto = 0;
  1659. int err;
  1660. int extra_len = 0;
  1661. /*
  1662. * Get and verify the address.
  1663. */
  1664. if (saddr) {
  1665. if (msg->msg_namelen < sizeof(struct sockaddr))
  1666. return -EINVAL;
  1667. if (msg->msg_namelen == sizeof(struct sockaddr_pkt))
  1668. proto = saddr->spkt_protocol;
  1669. } else
  1670. return -ENOTCONN; /* SOCK_PACKET must be sent giving an address */
  1671. /*
  1672. * Find the device first to size check it
  1673. */
  1674. saddr->spkt_device[sizeof(saddr->spkt_device) - 1] = 0;
  1675. retry:
  1676. rcu_read_lock();
  1677. dev = dev_get_by_name_rcu(sock_net(sk), saddr->spkt_device);
  1678. err = -ENODEV;
  1679. if (dev == NULL)
  1680. goto out_unlock;
  1681. err = -ENETDOWN;
  1682. if (!(dev->flags & IFF_UP))
  1683. goto out_unlock;
  1684. /*
  1685. * You may not queue a frame bigger than the mtu. This is the lowest level
  1686. * raw protocol and you must do your own fragmentation at this level.
  1687. */
  1688. if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
  1689. if (!netif_supports_nofcs(dev)) {
  1690. err = -EPROTONOSUPPORT;
  1691. goto out_unlock;
  1692. }
  1693. extra_len = 4; /* We're doing our own CRC */
  1694. }
  1695. err = -EMSGSIZE;
  1696. if (len > dev->mtu + dev->hard_header_len + VLAN_HLEN + extra_len)
  1697. goto out_unlock;
  1698. if (!skb) {
  1699. size_t reserved = LL_RESERVED_SPACE(dev);
  1700. int tlen = dev->needed_tailroom;
  1701. unsigned int hhlen = dev->header_ops ? dev->hard_header_len : 0;
  1702. rcu_read_unlock();
  1703. skb = sock_wmalloc(sk, len + reserved + tlen, 0, GFP_KERNEL);
  1704. if (skb == NULL)
  1705. return -ENOBUFS;
  1706. /* FIXME: Save some space for broken drivers that write a hard
  1707. * header at transmission time by themselves. PPP is the notable
  1708. * one here. This should really be fixed at the driver level.
  1709. */
  1710. skb_reserve(skb, reserved);
  1711. skb_reset_network_header(skb);
  1712. /* Try to align data part correctly */
  1713. if (hhlen) {
  1714. skb->data -= hhlen;
  1715. skb->tail -= hhlen;
  1716. if (len < hhlen)
  1717. skb_reset_network_header(skb);
  1718. }
  1719. err = memcpy_from_msg(skb_put(skb, len), msg, len);
  1720. if (err)
  1721. goto out_free;
  1722. goto retry;
  1723. }
  1724. if (!dev_validate_header(dev, skb->data, len) || !skb->len) {
  1725. err = -EINVAL;
  1726. goto out_unlock;
  1727. }
  1728. if (len > (dev->mtu + dev->hard_header_len + extra_len) &&
  1729. !packet_extra_vlan_len_allowed(dev, skb)) {
  1730. err = -EMSGSIZE;
  1731. goto out_unlock;
  1732. }
  1733. sockcm_init(&sockc, sk);
  1734. if (msg->msg_controllen) {
  1735. err = sock_cmsg_send(sk, msg, &sockc);
  1736. if (unlikely(err))
  1737. goto out_unlock;
  1738. }
  1739. skb->protocol = proto;
  1740. skb->dev = dev;
  1741. skb->priority = READ_ONCE(sk->sk_priority);
  1742. skb->mark = READ_ONCE(sk->sk_mark);
  1743. skb->tstamp = sockc.transmit_time;
  1744. skb_setup_tx_timestamp(skb, sockc.tsflags);
  1745. if (unlikely(extra_len == 4))
  1746. skb->no_fcs = 1;
  1747. packet_parse_headers(skb, sock);
  1748. dev_queue_xmit(skb);
  1749. rcu_read_unlock();
  1750. return len;
  1751. out_unlock:
  1752. rcu_read_unlock();
  1753. out_free:
  1754. kfree_skb(skb);
  1755. return err;
  1756. }
  1757. static unsigned int run_filter(struct sk_buff *skb,
  1758. const struct sock *sk,
  1759. unsigned int res)
  1760. {
  1761. struct sk_filter *filter;
  1762. rcu_read_lock();
  1763. filter = rcu_dereference(sk->sk_filter);
  1764. if (filter != NULL)
  1765. res = bpf_prog_run_clear_cb(filter->prog, skb);
  1766. rcu_read_unlock();
  1767. return res;
  1768. }
  1769. static int packet_rcv_vnet(struct msghdr *msg, const struct sk_buff *skb,
  1770. size_t *len)
  1771. {
  1772. struct virtio_net_hdr vnet_hdr;
  1773. if (*len < sizeof(vnet_hdr))
  1774. return -EINVAL;
  1775. *len -= sizeof(vnet_hdr);
  1776. if (virtio_net_hdr_from_skb(skb, &vnet_hdr, vio_le(), true, 0))
  1777. return -EINVAL;
  1778. return memcpy_to_msg(msg, (void *)&vnet_hdr, sizeof(vnet_hdr));
  1779. }
  1780. /*
  1781. * This function makes lazy skb cloning in hope that most of packets
  1782. * are discarded by BPF.
  1783. *
  1784. * Note tricky part: we DO mangle shared skb! skb->data, skb->len
  1785. * and skb->cb are mangled. It works because (and until) packets
  1786. * falling here are owned by current CPU. Output packets are cloned
  1787. * by dev_queue_xmit_nit(), input packets are processed by net_bh
  1788. * sequentially, so that if we return skb to original state on exit,
  1789. * we will not harm anyone.
  1790. */
  1791. static int packet_rcv(struct sk_buff *skb, struct net_device *dev,
  1792. struct packet_type *pt, struct net_device *orig_dev)
  1793. {
  1794. struct sock *sk;
  1795. struct sockaddr_ll *sll;
  1796. struct packet_sock *po;
  1797. u8 *skb_head = skb->data;
  1798. int skb_len = skb->len;
  1799. unsigned int snaplen, res;
  1800. bool is_drop_n_account = false;
  1801. if (skb->pkt_type == PACKET_LOOPBACK)
  1802. goto drop;
  1803. sk = pt->af_packet_priv;
  1804. po = pkt_sk(sk);
  1805. if (!net_eq(dev_net(dev), sock_net(sk)))
  1806. goto drop;
  1807. skb->dev = dev;
  1808. if (dev_has_header(dev)) {
  1809. /* The device has an explicit notion of ll header,
  1810. * exported to higher levels.
  1811. *
  1812. * Otherwise, the device hides details of its frame
  1813. * structure, so that corresponding packet head is
  1814. * never delivered to user.
  1815. */
  1816. if (sk->sk_type != SOCK_DGRAM)
  1817. skb_push(skb, skb->data - skb_mac_header(skb));
  1818. else if (skb->pkt_type == PACKET_OUTGOING) {
  1819. /* Special case: outgoing packets have ll header at head */
  1820. skb_pull(skb, skb_network_offset(skb));
  1821. }
  1822. }
  1823. snaplen = skb->len;
  1824. res = run_filter(skb, sk, snaplen);
  1825. if (!res)
  1826. goto drop_n_restore;
  1827. if (snaplen > res)
  1828. snaplen = res;
  1829. if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
  1830. goto drop_n_acct;
  1831. if (skb_shared(skb)) {
  1832. struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
  1833. if (nskb == NULL)
  1834. goto drop_n_acct;
  1835. if (skb_head != skb->data) {
  1836. skb->data = skb_head;
  1837. skb->len = skb_len;
  1838. }
  1839. consume_skb(skb);
  1840. skb = nskb;
  1841. }
  1842. sock_skb_cb_check_size(sizeof(*PACKET_SKB_CB(skb)) + MAX_ADDR_LEN - 8);
  1843. sll = &PACKET_SKB_CB(skb)->sa.ll;
  1844. sll->sll_hatype = dev->type;
  1845. sll->sll_pkttype = skb->pkt_type;
  1846. if (unlikely(packet_sock_flag(po, PACKET_SOCK_ORIGDEV)))
  1847. sll->sll_ifindex = orig_dev->ifindex;
  1848. else
  1849. sll->sll_ifindex = dev->ifindex;
  1850. sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
  1851. /* sll->sll_family and sll->sll_protocol are set in packet_recvmsg().
  1852. * Use their space for storing the original skb length.
  1853. */
  1854. PACKET_SKB_CB(skb)->sa.origlen = skb->len;
  1855. if (pskb_trim(skb, snaplen))
  1856. goto drop_n_acct;
  1857. skb_set_owner_r(skb, sk);
  1858. skb->dev = NULL;
  1859. skb_dst_drop(skb);
  1860. /* drop conntrack reference */
  1861. nf_reset_ct(skb);
  1862. spin_lock(&sk->sk_receive_queue.lock);
  1863. po->stats.stats1.tp_packets++;
  1864. sock_skb_set_dropcount(sk, skb);
  1865. skb_clear_delivery_time(skb);
  1866. __skb_queue_tail(&sk->sk_receive_queue, skb);
  1867. spin_unlock(&sk->sk_receive_queue.lock);
  1868. sk->sk_data_ready(sk);
  1869. return 0;
  1870. drop_n_acct:
  1871. is_drop_n_account = true;
  1872. atomic_inc(&po->tp_drops);
  1873. atomic_inc(&sk->sk_drops);
  1874. drop_n_restore:
  1875. if (skb_head != skb->data && skb_shared(skb)) {
  1876. skb->data = skb_head;
  1877. skb->len = skb_len;
  1878. }
  1879. drop:
  1880. if (!is_drop_n_account)
  1881. consume_skb(skb);
  1882. else
  1883. kfree_skb(skb);
  1884. return 0;
  1885. }
  1886. static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
  1887. struct packet_type *pt, struct net_device *orig_dev)
  1888. {
  1889. struct sock *sk;
  1890. struct packet_sock *po;
  1891. struct sockaddr_ll *sll;
  1892. union tpacket_uhdr h;
  1893. u8 *skb_head = skb->data;
  1894. int skb_len = skb->len;
  1895. unsigned int snaplen, res;
  1896. unsigned long status = TP_STATUS_USER;
  1897. unsigned short macoff, hdrlen;
  1898. unsigned int netoff;
  1899. struct sk_buff *copy_skb = NULL;
  1900. struct timespec64 ts;
  1901. __u32 ts_status;
  1902. bool is_drop_n_account = false;
  1903. unsigned int slot_id = 0;
  1904. bool do_vnet = false;
  1905. /* struct tpacket{2,3}_hdr is aligned to a multiple of TPACKET_ALIGNMENT.
  1906. * We may add members to them until current aligned size without forcing
  1907. * userspace to call getsockopt(..., PACKET_HDRLEN, ...).
  1908. */
  1909. BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h2)) != 32);
  1910. BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h3)) != 48);
  1911. if (skb->pkt_type == PACKET_LOOPBACK)
  1912. goto drop;
  1913. sk = pt->af_packet_priv;
  1914. po = pkt_sk(sk);
  1915. if (!net_eq(dev_net(dev), sock_net(sk)))
  1916. goto drop;
  1917. if (dev_has_header(dev)) {
  1918. if (sk->sk_type != SOCK_DGRAM)
  1919. skb_push(skb, skb->data - skb_mac_header(skb));
  1920. else if (skb->pkt_type == PACKET_OUTGOING) {
  1921. /* Special case: outgoing packets have ll header at head */
  1922. skb_pull(skb, skb_network_offset(skb));
  1923. }
  1924. }
  1925. snaplen = skb->len;
  1926. res = run_filter(skb, sk, snaplen);
  1927. if (!res)
  1928. goto drop_n_restore;
  1929. /* If we are flooded, just give up */
  1930. if (__packet_rcv_has_room(po, skb) == ROOM_NONE) {
  1931. atomic_inc(&po->tp_drops);
  1932. goto drop_n_restore;
  1933. }
  1934. if (skb->ip_summed == CHECKSUM_PARTIAL)
  1935. status |= TP_STATUS_CSUMNOTREADY;
  1936. else if (skb->pkt_type != PACKET_OUTGOING &&
  1937. skb_csum_unnecessary(skb))
  1938. status |= TP_STATUS_CSUM_VALID;
  1939. if (snaplen > res)
  1940. snaplen = res;
  1941. if (sk->sk_type == SOCK_DGRAM) {
  1942. macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
  1943. po->tp_reserve;
  1944. } else {
  1945. unsigned int maclen = skb_network_offset(skb);
  1946. netoff = TPACKET_ALIGN(po->tp_hdrlen +
  1947. (maclen < 16 ? 16 : maclen)) +
  1948. po->tp_reserve;
  1949. if (po->has_vnet_hdr) {
  1950. netoff += sizeof(struct virtio_net_hdr);
  1951. do_vnet = true;
  1952. }
  1953. macoff = netoff - maclen;
  1954. }
  1955. if (netoff > USHRT_MAX) {
  1956. atomic_inc(&po->tp_drops);
  1957. goto drop_n_restore;
  1958. }
  1959. if (po->tp_version <= TPACKET_V2) {
  1960. if (macoff + snaplen > po->rx_ring.frame_size) {
  1961. if (po->copy_thresh &&
  1962. atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {
  1963. if (skb_shared(skb)) {
  1964. copy_skb = skb_clone(skb, GFP_ATOMIC);
  1965. } else {
  1966. copy_skb = skb_get(skb);
  1967. skb_head = skb->data;
  1968. }
  1969. if (copy_skb) {
  1970. memset(&PACKET_SKB_CB(copy_skb)->sa.ll, 0,
  1971. sizeof(PACKET_SKB_CB(copy_skb)->sa.ll));
  1972. skb_set_owner_r(copy_skb, sk);
  1973. }
  1974. }
  1975. snaplen = po->rx_ring.frame_size - macoff;
  1976. if ((int)snaplen < 0) {
  1977. snaplen = 0;
  1978. do_vnet = false;
  1979. }
  1980. }
  1981. } else if (unlikely(macoff + snaplen >
  1982. GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) {
  1983. u32 nval;
  1984. nval = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len - macoff;
  1985. pr_err_once("tpacket_rcv: packet too big, clamped from %u to %u. macoff=%u\n",
  1986. snaplen, nval, macoff);
  1987. snaplen = nval;
  1988. if (unlikely((int)snaplen < 0)) {
  1989. snaplen = 0;
  1990. macoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len;
  1991. do_vnet = false;
  1992. }
  1993. }
  1994. spin_lock(&sk->sk_receive_queue.lock);
  1995. h.raw = packet_current_rx_frame(po, skb,
  1996. TP_STATUS_KERNEL, (macoff+snaplen));
  1997. if (!h.raw)
  1998. goto drop_n_account;
  1999. if (po->tp_version <= TPACKET_V2) {
  2000. slot_id = po->rx_ring.head;
  2001. if (test_bit(slot_id, po->rx_ring.rx_owner_map))
  2002. goto drop_n_account;
  2003. __set_bit(slot_id, po->rx_ring.rx_owner_map);
  2004. }
  2005. if (do_vnet &&
  2006. virtio_net_hdr_from_skb(skb, h.raw + macoff -
  2007. sizeof(struct virtio_net_hdr),
  2008. vio_le(), true, 0)) {
  2009. if (po->tp_version == TPACKET_V3)
  2010. prb_clear_blk_fill_status(&po->rx_ring);
  2011. goto drop_n_account;
  2012. }
  2013. if (po->tp_version <= TPACKET_V2) {
  2014. packet_increment_rx_head(po, &po->rx_ring);
  2015. /*
  2016. * LOSING will be reported till you read the stats,
  2017. * because it's COR - Clear On Read.
  2018. * Anyways, moving it for V1/V2 only as V3 doesn't need this
  2019. * at packet level.
  2020. */
  2021. if (atomic_read(&po->tp_drops))
  2022. status |= TP_STATUS_LOSING;
  2023. }
  2024. po->stats.stats1.tp_packets++;
  2025. if (copy_skb) {
  2026. status |= TP_STATUS_COPY;
  2027. skb_clear_delivery_time(copy_skb);
  2028. __skb_queue_tail(&sk->sk_receive_queue, copy_skb);
  2029. }
  2030. spin_unlock(&sk->sk_receive_queue.lock);
  2031. skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
  2032. /* Always timestamp; prefer an existing software timestamp taken
  2033. * closer to the time of capture.
  2034. */
  2035. ts_status = tpacket_get_timestamp(skb, &ts,
  2036. po->tp_tstamp | SOF_TIMESTAMPING_SOFTWARE);
  2037. if (!ts_status)
  2038. ktime_get_real_ts64(&ts);
  2039. status |= ts_status;
  2040. switch (po->tp_version) {
  2041. case TPACKET_V1:
  2042. h.h1->tp_len = skb->len;
  2043. h.h1->tp_snaplen = snaplen;
  2044. h.h1->tp_mac = macoff;
  2045. h.h1->tp_net = netoff;
  2046. h.h1->tp_sec = ts.tv_sec;
  2047. h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
  2048. hdrlen = sizeof(*h.h1);
  2049. break;
  2050. case TPACKET_V2:
  2051. h.h2->tp_len = skb->len;
  2052. h.h2->tp_snaplen = snaplen;
  2053. h.h2->tp_mac = macoff;
  2054. h.h2->tp_net = netoff;
  2055. h.h2->tp_sec = ts.tv_sec;
  2056. h.h2->tp_nsec = ts.tv_nsec;
  2057. if (skb_vlan_tag_present(skb)) {
  2058. h.h2->tp_vlan_tci = skb_vlan_tag_get(skb);
  2059. h.h2->tp_vlan_tpid = ntohs(skb->vlan_proto);
  2060. status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
  2061. } else {
  2062. h.h2->tp_vlan_tci = 0;
  2063. h.h2->tp_vlan_tpid = 0;
  2064. }
  2065. memset(h.h2->tp_padding, 0, sizeof(h.h2->tp_padding));
  2066. hdrlen = sizeof(*h.h2);
  2067. break;
  2068. case TPACKET_V3:
  2069. /* tp_nxt_offset,vlan are already populated above.
  2070. * So DONT clear those fields here
  2071. */
  2072. h.h3->tp_status |= status;
  2073. h.h3->tp_len = skb->len;
  2074. h.h3->tp_snaplen = snaplen;
  2075. h.h3->tp_mac = macoff;
  2076. h.h3->tp_net = netoff;
  2077. h.h3->tp_sec = ts.tv_sec;
  2078. h.h3->tp_nsec = ts.tv_nsec;
  2079. memset(h.h3->tp_padding, 0, sizeof(h.h3->tp_padding));
  2080. hdrlen = sizeof(*h.h3);
  2081. break;
  2082. default:
  2083. BUG();
  2084. }
  2085. sll = h.raw + TPACKET_ALIGN(hdrlen);
  2086. sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
  2087. sll->sll_family = AF_PACKET;
  2088. sll->sll_hatype = dev->type;
  2089. sll->sll_protocol = skb->protocol;
  2090. sll->sll_pkttype = skb->pkt_type;
  2091. if (unlikely(packet_sock_flag(po, PACKET_SOCK_ORIGDEV)))
  2092. sll->sll_ifindex = orig_dev->ifindex;
  2093. else
  2094. sll->sll_ifindex = dev->ifindex;
  2095. smp_mb();
  2096. #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
  2097. if (po->tp_version <= TPACKET_V2) {
  2098. u8 *start, *end;
  2099. end = (u8 *) PAGE_ALIGN((unsigned long) h.raw +
  2100. macoff + snaplen);
  2101. for (start = h.raw; start < end; start += PAGE_SIZE)
  2102. flush_dcache_page(pgv_to_page(start));
  2103. }
  2104. smp_wmb();
  2105. #endif
  2106. if (po->tp_version <= TPACKET_V2) {
  2107. spin_lock(&sk->sk_receive_queue.lock);
  2108. __packet_set_status(po, h.raw, status);
  2109. __clear_bit(slot_id, po->rx_ring.rx_owner_map);
  2110. spin_unlock(&sk->sk_receive_queue.lock);
  2111. sk->sk_data_ready(sk);
  2112. } else if (po->tp_version == TPACKET_V3) {
  2113. prb_clear_blk_fill_status(&po->rx_ring);
  2114. }
  2115. drop_n_restore:
  2116. if (skb_head != skb->data && skb_shared(skb)) {
  2117. skb->data = skb_head;
  2118. skb->len = skb_len;
  2119. }
  2120. drop:
  2121. if (!is_drop_n_account)
  2122. consume_skb(skb);
  2123. else
  2124. kfree_skb(skb);
  2125. return 0;
  2126. drop_n_account:
  2127. spin_unlock(&sk->sk_receive_queue.lock);
  2128. atomic_inc(&po->tp_drops);
  2129. is_drop_n_account = true;
  2130. sk->sk_data_ready(sk);
  2131. kfree_skb(copy_skb);
  2132. goto drop_n_restore;
  2133. }
  2134. static void tpacket_destruct_skb(struct sk_buff *skb)
  2135. {
  2136. struct packet_sock *po = pkt_sk(skb->sk);
  2137. if (likely(po->tx_ring.pg_vec)) {
  2138. void *ph;
  2139. __u32 ts;
  2140. ph = skb_zcopy_get_nouarg(skb);
  2141. packet_dec_pending(&po->tx_ring);
  2142. ts = __packet_set_timestamp(po, ph, skb);
  2143. __packet_set_status(po, ph, TP_STATUS_AVAILABLE | ts);
  2144. if (!packet_read_pending(&po->tx_ring))
  2145. complete(&po->skb_completion);
  2146. }
  2147. sock_wfree(skb);
  2148. }
  2149. static int __packet_snd_vnet_parse(struct virtio_net_hdr *vnet_hdr, size_t len)
  2150. {
  2151. if ((vnet_hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
  2152. (__virtio16_to_cpu(vio_le(), vnet_hdr->csum_start) +
  2153. __virtio16_to_cpu(vio_le(), vnet_hdr->csum_offset) + 2 >
  2154. __virtio16_to_cpu(vio_le(), vnet_hdr->hdr_len)))
  2155. vnet_hdr->hdr_len = __cpu_to_virtio16(vio_le(),
  2156. __virtio16_to_cpu(vio_le(), vnet_hdr->csum_start) +
  2157. __virtio16_to_cpu(vio_le(), vnet_hdr->csum_offset) + 2);
  2158. if (__virtio16_to_cpu(vio_le(), vnet_hdr->hdr_len) > len)
  2159. return -EINVAL;
  2160. return 0;
  2161. }
  2162. static int packet_snd_vnet_parse(struct msghdr *msg, size_t *len,
  2163. struct virtio_net_hdr *vnet_hdr)
  2164. {
  2165. if (*len < sizeof(*vnet_hdr))
  2166. return -EINVAL;
  2167. *len -= sizeof(*vnet_hdr);
  2168. if (!copy_from_iter_full(vnet_hdr, sizeof(*vnet_hdr), &msg->msg_iter))
  2169. return -EFAULT;
  2170. return __packet_snd_vnet_parse(vnet_hdr, *len);
  2171. }
  2172. static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
  2173. void *frame, struct net_device *dev, void *data, int tp_len,
  2174. __be16 proto, unsigned char *addr, int hlen, int copylen,
  2175. const struct sockcm_cookie *sockc)
  2176. {
  2177. union tpacket_uhdr ph;
  2178. int to_write, offset, len, nr_frags, len_max;
  2179. struct socket *sock = po->sk.sk_socket;
  2180. struct page *page;
  2181. int err;
  2182. ph.raw = frame;
  2183. skb->protocol = proto;
  2184. skb->dev = dev;
  2185. skb->priority = READ_ONCE(po->sk.sk_priority);
  2186. skb->mark = READ_ONCE(po->sk.sk_mark);
  2187. skb->tstamp = sockc->transmit_time;
  2188. skb_setup_tx_timestamp(skb, sockc->tsflags);
  2189. skb_zcopy_set_nouarg(skb, ph.raw);
  2190. skb_reserve(skb, hlen);
  2191. skb_reset_network_header(skb);
  2192. to_write = tp_len;
  2193. if (sock->type == SOCK_DGRAM) {
  2194. err = dev_hard_header(skb, dev, ntohs(proto), addr,
  2195. NULL, tp_len);
  2196. if (unlikely(err < 0))
  2197. return -EINVAL;
  2198. } else if (copylen) {
  2199. int hdrlen = min_t(int, copylen, tp_len);
  2200. skb_push(skb, dev->hard_header_len);
  2201. skb_put(skb, copylen - dev->hard_header_len);
  2202. err = skb_store_bits(skb, 0, data, hdrlen);
  2203. if (unlikely(err))
  2204. return err;
  2205. if (!dev_validate_header(dev, skb->data, hdrlen))
  2206. return -EINVAL;
  2207. data += hdrlen;
  2208. to_write -= hdrlen;
  2209. }
  2210. offset = offset_in_page(data);
  2211. len_max = PAGE_SIZE - offset;
  2212. len = ((to_write > len_max) ? len_max : to_write);
  2213. skb->data_len = to_write;
  2214. skb->len += to_write;
  2215. skb->truesize += to_write;
  2216. refcount_add(to_write, &po->sk.sk_wmem_alloc);
  2217. while (likely(to_write)) {
  2218. nr_frags = skb_shinfo(skb)->nr_frags;
  2219. if (unlikely(nr_frags >= MAX_SKB_FRAGS)) {
  2220. pr_err("Packet exceed the number of skb frags(%lu)\n",
  2221. MAX_SKB_FRAGS);
  2222. return -EFAULT;
  2223. }
  2224. page = pgv_to_page(data);
  2225. data += len;
  2226. flush_dcache_page(page);
  2227. get_page(page);
  2228. skb_fill_page_desc(skb, nr_frags, page, offset, len);
  2229. to_write -= len;
  2230. offset = 0;
  2231. len_max = PAGE_SIZE;
  2232. len = ((to_write > len_max) ? len_max : to_write);
  2233. }
  2234. packet_parse_headers(skb, sock);
  2235. return tp_len;
  2236. }
  2237. static int tpacket_parse_header(struct packet_sock *po, void *frame,
  2238. int size_max, void **data)
  2239. {
  2240. union tpacket_uhdr ph;
  2241. int tp_len, off;
  2242. ph.raw = frame;
  2243. switch (po->tp_version) {
  2244. case TPACKET_V3:
  2245. if (ph.h3->tp_next_offset != 0) {
  2246. pr_warn_once("variable sized slot not supported");
  2247. return -EINVAL;
  2248. }
  2249. tp_len = ph.h3->tp_len;
  2250. break;
  2251. case TPACKET_V2:
  2252. tp_len = ph.h2->tp_len;
  2253. break;
  2254. default:
  2255. tp_len = ph.h1->tp_len;
  2256. break;
  2257. }
  2258. if (unlikely(tp_len > size_max)) {
  2259. pr_err("packet size is too long (%d > %d)\n", tp_len, size_max);
  2260. return -EMSGSIZE;
  2261. }
  2262. if (unlikely(po->tp_tx_has_off)) {
  2263. int off_min, off_max;
  2264. off_min = po->tp_hdrlen - sizeof(struct sockaddr_ll);
  2265. off_max = po->tx_ring.frame_size - tp_len;
  2266. if (po->sk.sk_type == SOCK_DGRAM) {
  2267. switch (po->tp_version) {
  2268. case TPACKET_V3:
  2269. off = ph.h3->tp_net;
  2270. break;
  2271. case TPACKET_V2:
  2272. off = ph.h2->tp_net;
  2273. break;
  2274. default:
  2275. off = ph.h1->tp_net;
  2276. break;
  2277. }
  2278. } else {
  2279. switch (po->tp_version) {
  2280. case TPACKET_V3:
  2281. off = ph.h3->tp_mac;
  2282. break;
  2283. case TPACKET_V2:
  2284. off = ph.h2->tp_mac;
  2285. break;
  2286. default:
  2287. off = ph.h1->tp_mac;
  2288. break;
  2289. }
  2290. }
  2291. if (unlikely((off < off_min) || (off_max < off)))
  2292. return -EINVAL;
  2293. } else {
  2294. off = po->tp_hdrlen - sizeof(struct sockaddr_ll);
  2295. }
  2296. *data = frame + off;
  2297. return tp_len;
  2298. }
  2299. static int tpacket_snd(struct packet_sock *po, struct msghdr *msg)
  2300. {
  2301. struct sk_buff *skb = NULL;
  2302. struct net_device *dev;
  2303. struct virtio_net_hdr *vnet_hdr = NULL;
  2304. struct sockcm_cookie sockc;
  2305. __be16 proto;
  2306. int err, reserve = 0;
  2307. void *ph;
  2308. DECLARE_SOCKADDR(struct sockaddr_ll *, saddr, msg->msg_name);
  2309. bool need_wait = !(msg->msg_flags & MSG_DONTWAIT);
  2310. unsigned char *addr = NULL;
  2311. int tp_len, size_max;
  2312. void *data;
  2313. int len_sum = 0;
  2314. int status = TP_STATUS_AVAILABLE;
  2315. int hlen, tlen, copylen = 0;
  2316. long timeo = 0;
  2317. mutex_lock(&po->pg_vec_lock);
  2318. /* packet_sendmsg() check on tx_ring.pg_vec was lockless,
  2319. * we need to confirm it under protection of pg_vec_lock.
  2320. */
  2321. if (unlikely(!po->tx_ring.pg_vec)) {
  2322. err = -EBUSY;
  2323. goto out;
  2324. }
  2325. if (likely(saddr == NULL)) {
  2326. dev = packet_cached_dev_get(po);
  2327. proto = READ_ONCE(po->num);
  2328. } else {
  2329. err = -EINVAL;
  2330. if (msg->msg_namelen < sizeof(struct sockaddr_ll))
  2331. goto out;
  2332. if (msg->msg_namelen < (saddr->sll_halen
  2333. + offsetof(struct sockaddr_ll,
  2334. sll_addr)))
  2335. goto out;
  2336. proto = saddr->sll_protocol;
  2337. dev = dev_get_by_index(sock_net(&po->sk), saddr->sll_ifindex);
  2338. if (po->sk.sk_socket->type == SOCK_DGRAM) {
  2339. if (dev && msg->msg_namelen < dev->addr_len +
  2340. offsetof(struct sockaddr_ll, sll_addr))
  2341. goto out_put;
  2342. addr = saddr->sll_addr;
  2343. }
  2344. }
  2345. err = -ENXIO;
  2346. if (unlikely(dev == NULL))
  2347. goto out;
  2348. err = -ENETDOWN;
  2349. if (unlikely(!(dev->flags & IFF_UP)))
  2350. goto out_put;
  2351. sockcm_init(&sockc, &po->sk);
  2352. if (msg->msg_controllen) {
  2353. err = sock_cmsg_send(&po->sk, msg, &sockc);
  2354. if (unlikely(err))
  2355. goto out_put;
  2356. }
  2357. if (po->sk.sk_socket->type == SOCK_RAW)
  2358. reserve = dev->hard_header_len;
  2359. size_max = po->tx_ring.frame_size
  2360. - (po->tp_hdrlen - sizeof(struct sockaddr_ll));
  2361. if ((size_max > dev->mtu + reserve + VLAN_HLEN) && !po->has_vnet_hdr)
  2362. size_max = dev->mtu + reserve + VLAN_HLEN;
  2363. reinit_completion(&po->skb_completion);
  2364. do {
  2365. ph = packet_current_frame(po, &po->tx_ring,
  2366. TP_STATUS_SEND_REQUEST);
  2367. if (unlikely(ph == NULL)) {
  2368. if (need_wait && skb) {
  2369. timeo = sock_sndtimeo(&po->sk, msg->msg_flags & MSG_DONTWAIT);
  2370. timeo = wait_for_completion_interruptible_timeout(&po->skb_completion, timeo);
  2371. if (timeo <= 0) {
  2372. err = !timeo ? -ETIMEDOUT : -ERESTARTSYS;
  2373. goto out_put;
  2374. }
  2375. }
  2376. /* check for additional frames */
  2377. continue;
  2378. }
  2379. skb = NULL;
  2380. tp_len = tpacket_parse_header(po, ph, size_max, &data);
  2381. if (tp_len < 0)
  2382. goto tpacket_error;
  2383. status = TP_STATUS_SEND_REQUEST;
  2384. hlen = LL_RESERVED_SPACE(dev);
  2385. tlen = dev->needed_tailroom;
  2386. if (po->has_vnet_hdr) {
  2387. vnet_hdr = data;
  2388. data += sizeof(*vnet_hdr);
  2389. tp_len -= sizeof(*vnet_hdr);
  2390. if (tp_len < 0 ||
  2391. __packet_snd_vnet_parse(vnet_hdr, tp_len)) {
  2392. tp_len = -EINVAL;
  2393. goto tpacket_error;
  2394. }
  2395. copylen = __virtio16_to_cpu(vio_le(),
  2396. vnet_hdr->hdr_len);
  2397. }
  2398. copylen = max_t(int, copylen, dev->hard_header_len);
  2399. skb = sock_alloc_send_skb(&po->sk,
  2400. hlen + tlen + sizeof(struct sockaddr_ll) +
  2401. (copylen - dev->hard_header_len),
  2402. !need_wait, &err);
  2403. if (unlikely(skb == NULL)) {
  2404. /* we assume the socket was initially writeable ... */
  2405. if (likely(len_sum > 0))
  2406. err = len_sum;
  2407. goto out_status;
  2408. }
  2409. tp_len = tpacket_fill_skb(po, skb, ph, dev, data, tp_len, proto,
  2410. addr, hlen, copylen, &sockc);
  2411. if (likely(tp_len >= 0) &&
  2412. tp_len > dev->mtu + reserve &&
  2413. !po->has_vnet_hdr &&
  2414. !packet_extra_vlan_len_allowed(dev, skb))
  2415. tp_len = -EMSGSIZE;
  2416. if (unlikely(tp_len < 0)) {
  2417. tpacket_error:
  2418. if (po->tp_loss) {
  2419. __packet_set_status(po, ph,
  2420. TP_STATUS_AVAILABLE);
  2421. packet_increment_head(&po->tx_ring);
  2422. kfree_skb(skb);
  2423. continue;
  2424. } else {
  2425. status = TP_STATUS_WRONG_FORMAT;
  2426. err = tp_len;
  2427. goto out_status;
  2428. }
  2429. }
  2430. if (po->has_vnet_hdr) {
  2431. if (virtio_net_hdr_to_skb(skb, vnet_hdr, vio_le())) {
  2432. tp_len = -EINVAL;
  2433. goto tpacket_error;
  2434. }
  2435. virtio_net_hdr_set_proto(skb, vnet_hdr);
  2436. }
  2437. skb->destructor = tpacket_destruct_skb;
  2438. __packet_set_status(po, ph, TP_STATUS_SENDING);
  2439. packet_inc_pending(&po->tx_ring);
  2440. status = TP_STATUS_SEND_REQUEST;
  2441. /* Paired with WRITE_ONCE() in packet_setsockopt() */
  2442. err = READ_ONCE(po->xmit)(skb);
  2443. if (unlikely(err != 0)) {
  2444. if (err > 0)
  2445. err = net_xmit_errno(err);
  2446. if (err && __packet_get_status(po, ph) ==
  2447. TP_STATUS_AVAILABLE) {
  2448. /* skb was destructed already */
  2449. skb = NULL;
  2450. goto out_status;
  2451. }
  2452. /*
  2453. * skb was dropped but not destructed yet;
  2454. * let's treat it like congestion or err < 0
  2455. */
  2456. err = 0;
  2457. }
  2458. packet_increment_head(&po->tx_ring);
  2459. len_sum += tp_len;
  2460. } while (likely((ph != NULL) ||
  2461. /* Note: packet_read_pending() might be slow if we have
  2462. * to call it as it's per_cpu variable, but in fast-path
  2463. * we already short-circuit the loop with the first
  2464. * condition, and luckily don't have to go that path
  2465. * anyway.
  2466. */
  2467. (need_wait && packet_read_pending(&po->tx_ring))));
  2468. err = len_sum;
  2469. goto out_put;
  2470. out_status:
  2471. __packet_set_status(po, ph, status);
  2472. kfree_skb(skb);
  2473. out_put:
  2474. dev_put(dev);
  2475. out:
  2476. mutex_unlock(&po->pg_vec_lock);
  2477. return err;
  2478. }
  2479. static struct sk_buff *packet_alloc_skb(struct sock *sk, size_t prepad,
  2480. size_t reserve, size_t len,
  2481. size_t linear, int noblock,
  2482. int *err)
  2483. {
  2484. struct sk_buff *skb;
  2485. /* Under a page? Don't bother with paged skb. */
  2486. if (prepad + len < PAGE_SIZE || !linear)
  2487. linear = len;
  2488. skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
  2489. err, 0);
  2490. if (!skb)
  2491. return NULL;
  2492. skb_reserve(skb, reserve);
  2493. skb_put(skb, linear);
  2494. skb->data_len = len - linear;
  2495. skb->len += len - linear;
  2496. return skb;
  2497. }
  2498. static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len)
  2499. {
  2500. struct sock *sk = sock->sk;
  2501. DECLARE_SOCKADDR(struct sockaddr_ll *, saddr, msg->msg_name);
  2502. struct sk_buff *skb;
  2503. struct net_device *dev;
  2504. __be16 proto;
  2505. unsigned char *addr = NULL;
  2506. int err, reserve = 0;
  2507. struct sockcm_cookie sockc;
  2508. struct virtio_net_hdr vnet_hdr = { 0 };
  2509. int offset = 0;
  2510. struct packet_sock *po = pkt_sk(sk);
  2511. bool has_vnet_hdr = false;
  2512. int hlen, tlen, linear;
  2513. int extra_len = 0;
  2514. /*
  2515. * Get and verify the address.
  2516. */
  2517. if (likely(saddr == NULL)) {
  2518. dev = packet_cached_dev_get(po);
  2519. proto = READ_ONCE(po->num);
  2520. } else {
  2521. err = -EINVAL;
  2522. if (msg->msg_namelen < sizeof(struct sockaddr_ll))
  2523. goto out;
  2524. if (msg->msg_namelen < (saddr->sll_halen + offsetof(struct sockaddr_ll, sll_addr)))
  2525. goto out;
  2526. proto = saddr->sll_protocol;
  2527. dev = dev_get_by_index(sock_net(sk), saddr->sll_ifindex);
  2528. if (sock->type == SOCK_DGRAM) {
  2529. if (dev && msg->msg_namelen < dev->addr_len +
  2530. offsetof(struct sockaddr_ll, sll_addr))
  2531. goto out_unlock;
  2532. addr = saddr->sll_addr;
  2533. }
  2534. }
  2535. err = -ENXIO;
  2536. if (unlikely(dev == NULL))
  2537. goto out_unlock;
  2538. err = -ENETDOWN;
  2539. if (unlikely(!(dev->flags & IFF_UP)))
  2540. goto out_unlock;
  2541. sockcm_init(&sockc, sk);
  2542. sockc.mark = READ_ONCE(sk->sk_mark);
  2543. if (msg->msg_controllen) {
  2544. err = sock_cmsg_send(sk, msg, &sockc);
  2545. if (unlikely(err))
  2546. goto out_unlock;
  2547. }
  2548. if (sock->type == SOCK_RAW)
  2549. reserve = dev->hard_header_len;
  2550. if (po->has_vnet_hdr) {
  2551. err = packet_snd_vnet_parse(msg, &len, &vnet_hdr);
  2552. if (err)
  2553. goto out_unlock;
  2554. has_vnet_hdr = true;
  2555. }
  2556. if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
  2557. if (!netif_supports_nofcs(dev)) {
  2558. err = -EPROTONOSUPPORT;
  2559. goto out_unlock;
  2560. }
  2561. extra_len = 4; /* We're doing our own CRC */
  2562. }
  2563. err = -EMSGSIZE;
  2564. if (!vnet_hdr.gso_type &&
  2565. (len > dev->mtu + reserve + VLAN_HLEN + extra_len))
  2566. goto out_unlock;
  2567. err = -ENOBUFS;
  2568. hlen = LL_RESERVED_SPACE(dev);
  2569. tlen = dev->needed_tailroom;
  2570. linear = __virtio16_to_cpu(vio_le(), vnet_hdr.hdr_len);
  2571. linear = max(linear, min_t(int, len, dev->hard_header_len));
  2572. skb = packet_alloc_skb(sk, hlen + tlen, hlen, len, linear,
  2573. msg->msg_flags & MSG_DONTWAIT, &err);
  2574. if (skb == NULL)
  2575. goto out_unlock;
  2576. skb_reset_network_header(skb);
  2577. err = -EINVAL;
  2578. if (sock->type == SOCK_DGRAM) {
  2579. offset = dev_hard_header(skb, dev, ntohs(proto), addr, NULL, len);
  2580. if (unlikely(offset < 0))
  2581. goto out_free;
  2582. } else if (reserve) {
  2583. skb_reserve(skb, -reserve);
  2584. if (len < reserve + sizeof(struct ipv6hdr) &&
  2585. dev->min_header_len != dev->hard_header_len)
  2586. skb_reset_network_header(skb);
  2587. }
  2588. /* Returns -EFAULT on error */
  2589. err = skb_copy_datagram_from_iter(skb, offset, &msg->msg_iter, len);
  2590. if (err)
  2591. goto out_free;
  2592. if ((sock->type == SOCK_RAW &&
  2593. !dev_validate_header(dev, skb->data, len)) || !skb->len) {
  2594. err = -EINVAL;
  2595. goto out_free;
  2596. }
  2597. skb_setup_tx_timestamp(skb, sockc.tsflags);
  2598. if (!vnet_hdr.gso_type && (len > dev->mtu + reserve + extra_len) &&
  2599. !packet_extra_vlan_len_allowed(dev, skb)) {
  2600. err = -EMSGSIZE;
  2601. goto out_free;
  2602. }
  2603. skb->protocol = proto;
  2604. skb->dev = dev;
  2605. skb->priority = READ_ONCE(sk->sk_priority);
  2606. skb->mark = sockc.mark;
  2607. skb->tstamp = sockc.transmit_time;
  2608. if (unlikely(extra_len == 4))
  2609. skb->no_fcs = 1;
  2610. packet_parse_headers(skb, sock);
  2611. if (has_vnet_hdr) {
  2612. err = virtio_net_hdr_to_skb(skb, &vnet_hdr, vio_le());
  2613. if (err)
  2614. goto out_free;
  2615. len += sizeof(vnet_hdr);
  2616. virtio_net_hdr_set_proto(skb, &vnet_hdr);
  2617. }
  2618. /* Paired with WRITE_ONCE() in packet_setsockopt() */
  2619. err = READ_ONCE(po->xmit)(skb);
  2620. if (unlikely(err != 0)) {
  2621. if (err > 0)
  2622. err = net_xmit_errno(err);
  2623. if (err)
  2624. goto out_unlock;
  2625. }
  2626. dev_put(dev);
  2627. return len;
  2628. out_free:
  2629. kfree_skb(skb);
  2630. out_unlock:
  2631. dev_put(dev);
  2632. out:
  2633. return err;
  2634. }
  2635. static int packet_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
  2636. {
  2637. struct sock *sk = sock->sk;
  2638. struct packet_sock *po = pkt_sk(sk);
  2639. /* Reading tx_ring.pg_vec without holding pg_vec_lock is racy.
  2640. * tpacket_snd() will redo the check safely.
  2641. */
  2642. if (data_race(po->tx_ring.pg_vec))
  2643. return tpacket_snd(po, msg);
  2644. return packet_snd(sock, msg, len);
  2645. }
  2646. /*
  2647. * Close a PACKET socket. This is fairly simple. We immediately go
  2648. * to 'closed' state and remove our protocol entry in the device list.
  2649. */
  2650. static int packet_release(struct socket *sock)
  2651. {
  2652. struct sock *sk = sock->sk;
  2653. struct packet_sock *po;
  2654. struct packet_fanout *f;
  2655. struct net *net;
  2656. union tpacket_req_u req_u;
  2657. if (!sk)
  2658. return 0;
  2659. net = sock_net(sk);
  2660. po = pkt_sk(sk);
  2661. mutex_lock(&net->packet.sklist_lock);
  2662. sk_del_node_init_rcu(sk);
  2663. mutex_unlock(&net->packet.sklist_lock);
  2664. sock_prot_inuse_add(net, sk->sk_prot, -1);
  2665. spin_lock(&po->bind_lock);
  2666. unregister_prot_hook(sk, false);
  2667. packet_cached_dev_reset(po);
  2668. if (po->prot_hook.dev) {
  2669. netdev_put(po->prot_hook.dev, &po->prot_hook.dev_tracker);
  2670. po->prot_hook.dev = NULL;
  2671. }
  2672. spin_unlock(&po->bind_lock);
  2673. packet_flush_mclist(sk);
  2674. lock_sock(sk);
  2675. if (po->rx_ring.pg_vec) {
  2676. memset(&req_u, 0, sizeof(req_u));
  2677. packet_set_ring(sk, &req_u, 1, 0);
  2678. }
  2679. if (po->tx_ring.pg_vec) {
  2680. memset(&req_u, 0, sizeof(req_u));
  2681. packet_set_ring(sk, &req_u, 1, 1);
  2682. }
  2683. release_sock(sk);
  2684. f = fanout_release(sk);
  2685. synchronize_net();
  2686. kfree(po->rollover);
  2687. if (f) {
  2688. fanout_release_data(f);
  2689. kvfree(f);
  2690. }
  2691. /*
  2692. * Now the socket is dead. No more input will appear.
  2693. */
  2694. sock_orphan(sk);
  2695. sock->sk = NULL;
  2696. /* Purge queues */
  2697. skb_queue_purge(&sk->sk_receive_queue);
  2698. packet_free_pending(po);
  2699. sk_refcnt_debug_release(sk);
  2700. sock_put(sk);
  2701. return 0;
  2702. }
  2703. /*
  2704. * Attach a packet hook.
  2705. */
  2706. static int packet_do_bind(struct sock *sk, const char *name, int ifindex,
  2707. __be16 proto)
  2708. {
  2709. struct packet_sock *po = pkt_sk(sk);
  2710. struct net_device *dev = NULL;
  2711. bool unlisted = false;
  2712. bool need_rehook;
  2713. int ret = 0;
  2714. lock_sock(sk);
  2715. spin_lock(&po->bind_lock);
  2716. if (!proto)
  2717. proto = po->num;
  2718. rcu_read_lock();
  2719. if (po->fanout) {
  2720. ret = -EINVAL;
  2721. goto out_unlock;
  2722. }
  2723. if (name) {
  2724. dev = dev_get_by_name_rcu(sock_net(sk), name);
  2725. if (!dev) {
  2726. ret = -ENODEV;
  2727. goto out_unlock;
  2728. }
  2729. } else if (ifindex) {
  2730. dev = dev_get_by_index_rcu(sock_net(sk), ifindex);
  2731. if (!dev) {
  2732. ret = -ENODEV;
  2733. goto out_unlock;
  2734. }
  2735. }
  2736. need_rehook = po->prot_hook.type != proto || po->prot_hook.dev != dev;
  2737. if (need_rehook) {
  2738. dev_hold(dev);
  2739. if (po->running) {
  2740. rcu_read_unlock();
  2741. /* prevents packet_notifier() from calling
  2742. * register_prot_hook()
  2743. */
  2744. WRITE_ONCE(po->num, 0);
  2745. __unregister_prot_hook(sk, true);
  2746. rcu_read_lock();
  2747. if (dev)
  2748. unlisted = !dev_get_by_index_rcu(sock_net(sk),
  2749. dev->ifindex);
  2750. }
  2751. BUG_ON(po->running);
  2752. WRITE_ONCE(po->num, proto);
  2753. po->prot_hook.type = proto;
  2754. netdev_put(po->prot_hook.dev, &po->prot_hook.dev_tracker);
  2755. if (unlikely(unlisted)) {
  2756. po->prot_hook.dev = NULL;
  2757. WRITE_ONCE(po->ifindex, -1);
  2758. packet_cached_dev_reset(po);
  2759. } else {
  2760. netdev_hold(dev, &po->prot_hook.dev_tracker,
  2761. GFP_ATOMIC);
  2762. po->prot_hook.dev = dev;
  2763. WRITE_ONCE(po->ifindex, dev ? dev->ifindex : 0);
  2764. packet_cached_dev_assign(po, dev);
  2765. }
  2766. dev_put(dev);
  2767. }
  2768. if (proto == 0 || !need_rehook)
  2769. goto out_unlock;
  2770. if (!unlisted && (!dev || (dev->flags & IFF_UP))) {
  2771. register_prot_hook(sk);
  2772. } else {
  2773. sk->sk_err = ENETDOWN;
  2774. if (!sock_flag(sk, SOCK_DEAD))
  2775. sk_error_report(sk);
  2776. }
  2777. out_unlock:
  2778. rcu_read_unlock();
  2779. spin_unlock(&po->bind_lock);
  2780. release_sock(sk);
  2781. return ret;
  2782. }
  2783. /*
  2784. * Bind a packet socket to a device
  2785. */
  2786. static int packet_bind_spkt(struct socket *sock, struct sockaddr *uaddr,
  2787. int addr_len)
  2788. {
  2789. struct sock *sk = sock->sk;
  2790. char name[sizeof(uaddr->sa_data) + 1];
  2791. /*
  2792. * Check legality
  2793. */
  2794. if (addr_len != sizeof(struct sockaddr))
  2795. return -EINVAL;
  2796. /* uaddr->sa_data comes from the userspace, it's not guaranteed to be
  2797. * zero-terminated.
  2798. */
  2799. memcpy(name, uaddr->sa_data, sizeof(uaddr->sa_data));
  2800. name[sizeof(uaddr->sa_data)] = 0;
  2801. return packet_do_bind(sk, name, 0, 0);
  2802. }
  2803. static int packet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
  2804. {
  2805. struct sockaddr_ll *sll = (struct sockaddr_ll *)uaddr;
  2806. struct sock *sk = sock->sk;
  2807. /*
  2808. * Check legality
  2809. */
  2810. if (addr_len < sizeof(struct sockaddr_ll))
  2811. return -EINVAL;
  2812. if (sll->sll_family != AF_PACKET)
  2813. return -EINVAL;
  2814. return packet_do_bind(sk, NULL, sll->sll_ifindex, sll->sll_protocol);
  2815. }
  2816. static struct proto packet_proto = {
  2817. .name = "PACKET",
  2818. .owner = THIS_MODULE,
  2819. .obj_size = sizeof(struct packet_sock),
  2820. };
  2821. /*
  2822. * Create a packet of type SOCK_PACKET.
  2823. */
  2824. static int packet_create(struct net *net, struct socket *sock, int protocol,
  2825. int kern)
  2826. {
  2827. struct sock *sk;
  2828. struct packet_sock *po;
  2829. __be16 proto = (__force __be16)protocol; /* weird, but documented */
  2830. int err;
  2831. if (!ns_capable(net->user_ns, CAP_NET_RAW))
  2832. return -EPERM;
  2833. if (sock->type != SOCK_DGRAM && sock->type != SOCK_RAW &&
  2834. sock->type != SOCK_PACKET)
  2835. return -ESOCKTNOSUPPORT;
  2836. sock->state = SS_UNCONNECTED;
  2837. err = -ENOBUFS;
  2838. sk = sk_alloc(net, PF_PACKET, GFP_KERNEL, &packet_proto, kern);
  2839. if (sk == NULL)
  2840. goto out;
  2841. sock->ops = &packet_ops;
  2842. if (sock->type == SOCK_PACKET)
  2843. sock->ops = &packet_ops_spkt;
  2844. sock_init_data(sock, sk);
  2845. po = pkt_sk(sk);
  2846. init_completion(&po->skb_completion);
  2847. sk->sk_family = PF_PACKET;
  2848. po->num = proto;
  2849. po->xmit = dev_queue_xmit;
  2850. err = packet_alloc_pending(po);
  2851. if (err)
  2852. goto out2;
  2853. packet_cached_dev_reset(po);
  2854. sk->sk_destruct = packet_sock_destruct;
  2855. sk_refcnt_debug_inc(sk);
  2856. /*
  2857. * Attach a protocol block
  2858. */
  2859. spin_lock_init(&po->bind_lock);
  2860. mutex_init(&po->pg_vec_lock);
  2861. po->rollover = NULL;
  2862. po->prot_hook.func = packet_rcv;
  2863. if (sock->type == SOCK_PACKET)
  2864. po->prot_hook.func = packet_rcv_spkt;
  2865. po->prot_hook.af_packet_priv = sk;
  2866. po->prot_hook.af_packet_net = sock_net(sk);
  2867. if (proto) {
  2868. po->prot_hook.type = proto;
  2869. __register_prot_hook(sk);
  2870. }
  2871. mutex_lock(&net->packet.sklist_lock);
  2872. sk_add_node_tail_rcu(sk, &net->packet.sklist);
  2873. mutex_unlock(&net->packet.sklist_lock);
  2874. sock_prot_inuse_add(net, &packet_proto, 1);
  2875. return 0;
  2876. out2:
  2877. sk_free(sk);
  2878. out:
  2879. return err;
  2880. }
  2881. /*
  2882. * Pull a packet from our receive queue and hand it to the user.
  2883. * If necessary we block.
  2884. */
  2885. static int packet_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
  2886. int flags)
  2887. {
  2888. struct sock *sk = sock->sk;
  2889. struct sk_buff *skb;
  2890. int copied, err;
  2891. int vnet_hdr_len = 0;
  2892. unsigned int origlen = 0;
  2893. err = -EINVAL;
  2894. if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))
  2895. goto out;
  2896. #if 0
  2897. /* What error should we return now? EUNATTACH? */
  2898. if (pkt_sk(sk)->ifindex < 0)
  2899. return -ENODEV;
  2900. #endif
  2901. if (flags & MSG_ERRQUEUE) {
  2902. err = sock_recv_errqueue(sk, msg, len,
  2903. SOL_PACKET, PACKET_TX_TIMESTAMP);
  2904. goto out;
  2905. }
  2906. /*
  2907. * Call the generic datagram receiver. This handles all sorts
  2908. * of horrible races and re-entrancy so we can forget about it
  2909. * in the protocol layers.
  2910. *
  2911. * Now it will return ENETDOWN, if device have just gone down,
  2912. * but then it will block.
  2913. */
  2914. skb = skb_recv_datagram(sk, flags, &err);
  2915. /*
  2916. * An error occurred so return it. Because skb_recv_datagram()
  2917. * handles the blocking we don't see and worry about blocking
  2918. * retries.
  2919. */
  2920. if (skb == NULL)
  2921. goto out;
  2922. packet_rcv_try_clear_pressure(pkt_sk(sk));
  2923. if (pkt_sk(sk)->has_vnet_hdr) {
  2924. err = packet_rcv_vnet(msg, skb, &len);
  2925. if (err)
  2926. goto out_free;
  2927. vnet_hdr_len = sizeof(struct virtio_net_hdr);
  2928. }
  2929. /* You lose any data beyond the buffer you gave. If it worries
  2930. * a user program they can ask the device for its MTU
  2931. * anyway.
  2932. */
  2933. copied = skb->len;
  2934. if (copied > len) {
  2935. copied = len;
  2936. msg->msg_flags |= MSG_TRUNC;
  2937. }
  2938. err = skb_copy_datagram_msg(skb, 0, msg, copied);
  2939. if (err)
  2940. goto out_free;
  2941. if (sock->type != SOCK_PACKET) {
  2942. struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
  2943. /* Original length was stored in sockaddr_ll fields */
  2944. origlen = PACKET_SKB_CB(skb)->sa.origlen;
  2945. sll->sll_family = AF_PACKET;
  2946. sll->sll_protocol = skb->protocol;
  2947. }
  2948. sock_recv_cmsgs(msg, sk, skb);
  2949. if (msg->msg_name) {
  2950. const size_t max_len = min(sizeof(skb->cb),
  2951. sizeof(struct sockaddr_storage));
  2952. int copy_len;
  2953. /* If the address length field is there to be filled
  2954. * in, we fill it in now.
  2955. */
  2956. if (sock->type == SOCK_PACKET) {
  2957. __sockaddr_check_size(sizeof(struct sockaddr_pkt));
  2958. msg->msg_namelen = sizeof(struct sockaddr_pkt);
  2959. copy_len = msg->msg_namelen;
  2960. } else {
  2961. struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
  2962. msg->msg_namelen = sll->sll_halen +
  2963. offsetof(struct sockaddr_ll, sll_addr);
  2964. copy_len = msg->msg_namelen;
  2965. if (msg->msg_namelen < sizeof(struct sockaddr_ll)) {
  2966. memset(msg->msg_name +
  2967. offsetof(struct sockaddr_ll, sll_addr),
  2968. 0, sizeof(sll->sll_addr));
  2969. msg->msg_namelen = sizeof(struct sockaddr_ll);
  2970. }
  2971. }
  2972. if (WARN_ON_ONCE(copy_len > max_len)) {
  2973. copy_len = max_len;
  2974. msg->msg_namelen = copy_len;
  2975. }
  2976. memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa, copy_len);
  2977. }
  2978. if (packet_sock_flag(pkt_sk(sk), PACKET_SOCK_AUXDATA)) {
  2979. struct tpacket_auxdata aux;
  2980. aux.tp_status = TP_STATUS_USER;
  2981. if (skb->ip_summed == CHECKSUM_PARTIAL)
  2982. aux.tp_status |= TP_STATUS_CSUMNOTREADY;
  2983. else if (skb->pkt_type != PACKET_OUTGOING &&
  2984. skb_csum_unnecessary(skb))
  2985. aux.tp_status |= TP_STATUS_CSUM_VALID;
  2986. aux.tp_len = origlen;
  2987. aux.tp_snaplen = skb->len;
  2988. aux.tp_mac = 0;
  2989. aux.tp_net = skb_network_offset(skb);
  2990. if (skb_vlan_tag_present(skb)) {
  2991. aux.tp_vlan_tci = skb_vlan_tag_get(skb);
  2992. aux.tp_vlan_tpid = ntohs(skb->vlan_proto);
  2993. aux.tp_status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
  2994. } else {
  2995. aux.tp_vlan_tci = 0;
  2996. aux.tp_vlan_tpid = 0;
  2997. }
  2998. put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);
  2999. }
  3000. /*
  3001. * Free or return the buffer as appropriate. Again this
  3002. * hides all the races and re-entrancy issues from us.
  3003. */
  3004. err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);
  3005. out_free:
  3006. skb_free_datagram(sk, skb);
  3007. out:
  3008. return err;
  3009. }
  3010. static int packet_getname_spkt(struct socket *sock, struct sockaddr *uaddr,
  3011. int peer)
  3012. {
  3013. struct net_device *dev;
  3014. struct sock *sk = sock->sk;
  3015. if (peer)
  3016. return -EOPNOTSUPP;
  3017. uaddr->sa_family = AF_PACKET;
  3018. memset(uaddr->sa_data, 0, sizeof(uaddr->sa_data));
  3019. rcu_read_lock();
  3020. dev = dev_get_by_index_rcu(sock_net(sk), READ_ONCE(pkt_sk(sk)->ifindex));
  3021. if (dev)
  3022. strscpy(uaddr->sa_data, dev->name, sizeof(uaddr->sa_data));
  3023. rcu_read_unlock();
  3024. return sizeof(*uaddr);
  3025. }
  3026. static int packet_getname(struct socket *sock, struct sockaddr *uaddr,
  3027. int peer)
  3028. {
  3029. struct net_device *dev;
  3030. struct sock *sk = sock->sk;
  3031. struct packet_sock *po = pkt_sk(sk);
  3032. DECLARE_SOCKADDR(struct sockaddr_ll *, sll, uaddr);
  3033. int ifindex;
  3034. if (peer)
  3035. return -EOPNOTSUPP;
  3036. ifindex = READ_ONCE(po->ifindex);
  3037. sll->sll_family = AF_PACKET;
  3038. sll->sll_ifindex = ifindex;
  3039. sll->sll_protocol = READ_ONCE(po->num);
  3040. sll->sll_pkttype = 0;
  3041. rcu_read_lock();
  3042. dev = dev_get_by_index_rcu(sock_net(sk), ifindex);
  3043. if (dev) {
  3044. sll->sll_hatype = dev->type;
  3045. sll->sll_halen = dev->addr_len;
  3046. memcpy(sll->sll_addr, dev->dev_addr, dev->addr_len);
  3047. } else {
  3048. sll->sll_hatype = 0; /* Bad: we have no ARPHRD_UNSPEC */
  3049. sll->sll_halen = 0;
  3050. }
  3051. rcu_read_unlock();
  3052. return offsetof(struct sockaddr_ll, sll_addr) + sll->sll_halen;
  3053. }
  3054. static int packet_dev_mc(struct net_device *dev, struct packet_mclist *i,
  3055. int what)
  3056. {
  3057. switch (i->type) {
  3058. case PACKET_MR_MULTICAST:
  3059. if (i->alen != dev->addr_len)
  3060. return -EINVAL;
  3061. if (what > 0)
  3062. return dev_mc_add(dev, i->addr);
  3063. else
  3064. return dev_mc_del(dev, i->addr);
  3065. break;
  3066. case PACKET_MR_PROMISC:
  3067. return dev_set_promiscuity(dev, what);
  3068. case PACKET_MR_ALLMULTI:
  3069. return dev_set_allmulti(dev, what);
  3070. case PACKET_MR_UNICAST:
  3071. if (i->alen != dev->addr_len)
  3072. return -EINVAL;
  3073. if (what > 0)
  3074. return dev_uc_add(dev, i->addr);
  3075. else
  3076. return dev_uc_del(dev, i->addr);
  3077. break;
  3078. default:
  3079. break;
  3080. }
  3081. return 0;
  3082. }
  3083. static void packet_dev_mclist_delete(struct net_device *dev,
  3084. struct packet_mclist **mlp)
  3085. {
  3086. struct packet_mclist *ml;
  3087. while ((ml = *mlp) != NULL) {
  3088. if (ml->ifindex == dev->ifindex) {
  3089. packet_dev_mc(dev, ml, -1);
  3090. *mlp = ml->next;
  3091. kfree(ml);
  3092. } else
  3093. mlp = &ml->next;
  3094. }
  3095. }
  3096. static int packet_mc_add(struct sock *sk, struct packet_mreq_max *mreq)
  3097. {
  3098. struct packet_sock *po = pkt_sk(sk);
  3099. struct packet_mclist *ml, *i;
  3100. struct net_device *dev;
  3101. int err;
  3102. rtnl_lock();
  3103. err = -ENODEV;
  3104. dev = __dev_get_by_index(sock_net(sk), mreq->mr_ifindex);
  3105. if (!dev)
  3106. goto done;
  3107. err = -EINVAL;
  3108. if (mreq->mr_alen > dev->addr_len)
  3109. goto done;
  3110. err = -ENOBUFS;
  3111. i = kmalloc(sizeof(*i), GFP_KERNEL);
  3112. if (i == NULL)
  3113. goto done;
  3114. err = 0;
  3115. for (ml = po->mclist; ml; ml = ml->next) {
  3116. if (ml->ifindex == mreq->mr_ifindex &&
  3117. ml->type == mreq->mr_type &&
  3118. ml->alen == mreq->mr_alen &&
  3119. memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
  3120. ml->count++;
  3121. /* Free the new element ... */
  3122. kfree(i);
  3123. goto done;
  3124. }
  3125. }
  3126. i->type = mreq->mr_type;
  3127. i->ifindex = mreq->mr_ifindex;
  3128. i->alen = mreq->mr_alen;
  3129. memcpy(i->addr, mreq->mr_address, i->alen);
  3130. memset(i->addr + i->alen, 0, sizeof(i->addr) - i->alen);
  3131. i->count = 1;
  3132. i->next = po->mclist;
  3133. po->mclist = i;
  3134. err = packet_dev_mc(dev, i, 1);
  3135. if (err) {
  3136. po->mclist = i->next;
  3137. kfree(i);
  3138. }
  3139. done:
  3140. rtnl_unlock();
  3141. return err;
  3142. }
  3143. static int packet_mc_drop(struct sock *sk, struct packet_mreq_max *mreq)
  3144. {
  3145. struct packet_mclist *ml, **mlp;
  3146. rtnl_lock();
  3147. for (mlp = &pkt_sk(sk)->mclist; (ml = *mlp) != NULL; mlp = &ml->next) {
  3148. if (ml->ifindex == mreq->mr_ifindex &&
  3149. ml->type == mreq->mr_type &&
  3150. ml->alen == mreq->mr_alen &&
  3151. memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
  3152. if (--ml->count == 0) {
  3153. struct net_device *dev;
  3154. *mlp = ml->next;
  3155. dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
  3156. if (dev)
  3157. packet_dev_mc(dev, ml, -1);
  3158. kfree(ml);
  3159. }
  3160. break;
  3161. }
  3162. }
  3163. rtnl_unlock();
  3164. return 0;
  3165. }
  3166. static void packet_flush_mclist(struct sock *sk)
  3167. {
  3168. struct packet_sock *po = pkt_sk(sk);
  3169. struct packet_mclist *ml;
  3170. if (!po->mclist)
  3171. return;
  3172. rtnl_lock();
  3173. while ((ml = po->mclist) != NULL) {
  3174. struct net_device *dev;
  3175. po->mclist = ml->next;
  3176. dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
  3177. if (dev != NULL)
  3178. packet_dev_mc(dev, ml, -1);
  3179. kfree(ml);
  3180. }
  3181. rtnl_unlock();
  3182. }
  3183. static int
  3184. packet_setsockopt(struct socket *sock, int level, int optname, sockptr_t optval,
  3185. unsigned int optlen)
  3186. {
  3187. struct sock *sk = sock->sk;
  3188. struct packet_sock *po = pkt_sk(sk);
  3189. int ret;
  3190. if (level != SOL_PACKET)
  3191. return -ENOPROTOOPT;
  3192. switch (optname) {
  3193. case PACKET_ADD_MEMBERSHIP:
  3194. case PACKET_DROP_MEMBERSHIP:
  3195. {
  3196. struct packet_mreq_max mreq;
  3197. int len = optlen;
  3198. memset(&mreq, 0, sizeof(mreq));
  3199. if (len < sizeof(struct packet_mreq))
  3200. return -EINVAL;
  3201. if (len > sizeof(mreq))
  3202. len = sizeof(mreq);
  3203. if (copy_from_sockptr(&mreq, optval, len))
  3204. return -EFAULT;
  3205. if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address)))
  3206. return -EINVAL;
  3207. if (optname == PACKET_ADD_MEMBERSHIP)
  3208. ret = packet_mc_add(sk, &mreq);
  3209. else
  3210. ret = packet_mc_drop(sk, &mreq);
  3211. return ret;
  3212. }
  3213. case PACKET_RX_RING:
  3214. case PACKET_TX_RING:
  3215. {
  3216. union tpacket_req_u req_u;
  3217. int len;
  3218. lock_sock(sk);
  3219. switch (po->tp_version) {
  3220. case TPACKET_V1:
  3221. case TPACKET_V2:
  3222. len = sizeof(req_u.req);
  3223. break;
  3224. case TPACKET_V3:
  3225. default:
  3226. len = sizeof(req_u.req3);
  3227. break;
  3228. }
  3229. if (optlen < len) {
  3230. ret = -EINVAL;
  3231. } else {
  3232. if (copy_from_sockptr(&req_u.req, optval, len))
  3233. ret = -EFAULT;
  3234. else
  3235. ret = packet_set_ring(sk, &req_u, 0,
  3236. optname == PACKET_TX_RING);
  3237. }
  3238. release_sock(sk);
  3239. return ret;
  3240. }
  3241. case PACKET_COPY_THRESH:
  3242. {
  3243. int val;
  3244. if (optlen != sizeof(val))
  3245. return -EINVAL;
  3246. if (copy_from_sockptr(&val, optval, sizeof(val)))
  3247. return -EFAULT;
  3248. pkt_sk(sk)->copy_thresh = val;
  3249. return 0;
  3250. }
  3251. case PACKET_VERSION:
  3252. {
  3253. int val;
  3254. if (optlen != sizeof(val))
  3255. return -EINVAL;
  3256. if (copy_from_sockptr(&val, optval, sizeof(val)))
  3257. return -EFAULT;
  3258. switch (val) {
  3259. case TPACKET_V1:
  3260. case TPACKET_V2:
  3261. case TPACKET_V3:
  3262. break;
  3263. default:
  3264. return -EINVAL;
  3265. }
  3266. lock_sock(sk);
  3267. if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
  3268. ret = -EBUSY;
  3269. } else {
  3270. po->tp_version = val;
  3271. ret = 0;
  3272. }
  3273. release_sock(sk);
  3274. return ret;
  3275. }
  3276. case PACKET_RESERVE:
  3277. {
  3278. unsigned int val;
  3279. if (optlen != sizeof(val))
  3280. return -EINVAL;
  3281. if (copy_from_sockptr(&val, optval, sizeof(val)))
  3282. return -EFAULT;
  3283. if (val > INT_MAX)
  3284. return -EINVAL;
  3285. lock_sock(sk);
  3286. if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
  3287. ret = -EBUSY;
  3288. } else {
  3289. po->tp_reserve = val;
  3290. ret = 0;
  3291. }
  3292. release_sock(sk);
  3293. return ret;
  3294. }
  3295. case PACKET_LOSS:
  3296. {
  3297. unsigned int val;
  3298. if (optlen != sizeof(val))
  3299. return -EINVAL;
  3300. if (copy_from_sockptr(&val, optval, sizeof(val)))
  3301. return -EFAULT;
  3302. lock_sock(sk);
  3303. if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
  3304. ret = -EBUSY;
  3305. } else {
  3306. po->tp_loss = !!val;
  3307. ret = 0;
  3308. }
  3309. release_sock(sk);
  3310. return ret;
  3311. }
  3312. case PACKET_AUXDATA:
  3313. {
  3314. int val;
  3315. if (optlen < sizeof(val))
  3316. return -EINVAL;
  3317. if (copy_from_sockptr(&val, optval, sizeof(val)))
  3318. return -EFAULT;
  3319. packet_sock_flag_set(po, PACKET_SOCK_AUXDATA, val);
  3320. return 0;
  3321. }
  3322. case PACKET_ORIGDEV:
  3323. {
  3324. int val;
  3325. if (optlen < sizeof(val))
  3326. return -EINVAL;
  3327. if (copy_from_sockptr(&val, optval, sizeof(val)))
  3328. return -EFAULT;
  3329. packet_sock_flag_set(po, PACKET_SOCK_ORIGDEV, val);
  3330. return 0;
  3331. }
  3332. case PACKET_VNET_HDR:
  3333. {
  3334. int val;
  3335. if (sock->type != SOCK_RAW)
  3336. return -EINVAL;
  3337. if (optlen < sizeof(val))
  3338. return -EINVAL;
  3339. if (copy_from_sockptr(&val, optval, sizeof(val)))
  3340. return -EFAULT;
  3341. lock_sock(sk);
  3342. if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
  3343. ret = -EBUSY;
  3344. } else {
  3345. po->has_vnet_hdr = !!val;
  3346. ret = 0;
  3347. }
  3348. release_sock(sk);
  3349. return ret;
  3350. }
  3351. case PACKET_TIMESTAMP:
  3352. {
  3353. int val;
  3354. if (optlen != sizeof(val))
  3355. return -EINVAL;
  3356. if (copy_from_sockptr(&val, optval, sizeof(val)))
  3357. return -EFAULT;
  3358. po->tp_tstamp = val;
  3359. return 0;
  3360. }
  3361. case PACKET_FANOUT:
  3362. {
  3363. struct fanout_args args = { 0 };
  3364. if (optlen != sizeof(int) && optlen != sizeof(args))
  3365. return -EINVAL;
  3366. if (copy_from_sockptr(&args, optval, optlen))
  3367. return -EFAULT;
  3368. return fanout_add(sk, &args);
  3369. }
  3370. case PACKET_FANOUT_DATA:
  3371. {
  3372. /* Paired with the WRITE_ONCE() in fanout_add() */
  3373. if (!READ_ONCE(po->fanout))
  3374. return -EINVAL;
  3375. return fanout_set_data(po, optval, optlen);
  3376. }
  3377. case PACKET_IGNORE_OUTGOING:
  3378. {
  3379. int val;
  3380. if (optlen != sizeof(val))
  3381. return -EINVAL;
  3382. if (copy_from_sockptr(&val, optval, sizeof(val)))
  3383. return -EFAULT;
  3384. if (val < 0 || val > 1)
  3385. return -EINVAL;
  3386. po->prot_hook.ignore_outgoing = !!val;
  3387. return 0;
  3388. }
  3389. case PACKET_TX_HAS_OFF:
  3390. {
  3391. unsigned int val;
  3392. if (optlen != sizeof(val))
  3393. return -EINVAL;
  3394. if (copy_from_sockptr(&val, optval, sizeof(val)))
  3395. return -EFAULT;
  3396. lock_sock(sk);
  3397. if (!po->rx_ring.pg_vec && !po->tx_ring.pg_vec)
  3398. po->tp_tx_has_off = !!val;
  3399. release_sock(sk);
  3400. return 0;
  3401. }
  3402. case PACKET_QDISC_BYPASS:
  3403. {
  3404. int val;
  3405. if (optlen != sizeof(val))
  3406. return -EINVAL;
  3407. if (copy_from_sockptr(&val, optval, sizeof(val)))
  3408. return -EFAULT;
  3409. /* Paired with all lockless reads of po->xmit */
  3410. WRITE_ONCE(po->xmit, val ? packet_direct_xmit : dev_queue_xmit);
  3411. return 0;
  3412. }
  3413. default:
  3414. return -ENOPROTOOPT;
  3415. }
  3416. }
  3417. static int packet_getsockopt(struct socket *sock, int level, int optname,
  3418. char __user *optval, int __user *optlen)
  3419. {
  3420. int len;
  3421. int val, lv = sizeof(val);
  3422. struct sock *sk = sock->sk;
  3423. struct packet_sock *po = pkt_sk(sk);
  3424. void *data = &val;
  3425. union tpacket_stats_u st;
  3426. struct tpacket_rollover_stats rstats;
  3427. int drops;
  3428. if (level != SOL_PACKET)
  3429. return -ENOPROTOOPT;
  3430. if (get_user(len, optlen))
  3431. return -EFAULT;
  3432. if (len < 0)
  3433. return -EINVAL;
  3434. switch (optname) {
  3435. case PACKET_STATISTICS:
  3436. spin_lock_bh(&sk->sk_receive_queue.lock);
  3437. memcpy(&st, &po->stats, sizeof(st));
  3438. memset(&po->stats, 0, sizeof(po->stats));
  3439. spin_unlock_bh(&sk->sk_receive_queue.lock);
  3440. drops = atomic_xchg(&po->tp_drops, 0);
  3441. if (po->tp_version == TPACKET_V3) {
  3442. lv = sizeof(struct tpacket_stats_v3);
  3443. st.stats3.tp_drops = drops;
  3444. st.stats3.tp_packets += drops;
  3445. data = &st.stats3;
  3446. } else {
  3447. lv = sizeof(struct tpacket_stats);
  3448. st.stats1.tp_drops = drops;
  3449. st.stats1.tp_packets += drops;
  3450. data = &st.stats1;
  3451. }
  3452. break;
  3453. case PACKET_AUXDATA:
  3454. val = packet_sock_flag(po, PACKET_SOCK_AUXDATA);
  3455. break;
  3456. case PACKET_ORIGDEV:
  3457. val = packet_sock_flag(po, PACKET_SOCK_ORIGDEV);
  3458. break;
  3459. case PACKET_VNET_HDR:
  3460. val = po->has_vnet_hdr;
  3461. break;
  3462. case PACKET_VERSION:
  3463. val = po->tp_version;
  3464. break;
  3465. case PACKET_HDRLEN:
  3466. if (len > sizeof(int))
  3467. len = sizeof(int);
  3468. if (len < sizeof(int))
  3469. return -EINVAL;
  3470. if (copy_from_user(&val, optval, len))
  3471. return -EFAULT;
  3472. switch (val) {
  3473. case TPACKET_V1:
  3474. val = sizeof(struct tpacket_hdr);
  3475. break;
  3476. case TPACKET_V2:
  3477. val = sizeof(struct tpacket2_hdr);
  3478. break;
  3479. case TPACKET_V3:
  3480. val = sizeof(struct tpacket3_hdr);
  3481. break;
  3482. default:
  3483. return -EINVAL;
  3484. }
  3485. break;
  3486. case PACKET_RESERVE:
  3487. val = po->tp_reserve;
  3488. break;
  3489. case PACKET_LOSS:
  3490. val = po->tp_loss;
  3491. break;
  3492. case PACKET_TIMESTAMP:
  3493. val = po->tp_tstamp;
  3494. break;
  3495. case PACKET_FANOUT:
  3496. val = (po->fanout ?
  3497. ((u32)po->fanout->id |
  3498. ((u32)po->fanout->type << 16) |
  3499. ((u32)po->fanout->flags << 24)) :
  3500. 0);
  3501. break;
  3502. case PACKET_IGNORE_OUTGOING:
  3503. val = po->prot_hook.ignore_outgoing;
  3504. break;
  3505. case PACKET_ROLLOVER_STATS:
  3506. if (!po->rollover)
  3507. return -EINVAL;
  3508. rstats.tp_all = atomic_long_read(&po->rollover->num);
  3509. rstats.tp_huge = atomic_long_read(&po->rollover->num_huge);
  3510. rstats.tp_failed = atomic_long_read(&po->rollover->num_failed);
  3511. data = &rstats;
  3512. lv = sizeof(rstats);
  3513. break;
  3514. case PACKET_TX_HAS_OFF:
  3515. val = po->tp_tx_has_off;
  3516. break;
  3517. case PACKET_QDISC_BYPASS:
  3518. val = packet_use_direct_xmit(po);
  3519. break;
  3520. default:
  3521. return -ENOPROTOOPT;
  3522. }
  3523. if (len > lv)
  3524. len = lv;
  3525. if (put_user(len, optlen))
  3526. return -EFAULT;
  3527. if (copy_to_user(optval, data, len))
  3528. return -EFAULT;
  3529. return 0;
  3530. }
  3531. static int packet_notifier(struct notifier_block *this,
  3532. unsigned long msg, void *ptr)
  3533. {
  3534. struct sock *sk;
  3535. struct net_device *dev = netdev_notifier_info_to_dev(ptr);
  3536. struct net *net = dev_net(dev);
  3537. rcu_read_lock();
  3538. sk_for_each_rcu(sk, &net->packet.sklist) {
  3539. struct packet_sock *po = pkt_sk(sk);
  3540. switch (msg) {
  3541. case NETDEV_UNREGISTER:
  3542. if (po->mclist)
  3543. packet_dev_mclist_delete(dev, &po->mclist);
  3544. fallthrough;
  3545. case NETDEV_DOWN:
  3546. if (dev->ifindex == po->ifindex) {
  3547. spin_lock(&po->bind_lock);
  3548. if (po->running) {
  3549. __unregister_prot_hook(sk, false);
  3550. sk->sk_err = ENETDOWN;
  3551. if (!sock_flag(sk, SOCK_DEAD))
  3552. sk_error_report(sk);
  3553. }
  3554. if (msg == NETDEV_UNREGISTER) {
  3555. packet_cached_dev_reset(po);
  3556. WRITE_ONCE(po->ifindex, -1);
  3557. netdev_put(po->prot_hook.dev,
  3558. &po->prot_hook.dev_tracker);
  3559. po->prot_hook.dev = NULL;
  3560. }
  3561. spin_unlock(&po->bind_lock);
  3562. }
  3563. break;
  3564. case NETDEV_UP:
  3565. if (dev->ifindex == po->ifindex) {
  3566. spin_lock(&po->bind_lock);
  3567. if (po->num)
  3568. register_prot_hook(sk);
  3569. spin_unlock(&po->bind_lock);
  3570. }
  3571. break;
  3572. }
  3573. }
  3574. rcu_read_unlock();
  3575. return NOTIFY_DONE;
  3576. }
  3577. static int packet_ioctl(struct socket *sock, unsigned int cmd,
  3578. unsigned long arg)
  3579. {
  3580. struct sock *sk = sock->sk;
  3581. switch (cmd) {
  3582. case SIOCOUTQ:
  3583. {
  3584. int amount = sk_wmem_alloc_get(sk);
  3585. return put_user(amount, (int __user *)arg);
  3586. }
  3587. case SIOCINQ:
  3588. {
  3589. struct sk_buff *skb;
  3590. int amount = 0;
  3591. spin_lock_bh(&sk->sk_receive_queue.lock);
  3592. skb = skb_peek(&sk->sk_receive_queue);
  3593. if (skb)
  3594. amount = skb->len;
  3595. spin_unlock_bh(&sk->sk_receive_queue.lock);
  3596. return put_user(amount, (int __user *)arg);
  3597. }
  3598. #ifdef CONFIG_INET
  3599. case SIOCADDRT:
  3600. case SIOCDELRT:
  3601. case SIOCDARP:
  3602. case SIOCGARP:
  3603. case SIOCSARP:
  3604. case SIOCGIFADDR:
  3605. case SIOCSIFADDR:
  3606. case SIOCGIFBRDADDR:
  3607. case SIOCSIFBRDADDR:
  3608. case SIOCGIFNETMASK:
  3609. case SIOCSIFNETMASK:
  3610. case SIOCGIFDSTADDR:
  3611. case SIOCSIFDSTADDR:
  3612. case SIOCSIFFLAGS:
  3613. return inet_dgram_ops.ioctl(sock, cmd, arg);
  3614. #endif
  3615. default:
  3616. return -ENOIOCTLCMD;
  3617. }
  3618. return 0;
  3619. }
  3620. static __poll_t packet_poll(struct file *file, struct socket *sock,
  3621. poll_table *wait)
  3622. {
  3623. struct sock *sk = sock->sk;
  3624. struct packet_sock *po = pkt_sk(sk);
  3625. __poll_t mask = datagram_poll(file, sock, wait);
  3626. spin_lock_bh(&sk->sk_receive_queue.lock);
  3627. if (po->rx_ring.pg_vec) {
  3628. if (!packet_previous_rx_frame(po, &po->rx_ring,
  3629. TP_STATUS_KERNEL))
  3630. mask |= EPOLLIN | EPOLLRDNORM;
  3631. }
  3632. packet_rcv_try_clear_pressure(po);
  3633. spin_unlock_bh(&sk->sk_receive_queue.lock);
  3634. spin_lock_bh(&sk->sk_write_queue.lock);
  3635. if (po->tx_ring.pg_vec) {
  3636. if (packet_current_frame(po, &po->tx_ring, TP_STATUS_AVAILABLE))
  3637. mask |= EPOLLOUT | EPOLLWRNORM;
  3638. }
  3639. spin_unlock_bh(&sk->sk_write_queue.lock);
  3640. return mask;
  3641. }
  3642. /* Dirty? Well, I still did not learn better way to account
  3643. * for user mmaps.
  3644. */
  3645. static void packet_mm_open(struct vm_area_struct *vma)
  3646. {
  3647. struct file *file = vma->vm_file;
  3648. struct socket *sock = file->private_data;
  3649. struct sock *sk = sock->sk;
  3650. if (sk)
  3651. atomic_long_inc(&pkt_sk(sk)->mapped);
  3652. }
  3653. static void packet_mm_close(struct vm_area_struct *vma)
  3654. {
  3655. struct file *file = vma->vm_file;
  3656. struct socket *sock = file->private_data;
  3657. struct sock *sk = sock->sk;
  3658. if (sk)
  3659. atomic_long_dec(&pkt_sk(sk)->mapped);
  3660. }
  3661. static const struct vm_operations_struct packet_mmap_ops = {
  3662. .open = packet_mm_open,
  3663. .close = packet_mm_close,
  3664. };
  3665. static void free_pg_vec(struct pgv *pg_vec, unsigned int order,
  3666. unsigned int len)
  3667. {
  3668. int i;
  3669. for (i = 0; i < len; i++) {
  3670. if (likely(pg_vec[i].buffer)) {
  3671. if (is_vmalloc_addr(pg_vec[i].buffer))
  3672. vfree(pg_vec[i].buffer);
  3673. else
  3674. free_pages((unsigned long)pg_vec[i].buffer,
  3675. order);
  3676. pg_vec[i].buffer = NULL;
  3677. }
  3678. }
  3679. kfree(pg_vec);
  3680. }
  3681. static char *alloc_one_pg_vec_page(unsigned long order)
  3682. {
  3683. char *buffer;
  3684. gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
  3685. __GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
  3686. buffer = (char *) __get_free_pages(gfp_flags, order);
  3687. if (buffer)
  3688. return buffer;
  3689. /* __get_free_pages failed, fall back to vmalloc */
  3690. buffer = vzalloc(array_size((1 << order), PAGE_SIZE));
  3691. if (buffer)
  3692. return buffer;
  3693. /* vmalloc failed, lets dig into swap here */
  3694. gfp_flags &= ~__GFP_NORETRY;
  3695. buffer = (char *) __get_free_pages(gfp_flags, order);
  3696. if (buffer)
  3697. return buffer;
  3698. /* complete and utter failure */
  3699. return NULL;
  3700. }
  3701. static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
  3702. {
  3703. unsigned int block_nr = req->tp_block_nr;
  3704. struct pgv *pg_vec;
  3705. int i;
  3706. pg_vec = kcalloc(block_nr, sizeof(struct pgv), GFP_KERNEL | __GFP_NOWARN);
  3707. if (unlikely(!pg_vec))
  3708. goto out;
  3709. for (i = 0; i < block_nr; i++) {
  3710. pg_vec[i].buffer = alloc_one_pg_vec_page(order);
  3711. if (unlikely(!pg_vec[i].buffer))
  3712. goto out_free_pgvec;
  3713. }
  3714. out:
  3715. return pg_vec;
  3716. out_free_pgvec:
  3717. free_pg_vec(pg_vec, order, block_nr);
  3718. pg_vec = NULL;
  3719. goto out;
  3720. }
  3721. static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
  3722. int closing, int tx_ring)
  3723. {
  3724. struct pgv *pg_vec = NULL;
  3725. struct packet_sock *po = pkt_sk(sk);
  3726. unsigned long *rx_owner_map = NULL;
  3727. int was_running, order = 0;
  3728. struct packet_ring_buffer *rb;
  3729. struct sk_buff_head *rb_queue;
  3730. __be16 num;
  3731. int err;
  3732. /* Added to avoid minimal code churn */
  3733. struct tpacket_req *req = &req_u->req;
  3734. rb = tx_ring ? &po->tx_ring : &po->rx_ring;
  3735. rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
  3736. err = -EBUSY;
  3737. if (!closing) {
  3738. if (atomic_long_read(&po->mapped))
  3739. goto out;
  3740. if (packet_read_pending(rb))
  3741. goto out;
  3742. }
  3743. if (req->tp_block_nr) {
  3744. unsigned int min_frame_size;
  3745. /* Sanity tests and some calculations */
  3746. err = -EBUSY;
  3747. if (unlikely(rb->pg_vec))
  3748. goto out;
  3749. switch (po->tp_version) {
  3750. case TPACKET_V1:
  3751. po->tp_hdrlen = TPACKET_HDRLEN;
  3752. break;
  3753. case TPACKET_V2:
  3754. po->tp_hdrlen = TPACKET2_HDRLEN;
  3755. break;
  3756. case TPACKET_V3:
  3757. po->tp_hdrlen = TPACKET3_HDRLEN;
  3758. break;
  3759. }
  3760. err = -EINVAL;
  3761. if (unlikely((int)req->tp_block_size <= 0))
  3762. goto out;
  3763. if (unlikely(!PAGE_ALIGNED(req->tp_block_size)))
  3764. goto out;
  3765. min_frame_size = po->tp_hdrlen + po->tp_reserve;
  3766. if (po->tp_version >= TPACKET_V3 &&
  3767. req->tp_block_size <
  3768. BLK_PLUS_PRIV((u64)req_u->req3.tp_sizeof_priv) + min_frame_size)
  3769. goto out;
  3770. if (unlikely(req->tp_frame_size < min_frame_size))
  3771. goto out;
  3772. if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1)))
  3773. goto out;
  3774. rb->frames_per_block = req->tp_block_size / req->tp_frame_size;
  3775. if (unlikely(rb->frames_per_block == 0))
  3776. goto out;
  3777. if (unlikely(rb->frames_per_block > UINT_MAX / req->tp_block_nr))
  3778. goto out;
  3779. if (unlikely((rb->frames_per_block * req->tp_block_nr) !=
  3780. req->tp_frame_nr))
  3781. goto out;
  3782. err = -ENOMEM;
  3783. order = get_order(req->tp_block_size);
  3784. pg_vec = alloc_pg_vec(req, order);
  3785. if (unlikely(!pg_vec))
  3786. goto out;
  3787. switch (po->tp_version) {
  3788. case TPACKET_V3:
  3789. /* Block transmit is not supported yet */
  3790. if (!tx_ring) {
  3791. init_prb_bdqc(po, rb, pg_vec, req_u);
  3792. } else {
  3793. struct tpacket_req3 *req3 = &req_u->req3;
  3794. if (req3->tp_retire_blk_tov ||
  3795. req3->tp_sizeof_priv ||
  3796. req3->tp_feature_req_word) {
  3797. err = -EINVAL;
  3798. goto out_free_pg_vec;
  3799. }
  3800. }
  3801. break;
  3802. default:
  3803. if (!tx_ring) {
  3804. rx_owner_map = bitmap_alloc(req->tp_frame_nr,
  3805. GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO);
  3806. if (!rx_owner_map)
  3807. goto out_free_pg_vec;
  3808. }
  3809. break;
  3810. }
  3811. }
  3812. /* Done */
  3813. else {
  3814. err = -EINVAL;
  3815. if (unlikely(req->tp_frame_nr))
  3816. goto out;
  3817. }
  3818. /* Detach socket from network */
  3819. spin_lock(&po->bind_lock);
  3820. was_running = po->running;
  3821. num = po->num;
  3822. if (was_running) {
  3823. WRITE_ONCE(po->num, 0);
  3824. __unregister_prot_hook(sk, false);
  3825. }
  3826. spin_unlock(&po->bind_lock);
  3827. synchronize_net();
  3828. err = -EBUSY;
  3829. mutex_lock(&po->pg_vec_lock);
  3830. if (closing || atomic_long_read(&po->mapped) == 0) {
  3831. err = 0;
  3832. spin_lock_bh(&rb_queue->lock);
  3833. swap(rb->pg_vec, pg_vec);
  3834. if (po->tp_version <= TPACKET_V2)
  3835. swap(rb->rx_owner_map, rx_owner_map);
  3836. rb->frame_max = (req->tp_frame_nr - 1);
  3837. rb->head = 0;
  3838. rb->frame_size = req->tp_frame_size;
  3839. spin_unlock_bh(&rb_queue->lock);
  3840. swap(rb->pg_vec_order, order);
  3841. swap(rb->pg_vec_len, req->tp_block_nr);
  3842. rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE;
  3843. po->prot_hook.func = (po->rx_ring.pg_vec) ?
  3844. tpacket_rcv : packet_rcv;
  3845. skb_queue_purge(rb_queue);
  3846. if (atomic_long_read(&po->mapped))
  3847. pr_err("packet_mmap: vma is busy: %ld\n",
  3848. atomic_long_read(&po->mapped));
  3849. }
  3850. mutex_unlock(&po->pg_vec_lock);
  3851. spin_lock(&po->bind_lock);
  3852. if (was_running) {
  3853. WRITE_ONCE(po->num, num);
  3854. register_prot_hook(sk);
  3855. }
  3856. spin_unlock(&po->bind_lock);
  3857. if (pg_vec && (po->tp_version > TPACKET_V2)) {
  3858. /* Because we don't support block-based V3 on tx-ring */
  3859. if (!tx_ring)
  3860. prb_shutdown_retire_blk_timer(po, rb_queue);
  3861. }
  3862. out_free_pg_vec:
  3863. if (pg_vec) {
  3864. bitmap_free(rx_owner_map);
  3865. free_pg_vec(pg_vec, order, req->tp_block_nr);
  3866. }
  3867. out:
  3868. return err;
  3869. }
  3870. static int packet_mmap(struct file *file, struct socket *sock,
  3871. struct vm_area_struct *vma)
  3872. {
  3873. struct sock *sk = sock->sk;
  3874. struct packet_sock *po = pkt_sk(sk);
  3875. unsigned long size, expected_size;
  3876. struct packet_ring_buffer *rb;
  3877. unsigned long start;
  3878. int err = -EINVAL;
  3879. int i;
  3880. if (vma->vm_pgoff)
  3881. return -EINVAL;
  3882. mutex_lock(&po->pg_vec_lock);
  3883. expected_size = 0;
  3884. for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
  3885. if (rb->pg_vec) {
  3886. expected_size += rb->pg_vec_len
  3887. * rb->pg_vec_pages
  3888. * PAGE_SIZE;
  3889. }
  3890. }
  3891. if (expected_size == 0)
  3892. goto out;
  3893. size = vma->vm_end - vma->vm_start;
  3894. if (size != expected_size)
  3895. goto out;
  3896. start = vma->vm_start;
  3897. for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
  3898. if (rb->pg_vec == NULL)
  3899. continue;
  3900. for (i = 0; i < rb->pg_vec_len; i++) {
  3901. struct page *page;
  3902. void *kaddr = rb->pg_vec[i].buffer;
  3903. int pg_num;
  3904. for (pg_num = 0; pg_num < rb->pg_vec_pages; pg_num++) {
  3905. page = pgv_to_page(kaddr);
  3906. err = vm_insert_page(vma, start, page);
  3907. if (unlikely(err))
  3908. goto out;
  3909. start += PAGE_SIZE;
  3910. kaddr += PAGE_SIZE;
  3911. }
  3912. }
  3913. }
  3914. atomic_long_inc(&po->mapped);
  3915. vma->vm_ops = &packet_mmap_ops;
  3916. err = 0;
  3917. out:
  3918. mutex_unlock(&po->pg_vec_lock);
  3919. return err;
  3920. }
  3921. static const struct proto_ops packet_ops_spkt = {
  3922. .family = PF_PACKET,
  3923. .owner = THIS_MODULE,
  3924. .release = packet_release,
  3925. .bind = packet_bind_spkt,
  3926. .connect = sock_no_connect,
  3927. .socketpair = sock_no_socketpair,
  3928. .accept = sock_no_accept,
  3929. .getname = packet_getname_spkt,
  3930. .poll = datagram_poll,
  3931. .ioctl = packet_ioctl,
  3932. .gettstamp = sock_gettstamp,
  3933. .listen = sock_no_listen,
  3934. .shutdown = sock_no_shutdown,
  3935. .sendmsg = packet_sendmsg_spkt,
  3936. .recvmsg = packet_recvmsg,
  3937. .mmap = sock_no_mmap,
  3938. .sendpage = sock_no_sendpage,
  3939. };
  3940. static const struct proto_ops packet_ops = {
  3941. .family = PF_PACKET,
  3942. .owner = THIS_MODULE,
  3943. .release = packet_release,
  3944. .bind = packet_bind,
  3945. .connect = sock_no_connect,
  3946. .socketpair = sock_no_socketpair,
  3947. .accept = sock_no_accept,
  3948. .getname = packet_getname,
  3949. .poll = packet_poll,
  3950. .ioctl = packet_ioctl,
  3951. .gettstamp = sock_gettstamp,
  3952. .listen = sock_no_listen,
  3953. .shutdown = sock_no_shutdown,
  3954. .setsockopt = packet_setsockopt,
  3955. .getsockopt = packet_getsockopt,
  3956. .sendmsg = packet_sendmsg,
  3957. .recvmsg = packet_recvmsg,
  3958. .mmap = packet_mmap,
  3959. .sendpage = sock_no_sendpage,
  3960. };
  3961. static const struct net_proto_family packet_family_ops = {
  3962. .family = PF_PACKET,
  3963. .create = packet_create,
  3964. .owner = THIS_MODULE,
  3965. };
  3966. static struct notifier_block packet_netdev_notifier = {
  3967. .notifier_call = packet_notifier,
  3968. };
  3969. #ifdef CONFIG_PROC_FS
  3970. static void *packet_seq_start(struct seq_file *seq, loff_t *pos)
  3971. __acquires(RCU)
  3972. {
  3973. struct net *net = seq_file_net(seq);
  3974. rcu_read_lock();
  3975. return seq_hlist_start_head_rcu(&net->packet.sklist, *pos);
  3976. }
  3977. static void *packet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
  3978. {
  3979. struct net *net = seq_file_net(seq);
  3980. return seq_hlist_next_rcu(v, &net->packet.sklist, pos);
  3981. }
  3982. static void packet_seq_stop(struct seq_file *seq, void *v)
  3983. __releases(RCU)
  3984. {
  3985. rcu_read_unlock();
  3986. }
  3987. static int packet_seq_show(struct seq_file *seq, void *v)
  3988. {
  3989. if (v == SEQ_START_TOKEN)
  3990. seq_printf(seq,
  3991. "%*sRefCnt Type Proto Iface R Rmem User Inode\n",
  3992. IS_ENABLED(CONFIG_64BIT) ? -17 : -9, "sk");
  3993. else {
  3994. struct sock *s = sk_entry(v);
  3995. const struct packet_sock *po = pkt_sk(s);
  3996. seq_printf(seq,
  3997. "%pK %-6d %-4d %04x %-5d %1d %-6u %-6u %-6lu\n",
  3998. s,
  3999. refcount_read(&s->sk_refcnt),
  4000. s->sk_type,
  4001. ntohs(READ_ONCE(po->num)),
  4002. READ_ONCE(po->ifindex),
  4003. po->running,
  4004. atomic_read(&s->sk_rmem_alloc),
  4005. from_kuid_munged(seq_user_ns(seq), sock_i_uid(s)),
  4006. sock_i_ino(s));
  4007. }
  4008. return 0;
  4009. }
  4010. static const struct seq_operations packet_seq_ops = {
  4011. .start = packet_seq_start,
  4012. .next = packet_seq_next,
  4013. .stop = packet_seq_stop,
  4014. .show = packet_seq_show,
  4015. };
  4016. #endif
  4017. static int __net_init packet_net_init(struct net *net)
  4018. {
  4019. mutex_init(&net->packet.sklist_lock);
  4020. INIT_HLIST_HEAD(&net->packet.sklist);
  4021. #ifdef CONFIG_PROC_FS
  4022. if (!proc_create_net("packet", 0, net->proc_net, &packet_seq_ops,
  4023. sizeof(struct seq_net_private)))
  4024. return -ENOMEM;
  4025. #endif /* CONFIG_PROC_FS */
  4026. return 0;
  4027. }
  4028. static void __net_exit packet_net_exit(struct net *net)
  4029. {
  4030. remove_proc_entry("packet", net->proc_net);
  4031. WARN_ON_ONCE(!hlist_empty(&net->packet.sklist));
  4032. }
  4033. static struct pernet_operations packet_net_ops = {
  4034. .init = packet_net_init,
  4035. .exit = packet_net_exit,
  4036. };
  4037. static void __exit packet_exit(void)
  4038. {
  4039. sock_unregister(PF_PACKET);
  4040. proto_unregister(&packet_proto);
  4041. unregister_netdevice_notifier(&packet_netdev_notifier);
  4042. unregister_pernet_subsys(&packet_net_ops);
  4043. }
  4044. static int __init packet_init(void)
  4045. {
  4046. int rc;
  4047. rc = register_pernet_subsys(&packet_net_ops);
  4048. if (rc)
  4049. goto out;
  4050. rc = register_netdevice_notifier(&packet_netdev_notifier);
  4051. if (rc)
  4052. goto out_pernet;
  4053. rc = proto_register(&packet_proto, 0);
  4054. if (rc)
  4055. goto out_notifier;
  4056. rc = sock_register(&packet_family_ops);
  4057. if (rc)
  4058. goto out_proto;
  4059. return 0;
  4060. out_proto:
  4061. proto_unregister(&packet_proto);
  4062. out_notifier:
  4063. unregister_netdevice_notifier(&packet_netdev_notifier);
  4064. out_pernet:
  4065. unregister_pernet_subsys(&packet_net_ops);
  4066. out:
  4067. return rc;
  4068. }
  4069. module_init(packet_init);
  4070. module_exit(packet_exit);
  4071. MODULE_LICENSE("GPL");
  4072. MODULE_ALIAS_NETPROTO(PF_PACKET);