af_packet.c 111 KB

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